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);
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 writeUnpadded(const void* data, size_t len);
176     LIBBINDER_EXPORTED status_t writeInt32(int32_t val);
177     LIBBINDER_EXPORTED status_t writeUint32(uint32_t val);
178     LIBBINDER_EXPORTED status_t writeInt64(int64_t val);
179     LIBBINDER_EXPORTED status_t writeUint64(uint64_t val);
180     LIBBINDER_EXPORTED status_t writeFloat(float val);
181     LIBBINDER_EXPORTED status_t writeDouble(double val);
182     LIBBINDER_EXPORTED status_t writeCString(const char* str);
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     LIBBINDER_EXPORTED String8 readString8() const;
440     LIBBINDER_EXPORTED status_t readString8(String8* pArg) const;
441     LIBBINDER_EXPORTED const char* readString8Inplace(size_t* outLen) const;
442     LIBBINDER_EXPORTED String16 readString16() const;
443     LIBBINDER_EXPORTED status_t readString16(String16* pArg) const;
444     LIBBINDER_EXPORTED status_t readString16(std::optional<String16>* pArg) const;
445     LIBBINDER_EXPORTED status_t readString16(std::unique_ptr<String16>* pArg) const
446             __attribute__((deprecated("use std::optional version instead")));
447     LIBBINDER_EXPORTED const char16_t* readString16Inplace(size_t* outLen) const;
448     LIBBINDER_EXPORTED sp<IBinder> readStrongBinder() const;
449     LIBBINDER_EXPORTED status_t readStrongBinder(sp<IBinder>* val) const;
450     LIBBINDER_EXPORTED status_t readNullableStrongBinder(sp<IBinder>* val) const;
451 
452     // Read an Enum vector with underlying type int8_t.
453     // Does not use padding; each byte is contiguous.
454     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)455     status_t            readEnumVector(std::vector<T>* val) const
456             { return readData(val); }
457     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>
458     [[deprecated("use std::optional version instead")]] //
readEnumVector(std::unique_ptr<std::vector<T>> * val)459     status_t            readEnumVector(std::unique_ptr<std::vector<T>>* val) const
460             { return readData(val); }
461     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)462     status_t            readEnumVector(std::optional<std::vector<T>>* val) const
463             { return readData(val); }
464     // Read an Enum vector with underlying type != int8_t.
465     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)466     status_t            readEnumVector(std::vector<T>* val) const
467             { return readData(val); }
468     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>
469     [[deprecated("use std::optional version instead")]] //
readEnumVector(std::unique_ptr<std::vector<T>> * val)470     status_t            readEnumVector(std::unique_ptr<std::vector<T>>* val) const
471             { return readData(val); }
472     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)473     status_t            readEnumVector(std::optional<std::vector<T>>* val) const
474             { return readData(val); }
475 
476     template<typename T>
readParcelableVector(std::optional<std::vector<std::optional<T>>> * val)477     status_t            readParcelableVector(
478                             std::optional<std::vector<std::optional<T>>>* val) const
479             { return readData(val); }
480     template<typename T>
481     [[deprecated("use std::optional version instead")]] //
readParcelableVector(std::unique_ptr<std::vector<std::unique_ptr<T>>> * val)482     status_t            readParcelableVector(
483                             std::unique_ptr<std::vector<std::unique_ptr<T>>>* val) const
484             { return readData(val); }
485     template<typename T>
readParcelableVector(std::vector<T> * val)486     status_t            readParcelableVector(std::vector<T>* val) const
487             { return readData(val); }
488 
489     LIBBINDER_EXPORTED status_t readParcelable(Parcelable* parcelable) const;
490 
491     template<typename T>
readParcelable(std::optional<T> * parcelable)492     status_t            readParcelable(std::optional<T>* parcelable) const
493             { return readData(parcelable); }
494     template <typename T>
readParcelable(std::unique_ptr<T> * parcelable)495     status_t readParcelable(std::unique_ptr<T>* parcelable) const {
496         return readData(parcelable);
497     }
498 
499     // If strong binder would be nullptr, readStrongBinder() returns an error.
500     // TODO: T must be derived from IInterface, fix for clarity.
501     template<typename T>
502     status_t            readStrongBinder(sp<T>* val) const;
503 
504     template<typename T>
505     status_t            readNullableStrongBinder(sp<T>* val) const;
506 
507     LIBBINDER_EXPORTED status_t
508     readStrongBinderVector(std::optional<std::vector<sp<IBinder>>>* val) const;
509     LIBBINDER_EXPORTED status_t
510     readStrongBinderVector(std::unique_ptr<std::vector<sp<IBinder>>>* val) const
511             __attribute__((deprecated("use std::optional version instead")));
512     LIBBINDER_EXPORTED status_t readStrongBinderVector(std::vector<sp<IBinder>>* val) const;
513     template <typename T,
514               std::enable_if_t<std::is_base_of_v<::android::IInterface, T>, bool> = true>
readStrongBinderVector(std::vector<sp<T>> * val)515     status_t readStrongBinderVector(std::vector<sp<T>>* val) const {
516         return readData(val);
517     }
518     template <typename T,
519               std::enable_if_t<std::is_base_of_v<::android::IInterface, T>, bool> = true>
readStrongBinderVector(std::optional<std::vector<sp<T>>> * val)520     status_t readStrongBinderVector(std::optional<std::vector<sp<T>>>* val) const {
521         return readData(val);
522     }
523 
524     LIBBINDER_EXPORTED status_t readByteVector(std::optional<std::vector<int8_t>>* val) const;
525     LIBBINDER_EXPORTED status_t readByteVector(std::unique_ptr<std::vector<int8_t>>* val) const
526             __attribute__((deprecated("use std::optional version instead")));
527     LIBBINDER_EXPORTED status_t readByteVector(std::vector<int8_t>* val) const;
528     LIBBINDER_EXPORTED status_t readByteVector(std::optional<std::vector<uint8_t>>* val) const;
529     LIBBINDER_EXPORTED status_t readByteVector(std::unique_ptr<std::vector<uint8_t>>* val) const
530             __attribute__((deprecated("use std::optional version instead")));
531     LIBBINDER_EXPORTED status_t readByteVector(std::vector<uint8_t>* val) const;
532     LIBBINDER_EXPORTED status_t readInt32Vector(std::optional<std::vector<int32_t>>* val) const;
533     LIBBINDER_EXPORTED status_t readInt32Vector(std::unique_ptr<std::vector<int32_t>>* val) const
534             __attribute__((deprecated("use std::optional version instead")));
535     LIBBINDER_EXPORTED status_t readInt32Vector(std::vector<int32_t>* val) const;
536     LIBBINDER_EXPORTED status_t readInt64Vector(std::optional<std::vector<int64_t>>* val) const;
537     LIBBINDER_EXPORTED status_t readInt64Vector(std::unique_ptr<std::vector<int64_t>>* val) const
538             __attribute__((deprecated("use std::optional version instead")));
539     LIBBINDER_EXPORTED status_t readInt64Vector(std::vector<int64_t>* val) const;
540     LIBBINDER_EXPORTED status_t readUint64Vector(std::optional<std::vector<uint64_t>>* val) const;
541     LIBBINDER_EXPORTED status_t readUint64Vector(std::unique_ptr<std::vector<uint64_t>>* val) const
542             __attribute__((deprecated("use std::optional version instead")));
543     LIBBINDER_EXPORTED status_t readUint64Vector(std::vector<uint64_t>* val) const;
544     LIBBINDER_EXPORTED status_t readFloatVector(std::optional<std::vector<float>>* val) const;
545     LIBBINDER_EXPORTED status_t readFloatVector(std::unique_ptr<std::vector<float>>* val) const
546             __attribute__((deprecated("use std::optional version instead")));
547     LIBBINDER_EXPORTED status_t readFloatVector(std::vector<float>* val) const;
548     LIBBINDER_EXPORTED status_t readDoubleVector(std::optional<std::vector<double>>* val) const;
549     LIBBINDER_EXPORTED status_t readDoubleVector(std::unique_ptr<std::vector<double>>* val) const
550             __attribute__((deprecated("use std::optional version instead")));
551     LIBBINDER_EXPORTED status_t readDoubleVector(std::vector<double>* val) const;
552     LIBBINDER_EXPORTED status_t readBoolVector(std::optional<std::vector<bool>>* val) const;
553     LIBBINDER_EXPORTED status_t readBoolVector(std::unique_ptr<std::vector<bool>>* val) const
554             __attribute__((deprecated("use std::optional version instead")));
555     LIBBINDER_EXPORTED status_t readBoolVector(std::vector<bool>* val) const;
556     LIBBINDER_EXPORTED status_t readCharVector(std::optional<std::vector<char16_t>>* val) const;
557     LIBBINDER_EXPORTED status_t readCharVector(std::unique_ptr<std::vector<char16_t>>* val) const
558             __attribute__((deprecated("use std::optional version instead")));
559     LIBBINDER_EXPORTED status_t readCharVector(std::vector<char16_t>* val) const;
560     LIBBINDER_EXPORTED status_t
561     readString16Vector(std::optional<std::vector<std::optional<String16>>>* val) const;
562     LIBBINDER_EXPORTED status_t
563     readString16Vector(std::unique_ptr<std::vector<std::unique_ptr<String16>>>* val) const
564             __attribute__((deprecated("use std::optional version instead")));
565     LIBBINDER_EXPORTED status_t readString16Vector(std::vector<String16>* val) const;
566     LIBBINDER_EXPORTED status_t readUtf8VectorFromUtf16Vector(
567             std::optional<std::vector<std::optional<std::string>>>* val) const;
568     LIBBINDER_EXPORTED status_t readUtf8VectorFromUtf16Vector(
569             std::unique_ptr<std::vector<std::unique_ptr<std::string>>>* val) const
570             __attribute__((deprecated("use std::optional version instead")));
571     LIBBINDER_EXPORTED status_t readUtf8VectorFromUtf16Vector(std::vector<std::string>* val) const;
572 
573     template <typename T, size_t N>
readFixedArray(std::array<T,N> * val)574     status_t readFixedArray(std::array<T, N>* val) const {
575         return readData(val);
576     }
577     template <typename T, size_t N>
readFixedArray(std::optional<std::array<T,N>> * val)578     status_t readFixedArray(std::optional<std::array<T, N>>* val) const {
579         return readData(val);
580     }
581 
582     template<typename T>
583     status_t            read(Flattenable<T>& val) const;
584 
585     template<typename T>
586     status_t            read(LightFlattenable<T>& val) const;
587 
588     // resizeOutVector is used to resize AIDL out vector parameters.
589     template<typename T>
590     status_t            resizeOutVector(std::vector<T>* val) const;
591     template<typename T>
592     status_t            resizeOutVector(std::optional<std::vector<T>>* val) const;
593     template<typename T>
594     status_t            resizeOutVector(std::unique_ptr<std::vector<T>>* val) const __attribute__((deprecated("use std::optional version instead")));
595 
596     // Like Parcel.java's readExceptionCode().  Reads the first int32
597     // off of a Parcel's header, returning 0 or the negative error
598     // code on exceptions, but also deals with skipping over rich
599     // response headers.  Callers should use this to read & parse the
600     // response headers rather than doing it by hand.
601     LIBBINDER_EXPORTED int32_t readExceptionCode() const;
602 
603 #ifndef BINDER_DISABLE_NATIVE_HANDLE
604     // Retrieve native_handle from the parcel. This returns a copy of the
605     // parcel's native_handle (the caller takes ownership). The caller
606     // must free the native_handle with native_handle_close() and
607     // native_handle_delete().
608     LIBBINDER_EXPORTED native_handle* readNativeHandle() const;
609 #endif
610 
611     // Retrieve a file descriptor from the parcel.  This returns the raw fd
612     // in the parcel, which you do not own -- use dup() to get your own copy.
613     LIBBINDER_EXPORTED int readFileDescriptor() const;
614 
615     // Retrieve a Java "parcel file descriptor" from the parcel.  This returns the raw fd
616     // in the parcel, which you do not own -- use dup() to get your own copy.
617     LIBBINDER_EXPORTED int readParcelFileDescriptor() const;
618 
619     // Retrieve a smart file descriptor from the parcel.
620     LIBBINDER_EXPORTED status_t readUniqueFileDescriptor(binder::unique_fd* val) const;
621 
622     // Retrieve a Java "parcel file descriptor" from the parcel.
623     LIBBINDER_EXPORTED status_t readUniqueParcelFileDescriptor(binder::unique_fd* val) const;
624 
625     // Retrieve a vector of smart file descriptors from the parcel.
626     LIBBINDER_EXPORTED status_t
627     readUniqueFileDescriptorVector(std::optional<std::vector<binder::unique_fd>>* val) const;
628     LIBBINDER_EXPORTED status_t
629     readUniqueFileDescriptorVector(std::unique_ptr<std::vector<binder::unique_fd>>* val) const
630             __attribute__((deprecated("use std::optional version instead")));
631     LIBBINDER_EXPORTED status_t
632     readUniqueFileDescriptorVector(std::vector<binder::unique_fd>* val) const;
633 
634     // Reads a blob from the parcel.
635     // The caller should call release() on the blob after reading its contents.
636     LIBBINDER_EXPORTED status_t readBlob(size_t len, ReadableBlob* outBlob) const;
637 
638     LIBBINDER_EXPORTED const flat_binder_object* readObject(bool nullMetaData) const;
639 
640     // Explicitly close all file descriptors in the parcel.
641     LIBBINDER_EXPORTED void closeFileDescriptors();
642 
643     // Debugging: get metrics on current allocations.
644     LIBBINDER_EXPORTED static size_t getGlobalAllocSize();
645     LIBBINDER_EXPORTED static size_t getGlobalAllocCount();
646 
647     LIBBINDER_EXPORTED bool replaceCallingWorkSourceUid(uid_t uid);
648     // Returns the work source provided by the caller. This can only be trusted for trusted calling
649     // uid.
650     LIBBINDER_EXPORTED uid_t readCallingWorkSourceUid() const;
651 
652     LIBBINDER_EXPORTED void print(std::ostream& to, uint32_t flags = 0) const;
653 
654 private:
655     // `objects` and `objectsSize` always 0 for RPC Parcels.
656     typedef void (*release_func)(const uint8_t* data, size_t dataSize, const binder_size_t* objects,
657                                  size_t objectsSize);
658 
659     uintptr_t           ipcData() const;
660     size_t              ipcDataSize() const;
661     uintptr_t           ipcObjects() const;
662     size_t              ipcObjectsCount() const;
663     void ipcSetDataReference(const uint8_t* data, size_t dataSize, const binder_size_t* objects,
664                              size_t objectsCount, release_func relFunc);
665     // Takes ownership even when an error is returned.
666     status_t rpcSetDataReference(
667             const sp<RpcSession>& session, const uint8_t* data, size_t dataSize,
668             const uint32_t* objectTable, size_t objectTableSize,
669             std::vector<std::variant<binder::unique_fd, binder::borrowed_fd>>&& ancillaryFds,
670             release_func relFunc);
671 
672     status_t            finishWrite(size_t len);
673     void                releaseObjects();
674     void                acquireObjects();
675     status_t            growData(size_t len);
676     // Clear the Parcel and set the capacity to `desired`.
677     // Doesn't reset the RPC session association.
678     status_t            restartWrite(size_t desired);
679     // Set the capacity to `desired`, truncating the Parcel if necessary.
680     status_t            continueWrite(size_t desired);
681     status_t truncateRpcObjects(size_t newObjectsSize);
682     status_t            writePointer(uintptr_t val);
683     status_t            readPointer(uintptr_t *pArg) const;
684     uintptr_t           readPointer() const;
685     void                freeDataNoInit();
686     void                initState();
687     void                scanForFds() const;
688     status_t scanForBinders(bool* result) const;
689 
690     status_t            validateReadData(size_t len) const;
691 
692     void                updateWorkSourceRequestHeaderPosition() const;
693 
694     status_t            finishFlattenBinder(const sp<IBinder>& binder);
695     status_t            finishUnflattenBinder(const sp<IBinder>& binder, sp<IBinder>* out) const;
696     status_t            flattenBinder(const sp<IBinder>& binder);
697     status_t            unflattenBinder(sp<IBinder>* out) const;
698 
699     LIBBINDER_EXPORTED status_t readOutVectorSizeWithCheck(size_t elmSize, int32_t* size) const;
700 
701     template<class T>
702     status_t            readAligned(T *pArg) const;
703 
704     template<class T>   T readAligned() const;
705 
706     template<class T>
707     status_t            writeAligned(T val);
708 
709     status_t            writeRawNullableParcelable(const Parcelable*
710                                                    parcelable);
711 
712     //-----------------------------------------------------------------------------
713     // Generic type read and write methods for Parcel:
714     //
715     // readData(T *value) will read a value from the Parcel.
716     // writeData(const T& value) will write a value to the Parcel.
717     //
718     // Our approach to parceling is based on two overloaded functions
719     // readData() and writeData() that generate parceling code for an
720     // object automatically based on its type. The code from templates are generated at
721     // compile time (if constexpr), and decomposes an object through a call graph matching
722     // recursive descent of the template typename.
723     //
724     // This approach unifies handling of complex objects,
725     // resulting in fewer lines of code, greater consistency,
726     // extensibility to nested types, efficiency (decisions made at compile time),
727     // and better code maintainability and optimization.
728     //
729     // Design decision: Incorporate the read and write code into Parcel rather than
730     // as a non-intrusive serializer that emits a byte stream, as we have
731     // active objects, alignment, legacy code, and historical idiosyncrasies.
732     //
733     // --- Overview
734     //
735     // Parceling is a way of serializing objects into a sequence of bytes for communication
736     // between processes, as part of marshaling data for remote procedure calls.
737     //
738     // The Parcel instance contains objects serialized as bytes, such as the following:
739     //
740     // 1) Ordinary primitive data such as int, float.
741     // 2) Established structured data such as String16, std::string.
742     // 3) Parcelables, which are C++ objects that derive from Parcelable (and thus have a
743     //    readFromParcel and writeToParcel method).  (Similar for Java)
744     // 4) A std::vector<> of such data.
745     // 5) Nullable objects contained in std::optional, std::unique_ptr, or std::shared_ptr.
746     //
747     // And active objects from the Android ecosystem such as:
748     // 6) File descriptors, unique_fd (kernel object handles)
749     // 7) Binder objects, sp<IBinder> (active Android RPC handles)
750     //
751     // Objects from (1) through (5) serialize into the mData buffer.
752     // Active objects (6) and (7) serialize into both mData and mObjects buffers.
753     //
754     // --- Data layout details
755     //
756     // Data is read or written to the parcel by recursively decomposing the type of the parameter
757     // type T through readData() and writeData() methods.
758     //
759     // We focus on writeData() here in our explanation of the data layout.
760     //
761     // 1) Alignment
762     // Implementation detail: Regardless of the parameter type, writeData() calls are designed
763     // to finish at a multiple of 4 bytes, the default alignment of the Parcel.
764     //
765     // Writes of single uint8_t, int8_t, enums based on types of size 1, char16_t, etc
766     // will result in 4 bytes being written.  The data is widened to int32 and then written;
767     // hence the position of the nonzero bytes depend on the native endianness of the CPU.
768     //
769     // Writes of primitive values with 8 byte size, double, int64_t, uint64_t,
770     // are stored with 4 byte alignment.  The ARM and x86/x64 permit unaligned reads
771     // and writes (albeit with potential latency/throughput penalty) which may or may
772     // not be observable unless the process is IO bound.
773     //
774     // 2) Parcelables
775     // Parcelables are detected by the type's base class, and implemented through calling
776     // into the Parcelable type's readFromParcel() or writeToParcel() methods.
777     // Historically, due to null object detection, a (int32_t) 1 is prepended to the data written.
778     // Parcelables must have a default constructor (i.e. one that takes no arguments).
779     //
780     // 3) Arrays
781     // Arrays of uint8_t and int8_t, and enums based on size 1 are written as
782     // a contiguous packed byte stream.  Hidden zero padding is applied at the end of the byte
783     // stream to make a multiple of 4 bytes (and prevent info leakage when writing).
784     //
785     // All other array writes can be conceptually thought of as recursively calling
786     // writeData on the individual elements (though may be implemented differently for speed).
787     // As discussed in (1), alignment rules are therefore applied for each element
788     // write (not as an aggregate whole), so the wire representation of data can be
789     // substantially larger.
790     //
791     // Historical Note:
792     // Because of element-wise alignment, CharVector and BoolVector are expanded
793     // element-wise into integers even though they could have been optimized to be packed
794     // just like uint8_t, int8_t (size 1 data).
795     //
796     // 3.1) Arrays accessed by the std::vector type.  This is the default for AIDL.
797     //
798     // 4) Nullables
799     // std::optional, std::unique_ptr, std::shared_ptr are all parceled identically
800     // (i.e. result in identical byte layout).
801     // The target of the std::optional, std::unique_ptr, or std::shared_ptr
802     // can either be a std::vector, String16, std::string, or a Parcelable.
803     //
804     // Detection of null relies on peeking the first int32 data and checking if the
805     // the peeked value is considered invalid for the object:
806     // (-1 for vectors, String16, std::string) (0 for Parcelables).  If the peeked value
807     // is invalid, then a null is returned.
808     //
809     // Application Note: When to use each nullable type:
810     //
811     // std::optional: Embeds the object T by value rather than creating a new instance
812     // by managed pointer as std::unique_ptr or std::shared_ptr.  This will save a malloc
813     // when creating an optional instance.
814     //
815     // Use of std::optionals by value can result in copies of the underlying value stored in it,
816     // so a std::move may be used to move in and move out (for example) a vector value into
817     // the std::optional or for the std::optional itself.
818     //
819     // std::unique_ptr, std::shared_ptr: These are preferred when the lifetime of the object is
820     // already managed by the application.  This reduces unnecessary copying of data
821     // especially when the calls are local in-proc (rather than via binder rpc).
822     //
823     // 5) StrongBinder (sp<IBinder>)
824     // StrongBinder objects are written regardless of null. When read, null StrongBinder values
825     // will be interpreted as UNKNOWN_ERROR if the type is a single argument <sp<T>>
826     // or in a vector argument <std::vector<sp<T>>. However, they will be read without an error
827     // if present in a std::optional, std::unique_ptr, or std::shared_ptr vector, e.g.
828     // <std::optional<std::vector<sp<T>>>.
829     //
830     // See AIDL annotation @Nullable, readStrongBinder(), and readNullableStrongBinder().
831     //
832     // Historical Note: writing a vector of StrongBinder objects <std::vector<sp<T>>
833     // containing a null will not cause an error. However reading such a vector will cause
834     // an error _and_ early termination of the read.
835 
836     //  --- Examples
837     //
838     // Using recursive parceling, we can parcel complex data types so long
839     // as they obey the rules described above.
840     //
841     // Example #1
842     // Parceling of a 3D vector
843     //
844     // std::vector<std::vector<std::vector<int32_t>>> v1 {
845     //     { {1}, {2, 3}, {4} },
846     //     {},
847     //     { {10}, {20}, {30, 40} },
848     // };
849     // Parcel p1;
850     // p1.writeData(v1);
851     // decltype(v1) v2;
852     // p1.setDataPosition(0);
853     // p1.readData(&v2);
854     // ASSERT_EQ(v1, v2);
855     //
856     // Example #2
857     // Parceling of mixed shared pointers
858     //
859     // Parcel p1;
860     // auto sp1 = std::make_shared<std::vector<std::shared_ptr<std::vector<int>>>>(3);
861     // (*sp1)[2] = std::make_shared<std::vector<int>>(3);
862     // (*(*sp1)[2])[2] = 2;
863     // p1.writeData(sp1);
864     // decltype(sp1) sp2;
865     // p1.setDataPosition(0);
866     // p1.readData(&sp2);
867     // ASSERT_EQ((*sp1)[0], (*sp2)[0]); // nullptr
868     // ASSERT_EQ((*sp1)[1], (*sp2)[1]); // nullptr
869     // ASSERT_EQ(*(*sp1)[2], *(*sp2)[2]); // { 0, 0, 2}
870 
871     //  --- Helper Methods
872     // TODO: move this to a utils header.
873     //
874     // Determine if a type is a specialization of a templated type
875     // Example: is_specialization_v<T, std::vector>
876 
877     template <typename Test, template <typename...> class Ref>
878     struct is_specialization : std::false_type {};
879 
880     template <template <typename...> class Ref, typename... Args>
881     struct is_specialization<Ref<Args...>, Ref>: std::true_type {};
882 
883     template <typename Test, template <typename...> class Ref>
884     static inline constexpr bool is_specialization_v = is_specialization<Test, Ref>::value;
885 
886     // Get the first template type from a container, the T from MyClass<T, ...>.
887     template<typename T> struct first_template_type;
888 
889     template <template <typename ...> class V, typename T, typename... Args>
890     struct first_template_type<V<T, Args...>> {
891         using type_t = T;
892     };
893 
894     template <typename T>
895     using first_template_type_t = typename first_template_type<T>::type_t;
896 
897     // For static assert(false) we need a template version to avoid early failure.
898     template <typename T>
899     static inline constexpr bool dependent_false_v = false;
900 
901     // primitive types that we consider packed and trivially copyable as an array
902     template <typename T>
903     static inline constexpr bool is_pointer_equivalent_array_v =
904             std::is_same_v<T, int8_t>
905             || std::is_same_v<T, uint8_t>
906             // We could support int16_t and uint16_t, but those aren't currently AIDL types.
907             || std::is_same_v<T, int32_t>
908             || std::is_same_v<T, uint32_t>
909             || std::is_same_v<T, float>
910             // are unaligned reads and write support is assumed.
911             || std::is_same_v<T, uint64_t>
912             || std::is_same_v<T, int64_t>
913             || std::is_same_v<T, double>
914             || (std::is_enum_v<T> && (sizeof(T) == 1 || sizeof(T) == 4)); // size check not type
915 
916     // allowed "nullable" types
917     // These are nonintrusive containers std::optional, std::unique_ptr, std::shared_ptr.
918     template <typename T>
919     static inline constexpr bool is_parcel_nullable_type_v =
920             is_specialization_v<T, std::optional>
921             || is_specialization_v<T, std::unique_ptr>
922             || is_specialization_v<T, std::shared_ptr>;
923 
924     // Tells if T is a fixed-size array.
925     template <typename T>
926     struct is_fixed_array : std::false_type {};
927 
928     template <typename T, size_t N>
929     struct is_fixed_array<std::array<T, N>> : std::true_type {};
930 
931     template <typename T>
932     static inline constexpr bool is_fixed_array_v = is_fixed_array<T>::value;
933 
934     // special int32 value to indicate NonNull or Null parcelables
935     // This is fixed to be only 0 or 1 by contract, do not change.
936     static constexpr int32_t kNonNullParcelableFlag = 1;
937     static constexpr int32_t kNullParcelableFlag = 0;
938 
939     // special int32 size representing a null vector, when applicable in Nullable data.
940     // This fixed as -1 by contract, do not change.
941     static constexpr int32_t kNullVectorSize = -1;
942 
943     // --- readData and writeData methods.
944     // We choose a mixture of function and template overloads to improve code readability.
945     // TODO: Consider C++20 concepts when they become available.
946 
947     // writeData function overloads.
948     // Implementation detail: Function overloading improves code readability over
949     // template overloading, but prevents writeData<T> from being used for those types.
950 
951     status_t writeData(bool t) {
952         return writeBool(t);  // this writes as int32_t
953     }
954 
955     status_t writeData(int8_t t) {
956         return writeByte(t);  // this writes as int32_t
957     }
958 
959     status_t writeData(uint8_t t) {
960         return writeByte(static_cast<int8_t>(t));  // this writes as int32_t
961     }
962 
963     status_t writeData(char16_t t) {
964         return writeChar(t);  // this writes as int32_t
965     }
966 
967     status_t writeData(int32_t t) {
968         return writeInt32(t);
969     }
970 
971     status_t writeData(uint32_t t) {
972         return writeUint32(t);
973     }
974 
975     status_t writeData(int64_t t) {
976         return writeInt64(t);
977     }
978 
979     status_t writeData(uint64_t t) {
980         return writeUint64(t);
981     }
982 
983     status_t writeData(float t) {
984         return writeFloat(t);
985     }
986 
987     status_t writeData(double t) {
988         return writeDouble(t);
989     }
990 
991     status_t writeData(const String16& t) {
992         return writeString16(t);
993     }
994 
995     status_t writeData(const std::string& t) {
996         return writeUtf8AsUtf16(t);
997     }
998 
999     status_t writeData(const binder::unique_fd& t) { return writeUniqueFileDescriptor(t); }
1000 
1001     status_t writeData(const Parcelable& t) {  // std::is_base_of_v<Parcelable, T>
1002         // implemented here. writeParcelable() calls this.
1003         status_t status = writeData(static_cast<int32_t>(kNonNullParcelableFlag));
1004         if (status != OK) return status;
1005         return t.writeToParcel(this);
1006     }
1007 
1008     // writeData<T> template overloads.
1009     // Written such that the first template type parameter is the complete type
1010     // of the first function parameter.
1011     template <typename T,
1012             typename std::enable_if_t<std::is_enum_v<T>, bool> = true>
1013     status_t writeData(const T& t) {
1014         // implemented here. writeEnum() calls this.
1015         using UT = std::underlying_type_t<T>;
1016         return writeData(static_cast<UT>(t)); // recurse
1017     }
1018 
1019     template <typename T,
1020             typename std::enable_if_t<is_specialization_v<T, sp>, bool> = true>
1021     status_t writeData(const T& t) {
1022         return writeStrongBinder(t);
1023     }
1024 
1025     // std::optional, std::unique_ptr, std::shared_ptr special case.
1026     template <typename CT,
1027             typename std::enable_if_t<is_parcel_nullable_type_v<CT>, bool> = true>
1028     status_t writeData(const CT& c) {
1029         using T = first_template_type_t<CT>;  // The T in CT == C<T, ...>
1030         if constexpr (is_specialization_v<T, std::vector>
1031                 || std::is_same_v<T, String16>
1032                 || std::is_same_v<T, std::string>) {
1033             if (!c) return writeData(static_cast<int32_t>(kNullVectorSize));
1034         } else if constexpr (std::is_base_of_v<Parcelable, T>) {
1035             if (!c) return writeData(static_cast<int32_t>(kNullParcelableFlag));
1036         } else if constexpr (is_fixed_array_v<T>) {
1037             if (!c) return writeData(static_cast<int32_t>(kNullVectorSize));
1038         } else /* constexpr */ { // could define this, but raise as error.
1039             static_assert(dependent_false_v<CT>);
1040         }
1041         return writeData(*c);
1042     }
1043 
1044     template <typename CT,
1045             typename std::enable_if_t<is_specialization_v<CT, std::vector>, bool> = true>
1046     status_t writeData(const CT& c) {
1047         using T = first_template_type_t<CT>;  // The T in CT == C<T, ...>
1048         if (c.size() > static_cast<size_t>(std::numeric_limits<int32_t>::max())) return BAD_VALUE;
1049         const auto size = static_cast<int32_t>(c.size());
1050         writeData(size);
1051         if constexpr (is_pointer_equivalent_array_v<T>) {
1052             constexpr size_t limit = std::numeric_limits<size_t>::max() / sizeof(T);
1053             if (c.size() > limit) return BAD_VALUE;
1054             // is_pointer_equivalent types do not have gaps which could leak info,
1055             // which is only a concern when writing through binder.
1056 
1057             // TODO: Padding of the write is suboptimal when the length of the
1058             // data is not a multiple of 4.  Consider improving the write() method.
1059             return write(c.data(), c.size() * sizeof(T));
1060         } else if constexpr (std::is_same_v<T, bool>
1061                 || std::is_same_v<T, char16_t>) {
1062             // reserve data space to write to
1063             auto data = reinterpret_cast<int32_t*>(writeInplace(c.size() * sizeof(int32_t)));
1064             if (data == nullptr) return BAD_VALUE;
1065             for (const auto t: c) {
1066                 *data++ = static_cast<int32_t>(t);
1067             }
1068         } else /* constexpr */ {
1069             for (const auto &t : c) {
1070                 const status_t status = writeData(t);
1071                 if (status != OK) return status;
1072             }
1073         }
1074         return OK;
1075     }
1076 
1077     template <typename T, size_t N>
1078     status_t writeData(const std::array<T, N>& val) {
1079         static_assert(N <= std::numeric_limits<int32_t>::max());
1080         status_t status = writeData(static_cast<int32_t>(N));
1081         if (status != OK) return status;
1082         if constexpr (is_pointer_equivalent_array_v<T>) {
1083             static_assert(N <= std::numeric_limits<size_t>::max() / sizeof(T));
1084             return write(val.data(), val.size() * sizeof(T));
1085         } else /* constexpr */ {
1086             for (const auto& t : val) {
1087                 status = writeData(t);
1088                 if (status != OK) return status;
1089             }
1090             return OK;
1091         }
1092     }
1093 
1094     // readData function overloads.
1095     // Implementation detail: Function overloading improves code readability over
1096     // template overloading, but prevents readData<T> from being used for those types.
1097 
1098     status_t readData(bool* t) const {
1099         return readBool(t);  // this reads as int32_t
1100     }
1101 
1102     status_t readData(int8_t* t) const {
1103         return readByte(t);  // this reads as int32_t
1104     }
1105 
1106     status_t readData(uint8_t* t) const {
1107         return readByte(reinterpret_cast<int8_t*>(t));  // NOTE: this reads as int32_t
1108     }
1109 
1110     status_t readData(char16_t* t) const {
1111         return readChar(t);  // this reads as int32_t
1112     }
1113 
1114     status_t readData(int32_t* t) const {
1115         return readInt32(t);
1116     }
1117 
1118     status_t readData(uint32_t* t) const {
1119         return readUint32(t);
1120     }
1121 
1122     status_t readData(int64_t* t) const {
1123         return readInt64(t);
1124     }
1125 
1126     status_t readData(uint64_t* t) const {
1127         return readUint64(t);
1128     }
1129 
1130     status_t readData(float* t) const {
1131         return readFloat(t);
1132     }
1133 
1134     status_t readData(double* t) const {
1135         return readDouble(t);
1136     }
1137 
1138     status_t readData(String16* t) const {
1139         return readString16(t);
1140     }
1141 
1142     status_t readData(std::string* t) const {
1143         return readUtf8FromUtf16(t);
1144     }
1145 
1146     status_t readData(binder::unique_fd* t) const { return readUniqueFileDescriptor(t); }
1147 
1148     status_t readData(Parcelable* t) const { // std::is_base_of_v<Parcelable, T>
1149         // implemented here. readParcelable() calls this.
1150         int32_t present;
1151         status_t status = readData(&present);
1152         if (status != OK) return status;
1153         if (present != kNonNullParcelableFlag) return UNEXPECTED_NULL;
1154         return t->readFromParcel(this);
1155     }
1156 
1157     // readData<T> template overloads.
1158     // Written such that the first template type parameter is the complete type
1159     // of the first function parameter.
1160 
1161     template <typename T,
1162             typename std::enable_if_t<std::is_enum_v<T>, bool> = true>
1163     status_t readData(T* t) const {
1164         // implemented here. readEnum() calls this.
1165         using UT = std::underlying_type_t<T>;
1166         return readData(reinterpret_cast<UT*>(t));
1167     }
1168 
1169     template <typename T,
1170             typename std::enable_if_t<is_specialization_v<T, sp>, bool> = true>
1171     status_t readData(T* t) const {
1172         return readStrongBinder(t);  // Note: on null, returns failure
1173     }
1174 
1175 
1176     template <typename CT,
1177             typename std::enable_if_t<is_parcel_nullable_type_v<CT>, bool> = true>
1178     status_t readData(CT* c) const {
1179         using T = first_template_type_t<CT>;  // The T in CT == C<T, ...>
1180         const size_t startPos = dataPosition();
1181         int32_t peek;
1182         status_t status = readData(&peek);
1183         if (status != OK) return status;
1184         if constexpr (is_specialization_v<T, std::vector> || is_fixed_array_v<T> ||
1185                       std::is_same_v<T, String16> || std::is_same_v<T, std::string>) {
1186             if (peek == kNullVectorSize) {
1187                 c->reset();
1188                 return OK;
1189             }
1190         } else if constexpr (std::is_base_of_v<Parcelable, T>) {
1191             if (peek == kNullParcelableFlag) {
1192                 c->reset();
1193                 return OK;
1194             }
1195         } else /* constexpr */ { // could define this, but raise as error.
1196             static_assert(dependent_false_v<CT>);
1197         }
1198         // create a new object.
1199         if constexpr (is_specialization_v<CT, std::optional>) {
1200             // Call default constructor explicitly
1201             // - Clang bug: https://bugs.llvm.org/show_bug.cgi?id=35748
1202             //   std::optional::emplace() doesn't work with nested types.
1203             c->emplace(T());
1204         } else /* constexpr */ {
1205             T* const t = new (std::nothrow) T;  // contents read from Parcel below.
1206             if (t == nullptr) return NO_MEMORY;
1207             c->reset(t);
1208         }
1209         // rewind data ptr to reread (this is pretty quick), otherwise we could
1210         // pass an optional argument to readData to indicate a peeked value.
1211         setDataPosition(startPos);
1212         if constexpr (is_specialization_v<T, std::vector> || is_fixed_array_v<T>) {
1213             return readData(&**c, READ_FLAG_SP_NULLABLE);  // nullable sp<> allowed now
1214         } else {
1215             return readData(&**c);
1216         }
1217     }
1218 
1219     // std::vector special case, incorporating flags whether the vector
1220     // accepts nullable sp<> to be read.
1221     enum ReadFlags {
1222         READ_FLAG_NONE = 0,
1223         READ_FLAG_SP_NULLABLE = 1 << 0,
1224     };
1225 
1226     template <typename CT,
1227             typename std::enable_if_t<is_specialization_v<CT, std::vector>, bool> = true>
1228     status_t readData(CT* c, ReadFlags readFlags = READ_FLAG_NONE) const {
1229         using T = first_template_type_t<CT>;  // The T in CT == C<T, ...>
1230         int32_t size;
1231         status_t status = readInt32(&size);
1232         if (status != OK) return status;
1233         if (size < 0) return UNEXPECTED_NULL;
1234         const size_t availableBytes = dataAvail();  // coarse bound on vector size.
1235         if (static_cast<size_t>(size) > availableBytes) return BAD_VALUE;
1236         c->clear(); // must clear before resizing/reserving otherwise move ctors may be called.
1237         if constexpr (is_pointer_equivalent_array_v<T>) {
1238             // could consider POD without gaps and alignment of 4.
1239             size_t dataLen;
1240             if (__builtin_mul_overflow(size, sizeof(T), &dataLen)) {
1241                 return -EOVERFLOW;
1242             }
1243             auto data = reinterpret_cast<const T*>(readInplace(dataLen));
1244             if (data == nullptr) return BAD_VALUE;
1245             // std::vector::insert and similar methods will require type-dependent
1246             // byte alignment when inserting from a const iterator such as `data`,
1247             // e.g. 8 byte alignment for int64_t, and so will not work if `data`
1248             // is 4 byte aligned (which is all Parcel guarantees). Copying
1249             // the contents into the vector directly, where possible, circumvents
1250             // this.
1251             c->resize(size);
1252             memcpy(c->data(), data, dataLen);
1253         } else if constexpr (std::is_same_v<T, bool>
1254                 || std::is_same_v<T, char16_t>) {
1255             c->reserve(size); // avoids default initialization
1256             auto data = reinterpret_cast<const int32_t*>(
1257                     readInplace(static_cast<size_t>(size) * sizeof(int32_t)));
1258             if (data == nullptr) return BAD_VALUE;
1259             for (int32_t i = 0; i < size; ++i) {
1260                 c->emplace_back(static_cast<T>(*data++));
1261             }
1262         } else if constexpr (is_specialization_v<T, sp>) {
1263             c->resize(size); // calls ctor
1264             if (readFlags & READ_FLAG_SP_NULLABLE) {
1265                 for (auto &t : *c) {
1266                     status = readNullableStrongBinder(&t);  // allow nullable
1267                     if (status != OK) return status;
1268                 }
1269             } else {
1270                 for (auto &t : *c) {
1271                     status = readStrongBinder(&t);
1272                     if (status != OK) return status;
1273                 }
1274             }
1275         } else /* constexpr */ {
1276             c->resize(size); // calls ctor
1277             for (auto &t : *c) {
1278                 status = readData(&t);
1279                 if (status != OK) return status;
1280             }
1281         }
1282         return OK;
1283     }
1284 
1285     template <typename T, size_t N>
1286     status_t readData(std::array<T, N>* val, ReadFlags readFlags = READ_FLAG_NONE) const {
1287         static_assert(N <= std::numeric_limits<int32_t>::max());
1288         int32_t size;
1289         status_t status = readInt32(&size);
1290         if (status != OK) return status;
1291         if (size < 0) return UNEXPECTED_NULL;
1292         if (size != static_cast<int32_t>(N)) return BAD_VALUE;
1293         if constexpr (is_pointer_equivalent_array_v<T>) {
1294             auto data = reinterpret_cast<const T*>(readInplace(N * sizeof(T)));
1295             if (data == nullptr) return BAD_VALUE;
1296             memcpy(val->data(), data, N * sizeof(T));
1297         } else if constexpr (is_specialization_v<T, sp>) {
1298             for (auto& t : *val) {
1299                 if (readFlags & READ_FLAG_SP_NULLABLE) {
1300                     status = readNullableStrongBinder(&t); // allow nullable
1301                 } else {
1302                     status = readStrongBinder(&t);
1303                 }
1304                 if (status != OK) return status;
1305             }
1306         } else if constexpr (is_fixed_array_v<T>) { // pass readFlags down to nested arrays
1307             for (auto& t : *val) {
1308                 status = readData(&t, readFlags);
1309                 if (status != OK) return status;
1310             }
1311         } else /* constexpr */ {
1312             for (auto& t : *val) {
1313                 status = readData(&t);
1314                 if (status != OK) return status;
1315             }
1316         }
1317         return OK;
1318     }
1319 
1320     //-----------------------------------------------------------------------------
1321     private:
1322 
1323     status_t            mError;
1324     uint8_t*            mData;
1325     size_t              mDataSize;
1326     size_t              mDataCapacity;
1327     mutable size_t mDataPos;
1328 
1329     // Fields only needed when parcelling for "kernel Binder".
1330     struct KernelFields {
1331         KernelFields() {}
1332         binder_size_t* mObjects = nullptr;
1333         size_t mObjectsSize = 0;
1334         size_t mObjectsCapacity = 0;
1335         mutable size_t mNextObjectHint = 0;
1336 
1337         mutable size_t mWorkSourceRequestHeaderPosition = 0;
1338         mutable bool mRequestHeaderPresent = false;
1339 
1340         mutable bool mObjectsSorted = false;
1341         mutable bool mFdsKnown = true;
1342         mutable bool mHasFds = false;
1343     };
1344     // Fields only needed when parcelling for RPC Binder.
1345     struct RpcFields {
1346         RpcFields(const sp<RpcSession>& session);
1347 
1348         // Should always be non-null.
1349         const sp<RpcSession> mSession;
1350 
1351         enum ObjectType : int32_t {
1352             TYPE_BINDER_NULL = 0,
1353             TYPE_BINDER = 1,
1354             // FD to be passed via native transport (Trusty IPC or UNIX domain socket).
1355             TYPE_NATIVE_FILE_DESCRIPTOR = 2,
1356         };
1357 
1358         // Sorted.
1359         std::vector<uint32_t> mObjectPositions;
1360 
1361         // File descriptors referenced by the parcel data. Should be indexed
1362         // using the offsets in the parcel data. Don't assume the list is in the
1363         // same order as `mObjectPositions`.
1364         //
1365         // Boxed to save space. Lazy allocated.
1366         std::unique_ptr<std::vector<std::variant<binder::unique_fd, binder::borrowed_fd>>> mFds;
1367     };
1368     std::variant<KernelFields, RpcFields> mVariantFields;
1369 
1370     // Pointer to KernelFields in mVariantFields if present.
1371     KernelFields* maybeKernelFields() { return std::get_if<KernelFields>(&mVariantFields); }
1372     const KernelFields* maybeKernelFields() const {
1373         return std::get_if<KernelFields>(&mVariantFields);
1374     }
1375     // Pointer to RpcFields in mVariantFields if present.
1376     RpcFields* maybeRpcFields() { return std::get_if<RpcFields>(&mVariantFields); }
1377     const RpcFields* maybeRpcFields() const { return std::get_if<RpcFields>(&mVariantFields); }
1378 
1379     bool                mAllowFds;
1380 
1381     // if this parcelable is involved in a secure transaction, force the
1382     // data to be overridden with zero when deallocated
1383     mutable bool        mDeallocZero;
1384 
1385     // Set this to false to skip dataAvail checks.
1386     bool mEnforceNoDataAvail;
1387     bool mServiceFuzzing;
1388 
1389     release_func        mOwner;
1390 
1391     size_t mReserved;
1392 
1393     class Blob {
1394     public:
1395         LIBBINDER_EXPORTED Blob();
1396         LIBBINDER_EXPORTED ~Blob();
1397 
1398         LIBBINDER_EXPORTED void clear();
1399         LIBBINDER_EXPORTED void release();
1400         LIBBINDER_EXPORTED inline size_t size() const { return mSize; }
1401         LIBBINDER_EXPORTED inline int fd() const { return mFd; }
1402         LIBBINDER_EXPORTED inline bool isMutable() const { return mMutable; }
1403 
1404     protected:
1405         void init(int fd, void* data, size_t size, bool isMutable);
1406 
1407         int mFd; // owned by parcel so not closed when released
1408         void* mData;
1409         size_t mSize;
1410         bool mMutable;
1411     };
1412 
1413     #if defined(__clang__)
1414     #pragma clang diagnostic push
1415     #pragma clang diagnostic ignored "-Wweak-vtables"
1416     #endif
1417 
1418     // FlattenableHelperInterface and FlattenableHelper avoid generating a vtable entry in objects
1419     // following Flattenable template/protocol.
1420     class LIBBINDER_EXPORTED FlattenableHelperInterface {
1421     protected:
1422         ~FlattenableHelperInterface() { }
1423     public:
1424         virtual size_t getFlattenedSize() const = 0;
1425         virtual size_t getFdCount() const = 0;
1426         virtual status_t flatten(void* buffer, size_t size, int* fds, size_t count) const = 0;
1427         virtual status_t unflatten(void const* buffer, size_t size, int const* fds, size_t count) = 0;
1428     };
1429 
1430     #if defined(__clang__)
1431     #pragma clang diagnostic pop
1432     #endif
1433 
1434     // Concrete implementation of FlattenableHelperInterface that delegates virtual calls to the
1435     // specified class T implementing the Flattenable protocol. It "virtualizes" a compile-time
1436     // protocol.
1437     template<typename T>
1438     class FlattenableHelper : public FlattenableHelperInterface {
1439         friend class Parcel;
1440         const Flattenable<T>& val;
1441         explicit FlattenableHelper(const Flattenable<T>& _val) : val(_val) { }
1442 
1443     protected:
1444         ~FlattenableHelper() = default;
1445     public:
1446         virtual size_t getFlattenedSize() const {
1447             return val.getFlattenedSize();
1448         }
1449         virtual size_t getFdCount() const {
1450             return val.getFdCount();
1451         }
1452         virtual status_t flatten(void* buffer, size_t size, int* fds, size_t count) const {
1453             return val.flatten(buffer, size, fds, count);
1454         }
1455         virtual status_t unflatten(void const* buffer, size_t size, int const* fds, size_t count) {
1456             return const_cast<Flattenable<T>&>(val).unflatten(buffer, size, fds, count);
1457         }
1458     };
1459     LIBBINDER_EXPORTED status_t write(const FlattenableHelperInterface& val);
1460     LIBBINDER_EXPORTED status_t read(FlattenableHelperInterface& val) const;
1461 
1462 public:
1463     class ReadableBlob : public Blob {
1464         friend class Parcel;
1465     public:
1466         LIBBINDER_EXPORTED inline const void* data() const { return mData; }
1467         LIBBINDER_EXPORTED inline void* mutableData() { return isMutable() ? mData : nullptr; }
1468     };
1469 
1470     class WritableBlob : public Blob {
1471         friend class Parcel;
1472     public:
1473         LIBBINDER_EXPORTED inline void* data() { return mData; }
1474     };
1475 
1476     /**
1477      * Returns the total amount of ashmem memory owned by this object.
1478      *
1479      * Note: for historical reasons, this does not include ashmem memory which
1480      * is referenced by this Parcel, but which this parcel doesn't own (e.g.
1481      * writeFileDescriptor is called without 'takeOwnership' true).
1482      */
1483     LIBBINDER_EXPORTED size_t getOpenAshmemSize() const;
1484 
1485 private:
1486     // TODO(b/202029388): Remove 'getBlobAshmemSize' once no prebuilts reference
1487     // this
1488     LIBBINDER_EXPORTED size_t getBlobAshmemSize() const;
1489 
1490     // Needed so that we can save object metadata to the disk
1491     friend class android::binder::debug::RecordedTransaction;
1492 };
1493 
1494 // ---------------------------------------------------------------------------
1495 
1496 template<typename T>
1497 status_t Parcel::write(const Flattenable<T>& val) {
1498     const FlattenableHelper<T> helper(val);
1499     return write(helper);
1500 }
1501 
1502 template<typename T>
1503 status_t Parcel::write(const LightFlattenable<T>& val) {
1504     size_t size(val.getFlattenedSize());
1505     if (!val.isFixedSize()) {
1506         if (size > INT32_MAX) {
1507             return BAD_VALUE;
1508         }
1509         status_t err = writeInt32(static_cast<int32_t>(size));
1510         if (err != NO_ERROR) {
1511             return err;
1512         }
1513     }
1514     if (size) {
1515         void* buffer = writeInplace(size);
1516         if (buffer == nullptr)
1517             return NO_MEMORY;
1518         return val.flatten(buffer, size);
1519     }
1520     return NO_ERROR;
1521 }
1522 
1523 template<typename T>
1524 status_t Parcel::read(Flattenable<T>& val) const {
1525     FlattenableHelper<T> helper(val);
1526     return read(helper);
1527 }
1528 
1529 template<typename T>
1530 status_t Parcel::read(LightFlattenable<T>& val) const {
1531     size_t size;
1532     if (val.isFixedSize()) {
1533         size = val.getFlattenedSize();
1534     } else {
1535         int32_t s;
1536         status_t err = readInt32(&s);
1537         if (err != NO_ERROR) {
1538             return err;
1539         }
1540         size = static_cast<size_t>(s);
1541     }
1542     if (size) {
1543         void const* buffer = readInplace(size);
1544         return buffer == nullptr ? NO_MEMORY :
1545                 val.unflatten(buffer, size);
1546     }
1547     return NO_ERROR;
1548 }
1549 
1550 template<typename T>
1551 status_t Parcel::writeVectorSize(const std::vector<T>& val) {
1552     if (val.size() > INT32_MAX) {
1553         return BAD_VALUE;
1554     }
1555     return writeInt32(static_cast<int32_t>(val.size()));
1556 }
1557 
1558 template<typename T>
1559 status_t Parcel::writeVectorSize(const std::optional<std::vector<T>>& val) {
1560     if (!val) {
1561         return writeInt32(-1);
1562     }
1563 
1564     return writeVectorSize(*val);
1565 }
1566 
1567 template<typename T>
1568 status_t Parcel::writeVectorSize(const std::unique_ptr<std::vector<T>>& val) {
1569     if (!val) {
1570         return writeInt32(-1);
1571     }
1572 
1573     return writeVectorSize(*val);
1574 }
1575 
1576 template<typename T>
1577 status_t Parcel::resizeOutVector(std::vector<T>* val) const {
1578     int32_t size;
1579     status_t err = readOutVectorSizeWithCheck(sizeof(T), &size);
1580     if (err != NO_ERROR) {
1581         return err;
1582     }
1583 
1584     if (size < 0) {
1585         return UNEXPECTED_NULL;
1586     }
1587     val->resize(size_t(size));
1588     return OK;
1589 }
1590 
1591 template<typename T>
1592 status_t Parcel::resizeOutVector(std::optional<std::vector<T>>* val) const {
1593     int32_t size;
1594     status_t err = readOutVectorSizeWithCheck(sizeof(T), &size);
1595     if (err != NO_ERROR) {
1596         return err;
1597     }
1598 
1599     val->reset();
1600     if (size >= 0) {
1601         val->emplace(size_t(size));
1602     }
1603 
1604     return OK;
1605 }
1606 
1607 template<typename T>
1608 status_t Parcel::resizeOutVector(std::unique_ptr<std::vector<T>>* val) const {
1609     int32_t size;
1610     status_t err = readOutVectorSizeWithCheck(sizeof(T), &size);
1611     if (err != NO_ERROR) {
1612         return err;
1613     }
1614 
1615     val->reset();
1616     if (size >= 0) {
1617         val->reset(new std::vector<T>(size_t(size)));
1618     }
1619 
1620     return OK;
1621 }
1622 
1623 template<typename T>
1624 status_t Parcel::readStrongBinder(sp<T>* val) const {
1625     sp<IBinder> tmp;
1626     status_t ret = readStrongBinder(&tmp);
1627 
1628     if (ret == OK) {
1629         *val = interface_cast<T>(tmp);
1630 
1631         if (val->get() == nullptr) {
1632             return UNKNOWN_ERROR;
1633         }
1634     }
1635 
1636     return ret;
1637 }
1638 
1639 template<typename T>
1640 status_t Parcel::readNullableStrongBinder(sp<T>* val) const {
1641     sp<IBinder> tmp;
1642     status_t ret = readNullableStrongBinder(&tmp);
1643 
1644     if (ret == OK) {
1645         *val = interface_cast<T>(tmp);
1646 
1647         if (val->get() == nullptr && tmp.get() != nullptr) {
1648             ret = UNKNOWN_ERROR;
1649         }
1650     }
1651 
1652     return ret;
1653 }
1654 
1655 // ---------------------------------------------------------------------------
1656 
1657 inline std::ostream& operator<<(std::ostream& to, const Parcel& parcel) {
1658     parcel.print(to);
1659     return to;
1660 }
1661 
1662 } // namespace android
1663 
1664 // ---------------------------------------------------------------------------
1665