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.
462 mObjectsSorted = false;
465 status_t Parcel::setDataCapacity(size_t size)
467 if (size > INT32_MAX) {
468 // don't accept size_t values which may have come from an
469 // inadvertent conversion from a negative int.
473 if (size > mDataCapacity) return continueWrite(size);
477 status_t Parcel::setData(const uint8_t* buffer, size_t len)
479 if (len > INT32_MAX) {
480 // don't accept size_t values which may have come from an
481 // inadvertent conversion from a negative int.
485 status_t err = restartWrite(len);
486 if (err == NO_ERROR) {
487 memcpy(const_cast<uint8_t*>(data()), buffer, len);
494 status_t Parcel::appendFrom(const Parcel *parcel, size_t offset, size_t len)
496 const sp<ProcessState> proc(ProcessState::self());
498 const uint8_t *data = parcel->mData;
499 const binder_size_t *objects = parcel->mObjects;
500 size_t size = parcel->mObjectsSize;
501 int startPos = mDataPos;
502 int firstIndex = -1, lastIndex = -2;
508 if (len > INT32_MAX) {
509 // don't accept size_t values which may have come from an
510 // inadvertent conversion from a negative int.
514 // range checks against the source parcel size
515 if ((offset > parcel->mDataSize)
516 || (len > parcel->mDataSize)
517 || (offset + len > parcel->mDataSize)) {
521 // Count objects in range
522 for (int i = 0; i < (int) size; i++) {
523 size_t off = objects[i];
524 if ((off >= offset) && (off + sizeof(flat_binder_object) <= offset + len)) {
525 if (firstIndex == -1) {
531 int numObjects = lastIndex - firstIndex + 1;
533 if ((mDataSize+len) > mDataCapacity) {
536 if (err != NO_ERROR) {
542 memcpy(mData + mDataPos, data + offset, len);
548 if (numObjects > 0) {
550 if (mObjectsCapacity < mObjectsSize + numObjects) {
551 size_t newSize = ((mObjectsSize + numObjects)*3)/2;
552 if (newSize*sizeof(binder_size_t) < mObjectsSize) return NO_MEMORY; // overflow
553 binder_size_t *objects =
554 (binder_size_t*)realloc(mObjects, newSize*sizeof(binder_size_t));
555 if (objects == (binder_size_t*)0) {
559 mObjectsCapacity = newSize;
562 // append and acquire objects
563 int idx = mObjectsSize;
564 for (int i = firstIndex; i <= lastIndex; i++) {
565 size_t off = objects[i] - offset + startPos;
566 mObjects[idx++] = off;
569 flat_binder_object* flat
570 = reinterpret_cast<flat_binder_object*>(mData + off);
571 acquire_object(proc, *flat, this, &mOpenAshmemSize);
573 if (flat->type == BINDER_TYPE_FD) {
574 // If this is a file descriptor, we need to dup it so the
575 // new Parcel now owns its own fd, and can declare that we
576 // officially know we have fds.
577 flat->handle = dup(flat->handle);
579 mHasFds = mFdsKnown = true;
581 err = FDS_NOT_ALLOWED;
590 bool Parcel::allowFds() const
595 bool Parcel::pushAllowFds(bool allowFds)
597 const bool origValue = mAllowFds;
604 void Parcel::restoreAllowFds(bool lastValue)
606 mAllowFds = lastValue;
609 bool Parcel::hasFileDescriptors() const
617 // Write RPC headers. (previously just the interface token)
618 status_t Parcel::writeInterfaceToken(const String16& interface)
620 writeInt32(IPCThreadState::self()->getStrictModePolicy() |
621 STRICT_MODE_PENALTY_GATHER);
622 // currently the interface identification token is just its name as a string
623 return writeString16(interface);
626 bool Parcel::checkInterface(IBinder* binder) const
628 return enforceInterface(binder->getInterfaceDescriptor());
631 bool Parcel::enforceInterface(const String16& interface,
632 IPCThreadState* threadState) const
634 int32_t strictPolicy = readInt32();
635 if (threadState == NULL) {
636 threadState = IPCThreadState::self();
638 if ((threadState->getLastTransactionBinderFlags() &
639 IBinder::FLAG_ONEWAY) != 0) {
640 // For one-way calls, the callee is running entirely
641 // disconnected from the caller, so disable StrictMode entirely.
642 // Not only does disk/network usage not impact the caller, but
643 // there's no way to commuicate back any violations anyway.
644 threadState->setStrictModePolicy(0);
646 threadState->setStrictModePolicy(strictPolicy);
648 const String16 str(readString16());
649 if (str == interface) {
652 ALOGW("**** enforceInterface() expected '%s' but read '%s'",
653 String8(interface).string(), String8(str).string());
658 const binder_size_t* Parcel::objects() const
663 size_t Parcel::objectsCount() const
668 status_t Parcel::errorCheck() const
673 void Parcel::setError(status_t err)
678 status_t Parcel::finishWrite(size_t len)
680 if (len > INT32_MAX) {
681 // don't accept size_t values which may have come from an
682 // inadvertent conversion from a negative int.
686 //printf("Finish write of %d\n", len);
688 ALOGV("finishWrite Setting data pos of %p to %zu", this, mDataPos);
689 if (mDataPos > mDataSize) {
690 mDataSize = mDataPos;
691 ALOGV("finishWrite Setting data size of %p to %zu", this, mDataSize);
693 //printf("New pos=%d, size=%d\n", mDataPos, mDataSize);
697 status_t Parcel::writeUnpadded(const void* data, size_t len)
699 if (len > INT32_MAX) {
700 // don't accept size_t values which may have come from an
701 // inadvertent conversion from a negative int.
705 size_t end = mDataPos + len;
706 if (end < mDataPos) {
711 if (end <= mDataCapacity) {
713 memcpy(mData+mDataPos, data, len);
714 return finishWrite(len);
717 status_t err = growData(len);
718 if (err == NO_ERROR) goto restart_write;
722 status_t Parcel::write(const void* data, size_t len)
724 if (len > INT32_MAX) {
725 // don't accept size_t values which may have come from an
726 // inadvertent conversion from a negative int.
730 void* const d = writeInplace(len);
732 memcpy(d, data, len);
738 void* Parcel::writeInplace(size_t len)
740 if (len > INT32_MAX) {
741 // don't accept size_t values which may have come from an
742 // inadvertent conversion from a negative int.
746 const size_t padded = pad_size(len);
748 // sanity check for integer overflow
749 if (mDataPos+padded < mDataPos) {
753 if ((mDataPos+padded) <= mDataCapacity) {
755 //printf("Writing %ld bytes, padded to %ld\n", len, padded);
756 uint8_t* const data = mData+mDataPos;
758 // Need to pad at end?
760 #if BYTE_ORDER == BIG_ENDIAN
761 static const uint32_t mask[4] = {
762 0x00000000, 0xffffff00, 0xffff0000, 0xff000000
765 #if BYTE_ORDER == LITTLE_ENDIAN
766 static const uint32_t mask[4] = {
767 0x00000000, 0x00ffffff, 0x0000ffff, 0x000000ff
770 //printf("Applying pad mask: %p to %p\n", (void*)mask[padded-len],
771 // *reinterpret_cast<void**>(data+padded-4));
772 *reinterpret_cast<uint32_t*>(data+padded-4) &= mask[padded-len];
779 status_t err = growData(padded);
780 if (err == NO_ERROR) goto restart_write;
784 status_t Parcel::writeUtf8AsUtf16(const std::string& str) {
785 const uint8_t* strData = (uint8_t*)str.data();
786 const size_t strLen= str.length();
787 const ssize_t utf16Len = utf8_to_utf16_length(strData, strLen);
788 if (utf16Len < 0 || utf16Len> std::numeric_limits<int32_t>::max()) {
792 status_t err = writeInt32(utf16Len);
797 // Allocate enough bytes to hold our converted string and its terminating NULL.
798 void* dst = writeInplace((utf16Len + 1) * sizeof(char16_t));
803 utf8_to_utf16(strData, strLen, (char16_t*)dst);
808 status_t Parcel::writeUtf8AsUtf16(const std::unique_ptr<std::string>& str) {
810 return writeInt32(-1);
812 return writeUtf8AsUtf16(*str);
818 status_t writeByteVectorInternal(Parcel* parcel, const std::vector<T>& val)
821 if (val.size() > std::numeric_limits<int32_t>::max()) {
826 status = parcel->writeInt32(val.size());
831 void* data = parcel->writeInplace(val.size());
837 memcpy(data, val.data(), val.size());
842 status_t writeByteVectorInternalPtr(Parcel* parcel,
843 const std::unique_ptr<std::vector<T>>& val)
846 return parcel->writeInt32(-1);
849 return writeByteVectorInternal(parcel, *val);
854 status_t Parcel::writeByteVector(const std::vector<int8_t>& val) {
855 return writeByteVectorInternal(this, val);
858 status_t Parcel::writeByteVector(const std::unique_ptr<std::vector<int8_t>>& val)
860 return writeByteVectorInternalPtr(this, val);
863 status_t Parcel::writeByteVector(const std::vector<uint8_t>& val) {
864 return writeByteVectorInternal(this, val);
867 status_t Parcel::writeByteVector(const std::unique_ptr<std::vector<uint8_t>>& val)
869 return writeByteVectorInternalPtr(this, val);
872 status_t Parcel::writeInt32Vector(const std::vector<int32_t>& val)
874 return writeTypedVector(val, &Parcel::writeInt32);
877 status_t Parcel::writeInt32Vector(const std::unique_ptr<std::vector<int32_t>>& val)
879 return writeNullableTypedVector(val, &Parcel::writeInt32);
882 status_t Parcel::writeInt64Vector(const std::vector<int64_t>& val)
884 return writeTypedVector(val, &Parcel::writeInt64);
887 status_t Parcel::writeInt64Vector(const std::unique_ptr<std::vector<int64_t>>& val)
889 return writeNullableTypedVector(val, &Parcel::writeInt64);
892 status_t Parcel::writeFloatVector(const std::vector<float>& val)
894 return writeTypedVector(val, &Parcel::writeFloat);
897 status_t Parcel::writeFloatVector(const std::unique_ptr<std::vector<float>>& val)
899 return writeNullableTypedVector(val, &Parcel::writeFloat);
902 status_t Parcel::writeDoubleVector(const std::vector<double>& val)
904 return writeTypedVector(val, &Parcel::writeDouble);
907 status_t Parcel::writeDoubleVector(const std::unique_ptr<std::vector<double>>& val)
909 return writeNullableTypedVector(val, &Parcel::writeDouble);
912 status_t Parcel::writeBoolVector(const std::vector<bool>& val)
914 return writeTypedVector(val, &Parcel::writeBool);
917 status_t Parcel::writeBoolVector(const std::unique_ptr<std::vector<bool>>& val)
919 return writeNullableTypedVector(val, &Parcel::writeBool);
922 status_t Parcel::writeCharVector(const std::vector<char16_t>& val)
924 return writeTypedVector(val, &Parcel::writeChar);
927 status_t Parcel::writeCharVector(const std::unique_ptr<std::vector<char16_t>>& val)
929 return writeNullableTypedVector(val, &Parcel::writeChar);
932 status_t Parcel::writeString16Vector(const std::vector<String16>& val)
934 return writeTypedVector(val, &Parcel::writeString16);
937 status_t Parcel::writeString16Vector(
938 const std::unique_ptr<std::vector<std::unique_ptr<String16>>>& val)
940 return writeNullableTypedVector(val, &Parcel::writeString16);
943 status_t Parcel::writeUtf8VectorAsUtf16Vector(
944 const std::unique_ptr<std::vector<std::unique_ptr<std::string>>>& val) {
945 return writeNullableTypedVector(val, &Parcel::writeUtf8AsUtf16);
948 status_t Parcel::writeUtf8VectorAsUtf16Vector(const std::vector<std::string>& val) {
949 return writeTypedVector(val, &Parcel::writeUtf8AsUtf16);
952 status_t Parcel::writeInt32(int32_t val)
954 return writeAligned(val);
957 status_t Parcel::writeUint32(uint32_t val)
959 return writeAligned(val);
962 status_t Parcel::writeInt32Array(size_t len, const int32_t *val) {
963 if (len > INT32_MAX) {
964 // don't accept size_t values which may have come from an
965 // inadvertent conversion from a negative int.
970 return writeInt32(-1);
972 status_t ret = writeInt32(static_cast<uint32_t>(len));
973 if (ret == NO_ERROR) {
974 ret = write(val, len * sizeof(*val));
978 status_t Parcel::writeByteArray(size_t len, const uint8_t *val) {
979 if (len > INT32_MAX) {
980 // don't accept size_t values which may have come from an
981 // inadvertent conversion from a negative int.
986 return writeInt32(-1);
988 status_t ret = writeInt32(static_cast<uint32_t>(len));
989 if (ret == NO_ERROR) {
990 ret = write(val, len * sizeof(*val));
995 status_t Parcel::writeBool(bool val)
997 return writeInt32(int32_t(val));
1000 status_t Parcel::writeChar(char16_t val)
1002 return writeInt32(int32_t(val));
1005 status_t Parcel::writeByte(int8_t val)
1007 return writeInt32(int32_t(val));
1010 status_t Parcel::writeInt64(int64_t val)
1012 return writeAligned(val);
1015 status_t Parcel::writeUint64(uint64_t val)
1017 return writeAligned(val);
1020 status_t Parcel::writePointer(uintptr_t val)
1022 return writeAligned<binder_uintptr_t>(val);
1025 status_t Parcel::writeFloat(float val)
1027 return writeAligned(val);
1030 #if defined(__mips__) && defined(__mips_hard_float)
1032 status_t Parcel::writeDouble(double val)
1036 unsigned long long ll;
1039 return writeAligned(u.ll);
1044 status_t Parcel::writeDouble(double val)
1046 return writeAligned(val);
1051 status_t Parcel::writeCString(const char* str)
1053 return write(str, strlen(str)+1);
1056 status_t Parcel::writeString8(const String8& str)
1058 status_t err = writeInt32(str.bytes());
1059 // only write string if its length is more than zero characters,
1060 // as readString8 will only read if the length field is non-zero.
1061 // this is slightly different from how writeString16 works.
1062 if (str.bytes() > 0 && err == NO_ERROR) {
1063 err = write(str.string(), str.bytes()+1);
1068 status_t Parcel::writeString16(const std::unique_ptr<String16>& str)
1071 return writeInt32(-1);
1074 return writeString16(*str);
1077 status_t Parcel::writeString16(const String16& str)
1079 return writeString16(str.string(), str.size());
1082 status_t Parcel::writeString16(const char16_t* str, size_t len)
1084 if (str == NULL) return writeInt32(-1);
1086 status_t err = writeInt32(len);
1087 if (err == NO_ERROR) {
1088 len *= sizeof(char16_t);
1089 uint8_t* data = (uint8_t*)writeInplace(len+sizeof(char16_t));
1091 memcpy(data, str, len);
1092 *reinterpret_cast<char16_t*>(data+len) = 0;
1100 status_t Parcel::writeStrongBinder(const sp<IBinder>& val)
1102 return flatten_binder(ProcessState::self(), val, this);
1105 status_t Parcel::writeStrongBinderVector(const std::vector<sp<IBinder>>& val)
1107 return writeTypedVector(val, &Parcel::writeStrongBinder);
1110 status_t Parcel::writeStrongBinderVector(const std::unique_ptr<std::vector<sp<IBinder>>>& val)
1112 return writeNullableTypedVector(val, &Parcel::writeStrongBinder);
1115 status_t Parcel::readStrongBinderVector(std::unique_ptr<std::vector<sp<IBinder>>>* val) const {
1116 return readNullableTypedVector(val, &Parcel::readStrongBinder);
1119 status_t Parcel::readStrongBinderVector(std::vector<sp<IBinder>>* val) const {
1120 return readTypedVector(val, &Parcel::readStrongBinder);
1123 status_t Parcel::writeWeakBinder(const wp<IBinder>& val)
1125 return flatten_binder(ProcessState::self(), val, this);
1128 status_t Parcel::writeRawNullableParcelable(const Parcelable* parcelable) {
1130 return writeInt32(0);
1133 return writeParcelable(*parcelable);
1136 status_t Parcel::writeParcelable(const Parcelable& parcelable) {
1137 status_t status = writeInt32(1); // parcelable is not null.
1141 return parcelable.writeToParcel(this);
1144 status_t Parcel::writeNativeHandle(const native_handle* handle)
1146 if (!handle || handle->version != sizeof(native_handle))
1150 err = writeInt32(handle->numFds);
1151 if (err != NO_ERROR) return err;
1153 err = writeInt32(handle->numInts);
1154 if (err != NO_ERROR) return err;
1156 for (int i=0 ; err==NO_ERROR && i<handle->numFds ; i++)
1157 err = writeDupFileDescriptor(handle->data[i]);
1159 if (err != NO_ERROR) {
1160 ALOGD("write native handle, write dup fd failed");
1163 err = write(handle->data + handle->numFds, sizeof(int)*handle->numInts);
1167 status_t Parcel::writeFileDescriptor(int fd, bool takeOwnership)
1169 flat_binder_object obj;
1170 obj.type = BINDER_TYPE_FD;
1171 obj.flags = 0x7f | FLAT_BINDER_FLAG_ACCEPTS_FDS;
1172 obj.binder = 0; /* Don't pass uninitialized stack data to a remote process */
1174 obj.cookie = takeOwnership ? 1 : 0;
1175 return writeObject(obj, true);
1178 status_t Parcel::writeDupFileDescriptor(int fd)
1180 int dupFd = dup(fd);
1184 status_t err = writeFileDescriptor(dupFd, true /*takeOwnership*/);
1191 status_t Parcel::writeUniqueFileDescriptor(const ScopedFd& fd) {
1192 return writeDupFileDescriptor(fd.get());
1195 status_t Parcel::writeUniqueFileDescriptorVector(const std::vector<ScopedFd>& val) {
1196 return writeTypedVector(val, &Parcel::writeUniqueFileDescriptor);
1199 status_t Parcel::writeUniqueFileDescriptorVector(const std::unique_ptr<std::vector<ScopedFd>>& val) {
1200 return writeNullableTypedVector(val, &Parcel::writeUniqueFileDescriptor);
1203 status_t Parcel::writeBlob(size_t len, bool mutableCopy, WritableBlob* outBlob)
1205 if (len > INT32_MAX) {
1206 // don't accept size_t values which may have come from an
1207 // inadvertent conversion from a negative int.
1212 if (!mAllowFds || len <= BLOB_INPLACE_LIMIT) {
1213 ALOGV("writeBlob: write in place");
1214 status = writeInt32(BLOB_INPLACE);
1215 if (status) return status;
1217 void* ptr = writeInplace(len);
1218 if (!ptr) return NO_MEMORY;
1220 outBlob->init(-1, ptr, len, false);
1224 ALOGV("writeBlob: write to ashmem");
1225 int fd = ashmem_create_region("Parcel Blob", len);
1226 if (fd < 0) return NO_MEMORY;
1228 int result = ashmem_set_prot_region(fd, PROT_READ | PROT_WRITE);
1232 void* ptr = ::mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
1233 if (ptr == MAP_FAILED) {
1237 result = ashmem_set_prot_region(fd, PROT_READ);
1242 status = writeInt32(mutableCopy ? BLOB_ASHMEM_MUTABLE : BLOB_ASHMEM_IMMUTABLE);
1244 status = writeFileDescriptor(fd, true /*takeOwnership*/);
1246 outBlob->init(fd, ptr, len, mutableCopy);
1258 status_t Parcel::writeDupImmutableBlobFileDescriptor(int fd)
1260 // Must match up with what's done in writeBlob.
1261 if (!mAllowFds) return FDS_NOT_ALLOWED;
1262 status_t status = writeInt32(BLOB_ASHMEM_IMMUTABLE);
1263 if (status) return status;
1264 return writeDupFileDescriptor(fd);
1267 status_t Parcel::write(const FlattenableHelperInterface& val)
1272 const size_t len = val.getFlattenedSize();
1273 const size_t fd_count = val.getFdCount();
1275 if ((len > INT32_MAX) || (fd_count >= gMaxFds)) {
1276 // don't accept size_t values which may have come from an
1277 // inadvertent conversion from a negative int.
1281 err = this->writeInt32(len);
1282 if (err) return err;
1284 err = this->writeInt32(fd_count);
1285 if (err) return err;
1288 void* const buf = this->writeInplace(len);
1294 fds = new (std::nothrow) int[fd_count];
1295 if (fds == nullptr) {
1296 ALOGE("write: failed to allocate requested %zu fds", fd_count);
1301 err = val.flatten(buf, len, fds, fd_count);
1302 for (size_t i=0 ; i<fd_count && err==NO_ERROR ; i++) {
1303 err = this->writeDupFileDescriptor( fds[i] );
1313 status_t Parcel::writeObject(const flat_binder_object& val, bool nullMetaData)
1315 const bool enoughData = (mDataPos+sizeof(val)) <= mDataCapacity;
1316 const bool enoughObjects = mObjectsSize < mObjectsCapacity;
1317 if (enoughData && enoughObjects) {
1319 *reinterpret_cast<flat_binder_object*>(mData+mDataPos) = val;
1321 // remember if it's a file descriptor
1322 if (val.type == BINDER_TYPE_FD) {
1324 // fail before modifying our object index
1325 return FDS_NOT_ALLOWED;
1327 mHasFds = mFdsKnown = true;
1330 // Need to write meta-data?
1331 if (nullMetaData || val.binder != 0) {
1332 mObjects[mObjectsSize] = mDataPos;
1333 acquire_object(ProcessState::self(), val, this, &mOpenAshmemSize);
1337 return finishWrite(sizeof(flat_binder_object));
1341 const status_t err = growData(sizeof(val));
1342 if (err != NO_ERROR) return err;
1344 if (!enoughObjects) {
1345 size_t newSize = ((mObjectsSize+2)*3)/2;
1346 if (newSize*sizeof(binder_size_t) < mObjectsSize) return NO_MEMORY; // overflow
1347 binder_size_t* objects = (binder_size_t*)realloc(mObjects, newSize*sizeof(binder_size_t));
1348 if (objects == NULL) return NO_MEMORY;
1350 mObjectsCapacity = newSize;
1356 status_t Parcel::writeNoException()
1358 binder::Status status;
1359 return status.writeToParcel(this);
1362 void Parcel::remove(size_t /*start*/, size_t /*amt*/)
1364 LOG_ALWAYS_FATAL("Parcel::remove() not yet implemented!");
1367 status_t Parcel::validateReadData(size_t upperBound) const
1369 // Don't allow non-object reads on object data
1370 if (mObjectsSorted || mObjectsSize <= 1) {
1372 // Expect to check only against the next object
1373 if (mNextObjectHint < mObjectsSize && upperBound > mObjects[mNextObjectHint]) {
1374 // For some reason the current read position is greater than the next object
1375 // hint. Iterate until we find the right object
1376 size_t nextObject = mNextObjectHint;
1378 if (mDataPos < mObjects[nextObject] + sizeof(flat_binder_object)) {
1379 // Requested info overlaps with an object
1380 ALOGE("Attempt to read from protected data in Parcel %p", this);
1381 return PERMISSION_DENIED;
1384 } while (nextObject < mObjectsSize && upperBound > mObjects[nextObject]);
1385 mNextObjectHint = nextObject;
1389 // Quickly determine if mObjects is sorted.
1390 binder_size_t* currObj = mObjects + mObjectsSize - 1;
1391 binder_size_t* prevObj = currObj;
1392 while (currObj > mObjects) {
1394 if(*prevObj > *currObj) {
1399 mObjectsSorted = true;
1403 // Insertion Sort mObjects
1404 // Great for mostly sorted lists. If randomly sorted or reverse ordered mObjects become common,
1405 // switch to std::sort(mObjects, mObjects + mObjectsSize);
1406 for (binder_size_t* iter0 = mObjects + 1; iter0 < mObjects + mObjectsSize; iter0++) {
1407 binder_size_t temp = *iter0;
1408 binder_size_t* iter1 = iter0 - 1;
1409 while (iter1 >= mObjects && *iter1 > temp) {
1410 *(iter1 + 1) = *iter1;
1413 *(iter1 + 1) = temp;
1415 mNextObjectHint = 0;
1416 mObjectsSorted = true;
1420 status_t Parcel::read(void* outData, size_t len) const
1422 if (len > INT32_MAX) {
1423 // don't accept size_t values which may have come from an
1424 // inadvertent conversion from a negative int.
1428 if ((mDataPos+pad_size(len)) >= mDataPos && (mDataPos+pad_size(len)) <= mDataSize
1429 && len <= pad_size(len)) {
1430 if (mObjectsSize > 0) {
1431 status_t err = validateReadData(mDataPos + pad_size(len));
1432 if(err != NO_ERROR) return err;
1434 memcpy(outData, mData+mDataPos, len);
1435 mDataPos += pad_size(len);
1436 ALOGV("read Setting data pos of %p to %zu", this, mDataPos);
1439 return NOT_ENOUGH_DATA;
1442 const void* Parcel::readInplace(size_t len) const
1444 if (len > INT32_MAX) {
1445 // don't accept size_t values which may have come from an
1446 // inadvertent conversion from a negative int.
1450 if ((mDataPos+pad_size(len)) >= mDataPos && (mDataPos+pad_size(len)) <= mDataSize
1451 && len <= pad_size(len)) {
1452 if (mObjectsSize > 0) {
1453 status_t err = validateReadData(mDataPos + pad_size(len));
1454 if(err != NO_ERROR) return NULL;
1457 const void* data = mData+mDataPos;
1458 mDataPos += pad_size(len);
1459 ALOGV("readInplace Setting data pos of %p to %zu", this, mDataPos);
1466 status_t Parcel::readAligned(T *pArg) const {
1467 COMPILE_TIME_ASSERT_FUNCTION_SCOPE(PAD_SIZE_UNSAFE(sizeof(T)) == sizeof(T));
1469 if ((mDataPos+sizeof(T)) <= mDataSize) {
1470 if (mObjectsSize > 0) {
1471 status_t err = validateReadData(mDataPos + sizeof(T));
1472 if(err != NO_ERROR) return err;
1475 const void* data = mData+mDataPos;
1476 mDataPos += sizeof(T);
1477 *pArg = *reinterpret_cast<const T*>(data);
1480 return NOT_ENOUGH_DATA;
1485 T Parcel::readAligned() const {
1487 if (readAligned(&result) != NO_ERROR) {
1495 status_t Parcel::writeAligned(T val) {
1496 COMPILE_TIME_ASSERT_FUNCTION_SCOPE(PAD_SIZE_UNSAFE(sizeof(T)) == sizeof(T));
1498 if ((mDataPos+sizeof(val)) <= mDataCapacity) {
1500 *reinterpret_cast<T*>(mData+mDataPos) = val;
1501 return finishWrite(sizeof(val));
1504 status_t err = growData(sizeof(val));
1505 if (err == NO_ERROR) goto restart_write;
1511 template<typename T>
1512 status_t readByteVectorInternal(const Parcel* parcel,
1513 std::vector<T>* val) {
1517 status_t status = parcel->readInt32(&size);
1524 status = UNEXPECTED_NULL;
1527 if (size_t(size) > parcel->dataAvail()) {
1532 const void* data = parcel->readInplace(size);
1538 memcpy(val->data(), data, size);
1543 template<typename T>
1544 status_t readByteVectorInternalPtr(
1545 const Parcel* parcel,
1546 std::unique_ptr<std::vector<T>>* val) {
1547 const int32_t start = parcel->dataPosition();
1549 status_t status = parcel->readInt32(&size);
1552 if (status != OK || size < 0) {
1556 parcel->setDataPosition(start);
1557 val->reset(new (std::nothrow) std::vector<T>());
1559 status = readByteVectorInternal(parcel, val->get());
1570 status_t Parcel::readByteVector(std::vector<int8_t>* val) const {
1571 return readByteVectorInternal(this, val);
1574 status_t Parcel::readByteVector(std::vector<uint8_t>* val) const {
1575 return readByteVectorInternal(this, val);
1578 status_t Parcel::readByteVector(std::unique_ptr<std::vector<int8_t>>* val) const {
1579 return readByteVectorInternalPtr(this, val);
1582 status_t Parcel::readByteVector(std::unique_ptr<std::vector<uint8_t>>* val) const {
1583 return readByteVectorInternalPtr(this, val);
1586 status_t Parcel::readInt32Vector(std::unique_ptr<std::vector<int32_t>>* val) const {
1587 return readNullableTypedVector(val, &Parcel::readInt32);
1590 status_t Parcel::readInt32Vector(std::vector<int32_t>* val) const {
1591 return readTypedVector(val, &Parcel::readInt32);
1594 status_t Parcel::readInt64Vector(std::unique_ptr<std::vector<int64_t>>* val) const {
1595 return readNullableTypedVector(val, &Parcel::readInt64);
1598 status_t Parcel::readInt64Vector(std::vector<int64_t>* val) const {
1599 return readTypedVector(val, &Parcel::readInt64);
1602 status_t Parcel::readFloatVector(std::unique_ptr<std::vector<float>>* val) const {
1603 return readNullableTypedVector(val, &Parcel::readFloat);
1606 status_t Parcel::readFloatVector(std::vector<float>* val) const {
1607 return readTypedVector(val, &Parcel::readFloat);
1610 status_t Parcel::readDoubleVector(std::unique_ptr<std::vector<double>>* val) const {
1611 return readNullableTypedVector(val, &Parcel::readDouble);
1614 status_t Parcel::readDoubleVector(std::vector<double>* val) const {
1615 return readTypedVector(val, &Parcel::readDouble);
1618 status_t Parcel::readBoolVector(std::unique_ptr<std::vector<bool>>* val) const {
1619 const int32_t start = dataPosition();
1621 status_t status = readInt32(&size);
1624 if (status != OK || size < 0) {
1628 setDataPosition(start);
1629 val->reset(new (std::nothrow) std::vector<bool>());
1631 status = readBoolVector(val->get());
1640 status_t Parcel::readBoolVector(std::vector<bool>* val) const {
1642 status_t status = readInt32(&size);
1649 return UNEXPECTED_NULL;
1654 /* C++ bool handling means a vector of bools isn't necessarily addressable
1655 * (we might use individual bits)
1658 for (int32_t i = 0; i < size; ++i) {
1659 status = readBool(&data);
1670 status_t Parcel::readCharVector(std::unique_ptr<std::vector<char16_t>>* val) const {
1671 return readNullableTypedVector(val, &Parcel::readChar);
1674 status_t Parcel::readCharVector(std::vector<char16_t>* val) const {
1675 return readTypedVector(val, &Parcel::readChar);
1678 status_t Parcel::readString16Vector(
1679 std::unique_ptr<std::vector<std::unique_ptr<String16>>>* val) const {
1680 return readNullableTypedVector(val, &Parcel::readString16);
1683 status_t Parcel::readString16Vector(std::vector<String16>* val) const {
1684 return readTypedVector(val, &Parcel::readString16);
1687 status_t Parcel::readUtf8VectorFromUtf16Vector(
1688 std::unique_ptr<std::vector<std::unique_ptr<std::string>>>* val) const {
1689 return readNullableTypedVector(val, &Parcel::readUtf8FromUtf16);
1692 status_t Parcel::readUtf8VectorFromUtf16Vector(std::vector<std::string>* val) const {
1693 return readTypedVector(val, &Parcel::readUtf8FromUtf16);
1696 status_t Parcel::readInt32(int32_t *pArg) const
1698 return readAligned(pArg);
1701 int32_t Parcel::readInt32() const
1703 return readAligned<int32_t>();
1706 status_t Parcel::readUint32(uint32_t *pArg) const
1708 return readAligned(pArg);
1711 uint32_t Parcel::readUint32() const
1713 return readAligned<uint32_t>();
1716 status_t Parcel::readInt64(int64_t *pArg) const
1718 return readAligned(pArg);
1722 int64_t Parcel::readInt64() const
1724 return readAligned<int64_t>();
1727 status_t Parcel::readUint64(uint64_t *pArg) const
1729 return readAligned(pArg);
1732 uint64_t Parcel::readUint64() const
1734 return readAligned<uint64_t>();
1737 status_t Parcel::readPointer(uintptr_t *pArg) const
1740 binder_uintptr_t ptr;
1741 ret = readAligned(&ptr);
1747 uintptr_t Parcel::readPointer() const
1749 return readAligned<binder_uintptr_t>();
1753 status_t Parcel::readFloat(float *pArg) const
1755 return readAligned(pArg);
1759 float Parcel::readFloat() const
1761 return readAligned<float>();
1764 #if defined(__mips__) && defined(__mips_hard_float)
1766 status_t Parcel::readDouble(double *pArg) const
1770 unsigned long long ll;
1774 status = readAligned(&u.ll);
1779 double Parcel::readDouble() const
1783 unsigned long long ll;
1785 u.ll = readAligned<unsigned long long>();
1791 status_t Parcel::readDouble(double *pArg) const
1793 return readAligned(pArg);
1796 double Parcel::readDouble() const
1798 return readAligned<double>();
1803 status_t Parcel::readIntPtr(intptr_t *pArg) const
1805 return readAligned(pArg);
1809 intptr_t Parcel::readIntPtr() const
1811 return readAligned<intptr_t>();
1814 status_t Parcel::readBool(bool *pArg) const
1817 status_t ret = readInt32(&tmp);
1822 bool Parcel::readBool() const
1824 return readInt32() != 0;
1827 status_t Parcel::readChar(char16_t *pArg) const
1830 status_t ret = readInt32(&tmp);
1831 *pArg = char16_t(tmp);
1835 char16_t Parcel::readChar() const
1837 return char16_t(readInt32());
1840 status_t Parcel::readByte(int8_t *pArg) const
1843 status_t ret = readInt32(&tmp);
1844 *pArg = int8_t(tmp);
1848 int8_t Parcel::readByte() const
1850 return int8_t(readInt32());
1853 status_t Parcel::readUtf8FromUtf16(std::string* str) const {
1854 size_t utf16Size = 0;
1855 const char16_t* src = readString16Inplace(&utf16Size);
1857 return UNEXPECTED_NULL;
1860 // Save ourselves the trouble, we're done.
1861 if (utf16Size == 0u) {
1866 // Allow for closing '\0'
1867 ssize_t utf8Size = utf16_to_utf8_length(src, utf16Size) + 1;
1871 // Note that while it is probably safe to assume string::resize keeps a
1872 // spare byte around for the trailing null, we still pass the size including the trailing null
1873 str->resize(utf8Size);
1874 utf16_to_utf8(src, utf16Size, &((*str)[0]), utf8Size);
1875 str->resize(utf8Size - 1);
1879 status_t Parcel::readUtf8FromUtf16(std::unique_ptr<std::string>* str) const {
1880 const int32_t start = dataPosition();
1882 status_t status = readInt32(&size);
1885 if (status != OK || size < 0) {
1889 setDataPosition(start);
1890 str->reset(new (std::nothrow) std::string());
1891 return readUtf8FromUtf16(str->get());
1894 const char* Parcel::readCString() const
1896 const size_t avail = mDataSize-mDataPos;
1898 const char* str = reinterpret_cast<const char*>(mData+mDataPos);
1899 // is the string's trailing NUL within the parcel's valid bounds?
1900 const char* eos = reinterpret_cast<const char*>(memchr(str, 0, avail));
1902 const size_t len = eos - str;
1903 mDataPos += pad_size(len+1);
1904 ALOGV("readCString Setting data pos of %p to %zu", this, mDataPos);
1911 String8 Parcel::readString8() const
1913 int32_t size = readInt32();
1914 // watch for potential int overflow adding 1 for trailing NUL
1915 if (size > 0 && size < INT32_MAX) {
1916 const char* str = (const char*)readInplace(size+1);
1917 if (str) return String8(str, size);
1922 String16 Parcel::readString16() const
1925 const char16_t* str = readString16Inplace(&len);
1926 if (str) return String16(str, len);
1927 ALOGE("Reading a NULL string not supported here.");
1931 status_t Parcel::readString16(std::unique_ptr<String16>* pArg) const
1933 const int32_t start = dataPosition();
1935 status_t status = readInt32(&size);
1938 if (status != OK || size < 0) {
1942 setDataPosition(start);
1943 pArg->reset(new (std::nothrow) String16());
1945 status = readString16(pArg->get());
1954 status_t Parcel::readString16(String16* pArg) const
1957 const char16_t* str = readString16Inplace(&len);
1959 pArg->setTo(str, len);
1963 return UNEXPECTED_NULL;
1967 const char16_t* Parcel::readString16Inplace(size_t* outLen) const
1969 int32_t size = readInt32();
1970 // watch for potential int overflow from size+1
1971 if (size >= 0 && size < INT32_MAX) {
1973 const char16_t* str = (const char16_t*)readInplace((size+1)*sizeof(char16_t));
1982 status_t Parcel::readStrongBinder(sp<IBinder>* val) const
1984 return unflatten_binder(ProcessState::self(), *this, val);
1987 sp<IBinder> Parcel::readStrongBinder() const
1990 readStrongBinder(&val);
1994 wp<IBinder> Parcel::readWeakBinder() const
1997 unflatten_binder(ProcessState::self(), *this, &val);
2001 status_t Parcel::readParcelable(Parcelable* parcelable) const {
2002 int32_t have_parcelable = 0;
2003 status_t status = readInt32(&have_parcelable);
2007 if (!have_parcelable) {
2008 return UNEXPECTED_NULL;
2010 return parcelable->readFromParcel(this);
2013 int32_t Parcel::readExceptionCode() const
2015 binder::Status status;
2016 status.readFromParcel(*this);
2017 return status.exceptionCode();
2020 native_handle* Parcel::readNativeHandle() const
2022 int numFds, numInts;
2024 err = readInt32(&numFds);
2025 if (err != NO_ERROR) return 0;
2026 err = readInt32(&numInts);
2027 if (err != NO_ERROR) return 0;
2029 native_handle* h = native_handle_create(numFds, numInts);
2034 for (int i=0 ; err==NO_ERROR && i<numFds ; i++) {
2035 h->data[i] = dup(readFileDescriptor());
2036 if (h->data[i] < 0) {
2037 for (int j = 0; j < i; j++) {
2040 native_handle_delete(h);
2044 err = read(h->data + numFds, sizeof(int)*numInts);
2045 if (err != NO_ERROR) {
2046 native_handle_close(h);
2047 native_handle_delete(h);
2054 int Parcel::readFileDescriptor() const
2056 const flat_binder_object* flat = readObject(true);
2058 if (flat && flat->type == BINDER_TYPE_FD) {
2059 return flat->handle;
2065 status_t Parcel::readUniqueFileDescriptor(ScopedFd* val) const
2067 int got = readFileDescriptor();
2069 if (got == BAD_TYPE) {
2073 val->reset(dup(got));
2075 if (val->get() < 0) {
2083 status_t Parcel::readUniqueFileDescriptorVector(std::unique_ptr<std::vector<ScopedFd>>* val) const {
2084 return readNullableTypedVector(val, &Parcel::readUniqueFileDescriptor);
2087 status_t Parcel::readUniqueFileDescriptorVector(std::vector<ScopedFd>* val) const {
2088 return readTypedVector(val, &Parcel::readUniqueFileDescriptor);
2091 status_t Parcel::readBlob(size_t len, ReadableBlob* outBlob) const
2094 status_t status = readInt32(&blobType);
2095 if (status) return status;
2097 if (blobType == BLOB_INPLACE) {
2098 ALOGV("readBlob: read in place");
2099 const void* ptr = readInplace(len);
2100 if (!ptr) return BAD_VALUE;
2102 outBlob->init(-1, const_cast<void*>(ptr), len, false);
2106 ALOGV("readBlob: read from ashmem");
2107 bool isMutable = (blobType == BLOB_ASHMEM_MUTABLE);
2108 int fd = readFileDescriptor();
2109 if (fd == int(BAD_TYPE)) return BAD_VALUE;
2111 void* ptr = ::mmap(NULL, len, isMutable ? PROT_READ | PROT_WRITE : PROT_READ,
2113 if (ptr == MAP_FAILED) return NO_MEMORY;
2115 outBlob->init(fd, ptr, len, isMutable);
2119 status_t Parcel::read(FlattenableHelperInterface& val) const
2122 const size_t len = this->readInt32();
2123 const size_t fd_count = this->readInt32();
2125 if ((len > INT32_MAX) || (fd_count >= gMaxFds)) {
2126 // don't accept size_t values which may have come from an
2127 // inadvertent conversion from a negative int.
2132 void const* const buf = this->readInplace(pad_size(len));
2138 fds = new (std::nothrow) int[fd_count];
2139 if (fds == nullptr) {
2140 ALOGE("read: failed to allocate requested %zu fds", fd_count);
2145 status_t err = NO_ERROR;
2146 for (size_t i=0 ; i<fd_count && err==NO_ERROR ; i++) {
2147 fds[i] = dup(this->readFileDescriptor());
2150 ALOGE("dup() failed in Parcel::read, i is %zu, fds[i] is %d, fd_count is %zu, error: %s",
2151 i, fds[i], fd_count, strerror(errno));
2155 if (err == NO_ERROR) {
2156 err = val.unflatten(buf, len, fds, fd_count);
2165 const flat_binder_object* Parcel::readObject(bool nullMetaData) const
2167 const size_t DPOS = mDataPos;
2168 if ((DPOS+sizeof(flat_binder_object)) <= mDataSize) {
2169 const flat_binder_object* obj
2170 = reinterpret_cast<const flat_binder_object*>(mData+DPOS);
2171 mDataPos = DPOS + sizeof(flat_binder_object);
2172 if (!nullMetaData && (obj->cookie == 0 && obj->binder == 0)) {
2173 // When transferring a NULL object, we don't write it into
2174 // the object list, so we don't want to check for it when
2176 ALOGV("readObject Setting data pos of %p to %zu", this, mDataPos);
2180 // Ensure that this object is valid...
2181 binder_size_t* const OBJS = mObjects;
2182 const size_t N = mObjectsSize;
2183 size_t opos = mNextObjectHint;
2186 ALOGV("Parcel %p looking for obj at %zu, hint=%zu",
2189 // Start at the current hint position, looking for an object at
2190 // the current data position.
2192 while (opos < (N-1) && OBJS[opos] < DPOS) {
2198 if (OBJS[opos] == DPOS) {
2200 ALOGV("Parcel %p found obj %zu at index %zu with forward search",
2202 mNextObjectHint = opos+1;
2203 ALOGV("readObject Setting data pos of %p to %zu", this, mDataPos);
2207 // Look backwards for it...
2208 while (opos > 0 && OBJS[opos] > DPOS) {
2211 if (OBJS[opos] == DPOS) {
2213 ALOGV("Parcel %p found obj %zu at index %zu with backward search",
2215 mNextObjectHint = opos+1;
2216 ALOGV("readObject Setting data pos of %p to %zu", this, mDataPos);
2220 ALOGW("Attempt to read object from Parcel %p at offset %zu that is not in the object list",
2226 void Parcel::closeFileDescriptors()
2228 size_t i = mObjectsSize;
2230 //ALOGI("Closing file descriptors for %zu objects...", i);
2234 const flat_binder_object* flat
2235 = reinterpret_cast<flat_binder_object*>(mData+mObjects[i]);
2236 if (flat->type == BINDER_TYPE_FD) {
2237 //ALOGI("Closing fd: %ld", flat->handle);
2238 close(flat->handle);
2243 uintptr_t Parcel::ipcData() const
2245 return reinterpret_cast<uintptr_t>(mData);
2248 size_t Parcel::ipcDataSize() const
2250 return (mDataSize > mDataPos ? mDataSize : mDataPos);
2253 uintptr_t Parcel::ipcObjects() const
2255 return reinterpret_cast<uintptr_t>(mObjects);
2258 size_t Parcel::ipcObjectsCount() const
2260 return mObjectsSize;
2263 void Parcel::ipcSetDataReference(const uint8_t* data, size_t dataSize,
2264 const binder_size_t* objects, size_t objectsCount, release_func relFunc, void* relCookie)
2266 binder_size_t minOffset = 0;
2269 mData = const_cast<uint8_t*>(data);
2270 mDataSize = mDataCapacity = dataSize;
2271 //ALOGI("setDataReference Setting data size of %p to %lu (pid=%d)", this, mDataSize, getpid());
2273 ALOGV("setDataReference Setting data pos of %p to %zu", this, mDataPos);
2274 mObjects = const_cast<binder_size_t*>(objects);
2275 mObjectsSize = mObjectsCapacity = objectsCount;
2276 mNextObjectHint = 0;
2277 mObjectsSorted = false;
2279 mOwnerCookie = relCookie;
2280 for (size_t i = 0; i < mObjectsSize; i++) {
2281 binder_size_t offset = mObjects[i];
2282 if (offset < minOffset) {
2283 ALOGE("%s: bad object offset %" PRIu64 " < %" PRIu64 "\n",
2284 __func__, (uint64_t)offset, (uint64_t)minOffset);
2288 minOffset = offset + sizeof(flat_binder_object);
2293 void Parcel::print(TextOutput& to, uint32_t /*flags*/) const
2297 if (errorCheck() != NO_ERROR) {
2298 const status_t err = errorCheck();
2299 to << "Error: " << (void*)(intptr_t)err << " \"" << strerror(-err) << "\"";
2300 } else if (dataSize() > 0) {
2301 const uint8_t* DATA = data();
2302 to << indent << HexDump(DATA, dataSize()) << dedent;
2303 const binder_size_t* OBJS = objects();
2304 const size_t N = objectsCount();
2305 for (size_t i=0; i<N; i++) {
2306 const flat_binder_object* flat
2307 = reinterpret_cast<const flat_binder_object*>(DATA+OBJS[i]);
2308 to << endl << "Object #" << i << " @ " << (void*)OBJS[i] << ": "
2309 << TypeCode(flat->type & 0x7f7f7f00)
2310 << " = " << flat->binder;
2319 void Parcel::releaseObjects()
2321 const sp<ProcessState> proc(ProcessState::self());
2322 size_t i = mObjectsSize;
2323 uint8_t* const data = mData;
2324 binder_size_t* const objects = mObjects;
2327 const flat_binder_object* flat
2328 = reinterpret_cast<flat_binder_object*>(data+objects[i]);
2329 release_object(proc, *flat, this, &mOpenAshmemSize);
2333 void Parcel::acquireObjects()
2335 const sp<ProcessState> proc(ProcessState::self());
2336 size_t i = mObjectsSize;
2337 uint8_t* const data = mData;
2338 binder_size_t* const objects = mObjects;
2341 const flat_binder_object* flat
2342 = reinterpret_cast<flat_binder_object*>(data+objects[i]);
2343 acquire_object(proc, *flat, this, &mOpenAshmemSize);
2347 void Parcel::freeData()
2353 void Parcel::freeDataNoInit()
2356 LOG_ALLOC("Parcel %p: freeing other owner data", this);
2357 //ALOGI("Freeing data ref of %p (pid=%d)", this, getpid());
2358 mOwner(this, mData, mDataSize, mObjects, mObjectsSize, mOwnerCookie);
2360 LOG_ALLOC("Parcel %p: freeing allocated data", this);
2363 LOG_ALLOC("Parcel %p: freeing with %zu capacity", this, mDataCapacity);
2364 pthread_mutex_lock(&gParcelGlobalAllocSizeLock);
2365 if (mDataCapacity <= gParcelGlobalAllocSize) {
2366 gParcelGlobalAllocSize = gParcelGlobalAllocSize - mDataCapacity;
2368 gParcelGlobalAllocSize = 0;
2370 if (gParcelGlobalAllocCount > 0) {
2371 gParcelGlobalAllocCount--;
2373 pthread_mutex_unlock(&gParcelGlobalAllocSizeLock);
2376 if (mObjects) free(mObjects);
2380 status_t Parcel::growData(size_t len)
2382 if (len > INT32_MAX) {
2383 // don't accept size_t values which may have come from an
2384 // inadvertent conversion from a negative int.
2388 size_t newSize = ((mDataSize+len)*3)/2;
2389 return (newSize <= mDataSize)
2390 ? (status_t) NO_MEMORY
2391 : continueWrite(newSize);
2394 status_t Parcel::restartWrite(size_t desired)
2396 if (desired > INT32_MAX) {
2397 // don't accept size_t values which may have come from an
2398 // inadvertent conversion from a negative int.
2404 return continueWrite(desired);
2407 uint8_t* data = (uint8_t*)realloc(mData, desired);
2408 if (!data && desired > mDataCapacity) {
2416 LOG_ALLOC("Parcel %p: restart from %zu to %zu capacity", this, mDataCapacity, desired);
2417 pthread_mutex_lock(&gParcelGlobalAllocSizeLock);
2418 gParcelGlobalAllocSize += desired;
2419 gParcelGlobalAllocSize -= mDataCapacity;
2421 gParcelGlobalAllocCount++;
2423 pthread_mutex_unlock(&gParcelGlobalAllocSizeLock);
2425 mDataCapacity = desired;
2428 mDataSize = mDataPos = 0;
2429 ALOGV("restartWrite Setting data size of %p to %zu", this, mDataSize);
2430 ALOGV("restartWrite Setting data pos of %p to %zu", this, mDataPos);
2434 mObjectsSize = mObjectsCapacity = 0;
2435 mNextObjectHint = 0;
2436 mObjectsSorted = false;
2444 status_t Parcel::continueWrite(size_t desired)
2446 if (desired > INT32_MAX) {
2447 // don't accept size_t values which may have come from an
2448 // inadvertent conversion from a negative int.
2452 // If shrinking, first adjust for any objects that appear
2453 // after the new data size.
2454 size_t objectsSize = mObjectsSize;
2455 if (desired < mDataSize) {
2459 while (objectsSize > 0) {
2460 if (mObjects[objectsSize-1] < desired)
2468 // If the size is going to zero, just release the owner's data.
2474 // If there is a different owner, we need to take
2476 uint8_t* data = (uint8_t*)malloc(desired);
2481 binder_size_t* objects = NULL;
2484 objects = (binder_size_t*)calloc(objectsSize, sizeof(binder_size_t));
2492 // Little hack to only acquire references on objects
2493 // we will be keeping.
2494 size_t oldObjectsSize = mObjectsSize;
2495 mObjectsSize = objectsSize;
2497 mObjectsSize = oldObjectsSize;
2501 memcpy(data, mData, mDataSize < desired ? mDataSize : desired);
2503 if (objects && mObjects) {
2504 memcpy(objects, mObjects, objectsSize*sizeof(binder_size_t));
2506 //ALOGI("Freeing data ref of %p (pid=%d)", this, getpid());
2507 mOwner(this, mData, mDataSize, mObjects, mObjectsSize, mOwnerCookie);
2510 LOG_ALLOC("Parcel %p: taking ownership of %zu capacity", this, desired);
2511 pthread_mutex_lock(&gParcelGlobalAllocSizeLock);
2512 gParcelGlobalAllocSize += desired;
2513 gParcelGlobalAllocCount++;
2514 pthread_mutex_unlock(&gParcelGlobalAllocSizeLock);
2518 mDataSize = (mDataSize < desired) ? mDataSize : desired;
2519 ALOGV("continueWrite Setting data size of %p to %zu", this, mDataSize);
2520 mDataCapacity = desired;
2521 mObjectsSize = mObjectsCapacity = objectsSize;
2522 mNextObjectHint = 0;
2523 mObjectsSorted = false;
2526 if (objectsSize < mObjectsSize) {
2527 // Need to release refs on any objects we are dropping.
2528 const sp<ProcessState> proc(ProcessState::self());
2529 for (size_t i=objectsSize; i<mObjectsSize; i++) {
2530 const flat_binder_object* flat
2531 = reinterpret_cast<flat_binder_object*>(mData+mObjects[i]);
2532 if (flat->type == BINDER_TYPE_FD) {
2533 // will need to rescan because we may have lopped off the only FDs
2536 release_object(proc, *flat, this, &mOpenAshmemSize);
2538 binder_size_t* objects =
2539 (binder_size_t*)realloc(mObjects, objectsSize*sizeof(binder_size_t));
2543 mObjectsSize = objectsSize;
2544 mNextObjectHint = 0;
2545 mObjectsSorted = false;
2548 // We own the data, so we can just do a realloc().
2549 if (desired > mDataCapacity) {
2550 uint8_t* data = (uint8_t*)realloc(mData, desired);
2552 LOG_ALLOC("Parcel %p: continue from %zu to %zu capacity", this, mDataCapacity,
2554 pthread_mutex_lock(&gParcelGlobalAllocSizeLock);
2555 gParcelGlobalAllocSize += desired;
2556 gParcelGlobalAllocSize -= mDataCapacity;
2557 pthread_mutex_unlock(&gParcelGlobalAllocSizeLock);
2559 mDataCapacity = desired;
2560 } else if (desired > mDataCapacity) {
2565 if (mDataSize > desired) {
2566 mDataSize = desired;
2567 ALOGV("continueWrite Setting data size of %p to %zu", this, mDataSize);
2569 if (mDataPos > desired) {
2571 ALOGV("continueWrite Setting data pos of %p to %zu", this, mDataPos);
2576 // This is the first data. Easy!
2577 uint8_t* data = (uint8_t*)malloc(desired);
2583 if(!(mDataCapacity == 0 && mObjects == NULL
2584 && mObjectsCapacity == 0)) {
2585 ALOGE("continueWrite: %zu/%p/%zu/%zu", mDataCapacity, mObjects, mObjectsCapacity, desired);
2588 LOG_ALLOC("Parcel %p: allocating with %zu capacity", this, desired);
2589 pthread_mutex_lock(&gParcelGlobalAllocSizeLock);
2590 gParcelGlobalAllocSize += desired;
2591 gParcelGlobalAllocCount++;
2592 pthread_mutex_unlock(&gParcelGlobalAllocSizeLock);
2595 mDataSize = mDataPos = 0;
2596 ALOGV("continueWrite Setting data size of %p to %zu", this, mDataSize);
2597 ALOGV("continueWrite Setting data pos of %p to %zu", this, mDataPos);
2598 mDataCapacity = desired;
2604 void Parcel::initState()
2606 LOG_ALLOC("Parcel %p: initState", this);
2612 ALOGV("initState Setting data size of %p to %zu", this, mDataSize);
2613 ALOGV("initState Setting data pos of %p to %zu", this, mDataPos);
2616 mObjectsCapacity = 0;
2617 mNextObjectHint = 0;
2618 mObjectsSorted = false;
2623 mOpenAshmemSize = 0;
2625 // racing multiple init leads only to multiple identical write
2627 struct rlimit result;
2628 if (!getrlimit(RLIMIT_NOFILE, &result)) {
2629 gMaxFds = (size_t)result.rlim_cur;
2630 //ALOGI("parcel fd limit set to %zu", gMaxFds);
2632 ALOGW("Unable to getrlimit: %s", strerror(errno));
2638 void Parcel::scanForFds() const
2640 bool hasFds = false;
2641 for (size_t i=0; i<mObjectsSize; i++) {
2642 const flat_binder_object* flat
2643 = reinterpret_cast<const flat_binder_object*>(mData + mObjects[i]);
2644 if (flat->type == BINDER_TYPE_FD) {
2653 size_t Parcel::getBlobAshmemSize() const
2655 // This used to return the size of all blobs that were written to ashmem, now we're returning
2656 // the ashmem currently referenced by this Parcel, which should be equivalent.
2657 // TODO: Remove method once ABI can be changed.
2658 return mOpenAshmemSize;
2661 size_t Parcel::getOpenAshmemSize() const
2663 return mOpenAshmemSize;
2666 // --- Parcel::Blob ---
2668 Parcel::Blob::Blob() :
2669 mFd(-1), mData(NULL), mSize(0), mMutable(false) {
2672 Parcel::Blob::~Blob() {
2676 void Parcel::Blob::release() {
2677 if (mFd != -1 && mData) {
2678 ::munmap(mData, mSize);
2683 void Parcel::Blob::init(int fd, void* data, size_t size, bool isMutable) {
2687 mMutable = isMutable;
2690 void Parcel::Blob::clear() {
2697 }; // namespace android