2 * Copyright (C) 2005 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #define LOG_TAG "Parcel"
18 //#define LOG_NDEBUG 0
29 #include <sys/types.h>
30 #include <sys/resource.h>
33 #include <binder/Binder.h>
34 #include <binder/BpBinder.h>
35 #include <binder/IPCThreadState.h>
36 #include <binder/Parcel.h>
37 #include <binder/ProcessState.h>
38 #include <binder/Status.h>
39 #include <binder/TextOutput.h>
41 #include <cutils/ashmem.h>
42 #include <utils/Debug.h>
43 #include <utils/Flattenable.h>
44 #include <utils/Log.h>
45 #include <utils/misc.h>
46 #include <utils/String8.h>
47 #include <utils/String16.h>
49 #include <private/binder/binder_module.h>
50 #include <private/binder/Static.h>
53 #define INT32_MAX ((int32_t)(2147483647))
57 //#define LOG_REFS(...) ALOG(LOG_DEBUG, LOG_TAG, __VA_ARGS__)
58 #define LOG_ALLOC(...)
59 //#define LOG_ALLOC(...) ALOG(LOG_DEBUG, LOG_TAG, __VA_ARGS__)
61 // ---------------------------------------------------------------------------
63 // This macro should never be used at runtime, as a too large value
64 // of s could cause an integer overflow. Instead, you should always
65 // use the wrapper function pad_size()
66 #define PAD_SIZE_UNSAFE(s) (((s)+3)&~3)
68 static size_t pad_size(size_t s) {
69 if (s > (SIZE_T_MAX - 3)) {
72 return PAD_SIZE_UNSAFE(s);
75 // Note: must be kept in sync with android/os/StrictMode.java's PENALTY_GATHER
76 #define STRICT_MODE_PENALTY_GATHER (0x40 << 16)
78 // XXX This can be made public if we want to provide
79 // support for typed data.
80 struct small_flat_data
88 static pthread_mutex_t gParcelGlobalAllocSizeLock = PTHREAD_MUTEX_INITIALIZER;
89 static size_t gParcelGlobalAllocSize = 0;
90 static size_t gParcelGlobalAllocCount = 0;
92 static size_t gMaxFds = 0;
94 // Maximum size of a blob to transfer in-place.
95 static const size_t BLOB_INPLACE_LIMIT = 16 * 1024;
99 BLOB_ASHMEM_IMMUTABLE = 1,
100 BLOB_ASHMEM_MUTABLE = 2,
103 static dev_t ashmem_rdev()
105 static dev_t __ashmem_rdev;
106 static pthread_mutex_t __ashmem_rdev_lock = PTHREAD_MUTEX_INITIALIZER;
108 pthread_mutex_lock(&__ashmem_rdev_lock);
110 dev_t rdev = __ashmem_rdev;
112 int fd = TEMP_FAILURE_RETRY(open("/dev/ashmem", O_RDONLY));
116 int ret = TEMP_FAILURE_RETRY(fstat(fd, &st));
118 if ((ret >= 0) && S_ISCHR(st.st_mode)) {
119 rdev = __ashmem_rdev = st.st_rdev;
124 pthread_mutex_unlock(&__ashmem_rdev_lock);
129 void acquire_object(const sp<ProcessState>& proc,
130 const flat_binder_object& obj, const void* who, size_t* outAshmemSize)
133 case BINDER_TYPE_BINDER:
135 LOG_REFS("Parcel %p acquiring reference on local %p", who, obj.cookie);
136 reinterpret_cast<IBinder*>(obj.cookie)->incStrong(who);
139 case BINDER_TYPE_WEAK_BINDER:
141 reinterpret_cast<RefBase::weakref_type*>(obj.binder)->incWeak(who);
143 case BINDER_TYPE_HANDLE: {
144 const sp<IBinder> b = proc->getStrongProxyForHandle(obj.handle);
146 LOG_REFS("Parcel %p acquiring reference on remote %p", who, b.get());
151 case BINDER_TYPE_WEAK_HANDLE: {
152 const wp<IBinder> b = proc->getWeakProxyForHandle(obj.handle);
153 if (b != NULL) b.get_refs()->incWeak(who);
156 case BINDER_TYPE_FD: {
157 if ((obj.cookie != 0) && (outAshmemSize != NULL)) {
159 int ret = fstat(obj.handle, &st);
160 if (!ret && S_ISCHR(st.st_mode) && (st.st_rdev == ashmem_rdev())) {
161 // If we own an ashmem fd, keep track of how much memory it refers to.
162 int size = ashmem_get_size_region(obj.handle);
164 *outAshmemSize += size;
172 ALOGD("Invalid object type 0x%08x", obj.type);
175 void acquire_object(const sp<ProcessState>& proc,
176 const flat_binder_object& obj, const void* who)
178 acquire_object(proc, obj, who, NULL);
181 static void release_object(const sp<ProcessState>& proc,
182 const flat_binder_object& obj, const void* who, size_t* outAshmemSize)
185 case BINDER_TYPE_BINDER:
187 LOG_REFS("Parcel %p releasing reference on local %p", who, obj.cookie);
188 reinterpret_cast<IBinder*>(obj.cookie)->decStrong(who);
191 case BINDER_TYPE_WEAK_BINDER:
193 reinterpret_cast<RefBase::weakref_type*>(obj.binder)->decWeak(who);
195 case BINDER_TYPE_HANDLE: {
196 const sp<IBinder> b = proc->getStrongProxyForHandle(obj.handle);
198 LOG_REFS("Parcel %p releasing reference on remote %p", who, b.get());
203 case BINDER_TYPE_WEAK_HANDLE: {
204 const wp<IBinder> b = proc->getWeakProxyForHandle(obj.handle);
205 if (b != NULL) b.get_refs()->decWeak(who);
208 case BINDER_TYPE_FD: {
209 if (obj.cookie != 0) { // owned
210 if (outAshmemSize != NULL) {
212 int ret = fstat(obj.handle, &st);
213 if (!ret && S_ISCHR(st.st_mode) && (st.st_rdev == ashmem_rdev())) {
214 int size = ashmem_get_size_region(obj.handle);
216 *outAshmemSize -= size;
227 ALOGE("Invalid object type 0x%08x", obj.type);
230 void release_object(const sp<ProcessState>& proc,
231 const flat_binder_object& obj, const void* who)
233 release_object(proc, obj, who, NULL);
236 inline static status_t finish_flatten_binder(
237 const sp<IBinder>& /*binder*/, const flat_binder_object& flat, Parcel* out)
239 return out->writeObject(flat, false);
242 status_t flatten_binder(const sp<ProcessState>& /*proc*/,
243 const sp<IBinder>& binder, Parcel* out)
245 flat_binder_object obj;
247 obj.flags = 0x7f | FLAT_BINDER_FLAG_ACCEPTS_FDS;
248 if (binder != NULL) {
249 IBinder *local = binder->localBinder();
251 BpBinder *proxy = binder->remoteBinder();
255 const int32_t handle = proxy ? proxy->handle() : 0;
256 obj.type = BINDER_TYPE_HANDLE;
257 obj.binder = 0; /* Don't pass uninitialized stack data to a remote process */
261 obj.type = BINDER_TYPE_BINDER;
262 obj.binder = reinterpret_cast<uintptr_t>(local->getWeakRefs());
263 obj.cookie = reinterpret_cast<uintptr_t>(local);
266 obj.type = BINDER_TYPE_BINDER;
271 return finish_flatten_binder(binder, obj, out);
274 status_t flatten_binder(const sp<ProcessState>& /*proc*/,
275 const wp<IBinder>& binder, Parcel* out)
277 flat_binder_object obj;
279 obj.flags = 0x7f | FLAT_BINDER_FLAG_ACCEPTS_FDS;
280 if (binder != NULL) {
281 sp<IBinder> real = binder.promote();
283 IBinder *local = real->localBinder();
285 BpBinder *proxy = real->remoteBinder();
289 const int32_t handle = proxy ? proxy->handle() : 0;
290 obj.type = BINDER_TYPE_WEAK_HANDLE;
291 obj.binder = 0; /* Don't pass uninitialized stack data to a remote process */
295 obj.type = BINDER_TYPE_WEAK_BINDER;
296 obj.binder = reinterpret_cast<uintptr_t>(binder.get_refs());
297 obj.cookie = reinterpret_cast<uintptr_t>(binder.unsafe_get());
299 return finish_flatten_binder(real, obj, out);
302 // XXX How to deal? In order to flatten the given binder,
303 // we need to probe it for information, which requires a primary
304 // reference... but we don't have one.
306 // The OpenBinder implementation uses a dynamic_cast<> here,
307 // but we can't do that with the different reference counting
308 // implementation we are using.
309 ALOGE("Unable to unflatten Binder weak reference!");
310 obj.type = BINDER_TYPE_BINDER;
313 return finish_flatten_binder(NULL, obj, out);
316 obj.type = BINDER_TYPE_BINDER;
319 return finish_flatten_binder(NULL, obj, out);
323 inline static status_t finish_unflatten_binder(
324 BpBinder* /*proxy*/, const flat_binder_object& /*flat*/,
325 const Parcel& /*in*/)
330 status_t unflatten_binder(const sp<ProcessState>& proc,
331 const Parcel& in, sp<IBinder>* out)
333 const flat_binder_object* flat = in.readObject(false);
336 switch (flat->type) {
337 case BINDER_TYPE_BINDER:
338 *out = reinterpret_cast<IBinder*>(flat->cookie);
339 return finish_unflatten_binder(NULL, *flat, in);
340 case BINDER_TYPE_HANDLE:
341 *out = proc->getStrongProxyForHandle(flat->handle);
342 return finish_unflatten_binder(
343 static_cast<BpBinder*>(out->get()), *flat, in);
349 status_t unflatten_binder(const sp<ProcessState>& proc,
350 const Parcel& in, wp<IBinder>* out)
352 const flat_binder_object* flat = in.readObject(false);
355 switch (flat->type) {
356 case BINDER_TYPE_BINDER:
357 *out = reinterpret_cast<IBinder*>(flat->cookie);
358 return finish_unflatten_binder(NULL, *flat, in);
359 case BINDER_TYPE_WEAK_BINDER:
360 if (flat->binder != 0) {
361 out->set_object_and_refs(
362 reinterpret_cast<IBinder*>(flat->cookie),
363 reinterpret_cast<RefBase::weakref_type*>(flat->binder));
367 return finish_unflatten_binder(NULL, *flat, in);
368 case BINDER_TYPE_HANDLE:
369 case BINDER_TYPE_WEAK_HANDLE:
370 *out = proc->getWeakProxyForHandle(flat->handle);
371 return finish_unflatten_binder(
372 static_cast<BpBinder*>(out->unsafe_get()), *flat, in);
378 // ---------------------------------------------------------------------------
382 LOG_ALLOC("Parcel %p: constructing", this);
389 LOG_ALLOC("Parcel %p: destroyed", this);
392 size_t Parcel::getGlobalAllocSize() {
393 pthread_mutex_lock(&gParcelGlobalAllocSizeLock);
394 size_t size = gParcelGlobalAllocSize;
395 pthread_mutex_unlock(&gParcelGlobalAllocSizeLock);
399 size_t Parcel::getGlobalAllocCount() {
400 pthread_mutex_lock(&gParcelGlobalAllocSizeLock);
401 size_t count = gParcelGlobalAllocCount;
402 pthread_mutex_unlock(&gParcelGlobalAllocSizeLock);
406 const uint8_t* Parcel::data() const
411 size_t Parcel::dataSize() const
413 return (mDataSize > mDataPos ? mDataSize : mDataPos);
416 size_t Parcel::dataAvail() const
418 size_t result = dataSize() - dataPosition();
419 if (result > INT32_MAX) {
425 size_t Parcel::dataPosition() const
430 size_t Parcel::dataCapacity() const
432 return mDataCapacity;
435 status_t Parcel::setDataSize(size_t size)
437 if (size > INT32_MAX) {
438 // don't accept size_t values which may have come from an
439 // inadvertent conversion from a negative int.
444 err = continueWrite(size);
445 if (err == NO_ERROR) {
447 ALOGV("setDataSize Setting data size of %p to %zu", this, mDataSize);
452 void Parcel::setDataPosition(size_t pos) const
454 if (pos > INT32_MAX) {
455 // don't accept size_t values which may have come from an
456 // inadvertent conversion from a negative int.
464 status_t Parcel::setDataCapacity(size_t size)
466 if (size > INT32_MAX) {
467 // don't accept size_t values which may have come from an
468 // inadvertent conversion from a negative int.
472 if (size > mDataCapacity) return continueWrite(size);
476 status_t Parcel::setData(const uint8_t* buffer, size_t len)
478 if (len > INT32_MAX) {
479 // don't accept size_t values which may have come from an
480 // inadvertent conversion from a negative int.
484 status_t err = restartWrite(len);
485 if (err == NO_ERROR) {
486 memcpy(const_cast<uint8_t*>(data()), buffer, len);
493 status_t Parcel::appendFrom(const Parcel *parcel, size_t offset, size_t len)
495 const sp<ProcessState> proc(ProcessState::self());
497 const uint8_t *data = parcel->mData;
498 const binder_size_t *objects = parcel->mObjects;
499 size_t size = parcel->mObjectsSize;
500 int startPos = mDataPos;
501 int firstIndex = -1, lastIndex = -2;
507 if (len > INT32_MAX) {
508 // don't accept size_t values which may have come from an
509 // inadvertent conversion from a negative int.
513 // range checks against the source parcel size
514 if ((offset > parcel->mDataSize)
515 || (len > parcel->mDataSize)
516 || (offset + len > parcel->mDataSize)) {
520 // Count objects in range
521 for (int i = 0; i < (int) size; i++) {
522 size_t off = objects[i];
523 if ((off >= offset) && (off + sizeof(flat_binder_object) <= offset + len)) {
524 if (firstIndex == -1) {
530 int numObjects = lastIndex - firstIndex + 1;
532 if ((mDataSize+len) > mDataCapacity) {
535 if (err != NO_ERROR) {
541 memcpy(mData + mDataPos, data + offset, len);
547 if (numObjects > 0) {
549 if (mObjectsCapacity < mObjectsSize + numObjects) {
550 size_t newSize = ((mObjectsSize + numObjects)*3)/2;
551 if (newSize*sizeof(binder_size_t) < mObjectsSize) return NO_MEMORY; // overflow
552 binder_size_t *objects =
553 (binder_size_t*)realloc(mObjects, newSize*sizeof(binder_size_t));
554 if (objects == (binder_size_t*)0) {
558 mObjectsCapacity = newSize;
561 // append and acquire objects
562 int idx = mObjectsSize;
563 for (int i = firstIndex; i <= lastIndex; i++) {
564 size_t off = objects[i] - offset + startPos;
565 mObjects[idx++] = off;
568 flat_binder_object* flat
569 = reinterpret_cast<flat_binder_object*>(mData + off);
570 acquire_object(proc, *flat, this, &mOpenAshmemSize);
572 if (flat->type == BINDER_TYPE_FD) {
573 // If this is a file descriptor, we need to dup it so the
574 // new Parcel now owns its own fd, and can declare that we
575 // officially know we have fds.
576 flat->handle = dup(flat->handle);
578 mHasFds = mFdsKnown = true;
580 err = FDS_NOT_ALLOWED;
589 bool Parcel::allowFds() const
594 bool Parcel::pushAllowFds(bool allowFds)
596 const bool origValue = mAllowFds;
603 void Parcel::restoreAllowFds(bool lastValue)
605 mAllowFds = lastValue;
608 bool Parcel::hasFileDescriptors() const
616 // Write RPC headers. (previously just the interface token)
617 status_t Parcel::writeInterfaceToken(const String16& interface)
619 writeInt32(IPCThreadState::self()->getStrictModePolicy() |
620 STRICT_MODE_PENALTY_GATHER);
621 // currently the interface identification token is just its name as a string
622 return writeString16(interface);
625 bool Parcel::checkInterface(IBinder* binder) const
627 return enforceInterface(binder->getInterfaceDescriptor());
630 bool Parcel::enforceInterface(const String16& interface,
631 IPCThreadState* threadState) const
633 int32_t strictPolicy = readInt32();
634 if (threadState == NULL) {
635 threadState = IPCThreadState::self();
637 if ((threadState->getLastTransactionBinderFlags() &
638 IBinder::FLAG_ONEWAY) != 0) {
639 // For one-way calls, the callee is running entirely
640 // disconnected from the caller, so disable StrictMode entirely.
641 // Not only does disk/network usage not impact the caller, but
642 // there's no way to commuicate back any violations anyway.
643 threadState->setStrictModePolicy(0);
645 threadState->setStrictModePolicy(strictPolicy);
647 const String16 str(readString16());
648 if (str == interface) {
651 ALOGW("**** enforceInterface() expected '%s' but read '%s'",
652 String8(interface).string(), String8(str).string());
657 const binder_size_t* Parcel::objects() const
662 size_t Parcel::objectsCount() const
667 status_t Parcel::errorCheck() const
672 void Parcel::setError(status_t err)
677 status_t Parcel::finishWrite(size_t len)
679 if (len > INT32_MAX) {
680 // don't accept size_t values which may have come from an
681 // inadvertent conversion from a negative int.
685 //printf("Finish write of %d\n", len);
687 ALOGV("finishWrite Setting data pos of %p to %zu", this, mDataPos);
688 if (mDataPos > mDataSize) {
689 mDataSize = mDataPos;
690 ALOGV("finishWrite Setting data size of %p to %zu", this, mDataSize);
692 //printf("New pos=%d, size=%d\n", mDataPos, mDataSize);
696 status_t Parcel::writeUnpadded(const void* data, size_t len)
698 if (len > INT32_MAX) {
699 // don't accept size_t values which may have come from an
700 // inadvertent conversion from a negative int.
704 size_t end = mDataPos + len;
705 if (end < mDataPos) {
710 if (end <= mDataCapacity) {
712 memcpy(mData+mDataPos, data, len);
713 return finishWrite(len);
716 status_t err = growData(len);
717 if (err == NO_ERROR) goto restart_write;
721 status_t Parcel::write(const void* data, size_t len)
723 if (len > INT32_MAX) {
724 // don't accept size_t values which may have come from an
725 // inadvertent conversion from a negative int.
729 void* const d = writeInplace(len);
731 memcpy(d, data, len);
737 void* Parcel::writeInplace(size_t len)
739 if (len > INT32_MAX) {
740 // don't accept size_t values which may have come from an
741 // inadvertent conversion from a negative int.
745 const size_t padded = pad_size(len);
747 // sanity check for integer overflow
748 if (mDataPos+padded < mDataPos) {
752 if ((mDataPos+padded) <= mDataCapacity) {
754 //printf("Writing %ld bytes, padded to %ld\n", len, padded);
755 uint8_t* const data = mData+mDataPos;
757 // Need to pad at end?
759 #if BYTE_ORDER == BIG_ENDIAN
760 static const uint32_t mask[4] = {
761 0x00000000, 0xffffff00, 0xffff0000, 0xff000000
764 #if BYTE_ORDER == LITTLE_ENDIAN
765 static const uint32_t mask[4] = {
766 0x00000000, 0x00ffffff, 0x0000ffff, 0x000000ff
769 //printf("Applying pad mask: %p to %p\n", (void*)mask[padded-len],
770 // *reinterpret_cast<void**>(data+padded-4));
771 *reinterpret_cast<uint32_t*>(data+padded-4) &= mask[padded-len];
778 status_t err = growData(padded);
779 if (err == NO_ERROR) goto restart_write;
783 status_t Parcel::writeUtf8AsUtf16(const std::string& str) {
784 const uint8_t* strData = (uint8_t*)str.data();
785 const size_t strLen= str.length();
786 const ssize_t utf16Len = utf8_to_utf16_length(strData, strLen);
787 if (utf16Len < 0 || utf16Len> std::numeric_limits<int32_t>::max()) {
791 status_t err = writeInt32(utf16Len);
796 // Allocate enough bytes to hold our converted string and its terminating NULL.
797 void* dst = writeInplace((utf16Len + 1) * sizeof(char16_t));
802 utf8_to_utf16(strData, strLen, (char16_t*)dst);
807 status_t Parcel::writeUtf8AsUtf16(const std::unique_ptr<std::string>& str) {
809 return writeInt32(-1);
811 return writeUtf8AsUtf16(*str);
817 status_t writeByteVectorInternal(Parcel* parcel, const std::vector<T>& val)
820 if (val.size() > std::numeric_limits<int32_t>::max()) {
825 status = parcel->writeInt32(val.size());
830 void* data = parcel->writeInplace(val.size());
836 memcpy(data, val.data(), val.size());
841 status_t writeByteVectorInternalPtr(Parcel* parcel,
842 const std::unique_ptr<std::vector<T>>& val)
845 return parcel->writeInt32(-1);
848 return writeByteVectorInternal(parcel, *val);
853 status_t Parcel::writeByteVector(const std::vector<int8_t>& val) {
854 return writeByteVectorInternal(this, val);
857 status_t Parcel::writeByteVector(const std::unique_ptr<std::vector<int8_t>>& val)
859 return writeByteVectorInternalPtr(this, val);
862 status_t Parcel::writeByteVector(const std::vector<uint8_t>& val) {
863 return writeByteVectorInternal(this, val);
866 status_t Parcel::writeByteVector(const std::unique_ptr<std::vector<uint8_t>>& val)
868 return writeByteVectorInternalPtr(this, val);
871 status_t Parcel::writeInt32Vector(const std::vector<int32_t>& val)
873 return writeTypedVector(val, &Parcel::writeInt32);
876 status_t Parcel::writeInt32Vector(const std::unique_ptr<std::vector<int32_t>>& val)
878 return writeNullableTypedVector(val, &Parcel::writeInt32);
881 status_t Parcel::writeInt64Vector(const std::vector<int64_t>& val)
883 return writeTypedVector(val, &Parcel::writeInt64);
886 status_t Parcel::writeInt64Vector(const std::unique_ptr<std::vector<int64_t>>& val)
888 return writeNullableTypedVector(val, &Parcel::writeInt64);
891 status_t Parcel::writeFloatVector(const std::vector<float>& val)
893 return writeTypedVector(val, &Parcel::writeFloat);
896 status_t Parcel::writeFloatVector(const std::unique_ptr<std::vector<float>>& val)
898 return writeNullableTypedVector(val, &Parcel::writeFloat);
901 status_t Parcel::writeDoubleVector(const std::vector<double>& val)
903 return writeTypedVector(val, &Parcel::writeDouble);
906 status_t Parcel::writeDoubleVector(const std::unique_ptr<std::vector<double>>& val)
908 return writeNullableTypedVector(val, &Parcel::writeDouble);
911 status_t Parcel::writeBoolVector(const std::vector<bool>& val)
913 return writeTypedVector(val, &Parcel::writeBool);
916 status_t Parcel::writeBoolVector(const std::unique_ptr<std::vector<bool>>& val)
918 return writeNullableTypedVector(val, &Parcel::writeBool);
921 status_t Parcel::writeCharVector(const std::vector<char16_t>& val)
923 return writeTypedVector(val, &Parcel::writeChar);
926 status_t Parcel::writeCharVector(const std::unique_ptr<std::vector<char16_t>>& val)
928 return writeNullableTypedVector(val, &Parcel::writeChar);
931 status_t Parcel::writeString16Vector(const std::vector<String16>& val)
933 return writeTypedVector(val, &Parcel::writeString16);
936 status_t Parcel::writeString16Vector(
937 const std::unique_ptr<std::vector<std::unique_ptr<String16>>>& val)
939 return writeNullableTypedVector(val, &Parcel::writeString16);
942 status_t Parcel::writeUtf8VectorAsUtf16Vector(
943 const std::unique_ptr<std::vector<std::unique_ptr<std::string>>>& val) {
944 return writeNullableTypedVector(val, &Parcel::writeUtf8AsUtf16);
947 status_t Parcel::writeUtf8VectorAsUtf16Vector(const std::vector<std::string>& val) {
948 return writeTypedVector(val, &Parcel::writeUtf8AsUtf16);
951 status_t Parcel::writeInt32(int32_t val)
953 return writeAligned(val);
956 status_t Parcel::writeUint32(uint32_t val)
958 return writeAligned(val);
961 status_t Parcel::writeInt32Array(size_t len, const int32_t *val) {
962 if (len > INT32_MAX) {
963 // don't accept size_t values which may have come from an
964 // inadvertent conversion from a negative int.
969 return writeInt32(-1);
971 status_t ret = writeInt32(static_cast<uint32_t>(len));
972 if (ret == NO_ERROR) {
973 ret = write(val, len * sizeof(*val));
977 status_t Parcel::writeByteArray(size_t len, const uint8_t *val) {
978 if (len > INT32_MAX) {
979 // don't accept size_t values which may have come from an
980 // inadvertent conversion from a negative int.
985 return writeInt32(-1);
987 status_t ret = writeInt32(static_cast<uint32_t>(len));
988 if (ret == NO_ERROR) {
989 ret = write(val, len * sizeof(*val));
994 status_t Parcel::writeBool(bool val)
996 return writeInt32(int32_t(val));
999 status_t Parcel::writeChar(char16_t val)
1001 return writeInt32(int32_t(val));
1004 status_t Parcel::writeByte(int8_t val)
1006 return writeInt32(int32_t(val));
1009 status_t Parcel::writeInt64(int64_t val)
1011 return writeAligned(val);
1014 status_t Parcel::writeUint64(uint64_t val)
1016 return writeAligned(val);
1019 status_t Parcel::writePointer(uintptr_t val)
1021 return writeAligned<binder_uintptr_t>(val);
1024 status_t Parcel::writeFloat(float val)
1026 return writeAligned(val);
1029 #if defined(__mips__) && defined(__mips_hard_float)
1031 status_t Parcel::writeDouble(double val)
1035 unsigned long long ll;
1038 return writeAligned(u.ll);
1043 status_t Parcel::writeDouble(double val)
1045 return writeAligned(val);
1050 status_t Parcel::writeCString(const char* str)
1052 return write(str, strlen(str)+1);
1055 status_t Parcel::writeString8(const String8& str)
1057 status_t err = writeInt32(str.bytes());
1058 // only write string if its length is more than zero characters,
1059 // as readString8 will only read if the length field is non-zero.
1060 // this is slightly different from how writeString16 works.
1061 if (str.bytes() > 0 && err == NO_ERROR) {
1062 err = write(str.string(), str.bytes()+1);
1067 status_t Parcel::writeString16(const std::unique_ptr<String16>& str)
1070 return writeInt32(-1);
1073 return writeString16(*str);
1076 status_t Parcel::writeString16(const String16& str)
1078 return writeString16(str.string(), str.size());
1081 status_t Parcel::writeString16(const char16_t* str, size_t len)
1083 if (str == NULL) return writeInt32(-1);
1085 status_t err = writeInt32(len);
1086 if (err == NO_ERROR) {
1087 len *= sizeof(char16_t);
1088 uint8_t* data = (uint8_t*)writeInplace(len+sizeof(char16_t));
1090 memcpy(data, str, len);
1091 *reinterpret_cast<char16_t*>(data+len) = 0;
1099 status_t Parcel::writeStrongBinder(const sp<IBinder>& val)
1101 return flatten_binder(ProcessState::self(), val, this);
1104 status_t Parcel::writeStrongBinderVector(const std::vector<sp<IBinder>>& val)
1106 return writeTypedVector(val, &Parcel::writeStrongBinder);
1109 status_t Parcel::writeStrongBinderVector(const std::unique_ptr<std::vector<sp<IBinder>>>& val)
1111 return writeNullableTypedVector(val, &Parcel::writeStrongBinder);
1114 status_t Parcel::readStrongBinderVector(std::unique_ptr<std::vector<sp<IBinder>>>* val) const {
1115 return readNullableTypedVector(val, &Parcel::readStrongBinder);
1118 status_t Parcel::readStrongBinderVector(std::vector<sp<IBinder>>* val) const {
1119 return readTypedVector(val, &Parcel::readStrongBinder);
1122 status_t Parcel::writeWeakBinder(const wp<IBinder>& val)
1124 return flatten_binder(ProcessState::self(), val, this);
1127 status_t Parcel::writeRawNullableParcelable(const Parcelable* parcelable) {
1129 return writeInt32(0);
1132 return writeParcelable(*parcelable);
1135 status_t Parcel::writeParcelable(const Parcelable& parcelable) {
1136 status_t status = writeInt32(1); // parcelable is not null.
1140 return parcelable.writeToParcel(this);
1143 status_t Parcel::writeNativeHandle(const native_handle* handle)
1145 if (!handle || handle->version != sizeof(native_handle))
1149 err = writeInt32(handle->numFds);
1150 if (err != NO_ERROR) return err;
1152 err = writeInt32(handle->numInts);
1153 if (err != NO_ERROR) return err;
1155 for (int i=0 ; err==NO_ERROR && i<handle->numFds ; i++)
1156 err = writeDupFileDescriptor(handle->data[i]);
1158 if (err != NO_ERROR) {
1159 ALOGD("write native handle, write dup fd failed");
1162 err = write(handle->data + handle->numFds, sizeof(int)*handle->numInts);
1166 status_t Parcel::writeFileDescriptor(int fd, bool takeOwnership)
1168 flat_binder_object obj;
1169 obj.type = BINDER_TYPE_FD;
1170 obj.flags = 0x7f | FLAT_BINDER_FLAG_ACCEPTS_FDS;
1171 obj.binder = 0; /* Don't pass uninitialized stack data to a remote process */
1173 obj.cookie = takeOwnership ? 1 : 0;
1174 return writeObject(obj, true);
1177 status_t Parcel::writeDupFileDescriptor(int fd)
1179 int dupFd = dup(fd);
1183 status_t err = writeFileDescriptor(dupFd, true /*takeOwnership*/);
1190 status_t Parcel::writeUniqueFileDescriptor(const ScopedFd& fd) {
1191 return writeDupFileDescriptor(fd.get());
1194 status_t Parcel::writeUniqueFileDescriptorVector(const std::vector<ScopedFd>& val) {
1195 return writeTypedVector(val, &Parcel::writeUniqueFileDescriptor);
1198 status_t Parcel::writeUniqueFileDescriptorVector(const std::unique_ptr<std::vector<ScopedFd>>& val) {
1199 return writeNullableTypedVector(val, &Parcel::writeUniqueFileDescriptor);
1202 status_t Parcel::writeBlob(size_t len, bool mutableCopy, WritableBlob* outBlob)
1204 if (len > INT32_MAX) {
1205 // don't accept size_t values which may have come from an
1206 // inadvertent conversion from a negative int.
1211 if (!mAllowFds || len <= BLOB_INPLACE_LIMIT) {
1212 ALOGV("writeBlob: write in place");
1213 status = writeInt32(BLOB_INPLACE);
1214 if (status) return status;
1216 void* ptr = writeInplace(len);
1217 if (!ptr) return NO_MEMORY;
1219 outBlob->init(-1, ptr, len, false);
1223 ALOGV("writeBlob: write to ashmem");
1224 int fd = ashmem_create_region("Parcel Blob", len);
1225 if (fd < 0) return NO_MEMORY;
1227 int result = ashmem_set_prot_region(fd, PROT_READ | PROT_WRITE);
1231 void* ptr = ::mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
1232 if (ptr == MAP_FAILED) {
1236 result = ashmem_set_prot_region(fd, PROT_READ);
1241 status = writeInt32(mutableCopy ? BLOB_ASHMEM_MUTABLE : BLOB_ASHMEM_IMMUTABLE);
1243 status = writeFileDescriptor(fd, true /*takeOwnership*/);
1245 outBlob->init(fd, ptr, len, mutableCopy);
1257 status_t Parcel::writeDupImmutableBlobFileDescriptor(int fd)
1259 // Must match up with what's done in writeBlob.
1260 if (!mAllowFds) return FDS_NOT_ALLOWED;
1261 status_t status = writeInt32(BLOB_ASHMEM_IMMUTABLE);
1262 if (status) return status;
1263 return writeDupFileDescriptor(fd);
1266 status_t Parcel::write(const FlattenableHelperInterface& val)
1271 const size_t len = val.getFlattenedSize();
1272 const size_t fd_count = val.getFdCount();
1274 if ((len > INT32_MAX) || (fd_count >= gMaxFds)) {
1275 // don't accept size_t values which may have come from an
1276 // inadvertent conversion from a negative int.
1280 err = this->writeInt32(len);
1281 if (err) return err;
1283 err = this->writeInt32(fd_count);
1284 if (err) return err;
1287 void* const buf = this->writeInplace(pad_size(len));
1293 fds = new (std::nothrow) int[fd_count];
1294 if (fds == nullptr) {
1295 ALOGE("write: failed to allocate requested %zu fds", fd_count);
1300 err = val.flatten(buf, len, fds, fd_count);
1301 for (size_t i=0 ; i<fd_count && err==NO_ERROR ; i++) {
1302 err = this->writeDupFileDescriptor( fds[i] );
1312 status_t Parcel::writeObject(const flat_binder_object& val, bool nullMetaData)
1314 const bool enoughData = (mDataPos+sizeof(val)) <= mDataCapacity;
1315 const bool enoughObjects = mObjectsSize < mObjectsCapacity;
1316 if (enoughData && enoughObjects) {
1318 *reinterpret_cast<flat_binder_object*>(mData+mDataPos) = val;
1320 // remember if it's a file descriptor
1321 if (val.type == BINDER_TYPE_FD) {
1323 // fail before modifying our object index
1324 return FDS_NOT_ALLOWED;
1326 mHasFds = mFdsKnown = true;
1329 // Need to write meta-data?
1330 if (nullMetaData || val.binder != 0) {
1331 mObjects[mObjectsSize] = mDataPos;
1332 acquire_object(ProcessState::self(), val, this, &mOpenAshmemSize);
1336 return finishWrite(sizeof(flat_binder_object));
1340 const status_t err = growData(sizeof(val));
1341 if (err != NO_ERROR) return err;
1343 if (!enoughObjects) {
1344 size_t newSize = ((mObjectsSize+2)*3)/2;
1345 if (newSize*sizeof(binder_size_t) < mObjectsSize) return NO_MEMORY; // overflow
1346 binder_size_t* objects = (binder_size_t*)realloc(mObjects, newSize*sizeof(binder_size_t));
1347 if (objects == NULL) return NO_MEMORY;
1349 mObjectsCapacity = newSize;
1355 status_t Parcel::writeNoException()
1357 binder::Status status;
1358 return status.writeToParcel(this);
1361 void Parcel::remove(size_t /*start*/, size_t /*amt*/)
1363 LOG_ALWAYS_FATAL("Parcel::remove() not yet implemented!");
1366 status_t Parcel::read(void* outData, size_t len) const
1368 if (len > INT32_MAX) {
1369 // don't accept size_t values which may have come from an
1370 // inadvertent conversion from a negative int.
1374 if ((mDataPos+pad_size(len)) >= mDataPos && (mDataPos+pad_size(len)) <= mDataSize
1375 && len <= pad_size(len)) {
1376 memcpy(outData, mData+mDataPos, len);
1377 mDataPos += pad_size(len);
1378 ALOGV("read Setting data pos of %p to %zu", this, mDataPos);
1381 return NOT_ENOUGH_DATA;
1384 const void* Parcel::readInplace(size_t len) const
1386 if (len > INT32_MAX) {
1387 // don't accept size_t values which may have come from an
1388 // inadvertent conversion from a negative int.
1392 if ((mDataPos+pad_size(len)) >= mDataPos && (mDataPos+pad_size(len)) <= mDataSize
1393 && len <= pad_size(len)) {
1394 const void* data = mData+mDataPos;
1395 mDataPos += pad_size(len);
1396 ALOGV("readInplace Setting data pos of %p to %zu", this, mDataPos);
1403 status_t Parcel::readAligned(T *pArg) const {
1404 COMPILE_TIME_ASSERT_FUNCTION_SCOPE(PAD_SIZE_UNSAFE(sizeof(T)) == sizeof(T));
1406 if ((mDataPos+sizeof(T)) <= mDataSize) {
1407 const void* data = mData+mDataPos;
1408 mDataPos += sizeof(T);
1409 *pArg = *reinterpret_cast<const T*>(data);
1412 return NOT_ENOUGH_DATA;
1417 T Parcel::readAligned() const {
1419 if (readAligned(&result) != NO_ERROR) {
1427 status_t Parcel::writeAligned(T val) {
1428 COMPILE_TIME_ASSERT_FUNCTION_SCOPE(PAD_SIZE_UNSAFE(sizeof(T)) == sizeof(T));
1430 if ((mDataPos+sizeof(val)) <= mDataCapacity) {
1432 *reinterpret_cast<T*>(mData+mDataPos) = val;
1433 return finishWrite(sizeof(val));
1436 status_t err = growData(sizeof(val));
1437 if (err == NO_ERROR) goto restart_write;
1443 template<typename T>
1444 status_t readByteVectorInternal(const Parcel* parcel,
1445 std::vector<T>* val) {
1449 status_t status = parcel->readInt32(&size);
1456 status = UNEXPECTED_NULL;
1459 if (size_t(size) > parcel->dataAvail()) {
1464 const void* data = parcel->readInplace(size);
1470 memcpy(val->data(), data, size);
1475 template<typename T>
1476 status_t readByteVectorInternalPtr(
1477 const Parcel* parcel,
1478 std::unique_ptr<std::vector<T>>* val) {
1479 const int32_t start = parcel->dataPosition();
1481 status_t status = parcel->readInt32(&size);
1484 if (status != OK || size < 0) {
1488 parcel->setDataPosition(start);
1489 val->reset(new (std::nothrow) std::vector<T>());
1491 status = readByteVectorInternal(parcel, val->get());
1502 status_t Parcel::readByteVector(std::vector<int8_t>* val) const {
1503 return readByteVectorInternal(this, val);
1506 status_t Parcel::readByteVector(std::vector<uint8_t>* val) const {
1507 return readByteVectorInternal(this, val);
1510 status_t Parcel::readByteVector(std::unique_ptr<std::vector<int8_t>>* val) const {
1511 return readByteVectorInternalPtr(this, val);
1514 status_t Parcel::readByteVector(std::unique_ptr<std::vector<uint8_t>>* val) const {
1515 return readByteVectorInternalPtr(this, val);
1518 status_t Parcel::readInt32Vector(std::unique_ptr<std::vector<int32_t>>* val) const {
1519 return readNullableTypedVector(val, &Parcel::readInt32);
1522 status_t Parcel::readInt32Vector(std::vector<int32_t>* val) const {
1523 return readTypedVector(val, &Parcel::readInt32);
1526 status_t Parcel::readInt64Vector(std::unique_ptr<std::vector<int64_t>>* val) const {
1527 return readNullableTypedVector(val, &Parcel::readInt64);
1530 status_t Parcel::readInt64Vector(std::vector<int64_t>* val) const {
1531 return readTypedVector(val, &Parcel::readInt64);
1534 status_t Parcel::readFloatVector(std::unique_ptr<std::vector<float>>* val) const {
1535 return readNullableTypedVector(val, &Parcel::readFloat);
1538 status_t Parcel::readFloatVector(std::vector<float>* val) const {
1539 return readTypedVector(val, &Parcel::readFloat);
1542 status_t Parcel::readDoubleVector(std::unique_ptr<std::vector<double>>* val) const {
1543 return readNullableTypedVector(val, &Parcel::readDouble);
1546 status_t Parcel::readDoubleVector(std::vector<double>* val) const {
1547 return readTypedVector(val, &Parcel::readDouble);
1550 status_t Parcel::readBoolVector(std::unique_ptr<std::vector<bool>>* val) const {
1551 const int32_t start = dataPosition();
1553 status_t status = readInt32(&size);
1556 if (status != OK || size < 0) {
1560 setDataPosition(start);
1561 val->reset(new (std::nothrow) std::vector<bool>());
1563 status = readBoolVector(val->get());
1572 status_t Parcel::readBoolVector(std::vector<bool>* val) const {
1574 status_t status = readInt32(&size);
1581 return UNEXPECTED_NULL;
1586 /* C++ bool handling means a vector of bools isn't necessarily addressable
1587 * (we might use individual bits)
1590 for (int32_t i = 0; i < size; ++i) {
1591 status = readBool(&data);
1602 status_t Parcel::readCharVector(std::unique_ptr<std::vector<char16_t>>* val) const {
1603 return readNullableTypedVector(val, &Parcel::readChar);
1606 status_t Parcel::readCharVector(std::vector<char16_t>* val) const {
1607 return readTypedVector(val, &Parcel::readChar);
1610 status_t Parcel::readString16Vector(
1611 std::unique_ptr<std::vector<std::unique_ptr<String16>>>* val) const {
1612 return readNullableTypedVector(val, &Parcel::readString16);
1615 status_t Parcel::readString16Vector(std::vector<String16>* val) const {
1616 return readTypedVector(val, &Parcel::readString16);
1619 status_t Parcel::readUtf8VectorFromUtf16Vector(
1620 std::unique_ptr<std::vector<std::unique_ptr<std::string>>>* val) const {
1621 return readNullableTypedVector(val, &Parcel::readUtf8FromUtf16);
1624 status_t Parcel::readUtf8VectorFromUtf16Vector(std::vector<std::string>* val) const {
1625 return readTypedVector(val, &Parcel::readUtf8FromUtf16);
1628 status_t Parcel::readInt32(int32_t *pArg) const
1630 return readAligned(pArg);
1633 int32_t Parcel::readInt32() const
1635 return readAligned<int32_t>();
1638 status_t Parcel::readUint32(uint32_t *pArg) const
1640 return readAligned(pArg);
1643 uint32_t Parcel::readUint32() const
1645 return readAligned<uint32_t>();
1648 status_t Parcel::readInt64(int64_t *pArg) const
1650 return readAligned(pArg);
1654 int64_t Parcel::readInt64() const
1656 return readAligned<int64_t>();
1659 status_t Parcel::readUint64(uint64_t *pArg) const
1661 return readAligned(pArg);
1664 uint64_t Parcel::readUint64() const
1666 return readAligned<uint64_t>();
1669 status_t Parcel::readPointer(uintptr_t *pArg) const
1672 binder_uintptr_t ptr;
1673 ret = readAligned(&ptr);
1679 uintptr_t Parcel::readPointer() const
1681 return readAligned<binder_uintptr_t>();
1685 status_t Parcel::readFloat(float *pArg) const
1687 return readAligned(pArg);
1691 float Parcel::readFloat() const
1693 return readAligned<float>();
1696 #if defined(__mips__) && defined(__mips_hard_float)
1698 status_t Parcel::readDouble(double *pArg) const
1702 unsigned long long ll;
1706 status = readAligned(&u.ll);
1711 double Parcel::readDouble() const
1715 unsigned long long ll;
1717 u.ll = readAligned<unsigned long long>();
1723 status_t Parcel::readDouble(double *pArg) const
1725 return readAligned(pArg);
1728 double Parcel::readDouble() const
1730 return readAligned<double>();
1735 status_t Parcel::readIntPtr(intptr_t *pArg) const
1737 return readAligned(pArg);
1741 intptr_t Parcel::readIntPtr() const
1743 return readAligned<intptr_t>();
1746 status_t Parcel::readBool(bool *pArg) const
1749 status_t ret = readInt32(&tmp);
1754 bool Parcel::readBool() const
1756 return readInt32() != 0;
1759 status_t Parcel::readChar(char16_t *pArg) const
1762 status_t ret = readInt32(&tmp);
1763 *pArg = char16_t(tmp);
1767 char16_t Parcel::readChar() const
1769 return char16_t(readInt32());
1772 status_t Parcel::readByte(int8_t *pArg) const
1775 status_t ret = readInt32(&tmp);
1776 *pArg = int8_t(tmp);
1780 int8_t Parcel::readByte() const
1782 return int8_t(readInt32());
1785 status_t Parcel::readUtf8FromUtf16(std::string* str) const {
1786 size_t utf16Size = 0;
1787 const char16_t* src = readString16Inplace(&utf16Size);
1789 return UNEXPECTED_NULL;
1792 // Save ourselves the trouble, we're done.
1793 if (utf16Size == 0u) {
1798 // Allow for closing '\0'
1799 ssize_t utf8Size = utf16_to_utf8_length(src, utf16Size) + 1;
1803 // Note that while it is probably safe to assume string::resize keeps a
1804 // spare byte around for the trailing null, we still pass the size including the trailing null
1805 str->resize(utf8Size);
1806 utf16_to_utf8(src, utf16Size, &((*str)[0]), utf8Size);
1807 str->resize(utf8Size - 1);
1811 status_t Parcel::readUtf8FromUtf16(std::unique_ptr<std::string>* str) const {
1812 const int32_t start = dataPosition();
1814 status_t status = readInt32(&size);
1817 if (status != OK || size < 0) {
1821 setDataPosition(start);
1822 str->reset(new (std::nothrow) std::string());
1823 return readUtf8FromUtf16(str->get());
1826 const char* Parcel::readCString() const
1828 const size_t avail = mDataSize-mDataPos;
1830 const char* str = reinterpret_cast<const char*>(mData+mDataPos);
1831 // is the string's trailing NUL within the parcel's valid bounds?
1832 const char* eos = reinterpret_cast<const char*>(memchr(str, 0, avail));
1834 const size_t len = eos - str;
1835 mDataPos += pad_size(len+1);
1836 ALOGV("readCString Setting data pos of %p to %zu", this, mDataPos);
1843 String8 Parcel::readString8() const
1845 int32_t size = readInt32();
1846 // watch for potential int overflow adding 1 for trailing NUL
1847 if (size > 0 && size < INT32_MAX) {
1848 const char* str = (const char*)readInplace(size+1);
1849 if (str) return String8(str, size);
1854 String16 Parcel::readString16() const
1857 const char16_t* str = readString16Inplace(&len);
1858 if (str) return String16(str, len);
1859 ALOGE("Reading a NULL string not supported here.");
1863 status_t Parcel::readString16(std::unique_ptr<String16>* pArg) const
1865 const int32_t start = dataPosition();
1867 status_t status = readInt32(&size);
1870 if (status != OK || size < 0) {
1874 setDataPosition(start);
1875 pArg->reset(new (std::nothrow) String16());
1877 status = readString16(pArg->get());
1886 status_t Parcel::readString16(String16* pArg) const
1889 const char16_t* str = readString16Inplace(&len);
1891 pArg->setTo(str, len);
1895 return UNEXPECTED_NULL;
1899 const char16_t* Parcel::readString16Inplace(size_t* outLen) const
1901 int32_t size = readInt32();
1902 // watch for potential int overflow from size+1
1903 if (size >= 0 && size < INT32_MAX) {
1905 const char16_t* str = (const char16_t*)readInplace((size+1)*sizeof(char16_t));
1914 status_t Parcel::readStrongBinder(sp<IBinder>* val) const
1916 return unflatten_binder(ProcessState::self(), *this, val);
1919 sp<IBinder> Parcel::readStrongBinder() const
1922 readStrongBinder(&val);
1926 wp<IBinder> Parcel::readWeakBinder() const
1929 unflatten_binder(ProcessState::self(), *this, &val);
1933 status_t Parcel::readParcelable(Parcelable* parcelable) const {
1934 int32_t have_parcelable = 0;
1935 status_t status = readInt32(&have_parcelable);
1939 if (!have_parcelable) {
1940 return UNEXPECTED_NULL;
1942 return parcelable->readFromParcel(this);
1945 int32_t Parcel::readExceptionCode() const
1947 binder::Status status;
1948 status.readFromParcel(*this);
1949 return status.exceptionCode();
1952 native_handle* Parcel::readNativeHandle() const
1954 int numFds, numInts;
1956 err = readInt32(&numFds);
1957 if (err != NO_ERROR) return 0;
1958 err = readInt32(&numInts);
1959 if (err != NO_ERROR) return 0;
1961 native_handle* h = native_handle_create(numFds, numInts);
1966 for (int i=0 ; err==NO_ERROR && i<numFds ; i++) {
1967 h->data[i] = dup(readFileDescriptor());
1968 if (h->data[i] < 0) {
1969 for (int j = 0; j < i; j++) {
1972 native_handle_delete(h);
1976 err = read(h->data + numFds, sizeof(int)*numInts);
1977 if (err != NO_ERROR) {
1978 native_handle_close(h);
1979 native_handle_delete(h);
1986 int Parcel::readFileDescriptor() const
1988 const flat_binder_object* flat = readObject(true);
1990 if (flat && flat->type == BINDER_TYPE_FD) {
1991 return flat->handle;
1997 status_t Parcel::readUniqueFileDescriptor(ScopedFd* val) const
1999 int got = readFileDescriptor();
2001 if (got == BAD_TYPE) {
2005 val->reset(dup(got));
2007 if (val->get() < 0) {
2015 status_t Parcel::readUniqueFileDescriptorVector(std::unique_ptr<std::vector<ScopedFd>>* val) const {
2016 return readNullableTypedVector(val, &Parcel::readUniqueFileDescriptor);
2019 status_t Parcel::readUniqueFileDescriptorVector(std::vector<ScopedFd>* val) const {
2020 return readTypedVector(val, &Parcel::readUniqueFileDescriptor);
2023 status_t Parcel::readBlob(size_t len, ReadableBlob* outBlob) const
2026 status_t status = readInt32(&blobType);
2027 if (status) return status;
2029 if (blobType == BLOB_INPLACE) {
2030 ALOGV("readBlob: read in place");
2031 const void* ptr = readInplace(len);
2032 if (!ptr) return BAD_VALUE;
2034 outBlob->init(-1, const_cast<void*>(ptr), len, false);
2038 ALOGV("readBlob: read from ashmem");
2039 bool isMutable = (blobType == BLOB_ASHMEM_MUTABLE);
2040 int fd = readFileDescriptor();
2041 if (fd == int(BAD_TYPE)) return BAD_VALUE;
2043 void* ptr = ::mmap(NULL, len, isMutable ? PROT_READ | PROT_WRITE : PROT_READ,
2045 if (ptr == MAP_FAILED) return NO_MEMORY;
2047 outBlob->init(fd, ptr, len, isMutable);
2051 status_t Parcel::read(FlattenableHelperInterface& val) const
2054 const size_t len = this->readInt32();
2055 const size_t fd_count = this->readInt32();
2057 if ((len > INT32_MAX) || (fd_count >= gMaxFds)) {
2058 // don't accept size_t values which may have come from an
2059 // inadvertent conversion from a negative int.
2064 void const* const buf = this->readInplace(pad_size(len));
2070 fds = new (std::nothrow) int[fd_count];
2071 if (fds == nullptr) {
2072 ALOGE("read: failed to allocate requested %zu fds", fd_count);
2077 status_t err = NO_ERROR;
2078 for (size_t i=0 ; i<fd_count && err==NO_ERROR ; i++) {
2079 fds[i] = dup(this->readFileDescriptor());
2082 ALOGE("dup() failed in Parcel::read, i is %zu, fds[i] is %d, fd_count is %zu, error: %s",
2083 i, fds[i], fd_count, strerror(errno));
2087 if (err == NO_ERROR) {
2088 err = val.unflatten(buf, len, fds, fd_count);
2097 const flat_binder_object* Parcel::readObject(bool nullMetaData) const
2099 const size_t DPOS = mDataPos;
2100 if ((DPOS+sizeof(flat_binder_object)) <= mDataSize) {
2101 const flat_binder_object* obj
2102 = reinterpret_cast<const flat_binder_object*>(mData+DPOS);
2103 mDataPos = DPOS + sizeof(flat_binder_object);
2104 if (!nullMetaData && (obj->cookie == 0 && obj->binder == 0)) {
2105 // When transferring a NULL object, we don't write it into
2106 // the object list, so we don't want to check for it when
2108 ALOGV("readObject Setting data pos of %p to %zu", this, mDataPos);
2112 // Ensure that this object is valid...
2113 binder_size_t* const OBJS = mObjects;
2114 const size_t N = mObjectsSize;
2115 size_t opos = mNextObjectHint;
2118 ALOGV("Parcel %p looking for obj at %zu, hint=%zu",
2121 // Start at the current hint position, looking for an object at
2122 // the current data position.
2124 while (opos < (N-1) && OBJS[opos] < DPOS) {
2130 if (OBJS[opos] == DPOS) {
2132 ALOGV("Parcel %p found obj %zu at index %zu with forward search",
2134 mNextObjectHint = opos+1;
2135 ALOGV("readObject Setting data pos of %p to %zu", this, mDataPos);
2139 // Look backwards for it...
2140 while (opos > 0 && OBJS[opos] > DPOS) {
2143 if (OBJS[opos] == DPOS) {
2145 ALOGV("Parcel %p found obj %zu at index %zu with backward search",
2147 mNextObjectHint = opos+1;
2148 ALOGV("readObject Setting data pos of %p to %zu", this, mDataPos);
2152 ALOGW("Attempt to read object from Parcel %p at offset %zu that is not in the object list",
2158 void Parcel::closeFileDescriptors()
2160 size_t i = mObjectsSize;
2162 //ALOGI("Closing file descriptors for %zu objects...", i);
2166 const flat_binder_object* flat
2167 = reinterpret_cast<flat_binder_object*>(mData+mObjects[i]);
2168 if (flat->type == BINDER_TYPE_FD) {
2169 //ALOGI("Closing fd: %ld", flat->handle);
2170 close(flat->handle);
2175 uintptr_t Parcel::ipcData() const
2177 return reinterpret_cast<uintptr_t>(mData);
2180 size_t Parcel::ipcDataSize() const
2182 return (mDataSize > mDataPos ? mDataSize : mDataPos);
2185 uintptr_t Parcel::ipcObjects() const
2187 return reinterpret_cast<uintptr_t>(mObjects);
2190 size_t Parcel::ipcObjectsCount() const
2192 return mObjectsSize;
2195 void Parcel::ipcSetDataReference(const uint8_t* data, size_t dataSize,
2196 const binder_size_t* objects, size_t objectsCount, release_func relFunc, void* relCookie)
2198 binder_size_t minOffset = 0;
2201 mData = const_cast<uint8_t*>(data);
2202 mDataSize = mDataCapacity = dataSize;
2203 //ALOGI("setDataReference Setting data size of %p to %lu (pid=%d)", this, mDataSize, getpid());
2205 ALOGV("setDataReference Setting data pos of %p to %zu", this, mDataPos);
2206 mObjects = const_cast<binder_size_t*>(objects);
2207 mObjectsSize = mObjectsCapacity = objectsCount;
2208 mNextObjectHint = 0;
2210 mOwnerCookie = relCookie;
2211 for (size_t i = 0; i < mObjectsSize; i++) {
2212 binder_size_t offset = mObjects[i];
2213 if (offset < minOffset) {
2214 ALOGE("%s: bad object offset %" PRIu64 " < %" PRIu64 "\n",
2215 __func__, (uint64_t)offset, (uint64_t)minOffset);
2219 minOffset = offset + sizeof(flat_binder_object);
2224 void Parcel::print(TextOutput& to, uint32_t /*flags*/) const
2228 if (errorCheck() != NO_ERROR) {
2229 const status_t err = errorCheck();
2230 to << "Error: " << (void*)(intptr_t)err << " \"" << strerror(-err) << "\"";
2231 } else if (dataSize() > 0) {
2232 const uint8_t* DATA = data();
2233 to << indent << HexDump(DATA, dataSize()) << dedent;
2234 const binder_size_t* OBJS = objects();
2235 const size_t N = objectsCount();
2236 for (size_t i=0; i<N; i++) {
2237 const flat_binder_object* flat
2238 = reinterpret_cast<const flat_binder_object*>(DATA+OBJS[i]);
2239 to << endl << "Object #" << i << " @ " << (void*)OBJS[i] << ": "
2240 << TypeCode(flat->type & 0x7f7f7f00)
2241 << " = " << flat->binder;
2250 void Parcel::releaseObjects()
2252 const sp<ProcessState> proc(ProcessState::self());
2253 size_t i = mObjectsSize;
2254 uint8_t* const data = mData;
2255 binder_size_t* const objects = mObjects;
2258 const flat_binder_object* flat
2259 = reinterpret_cast<flat_binder_object*>(data+objects[i]);
2260 release_object(proc, *flat, this, &mOpenAshmemSize);
2264 void Parcel::acquireObjects()
2266 const sp<ProcessState> proc(ProcessState::self());
2267 size_t i = mObjectsSize;
2268 uint8_t* const data = mData;
2269 binder_size_t* const objects = mObjects;
2272 const flat_binder_object* flat
2273 = reinterpret_cast<flat_binder_object*>(data+objects[i]);
2274 acquire_object(proc, *flat, this, &mOpenAshmemSize);
2278 void Parcel::freeData()
2284 void Parcel::freeDataNoInit()
2287 LOG_ALLOC("Parcel %p: freeing other owner data", this);
2288 //ALOGI("Freeing data ref of %p (pid=%d)", this, getpid());
2289 mOwner(this, mData, mDataSize, mObjects, mObjectsSize, mOwnerCookie);
2291 LOG_ALLOC("Parcel %p: freeing allocated data", this);
2294 LOG_ALLOC("Parcel %p: freeing with %zu capacity", this, mDataCapacity);
2295 pthread_mutex_lock(&gParcelGlobalAllocSizeLock);
2296 if (mDataCapacity <= gParcelGlobalAllocSize) {
2297 gParcelGlobalAllocSize = gParcelGlobalAllocSize - mDataCapacity;
2299 gParcelGlobalAllocSize = 0;
2301 if (gParcelGlobalAllocCount > 0) {
2302 gParcelGlobalAllocCount--;
2304 pthread_mutex_unlock(&gParcelGlobalAllocSizeLock);
2307 if (mObjects) free(mObjects);
2311 status_t Parcel::growData(size_t len)
2313 if (len > INT32_MAX) {
2314 // don't accept size_t values which may have come from an
2315 // inadvertent conversion from a negative int.
2319 size_t newSize = ((mDataSize+len)*3)/2;
2320 return (newSize <= mDataSize)
2321 ? (status_t) NO_MEMORY
2322 : continueWrite(newSize);
2325 status_t Parcel::restartWrite(size_t desired)
2327 if (desired > INT32_MAX) {
2328 // don't accept size_t values which may have come from an
2329 // inadvertent conversion from a negative int.
2335 return continueWrite(desired);
2338 uint8_t* data = (uint8_t*)realloc(mData, desired);
2339 if (!data && desired > mDataCapacity) {
2347 LOG_ALLOC("Parcel %p: restart from %zu to %zu capacity", this, mDataCapacity, desired);
2348 pthread_mutex_lock(&gParcelGlobalAllocSizeLock);
2349 gParcelGlobalAllocSize += desired;
2350 gParcelGlobalAllocSize -= mDataCapacity;
2352 gParcelGlobalAllocCount++;
2354 pthread_mutex_unlock(&gParcelGlobalAllocSizeLock);
2356 mDataCapacity = desired;
2359 mDataSize = mDataPos = 0;
2360 ALOGV("restartWrite Setting data size of %p to %zu", this, mDataSize);
2361 ALOGV("restartWrite Setting data pos of %p to %zu", this, mDataPos);
2365 mObjectsSize = mObjectsCapacity = 0;
2366 mNextObjectHint = 0;
2374 status_t Parcel::continueWrite(size_t desired)
2376 if (desired > INT32_MAX) {
2377 // don't accept size_t values which may have come from an
2378 // inadvertent conversion from a negative int.
2382 // If shrinking, first adjust for any objects that appear
2383 // after the new data size.
2384 size_t objectsSize = mObjectsSize;
2385 if (desired < mDataSize) {
2389 while (objectsSize > 0) {
2390 if (mObjects[objectsSize-1] < desired)
2398 // If the size is going to zero, just release the owner's data.
2404 // If there is a different owner, we need to take
2406 uint8_t* data = (uint8_t*)malloc(desired);
2411 binder_size_t* objects = NULL;
2414 objects = (binder_size_t*)calloc(objectsSize, sizeof(binder_size_t));
2422 // Little hack to only acquire references on objects
2423 // we will be keeping.
2424 size_t oldObjectsSize = mObjectsSize;
2425 mObjectsSize = objectsSize;
2427 mObjectsSize = oldObjectsSize;
2431 memcpy(data, mData, mDataSize < desired ? mDataSize : desired);
2433 if (objects && mObjects) {
2434 memcpy(objects, mObjects, objectsSize*sizeof(binder_size_t));
2436 //ALOGI("Freeing data ref of %p (pid=%d)", this, getpid());
2437 mOwner(this, mData, mDataSize, mObjects, mObjectsSize, mOwnerCookie);
2440 LOG_ALLOC("Parcel %p: taking ownership of %zu capacity", this, desired);
2441 pthread_mutex_lock(&gParcelGlobalAllocSizeLock);
2442 gParcelGlobalAllocSize += desired;
2443 gParcelGlobalAllocCount++;
2444 pthread_mutex_unlock(&gParcelGlobalAllocSizeLock);
2448 mDataSize = (mDataSize < desired) ? mDataSize : desired;
2449 ALOGV("continueWrite Setting data size of %p to %zu", this, mDataSize);
2450 mDataCapacity = desired;
2451 mObjectsSize = mObjectsCapacity = objectsSize;
2452 mNextObjectHint = 0;
2455 if (objectsSize < mObjectsSize) {
2456 // Need to release refs on any objects we are dropping.
2457 const sp<ProcessState> proc(ProcessState::self());
2458 for (size_t i=objectsSize; i<mObjectsSize; i++) {
2459 const flat_binder_object* flat
2460 = reinterpret_cast<flat_binder_object*>(mData+mObjects[i]);
2461 if (flat->type == BINDER_TYPE_FD) {
2462 // will need to rescan because we may have lopped off the only FDs
2465 release_object(proc, *flat, this, &mOpenAshmemSize);
2467 binder_size_t* objects =
2468 (binder_size_t*)realloc(mObjects, objectsSize*sizeof(binder_size_t));
2472 mObjectsSize = objectsSize;
2473 mNextObjectHint = 0;
2476 // We own the data, so we can just do a realloc().
2477 if (desired > mDataCapacity) {
2478 uint8_t* data = (uint8_t*)realloc(mData, desired);
2480 LOG_ALLOC("Parcel %p: continue from %zu to %zu capacity", this, mDataCapacity,
2482 pthread_mutex_lock(&gParcelGlobalAllocSizeLock);
2483 gParcelGlobalAllocSize += desired;
2484 gParcelGlobalAllocSize -= mDataCapacity;
2485 pthread_mutex_unlock(&gParcelGlobalAllocSizeLock);
2487 mDataCapacity = desired;
2488 } else if (desired > mDataCapacity) {
2493 if (mDataSize > desired) {
2494 mDataSize = desired;
2495 ALOGV("continueWrite Setting data size of %p to %zu", this, mDataSize);
2497 if (mDataPos > desired) {
2499 ALOGV("continueWrite Setting data pos of %p to %zu", this, mDataPos);
2504 // This is the first data. Easy!
2505 uint8_t* data = (uint8_t*)malloc(desired);
2511 if(!(mDataCapacity == 0 && mObjects == NULL
2512 && mObjectsCapacity == 0)) {
2513 ALOGE("continueWrite: %zu/%p/%zu/%zu", mDataCapacity, mObjects, mObjectsCapacity, desired);
2516 LOG_ALLOC("Parcel %p: allocating with %zu capacity", this, desired);
2517 pthread_mutex_lock(&gParcelGlobalAllocSizeLock);
2518 gParcelGlobalAllocSize += desired;
2519 gParcelGlobalAllocCount++;
2520 pthread_mutex_unlock(&gParcelGlobalAllocSizeLock);
2523 mDataSize = mDataPos = 0;
2524 ALOGV("continueWrite Setting data size of %p to %zu", this, mDataSize);
2525 ALOGV("continueWrite Setting data pos of %p to %zu", this, mDataPos);
2526 mDataCapacity = desired;
2532 void Parcel::initState()
2534 LOG_ALLOC("Parcel %p: initState", this);
2540 ALOGV("initState Setting data size of %p to %zu", this, mDataSize);
2541 ALOGV("initState Setting data pos of %p to %zu", this, mDataPos);
2544 mObjectsCapacity = 0;
2545 mNextObjectHint = 0;
2550 mOpenAshmemSize = 0;
2552 // racing multiple init leads only to multiple identical write
2554 struct rlimit result;
2555 if (!getrlimit(RLIMIT_NOFILE, &result)) {
2556 gMaxFds = (size_t)result.rlim_cur;
2557 //ALOGI("parcel fd limit set to %zu", gMaxFds);
2559 ALOGW("Unable to getrlimit: %s", strerror(errno));
2565 void Parcel::scanForFds() const
2567 bool hasFds = false;
2568 for (size_t i=0; i<mObjectsSize; i++) {
2569 const flat_binder_object* flat
2570 = reinterpret_cast<const flat_binder_object*>(mData + mObjects[i]);
2571 if (flat->type == BINDER_TYPE_FD) {
2580 size_t Parcel::getBlobAshmemSize() const
2582 // This used to return the size of all blobs that were written to ashmem, now we're returning
2583 // the ashmem currently referenced by this Parcel, which should be equivalent.
2584 // TODO: Remove method once ABI can be changed.
2585 return mOpenAshmemSize;
2588 size_t Parcel::getOpenAshmemSize() const
2590 return mOpenAshmemSize;
2593 // --- Parcel::Blob ---
2595 Parcel::Blob::Blob() :
2596 mFd(-1), mData(NULL), mSize(0), mMutable(false) {
2599 Parcel::Blob::~Blob() {
2603 void Parcel::Blob::release() {
2604 if (mFd != -1 && mData) {
2605 ::munmap(mData, mSize);
2610 void Parcel::Blob::init(int fd, void* data, size_t size, bool isMutable) {
2614 mMutable = isMutable;
2617 void Parcel::Blob::clear() {
2624 }; // namespace android