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