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 void acquire_object(const sp<ProcessState>& proc,
104 const flat_binder_object& obj, const void* who, size_t* outAshmemSize)
107 case BINDER_TYPE_BINDER:
109 LOG_REFS("Parcel %p acquiring reference on local %p", who, obj.cookie);
110 reinterpret_cast<IBinder*>(obj.cookie)->incStrong(who);
113 case BINDER_TYPE_WEAK_BINDER:
115 reinterpret_cast<RefBase::weakref_type*>(obj.binder)->incWeak(who);
117 case BINDER_TYPE_HANDLE: {
118 const sp<IBinder> b = proc->getStrongProxyForHandle(obj.handle);
120 LOG_REFS("Parcel %p acquiring reference on remote %p", who, b.get());
125 case BINDER_TYPE_WEAK_HANDLE: {
126 const wp<IBinder> b = proc->getWeakProxyForHandle(obj.handle);
127 if (b != NULL) b.get_refs()->incWeak(who);
130 case BINDER_TYPE_FD: {
131 if ((obj.cookie != 0) && (outAshmemSize != NULL) && ashmem_valid(obj.handle)) {
132 // If we own an ashmem fd, keep track of how much memory it refers to.
133 int size = ashmem_get_size_region(obj.handle);
135 *outAshmemSize += size;
142 ALOGD("Invalid object type 0x%08x", obj.type);
145 void acquire_object(const sp<ProcessState>& proc,
146 const flat_binder_object& obj, const void* who)
148 acquire_object(proc, obj, who, NULL);
151 static void release_object(const sp<ProcessState>& proc,
152 const flat_binder_object& obj, const void* who, size_t* outAshmemSize)
155 case BINDER_TYPE_BINDER:
157 LOG_REFS("Parcel %p releasing reference on local %p", who, obj.cookie);
158 reinterpret_cast<IBinder*>(obj.cookie)->decStrong(who);
161 case BINDER_TYPE_WEAK_BINDER:
163 reinterpret_cast<RefBase::weakref_type*>(obj.binder)->decWeak(who);
165 case BINDER_TYPE_HANDLE: {
166 const sp<IBinder> b = proc->getStrongProxyForHandle(obj.handle);
168 LOG_REFS("Parcel %p releasing reference on remote %p", who, b.get());
173 case BINDER_TYPE_WEAK_HANDLE: {
174 const wp<IBinder> b = proc->getWeakProxyForHandle(obj.handle);
175 if (b != NULL) b.get_refs()->decWeak(who);
178 case BINDER_TYPE_FD: {
179 if (obj.cookie != 0) { // owned
180 if ((outAshmemSize != NULL) && ashmem_valid(obj.handle)) {
181 int size = ashmem_get_size_region(obj.handle);
183 *outAshmemSize -= size;
193 ALOGE("Invalid object type 0x%08x", obj.type);
196 void release_object(const sp<ProcessState>& proc,
197 const flat_binder_object& obj, const void* who)
199 release_object(proc, obj, who, NULL);
202 inline static status_t finish_flatten_binder(
203 const sp<IBinder>& /*binder*/, const flat_binder_object& flat, Parcel* out)
205 return out->writeObject(flat, false);
208 status_t flatten_binder(const sp<ProcessState>& /*proc*/,
209 const sp<IBinder>& binder, Parcel* out)
211 flat_binder_object obj;
213 obj.flags = 0x7f | FLAT_BINDER_FLAG_ACCEPTS_FDS;
214 if (binder != NULL) {
215 IBinder *local = binder->localBinder();
217 BpBinder *proxy = binder->remoteBinder();
221 const int32_t handle = proxy ? proxy->handle() : 0;
222 obj.type = BINDER_TYPE_HANDLE;
223 obj.binder = 0; /* Don't pass uninitialized stack data to a remote process */
227 obj.type = BINDER_TYPE_BINDER;
228 obj.binder = reinterpret_cast<uintptr_t>(local->getWeakRefs());
229 obj.cookie = reinterpret_cast<uintptr_t>(local);
232 obj.type = BINDER_TYPE_BINDER;
237 return finish_flatten_binder(binder, obj, out);
240 status_t flatten_binder(const sp<ProcessState>& /*proc*/,
241 const wp<IBinder>& binder, Parcel* out)
243 flat_binder_object obj;
245 obj.flags = 0x7f | FLAT_BINDER_FLAG_ACCEPTS_FDS;
246 if (binder != NULL) {
247 sp<IBinder> real = binder.promote();
249 IBinder *local = real->localBinder();
251 BpBinder *proxy = real->remoteBinder();
255 const int32_t handle = proxy ? proxy->handle() : 0;
256 obj.type = BINDER_TYPE_WEAK_HANDLE;
257 obj.binder = 0; /* Don't pass uninitialized stack data to a remote process */
261 obj.type = BINDER_TYPE_WEAK_BINDER;
262 obj.binder = reinterpret_cast<uintptr_t>(binder.get_refs());
263 obj.cookie = reinterpret_cast<uintptr_t>(binder.unsafe_get());
265 return finish_flatten_binder(real, obj, out);
268 // XXX How to deal? In order to flatten the given binder,
269 // we need to probe it for information, which requires a primary
270 // reference... but we don't have one.
272 // The OpenBinder implementation uses a dynamic_cast<> here,
273 // but we can't do that with the different reference counting
274 // implementation we are using.
275 ALOGE("Unable to unflatten Binder weak reference!");
276 obj.type = BINDER_TYPE_BINDER;
279 return finish_flatten_binder(NULL, obj, out);
282 obj.type = BINDER_TYPE_BINDER;
285 return finish_flatten_binder(NULL, obj, out);
289 inline static status_t finish_unflatten_binder(
290 BpBinder* /*proxy*/, const flat_binder_object& /*flat*/,
291 const Parcel& /*in*/)
296 status_t unflatten_binder(const sp<ProcessState>& proc,
297 const Parcel& in, sp<IBinder>* out)
299 const flat_binder_object* flat = in.readObject(false);
302 switch (flat->type) {
303 case BINDER_TYPE_BINDER:
304 *out = reinterpret_cast<IBinder*>(flat->cookie);
305 return finish_unflatten_binder(NULL, *flat, in);
306 case BINDER_TYPE_HANDLE:
307 *out = proc->getStrongProxyForHandle(flat->handle);
308 return finish_unflatten_binder(
309 static_cast<BpBinder*>(out->get()), *flat, in);
315 status_t unflatten_binder(const sp<ProcessState>& proc,
316 const Parcel& in, wp<IBinder>* out)
318 const flat_binder_object* flat = in.readObject(false);
321 switch (flat->type) {
322 case BINDER_TYPE_BINDER:
323 *out = reinterpret_cast<IBinder*>(flat->cookie);
324 return finish_unflatten_binder(NULL, *flat, in);
325 case BINDER_TYPE_WEAK_BINDER:
326 if (flat->binder != 0) {
327 out->set_object_and_refs(
328 reinterpret_cast<IBinder*>(flat->cookie),
329 reinterpret_cast<RefBase::weakref_type*>(flat->binder));
333 return finish_unflatten_binder(NULL, *flat, in);
334 case BINDER_TYPE_HANDLE:
335 case BINDER_TYPE_WEAK_HANDLE:
336 *out = proc->getWeakProxyForHandle(flat->handle);
337 return finish_unflatten_binder(
338 static_cast<BpBinder*>(out->unsafe_get()), *flat, in);
344 // ---------------------------------------------------------------------------
348 LOG_ALLOC("Parcel %p: constructing", this);
355 LOG_ALLOC("Parcel %p: destroyed", this);
358 size_t Parcel::getGlobalAllocSize() {
359 pthread_mutex_lock(&gParcelGlobalAllocSizeLock);
360 size_t size = gParcelGlobalAllocSize;
361 pthread_mutex_unlock(&gParcelGlobalAllocSizeLock);
365 size_t Parcel::getGlobalAllocCount() {
366 pthread_mutex_lock(&gParcelGlobalAllocSizeLock);
367 size_t count = gParcelGlobalAllocCount;
368 pthread_mutex_unlock(&gParcelGlobalAllocSizeLock);
372 const uint8_t* Parcel::data() const
377 size_t Parcel::dataSize() const
379 return (mDataSize > mDataPos ? mDataSize : mDataPos);
382 size_t Parcel::dataAvail() const
384 size_t result = dataSize() - dataPosition();
385 if (result > INT32_MAX) {
391 size_t Parcel::dataPosition() const
396 size_t Parcel::dataCapacity() const
398 return mDataCapacity;
401 status_t Parcel::setDataSize(size_t size)
403 if (size > INT32_MAX) {
404 // don't accept size_t values which may have come from an
405 // inadvertent conversion from a negative int.
410 err = continueWrite(size);
411 if (err == NO_ERROR) {
413 ALOGV("setDataSize Setting data size of %p to %zu", this, mDataSize);
418 void Parcel::setDataPosition(size_t pos) const
420 if (pos > INT32_MAX) {
421 // don't accept size_t values which may have come from an
422 // inadvertent conversion from a negative int.
430 status_t Parcel::setDataCapacity(size_t size)
432 if (size > INT32_MAX) {
433 // don't accept size_t values which may have come from an
434 // inadvertent conversion from a negative int.
438 if (size > mDataCapacity) return continueWrite(size);
442 status_t Parcel::setData(const uint8_t* buffer, size_t len)
444 if (len > INT32_MAX) {
445 // don't accept size_t values which may have come from an
446 // inadvertent conversion from a negative int.
450 status_t err = restartWrite(len);
451 if (err == NO_ERROR) {
452 memcpy(const_cast<uint8_t*>(data()), buffer, len);
459 status_t Parcel::appendFrom(const Parcel *parcel, size_t offset, size_t len)
461 const sp<ProcessState> proc(ProcessState::self());
463 const uint8_t *data = parcel->mData;
464 const binder_size_t *objects = parcel->mObjects;
465 size_t size = parcel->mObjectsSize;
466 int startPos = mDataPos;
467 int firstIndex = -1, lastIndex = -2;
473 if (len > INT32_MAX) {
474 // don't accept size_t values which may have come from an
475 // inadvertent conversion from a negative int.
479 // range checks against the source parcel size
480 if ((offset > parcel->mDataSize)
481 || (len > parcel->mDataSize)
482 || (offset + len > parcel->mDataSize)) {
486 // Count objects in range
487 for (int i = 0; i < (int) size; i++) {
488 size_t off = objects[i];
489 if ((off >= offset) && (off + sizeof(flat_binder_object) <= offset + len)) {
490 if (firstIndex == -1) {
496 int numObjects = lastIndex - firstIndex + 1;
498 if ((mDataSize+len) > mDataCapacity) {
501 if (err != NO_ERROR) {
507 memcpy(mData + mDataPos, data + offset, len);
513 if (numObjects > 0) {
515 if (mObjectsCapacity < mObjectsSize + numObjects) {
516 size_t newSize = ((mObjectsSize + numObjects)*3)/2;
517 if (newSize*sizeof(binder_size_t) < mObjectsSize) return NO_MEMORY; // overflow
518 binder_size_t *objects =
519 (binder_size_t*)realloc(mObjects, newSize*sizeof(binder_size_t));
520 if (objects == (binder_size_t*)0) {
524 mObjectsCapacity = newSize;
527 // append and acquire objects
528 int idx = mObjectsSize;
529 for (int i = firstIndex; i <= lastIndex; i++) {
530 size_t off = objects[i] - offset + startPos;
531 mObjects[idx++] = off;
534 flat_binder_object* flat
535 = reinterpret_cast<flat_binder_object*>(mData + off);
536 acquire_object(proc, *flat, this, &mOpenAshmemSize);
538 if (flat->type == BINDER_TYPE_FD) {
539 // If this is a file descriptor, we need to dup it so the
540 // new Parcel now owns its own fd, and can declare that we
541 // officially know we have fds.
542 flat->handle = dup(flat->handle);
544 mHasFds = mFdsKnown = true;
546 err = FDS_NOT_ALLOWED;
555 bool Parcel::allowFds() const
560 bool Parcel::pushAllowFds(bool allowFds)
562 const bool origValue = mAllowFds;
569 void Parcel::restoreAllowFds(bool lastValue)
571 mAllowFds = lastValue;
574 bool Parcel::hasFileDescriptors() const
582 // Write RPC headers. (previously just the interface token)
583 status_t Parcel::writeInterfaceToken(const String16& interface)
585 writeInt32(IPCThreadState::self()->getStrictModePolicy() |
586 STRICT_MODE_PENALTY_GATHER);
587 // currently the interface identification token is just its name as a string
588 return writeString16(interface);
591 bool Parcel::checkInterface(IBinder* binder) const
593 return enforceInterface(binder->getInterfaceDescriptor());
596 bool Parcel::enforceInterface(const String16& interface,
597 IPCThreadState* threadState) const
599 int32_t strictPolicy = readInt32();
600 if (threadState == NULL) {
601 threadState = IPCThreadState::self();
603 if ((threadState->getLastTransactionBinderFlags() &
604 IBinder::FLAG_ONEWAY) != 0) {
605 // For one-way calls, the callee is running entirely
606 // disconnected from the caller, so disable StrictMode entirely.
607 // Not only does disk/network usage not impact the caller, but
608 // there's no way to commuicate back any violations anyway.
609 threadState->setStrictModePolicy(0);
611 threadState->setStrictModePolicy(strictPolicy);
613 const String16 str(readString16());
614 if (str == interface) {
617 ALOGW("**** enforceInterface() expected '%s' but read '%s'",
618 String8(interface).string(), String8(str).string());
623 const binder_size_t* Parcel::objects() const
628 size_t Parcel::objectsCount() const
633 status_t Parcel::errorCheck() const
638 void Parcel::setError(status_t err)
643 status_t Parcel::finishWrite(size_t len)
645 if (len > INT32_MAX) {
646 // don't accept size_t values which may have come from an
647 // inadvertent conversion from a negative int.
651 //printf("Finish write of %d\n", len);
653 ALOGV("finishWrite Setting data pos of %p to %zu", this, mDataPos);
654 if (mDataPos > mDataSize) {
655 mDataSize = mDataPos;
656 ALOGV("finishWrite Setting data size of %p to %zu", this, mDataSize);
658 //printf("New pos=%d, size=%d\n", mDataPos, mDataSize);
662 status_t Parcel::writeUnpadded(const void* data, size_t len)
664 if (len > INT32_MAX) {
665 // don't accept size_t values which may have come from an
666 // inadvertent conversion from a negative int.
670 size_t end = mDataPos + len;
671 if (end < mDataPos) {
676 if (end <= mDataCapacity) {
678 memcpy(mData+mDataPos, data, len);
679 return finishWrite(len);
682 status_t err = growData(len);
683 if (err == NO_ERROR) goto restart_write;
687 status_t Parcel::write(const void* data, size_t len)
689 if (len > INT32_MAX) {
690 // don't accept size_t values which may have come from an
691 // inadvertent conversion from a negative int.
695 void* const d = writeInplace(len);
697 memcpy(d, data, len);
703 void* Parcel::writeInplace(size_t len)
705 if (len > INT32_MAX) {
706 // don't accept size_t values which may have come from an
707 // inadvertent conversion from a negative int.
711 const size_t padded = pad_size(len);
713 // sanity check for integer overflow
714 if (mDataPos+padded < mDataPos) {
718 if ((mDataPos+padded) <= mDataCapacity) {
720 //printf("Writing %ld bytes, padded to %ld\n", len, padded);
721 uint8_t* const data = mData+mDataPos;
723 // Need to pad at end?
725 #if BYTE_ORDER == BIG_ENDIAN
726 static const uint32_t mask[4] = {
727 0x00000000, 0xffffff00, 0xffff0000, 0xff000000
730 #if BYTE_ORDER == LITTLE_ENDIAN
731 static const uint32_t mask[4] = {
732 0x00000000, 0x00ffffff, 0x0000ffff, 0x000000ff
735 //printf("Applying pad mask: %p to %p\n", (void*)mask[padded-len],
736 // *reinterpret_cast<void**>(data+padded-4));
737 *reinterpret_cast<uint32_t*>(data+padded-4) &= mask[padded-len];
744 status_t err = growData(padded);
745 if (err == NO_ERROR) goto restart_write;
749 status_t Parcel::writeUtf8AsUtf16(const std::string& str) {
750 const uint8_t* strData = (uint8_t*)str.data();
751 const size_t strLen= str.length();
752 const ssize_t utf16Len = utf8_to_utf16_length(strData, strLen);
753 if (utf16Len < 0 || utf16Len > std::numeric_limits<int32_t>::max()) {
757 status_t err = writeInt32(utf16Len);
762 // Allocate enough bytes to hold our converted string and its terminating NULL.
763 void* dst = writeInplace((utf16Len + 1) * sizeof(char16_t));
768 utf8_to_utf16(strData, strLen, (char16_t*)dst, (size_t) utf16Len + 1);
773 status_t Parcel::writeUtf8AsUtf16(const std::unique_ptr<std::string>& str) {
775 return writeInt32(-1);
777 return writeUtf8AsUtf16(*str);
783 status_t writeByteVectorInternal(Parcel* parcel, const std::vector<T>& val)
786 if (val.size() > std::numeric_limits<int32_t>::max()) {
791 status = parcel->writeInt32(val.size());
796 void* data = parcel->writeInplace(val.size());
802 memcpy(data, val.data(), val.size());
807 status_t writeByteVectorInternalPtr(Parcel* parcel,
808 const std::unique_ptr<std::vector<T>>& val)
811 return parcel->writeInt32(-1);
814 return writeByteVectorInternal(parcel, *val);
819 status_t Parcel::writeByteVector(const std::vector<int8_t>& val) {
820 return writeByteVectorInternal(this, val);
823 status_t Parcel::writeByteVector(const std::unique_ptr<std::vector<int8_t>>& val)
825 return writeByteVectorInternalPtr(this, val);
828 status_t Parcel::writeByteVector(const std::vector<uint8_t>& val) {
829 return writeByteVectorInternal(this, val);
832 status_t Parcel::writeByteVector(const std::unique_ptr<std::vector<uint8_t>>& val)
834 return writeByteVectorInternalPtr(this, val);
837 status_t Parcel::writeInt32Vector(const std::vector<int32_t>& val)
839 return writeTypedVector(val, &Parcel::writeInt32);
842 status_t Parcel::writeInt32Vector(const std::unique_ptr<std::vector<int32_t>>& val)
844 return writeNullableTypedVector(val, &Parcel::writeInt32);
847 status_t Parcel::writeInt64Vector(const std::vector<int64_t>& val)
849 return writeTypedVector(val, &Parcel::writeInt64);
852 status_t Parcel::writeInt64Vector(const std::unique_ptr<std::vector<int64_t>>& val)
854 return writeNullableTypedVector(val, &Parcel::writeInt64);
857 status_t Parcel::writeFloatVector(const std::vector<float>& val)
859 return writeTypedVector(val, &Parcel::writeFloat);
862 status_t Parcel::writeFloatVector(const std::unique_ptr<std::vector<float>>& val)
864 return writeNullableTypedVector(val, &Parcel::writeFloat);
867 status_t Parcel::writeDoubleVector(const std::vector<double>& val)
869 return writeTypedVector(val, &Parcel::writeDouble);
872 status_t Parcel::writeDoubleVector(const std::unique_ptr<std::vector<double>>& val)
874 return writeNullableTypedVector(val, &Parcel::writeDouble);
877 status_t Parcel::writeBoolVector(const std::vector<bool>& val)
879 return writeTypedVector(val, &Parcel::writeBool);
882 status_t Parcel::writeBoolVector(const std::unique_ptr<std::vector<bool>>& val)
884 return writeNullableTypedVector(val, &Parcel::writeBool);
887 status_t Parcel::writeCharVector(const std::vector<char16_t>& val)
889 return writeTypedVector(val, &Parcel::writeChar);
892 status_t Parcel::writeCharVector(const std::unique_ptr<std::vector<char16_t>>& val)
894 return writeNullableTypedVector(val, &Parcel::writeChar);
897 status_t Parcel::writeString16Vector(const std::vector<String16>& val)
899 return writeTypedVector(val, &Parcel::writeString16);
902 status_t Parcel::writeString16Vector(
903 const std::unique_ptr<std::vector<std::unique_ptr<String16>>>& val)
905 return writeNullableTypedVector(val, &Parcel::writeString16);
908 status_t Parcel::writeUtf8VectorAsUtf16Vector(
909 const std::unique_ptr<std::vector<std::unique_ptr<std::string>>>& val) {
910 return writeNullableTypedVector(val, &Parcel::writeUtf8AsUtf16);
913 status_t Parcel::writeUtf8VectorAsUtf16Vector(const std::vector<std::string>& val) {
914 return writeTypedVector(val, &Parcel::writeUtf8AsUtf16);
917 status_t Parcel::writeInt32(int32_t val)
919 return writeAligned(val);
922 status_t Parcel::writeUint32(uint32_t val)
924 return writeAligned(val);
927 status_t Parcel::writeInt32Array(size_t len, const int32_t *val) {
928 if (len > INT32_MAX) {
929 // don't accept size_t values which may have come from an
930 // inadvertent conversion from a negative int.
935 return writeInt32(-1);
937 status_t ret = writeInt32(static_cast<uint32_t>(len));
938 if (ret == NO_ERROR) {
939 ret = write(val, len * sizeof(*val));
943 status_t Parcel::writeByteArray(size_t len, const uint8_t *val) {
944 if (len > INT32_MAX) {
945 // don't accept size_t values which may have come from an
946 // inadvertent conversion from a negative int.
951 return writeInt32(-1);
953 status_t ret = writeInt32(static_cast<uint32_t>(len));
954 if (ret == NO_ERROR) {
955 ret = write(val, len * sizeof(*val));
960 status_t Parcel::writeBool(bool val)
962 return writeInt32(int32_t(val));
965 status_t Parcel::writeChar(char16_t val)
967 return writeInt32(int32_t(val));
970 status_t Parcel::writeByte(int8_t val)
972 return writeInt32(int32_t(val));
975 status_t Parcel::writeInt64(int64_t val)
977 return writeAligned(val);
980 status_t Parcel::writeUint64(uint64_t val)
982 return writeAligned(val);
985 status_t Parcel::writePointer(uintptr_t val)
987 return writeAligned<binder_uintptr_t>(val);
990 status_t Parcel::writeFloat(float val)
992 return writeAligned(val);
995 #if defined(__mips__) && defined(__mips_hard_float)
997 status_t Parcel::writeDouble(double val)
1001 unsigned long long ll;
1004 return writeAligned(u.ll);
1009 status_t Parcel::writeDouble(double val)
1011 return writeAligned(val);
1016 status_t Parcel::writeCString(const char* str)
1018 return write(str, strlen(str)+1);
1021 status_t Parcel::writeString8(const String8& str)
1023 status_t err = writeInt32(str.bytes());
1024 // only write string if its length is more than zero characters,
1025 // as readString8 will only read if the length field is non-zero.
1026 // this is slightly different from how writeString16 works.
1027 if (str.bytes() > 0 && err == NO_ERROR) {
1028 err = write(str.string(), str.bytes()+1);
1033 status_t Parcel::writeString16(const std::unique_ptr<String16>& str)
1036 return writeInt32(-1);
1039 return writeString16(*str);
1042 status_t Parcel::writeString16(const String16& str)
1044 return writeString16(str.string(), str.size());
1047 status_t Parcel::writeString16(const char16_t* str, size_t len)
1049 if (str == NULL) return writeInt32(-1);
1051 status_t err = writeInt32(len);
1052 if (err == NO_ERROR) {
1053 len *= sizeof(char16_t);
1054 uint8_t* data = (uint8_t*)writeInplace(len+sizeof(char16_t));
1056 memcpy(data, str, len);
1057 *reinterpret_cast<char16_t*>(data+len) = 0;
1065 status_t Parcel::writeStrongBinder(const sp<IBinder>& val)
1067 return flatten_binder(ProcessState::self(), val, this);
1070 status_t Parcel::writeStrongBinderVector(const std::vector<sp<IBinder>>& val)
1072 return writeTypedVector(val, &Parcel::writeStrongBinder);
1075 status_t Parcel::writeStrongBinderVector(const std::unique_ptr<std::vector<sp<IBinder>>>& val)
1077 return writeNullableTypedVector(val, &Parcel::writeStrongBinder);
1080 status_t Parcel::readStrongBinderVector(std::unique_ptr<std::vector<sp<IBinder>>>* val) const {
1081 return readNullableTypedVector(val, &Parcel::readNullableStrongBinder);
1084 status_t Parcel::readStrongBinderVector(std::vector<sp<IBinder>>* val) const {
1085 return readTypedVector(val, &Parcel::readStrongBinder);
1088 status_t Parcel::writeWeakBinder(const wp<IBinder>& val)
1090 return flatten_binder(ProcessState::self(), val, this);
1093 status_t Parcel::writeRawNullableParcelable(const Parcelable* parcelable) {
1095 return writeInt32(0);
1098 return writeParcelable(*parcelable);
1101 status_t Parcel::writeParcelable(const Parcelable& parcelable) {
1102 status_t status = writeInt32(1); // parcelable is not null.
1106 return parcelable.writeToParcel(this);
1109 status_t Parcel::writeNativeHandle(const native_handle* handle)
1111 if (!handle || handle->version != sizeof(native_handle))
1115 err = writeInt32(handle->numFds);
1116 if (err != NO_ERROR) return err;
1118 err = writeInt32(handle->numInts);
1119 if (err != NO_ERROR) return err;
1121 for (int i=0 ; err==NO_ERROR && i<handle->numFds ; i++)
1122 err = writeDupFileDescriptor(handle->data[i]);
1124 if (err != NO_ERROR) {
1125 ALOGD("write native handle, write dup fd failed");
1128 err = write(handle->data + handle->numFds, sizeof(int)*handle->numInts);
1132 status_t Parcel::writeFileDescriptor(int fd, bool takeOwnership)
1134 flat_binder_object obj;
1135 obj.type = BINDER_TYPE_FD;
1136 obj.flags = 0x7f | FLAT_BINDER_FLAG_ACCEPTS_FDS;
1137 obj.binder = 0; /* Don't pass uninitialized stack data to a remote process */
1139 obj.cookie = takeOwnership ? 1 : 0;
1140 return writeObject(obj, true);
1143 status_t Parcel::writeDupFileDescriptor(int fd)
1145 int dupFd = dup(fd);
1149 status_t err = writeFileDescriptor(dupFd, true /*takeOwnership*/);
1156 status_t Parcel::writeUniqueFileDescriptor(const base::unique_fd& fd) {
1157 return writeDupFileDescriptor(fd.get());
1160 status_t Parcel::writeUniqueFileDescriptorVector(const std::vector<base::unique_fd>& val) {
1161 return writeTypedVector(val, &Parcel::writeUniqueFileDescriptor);
1164 status_t Parcel::writeUniqueFileDescriptorVector(const std::unique_ptr<std::vector<base::unique_fd>>& val) {
1165 return writeNullableTypedVector(val, &Parcel::writeUniqueFileDescriptor);
1168 status_t Parcel::writeBlob(size_t len, bool mutableCopy, WritableBlob* outBlob)
1170 if (len > INT32_MAX) {
1171 // don't accept size_t values which may have come from an
1172 // inadvertent conversion from a negative int.
1177 if (!mAllowFds || len <= BLOB_INPLACE_LIMIT) {
1178 ALOGV("writeBlob: write in place");
1179 status = writeInt32(BLOB_INPLACE);
1180 if (status) return status;
1182 void* ptr = writeInplace(len);
1183 if (!ptr) return NO_MEMORY;
1185 outBlob->init(-1, ptr, len, false);
1189 ALOGV("writeBlob: write to ashmem");
1190 int fd = ashmem_create_region("Parcel Blob", len);
1191 if (fd < 0) return NO_MEMORY;
1193 int result = ashmem_set_prot_region(fd, PROT_READ | PROT_WRITE);
1197 void* ptr = ::mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
1198 if (ptr == MAP_FAILED) {
1202 result = ashmem_set_prot_region(fd, PROT_READ);
1207 status = writeInt32(mutableCopy ? BLOB_ASHMEM_MUTABLE : BLOB_ASHMEM_IMMUTABLE);
1209 status = writeFileDescriptor(fd, true /*takeOwnership*/);
1211 outBlob->init(fd, ptr, len, mutableCopy);
1223 status_t Parcel::writeDupImmutableBlobFileDescriptor(int fd)
1225 // Must match up with what's done in writeBlob.
1226 if (!mAllowFds) return FDS_NOT_ALLOWED;
1227 status_t status = writeInt32(BLOB_ASHMEM_IMMUTABLE);
1228 if (status) return status;
1229 return writeDupFileDescriptor(fd);
1232 status_t Parcel::write(const FlattenableHelperInterface& val)
1237 const size_t len = val.getFlattenedSize();
1238 const size_t fd_count = val.getFdCount();
1240 if ((len > INT32_MAX) || (fd_count >= gMaxFds)) {
1241 // don't accept size_t values which may have come from an
1242 // inadvertent conversion from a negative int.
1246 err = this->writeInt32(len);
1247 if (err) return err;
1249 err = this->writeInt32(fd_count);
1250 if (err) return err;
1253 void* const buf = this->writeInplace(pad_size(len));
1259 fds = new (std::nothrow) int[fd_count];
1260 if (fds == nullptr) {
1261 ALOGE("write: failed to allocate requested %zu fds", fd_count);
1266 err = val.flatten(buf, len, fds, fd_count);
1267 for (size_t i=0 ; i<fd_count && err==NO_ERROR ; i++) {
1268 err = this->writeDupFileDescriptor( fds[i] );
1278 status_t Parcel::writeObject(const flat_binder_object& val, bool nullMetaData)
1280 const bool enoughData = (mDataPos+sizeof(val)) <= mDataCapacity;
1281 const bool enoughObjects = mObjectsSize < mObjectsCapacity;
1282 if (enoughData && enoughObjects) {
1284 *reinterpret_cast<flat_binder_object*>(mData+mDataPos) = val;
1286 // remember if it's a file descriptor
1287 if (val.type == BINDER_TYPE_FD) {
1289 // fail before modifying our object index
1290 return FDS_NOT_ALLOWED;
1292 mHasFds = mFdsKnown = true;
1295 // Need to write meta-data?
1296 if (nullMetaData || val.binder != 0) {
1297 mObjects[mObjectsSize] = mDataPos;
1298 acquire_object(ProcessState::self(), val, this, &mOpenAshmemSize);
1302 return finishWrite(sizeof(flat_binder_object));
1306 const status_t err = growData(sizeof(val));
1307 if (err != NO_ERROR) return err;
1309 if (!enoughObjects) {
1310 size_t newSize = ((mObjectsSize+2)*3)/2;
1311 if (newSize*sizeof(binder_size_t) < mObjectsSize) return NO_MEMORY; // overflow
1312 binder_size_t* objects = (binder_size_t*)realloc(mObjects, newSize*sizeof(binder_size_t));
1313 if (objects == NULL) return NO_MEMORY;
1315 mObjectsCapacity = newSize;
1321 status_t Parcel::writeNoException()
1323 binder::Status status;
1324 return status.writeToParcel(this);
1327 void Parcel::remove(size_t /*start*/, size_t /*amt*/)
1329 LOG_ALWAYS_FATAL("Parcel::remove() not yet implemented!");
1332 status_t Parcel::read(void* outData, size_t len) const
1334 if (len > INT32_MAX) {
1335 // don't accept size_t values which may have come from an
1336 // inadvertent conversion from a negative int.
1340 if ((mDataPos+pad_size(len)) >= mDataPos && (mDataPos+pad_size(len)) <= mDataSize
1341 && len <= pad_size(len)) {
1342 memcpy(outData, mData+mDataPos, len);
1343 mDataPos += pad_size(len);
1344 ALOGV("read Setting data pos of %p to %zu", this, mDataPos);
1347 return NOT_ENOUGH_DATA;
1350 const void* Parcel::readInplace(size_t len) const
1352 if (len > INT32_MAX) {
1353 // don't accept size_t values which may have come from an
1354 // inadvertent conversion from a negative int.
1358 if ((mDataPos+pad_size(len)) >= mDataPos && (mDataPos+pad_size(len)) <= mDataSize
1359 && len <= pad_size(len)) {
1360 const void* data = mData+mDataPos;
1361 mDataPos += pad_size(len);
1362 ALOGV("readInplace Setting data pos of %p to %zu", this, mDataPos);
1369 status_t Parcel::readAligned(T *pArg) const {
1370 COMPILE_TIME_ASSERT_FUNCTION_SCOPE(PAD_SIZE_UNSAFE(sizeof(T)) == sizeof(T));
1372 if ((mDataPos+sizeof(T)) <= mDataSize) {
1373 const void* data = mData+mDataPos;
1374 mDataPos += sizeof(T);
1375 *pArg = *reinterpret_cast<const T*>(data);
1378 return NOT_ENOUGH_DATA;
1383 T Parcel::readAligned() const {
1385 if (readAligned(&result) != NO_ERROR) {
1393 status_t Parcel::writeAligned(T val) {
1394 COMPILE_TIME_ASSERT_FUNCTION_SCOPE(PAD_SIZE_UNSAFE(sizeof(T)) == sizeof(T));
1396 if ((mDataPos+sizeof(val)) <= mDataCapacity) {
1398 *reinterpret_cast<T*>(mData+mDataPos) = val;
1399 return finishWrite(sizeof(val));
1402 status_t err = growData(sizeof(val));
1403 if (err == NO_ERROR) goto restart_write;
1409 template<typename T>
1410 status_t readByteVectorInternal(const Parcel* parcel,
1411 std::vector<T>* val) {
1415 status_t status = parcel->readInt32(&size);
1422 status = UNEXPECTED_NULL;
1425 if (size_t(size) > parcel->dataAvail()) {
1430 const void* data = parcel->readInplace(size);
1436 memcpy(val->data(), data, size);
1441 template<typename T>
1442 status_t readByteVectorInternalPtr(
1443 const Parcel* parcel,
1444 std::unique_ptr<std::vector<T>>* val) {
1445 const int32_t start = parcel->dataPosition();
1447 status_t status = parcel->readInt32(&size);
1450 if (status != OK || size < 0) {
1454 parcel->setDataPosition(start);
1455 val->reset(new (std::nothrow) std::vector<T>());
1457 status = readByteVectorInternal(parcel, val->get());
1468 status_t Parcel::readByteVector(std::vector<int8_t>* val) const {
1469 return readByteVectorInternal(this, val);
1472 status_t Parcel::readByteVector(std::vector<uint8_t>* val) const {
1473 return readByteVectorInternal(this, val);
1476 status_t Parcel::readByteVector(std::unique_ptr<std::vector<int8_t>>* val) const {
1477 return readByteVectorInternalPtr(this, val);
1480 status_t Parcel::readByteVector(std::unique_ptr<std::vector<uint8_t>>* val) const {
1481 return readByteVectorInternalPtr(this, val);
1484 status_t Parcel::readInt32Vector(std::unique_ptr<std::vector<int32_t>>* val) const {
1485 return readNullableTypedVector(val, &Parcel::readInt32);
1488 status_t Parcel::readInt32Vector(std::vector<int32_t>* val) const {
1489 return readTypedVector(val, &Parcel::readInt32);
1492 status_t Parcel::readInt64Vector(std::unique_ptr<std::vector<int64_t>>* val) const {
1493 return readNullableTypedVector(val, &Parcel::readInt64);
1496 status_t Parcel::readInt64Vector(std::vector<int64_t>* val) const {
1497 return readTypedVector(val, &Parcel::readInt64);
1500 status_t Parcel::readFloatVector(std::unique_ptr<std::vector<float>>* val) const {
1501 return readNullableTypedVector(val, &Parcel::readFloat);
1504 status_t Parcel::readFloatVector(std::vector<float>* val) const {
1505 return readTypedVector(val, &Parcel::readFloat);
1508 status_t Parcel::readDoubleVector(std::unique_ptr<std::vector<double>>* val) const {
1509 return readNullableTypedVector(val, &Parcel::readDouble);
1512 status_t Parcel::readDoubleVector(std::vector<double>* val) const {
1513 return readTypedVector(val, &Parcel::readDouble);
1516 status_t Parcel::readBoolVector(std::unique_ptr<std::vector<bool>>* val) const {
1517 const int32_t start = dataPosition();
1519 status_t status = readInt32(&size);
1522 if (status != OK || size < 0) {
1526 setDataPosition(start);
1527 val->reset(new (std::nothrow) std::vector<bool>());
1529 status = readBoolVector(val->get());
1538 status_t Parcel::readBoolVector(std::vector<bool>* val) const {
1540 status_t status = readInt32(&size);
1547 return UNEXPECTED_NULL;
1552 /* C++ bool handling means a vector of bools isn't necessarily addressable
1553 * (we might use individual bits)
1556 for (int32_t i = 0; i < size; ++i) {
1557 status = readBool(&data);
1568 status_t Parcel::readCharVector(std::unique_ptr<std::vector<char16_t>>* val) const {
1569 return readNullableTypedVector(val, &Parcel::readChar);
1572 status_t Parcel::readCharVector(std::vector<char16_t>* val) const {
1573 return readTypedVector(val, &Parcel::readChar);
1576 status_t Parcel::readString16Vector(
1577 std::unique_ptr<std::vector<std::unique_ptr<String16>>>* val) const {
1578 return readNullableTypedVector(val, &Parcel::readString16);
1581 status_t Parcel::readString16Vector(std::vector<String16>* val) const {
1582 return readTypedVector(val, &Parcel::readString16);
1585 status_t Parcel::readUtf8VectorFromUtf16Vector(
1586 std::unique_ptr<std::vector<std::unique_ptr<std::string>>>* val) const {
1587 return readNullableTypedVector(val, &Parcel::readUtf8FromUtf16);
1590 status_t Parcel::readUtf8VectorFromUtf16Vector(std::vector<std::string>* val) const {
1591 return readTypedVector(val, &Parcel::readUtf8FromUtf16);
1594 status_t Parcel::readInt32(int32_t *pArg) const
1596 return readAligned(pArg);
1599 int32_t Parcel::readInt32() const
1601 return readAligned<int32_t>();
1604 status_t Parcel::readUint32(uint32_t *pArg) const
1606 return readAligned(pArg);
1609 uint32_t Parcel::readUint32() const
1611 return readAligned<uint32_t>();
1614 status_t Parcel::readInt64(int64_t *pArg) const
1616 return readAligned(pArg);
1620 int64_t Parcel::readInt64() const
1622 return readAligned<int64_t>();
1625 status_t Parcel::readUint64(uint64_t *pArg) const
1627 return readAligned(pArg);
1630 uint64_t Parcel::readUint64() const
1632 return readAligned<uint64_t>();
1635 status_t Parcel::readPointer(uintptr_t *pArg) const
1638 binder_uintptr_t ptr;
1639 ret = readAligned(&ptr);
1645 uintptr_t Parcel::readPointer() const
1647 return readAligned<binder_uintptr_t>();
1651 status_t Parcel::readFloat(float *pArg) const
1653 return readAligned(pArg);
1657 float Parcel::readFloat() const
1659 return readAligned<float>();
1662 #if defined(__mips__) && defined(__mips_hard_float)
1664 status_t Parcel::readDouble(double *pArg) const
1668 unsigned long long ll;
1672 status = readAligned(&u.ll);
1677 double Parcel::readDouble() const
1681 unsigned long long ll;
1683 u.ll = readAligned<unsigned long long>();
1689 status_t Parcel::readDouble(double *pArg) const
1691 return readAligned(pArg);
1694 double Parcel::readDouble() const
1696 return readAligned<double>();
1701 status_t Parcel::readIntPtr(intptr_t *pArg) const
1703 return readAligned(pArg);
1707 intptr_t Parcel::readIntPtr() const
1709 return readAligned<intptr_t>();
1712 status_t Parcel::readBool(bool *pArg) const
1715 status_t ret = readInt32(&tmp);
1720 bool Parcel::readBool() const
1722 return readInt32() != 0;
1725 status_t Parcel::readChar(char16_t *pArg) const
1728 status_t ret = readInt32(&tmp);
1729 *pArg = char16_t(tmp);
1733 char16_t Parcel::readChar() const
1735 return char16_t(readInt32());
1738 status_t Parcel::readByte(int8_t *pArg) const
1741 status_t ret = readInt32(&tmp);
1742 *pArg = int8_t(tmp);
1746 int8_t Parcel::readByte() const
1748 return int8_t(readInt32());
1751 status_t Parcel::readUtf8FromUtf16(std::string* str) const {
1752 size_t utf16Size = 0;
1753 const char16_t* src = readString16Inplace(&utf16Size);
1755 return UNEXPECTED_NULL;
1758 // Save ourselves the trouble, we're done.
1759 if (utf16Size == 0u) {
1764 // Allow for closing '\0'
1765 ssize_t utf8Size = utf16_to_utf8_length(src, utf16Size) + 1;
1769 // Note that while it is probably safe to assume string::resize keeps a
1770 // spare byte around for the trailing null, we still pass the size including the trailing null
1771 str->resize(utf8Size);
1772 utf16_to_utf8(src, utf16Size, &((*str)[0]), utf8Size);
1773 str->resize(utf8Size - 1);
1777 status_t Parcel::readUtf8FromUtf16(std::unique_ptr<std::string>* str) const {
1778 const int32_t start = dataPosition();
1780 status_t status = readInt32(&size);
1783 if (status != OK || size < 0) {
1787 setDataPosition(start);
1788 str->reset(new (std::nothrow) std::string());
1789 return readUtf8FromUtf16(str->get());
1792 const char* Parcel::readCString() const
1794 const size_t avail = mDataSize-mDataPos;
1796 const char* str = reinterpret_cast<const char*>(mData+mDataPos);
1797 // is the string's trailing NUL within the parcel's valid bounds?
1798 const char* eos = reinterpret_cast<const char*>(memchr(str, 0, avail));
1800 const size_t len = eos - str;
1801 mDataPos += pad_size(len+1);
1802 ALOGV("readCString Setting data pos of %p to %zu", this, mDataPos);
1809 String8 Parcel::readString8() const
1812 status_t status = readString8(&retString);
1814 // We don't care about errors here, so just return an empty string.
1820 status_t Parcel::readString8(String8* pArg) const
1823 status_t status = readInt32(&size);
1827 // watch for potential int overflow from size+1
1828 if (size < 0 || size >= INT32_MAX) {
1831 // |writeString8| writes nothing for empty string.
1836 const char* str = (const char*)readInplace(size + 1);
1840 pArg->setTo(str, size);
1844 String16 Parcel::readString16() const
1847 const char16_t* str = readString16Inplace(&len);
1848 if (str) return String16(str, len);
1849 ALOGE("Reading a NULL string not supported here.");
1853 status_t Parcel::readString16(std::unique_ptr<String16>* pArg) const
1855 const int32_t start = dataPosition();
1857 status_t status = readInt32(&size);
1860 if (status != OK || size < 0) {
1864 setDataPosition(start);
1865 pArg->reset(new (std::nothrow) String16());
1867 status = readString16(pArg->get());
1876 status_t Parcel::readString16(String16* pArg) const
1879 const char16_t* str = readString16Inplace(&len);
1881 pArg->setTo(str, len);
1885 return UNEXPECTED_NULL;
1889 const char16_t* Parcel::readString16Inplace(size_t* outLen) const
1891 int32_t size = readInt32();
1892 // watch for potential int overflow from size+1
1893 if (size >= 0 && size < INT32_MAX) {
1895 const char16_t* str = (const char16_t*)readInplace((size+1)*sizeof(char16_t));
1904 status_t Parcel::readStrongBinder(sp<IBinder>* val) const
1906 status_t status = readNullableStrongBinder(val);
1907 if (status == OK && !val->get()) {
1908 status = UNEXPECTED_NULL;
1913 status_t Parcel::readNullableStrongBinder(sp<IBinder>* val) const
1915 return unflatten_binder(ProcessState::self(), *this, val);
1918 sp<IBinder> Parcel::readStrongBinder() const
1921 // Note that a lot of code in Android reads binders by hand with this
1922 // method, and that code has historically been ok with getting nullptr
1923 // back (while ignoring error codes).
1924 readNullableStrongBinder(&val);
1928 wp<IBinder> Parcel::readWeakBinder() const
1931 unflatten_binder(ProcessState::self(), *this, &val);
1935 status_t Parcel::readParcelable(Parcelable* parcelable) const {
1936 int32_t have_parcelable = 0;
1937 status_t status = readInt32(&have_parcelable);
1941 if (!have_parcelable) {
1942 return UNEXPECTED_NULL;
1944 return parcelable->readFromParcel(this);
1947 int32_t Parcel::readExceptionCode() const
1949 binder::Status status;
1950 status.readFromParcel(*this);
1951 return status.exceptionCode();
1954 native_handle* Parcel::readNativeHandle() const
1956 int numFds, numInts;
1958 err = readInt32(&numFds);
1959 if (err != NO_ERROR) return 0;
1960 err = readInt32(&numInts);
1961 if (err != NO_ERROR) return 0;
1963 native_handle* h = native_handle_create(numFds, numInts);
1968 for (int i=0 ; err==NO_ERROR && i<numFds ; i++) {
1969 h->data[i] = dup(readFileDescriptor());
1970 if (h->data[i] < 0) {
1971 for (int j = 0; j < i; j++) {
1974 native_handle_delete(h);
1978 err = read(h->data + numFds, sizeof(int)*numInts);
1979 if (err != NO_ERROR) {
1980 native_handle_close(h);
1981 native_handle_delete(h);
1988 int Parcel::readFileDescriptor() const
1990 const flat_binder_object* flat = readObject(true);
1992 if (flat && flat->type == BINDER_TYPE_FD) {
1993 return flat->handle;
1999 status_t Parcel::readUniqueFileDescriptor(base::unique_fd* val) const
2001 int got = readFileDescriptor();
2003 if (got == BAD_TYPE) {
2007 val->reset(dup(got));
2009 if (val->get() < 0) {
2017 status_t Parcel::readUniqueFileDescriptorVector(std::unique_ptr<std::vector<base::unique_fd>>* val) const {
2018 return readNullableTypedVector(val, &Parcel::readUniqueFileDescriptor);
2021 status_t Parcel::readUniqueFileDescriptorVector(std::vector<base::unique_fd>* val) const {
2022 return readTypedVector(val, &Parcel::readUniqueFileDescriptor);
2025 status_t Parcel::readBlob(size_t len, ReadableBlob* outBlob) const
2028 status_t status = readInt32(&blobType);
2029 if (status) return status;
2031 if (blobType == BLOB_INPLACE) {
2032 ALOGV("readBlob: read in place");
2033 const void* ptr = readInplace(len);
2034 if (!ptr) return BAD_VALUE;
2036 outBlob->init(-1, const_cast<void*>(ptr), len, false);
2040 ALOGV("readBlob: read from ashmem");
2041 bool isMutable = (blobType == BLOB_ASHMEM_MUTABLE);
2042 int fd = readFileDescriptor();
2043 if (fd == int(BAD_TYPE)) return BAD_VALUE;
2045 void* ptr = ::mmap(NULL, len, isMutable ? PROT_READ | PROT_WRITE : PROT_READ,
2047 if (ptr == MAP_FAILED) return NO_MEMORY;
2049 outBlob->init(fd, ptr, len, isMutable);
2053 status_t Parcel::read(FlattenableHelperInterface& val) const
2056 const size_t len = this->readInt32();
2057 const size_t fd_count = this->readInt32();
2059 if ((len > INT32_MAX) || (fd_count >= gMaxFds)) {
2060 // don't accept size_t values which may have come from an
2061 // inadvertent conversion from a negative int.
2066 void const* const buf = this->readInplace(pad_size(len));
2072 fds = new (std::nothrow) int[fd_count];
2073 if (fds == nullptr) {
2074 ALOGE("read: failed to allocate requested %zu fds", fd_count);
2079 status_t err = NO_ERROR;
2080 for (size_t i=0 ; i<fd_count && err==NO_ERROR ; i++) {
2081 fds[i] = dup(this->readFileDescriptor());
2084 ALOGE("dup() failed in Parcel::read, i is %zu, fds[i] is %d, fd_count is %zu, error: %s",
2085 i, fds[i], fd_count, strerror(errno));
2089 if (err == NO_ERROR) {
2090 err = val.unflatten(buf, len, fds, fd_count);
2099 const flat_binder_object* Parcel::readObject(bool nullMetaData) const
2101 const size_t DPOS = mDataPos;
2102 if ((DPOS+sizeof(flat_binder_object)) <= mDataSize) {
2103 const flat_binder_object* obj
2104 = reinterpret_cast<const flat_binder_object*>(mData+DPOS);
2105 mDataPos = DPOS + sizeof(flat_binder_object);
2106 if (!nullMetaData && (obj->cookie == 0 && obj->binder == 0)) {
2107 // When transferring a NULL object, we don't write it into
2108 // the object list, so we don't want to check for it when
2110 ALOGV("readObject Setting data pos of %p to %zu", this, mDataPos);
2114 // Ensure that this object is valid...
2115 binder_size_t* const OBJS = mObjects;
2116 const size_t N = mObjectsSize;
2117 size_t opos = mNextObjectHint;
2120 ALOGV("Parcel %p looking for obj at %zu, hint=%zu",
2123 // Start at the current hint position, looking for an object at
2124 // the current data position.
2126 while (opos < (N-1) && OBJS[opos] < DPOS) {
2132 if (OBJS[opos] == DPOS) {
2134 ALOGV("Parcel %p found obj %zu at index %zu with forward search",
2136 mNextObjectHint = opos+1;
2137 ALOGV("readObject Setting data pos of %p to %zu", this, mDataPos);
2141 // Look backwards for it...
2142 while (opos > 0 && OBJS[opos] > DPOS) {
2145 if (OBJS[opos] == DPOS) {
2147 ALOGV("Parcel %p found obj %zu at index %zu with backward search",
2149 mNextObjectHint = opos+1;
2150 ALOGV("readObject Setting data pos of %p to %zu", this, mDataPos);
2154 ALOGW("Attempt to read object from Parcel %p at offset %zu that is not in the object list",
2160 void Parcel::closeFileDescriptors()
2162 size_t i = mObjectsSize;
2164 //ALOGI("Closing file descriptors for %zu objects...", i);
2168 const flat_binder_object* flat
2169 = reinterpret_cast<flat_binder_object*>(mData+mObjects[i]);
2170 if (flat->type == BINDER_TYPE_FD) {
2171 //ALOGI("Closing fd: %ld", flat->handle);
2172 close(flat->handle);
2177 uintptr_t Parcel::ipcData() const
2179 return reinterpret_cast<uintptr_t>(mData);
2182 size_t Parcel::ipcDataSize() const
2184 return (mDataSize > mDataPos ? mDataSize : mDataPos);
2187 uintptr_t Parcel::ipcObjects() const
2189 return reinterpret_cast<uintptr_t>(mObjects);
2192 size_t Parcel::ipcObjectsCount() const
2194 return mObjectsSize;
2197 void Parcel::ipcSetDataReference(const uint8_t* data, size_t dataSize,
2198 const binder_size_t* objects, size_t objectsCount, release_func relFunc, void* relCookie)
2200 binder_size_t minOffset = 0;
2203 mData = const_cast<uint8_t*>(data);
2204 mDataSize = mDataCapacity = dataSize;
2205 //ALOGI("setDataReference Setting data size of %p to %lu (pid=%d)", this, mDataSize, getpid());
2207 ALOGV("setDataReference Setting data pos of %p to %zu", this, mDataPos);
2208 mObjects = const_cast<binder_size_t*>(objects);
2209 mObjectsSize = mObjectsCapacity = objectsCount;
2210 mNextObjectHint = 0;
2212 mOwnerCookie = relCookie;
2213 for (size_t i = 0; i < mObjectsSize; i++) {
2214 binder_size_t offset = mObjects[i];
2215 if (offset < minOffset) {
2216 ALOGE("%s: bad object offset %" PRIu64 " < %" PRIu64 "\n",
2217 __func__, (uint64_t)offset, (uint64_t)minOffset);
2221 minOffset = offset + sizeof(flat_binder_object);
2226 void Parcel::print(TextOutput& to, uint32_t /*flags*/) const
2230 if (errorCheck() != NO_ERROR) {
2231 const status_t err = errorCheck();
2232 to << "Error: " << (void*)(intptr_t)err << " \"" << strerror(-err) << "\"";
2233 } else if (dataSize() > 0) {
2234 const uint8_t* DATA = data();
2235 to << indent << HexDump(DATA, dataSize()) << dedent;
2236 const binder_size_t* OBJS = objects();
2237 const size_t N = objectsCount();
2238 for (size_t i=0; i<N; i++) {
2239 const flat_binder_object* flat
2240 = reinterpret_cast<const flat_binder_object*>(DATA+OBJS[i]);
2241 to << endl << "Object #" << i << " @ " << (void*)OBJS[i] << ": "
2242 << TypeCode(flat->type & 0x7f7f7f00)
2243 << " = " << flat->binder;
2252 void Parcel::releaseObjects()
2254 const sp<ProcessState> proc(ProcessState::self());
2255 size_t i = mObjectsSize;
2256 uint8_t* const data = mData;
2257 binder_size_t* const objects = mObjects;
2260 const flat_binder_object* flat
2261 = reinterpret_cast<flat_binder_object*>(data+objects[i]);
2262 release_object(proc, *flat, this, &mOpenAshmemSize);
2266 void Parcel::acquireObjects()
2268 const sp<ProcessState> proc(ProcessState::self());
2269 size_t i = mObjectsSize;
2270 uint8_t* const data = mData;
2271 binder_size_t* const objects = mObjects;
2274 const flat_binder_object* flat
2275 = reinterpret_cast<flat_binder_object*>(data+objects[i]);
2276 acquire_object(proc, *flat, this, &mOpenAshmemSize);
2280 void Parcel::freeData()
2286 void Parcel::freeDataNoInit()
2289 LOG_ALLOC("Parcel %p: freeing other owner data", this);
2290 //ALOGI("Freeing data ref of %p (pid=%d)", this, getpid());
2291 mOwner(this, mData, mDataSize, mObjects, mObjectsSize, mOwnerCookie);
2293 LOG_ALLOC("Parcel %p: freeing allocated data", this);
2296 LOG_ALLOC("Parcel %p: freeing with %zu capacity", this, mDataCapacity);
2297 pthread_mutex_lock(&gParcelGlobalAllocSizeLock);
2298 if (mDataCapacity <= gParcelGlobalAllocSize) {
2299 gParcelGlobalAllocSize = gParcelGlobalAllocSize - mDataCapacity;
2301 gParcelGlobalAllocSize = 0;
2303 if (gParcelGlobalAllocCount > 0) {
2304 gParcelGlobalAllocCount--;
2306 pthread_mutex_unlock(&gParcelGlobalAllocSizeLock);
2309 if (mObjects) free(mObjects);
2313 status_t Parcel::growData(size_t len)
2315 if (len > INT32_MAX) {
2316 // don't accept size_t values which may have come from an
2317 // inadvertent conversion from a negative int.
2321 size_t newSize = ((mDataSize+len)*3)/2;
2322 return (newSize <= mDataSize)
2323 ? (status_t) NO_MEMORY
2324 : continueWrite(newSize);
2327 status_t Parcel::restartWrite(size_t desired)
2329 if (desired > INT32_MAX) {
2330 // don't accept size_t values which may have come from an
2331 // inadvertent conversion from a negative int.
2337 return continueWrite(desired);
2340 uint8_t* data = (uint8_t*)realloc(mData, desired);
2341 if (!data && desired > mDataCapacity) {
2349 LOG_ALLOC("Parcel %p: restart from %zu to %zu capacity", this, mDataCapacity, desired);
2350 pthread_mutex_lock(&gParcelGlobalAllocSizeLock);
2351 gParcelGlobalAllocSize += desired;
2352 gParcelGlobalAllocSize -= mDataCapacity;
2354 gParcelGlobalAllocCount++;
2356 pthread_mutex_unlock(&gParcelGlobalAllocSizeLock);
2358 mDataCapacity = desired;
2361 mDataSize = mDataPos = 0;
2362 ALOGV("restartWrite Setting data size of %p to %zu", this, mDataSize);
2363 ALOGV("restartWrite Setting data pos of %p to %zu", this, mDataPos);
2367 mObjectsSize = mObjectsCapacity = 0;
2368 mNextObjectHint = 0;
2376 status_t Parcel::continueWrite(size_t desired)
2378 if (desired > INT32_MAX) {
2379 // don't accept size_t values which may have come from an
2380 // inadvertent conversion from a negative int.
2384 // If shrinking, first adjust for any objects that appear
2385 // after the new data size.
2386 size_t objectsSize = mObjectsSize;
2387 if (desired < mDataSize) {
2391 while (objectsSize > 0) {
2392 if (mObjects[objectsSize-1] < desired)
2400 // If the size is going to zero, just release the owner's data.
2406 // If there is a different owner, we need to take
2408 uint8_t* data = (uint8_t*)malloc(desired);
2413 binder_size_t* objects = NULL;
2416 objects = (binder_size_t*)calloc(objectsSize, sizeof(binder_size_t));
2424 // Little hack to only acquire references on objects
2425 // we will be keeping.
2426 size_t oldObjectsSize = mObjectsSize;
2427 mObjectsSize = objectsSize;
2429 mObjectsSize = oldObjectsSize;
2433 memcpy(data, mData, mDataSize < desired ? mDataSize : desired);
2435 if (objects && mObjects) {
2436 memcpy(objects, mObjects, objectsSize*sizeof(binder_size_t));
2438 //ALOGI("Freeing data ref of %p (pid=%d)", this, getpid());
2439 mOwner(this, mData, mDataSize, mObjects, mObjectsSize, mOwnerCookie);
2442 LOG_ALLOC("Parcel %p: taking ownership of %zu capacity", this, desired);
2443 pthread_mutex_lock(&gParcelGlobalAllocSizeLock);
2444 gParcelGlobalAllocSize += desired;
2445 gParcelGlobalAllocCount++;
2446 pthread_mutex_unlock(&gParcelGlobalAllocSizeLock);
2450 mDataSize = (mDataSize < desired) ? mDataSize : desired;
2451 ALOGV("continueWrite Setting data size of %p to %zu", this, mDataSize);
2452 mDataCapacity = desired;
2453 mObjectsSize = mObjectsCapacity = objectsSize;
2454 mNextObjectHint = 0;
2457 if (objectsSize < mObjectsSize) {
2458 // Need to release refs on any objects we are dropping.
2459 const sp<ProcessState> proc(ProcessState::self());
2460 for (size_t i=objectsSize; i<mObjectsSize; i++) {
2461 const flat_binder_object* flat
2462 = reinterpret_cast<flat_binder_object*>(mData+mObjects[i]);
2463 if (flat->type == BINDER_TYPE_FD) {
2464 // will need to rescan because we may have lopped off the only FDs
2467 release_object(proc, *flat, this, &mOpenAshmemSize);
2469 binder_size_t* objects =
2470 (binder_size_t*)realloc(mObjects, objectsSize*sizeof(binder_size_t));
2474 mObjectsSize = objectsSize;
2475 mNextObjectHint = 0;
2478 // We own the data, so we can just do a realloc().
2479 if (desired > mDataCapacity) {
2480 uint8_t* data = (uint8_t*)realloc(mData, desired);
2482 LOG_ALLOC("Parcel %p: continue from %zu to %zu capacity", this, mDataCapacity,
2484 pthread_mutex_lock(&gParcelGlobalAllocSizeLock);
2485 gParcelGlobalAllocSize += desired;
2486 gParcelGlobalAllocSize -= mDataCapacity;
2487 pthread_mutex_unlock(&gParcelGlobalAllocSizeLock);
2489 mDataCapacity = desired;
2490 } else if (desired > mDataCapacity) {
2495 if (mDataSize > desired) {
2496 mDataSize = desired;
2497 ALOGV("continueWrite Setting data size of %p to %zu", this, mDataSize);
2499 if (mDataPos > desired) {
2501 ALOGV("continueWrite Setting data pos of %p to %zu", this, mDataPos);
2506 // This is the first data. Easy!
2507 uint8_t* data = (uint8_t*)malloc(desired);
2513 if(!(mDataCapacity == 0 && mObjects == NULL
2514 && mObjectsCapacity == 0)) {
2515 ALOGE("continueWrite: %zu/%p/%zu/%zu", mDataCapacity, mObjects, mObjectsCapacity, desired);
2518 LOG_ALLOC("Parcel %p: allocating with %zu capacity", this, desired);
2519 pthread_mutex_lock(&gParcelGlobalAllocSizeLock);
2520 gParcelGlobalAllocSize += desired;
2521 gParcelGlobalAllocCount++;
2522 pthread_mutex_unlock(&gParcelGlobalAllocSizeLock);
2525 mDataSize = mDataPos = 0;
2526 ALOGV("continueWrite Setting data size of %p to %zu", this, mDataSize);
2527 ALOGV("continueWrite Setting data pos of %p to %zu", this, mDataPos);
2528 mDataCapacity = desired;
2534 void Parcel::initState()
2536 LOG_ALLOC("Parcel %p: initState", this);
2542 ALOGV("initState Setting data size of %p to %zu", this, mDataSize);
2543 ALOGV("initState Setting data pos of %p to %zu", this, mDataPos);
2546 mObjectsCapacity = 0;
2547 mNextObjectHint = 0;
2552 mOpenAshmemSize = 0;
2554 // racing multiple init leads only to multiple identical write
2556 struct rlimit result;
2557 if (!getrlimit(RLIMIT_NOFILE, &result)) {
2558 gMaxFds = (size_t)result.rlim_cur;
2559 //ALOGI("parcel fd limit set to %zu", gMaxFds);
2561 ALOGW("Unable to getrlimit: %s", strerror(errno));
2567 void Parcel::scanForFds() const
2569 bool hasFds = false;
2570 for (size_t i=0; i<mObjectsSize; i++) {
2571 const flat_binder_object* flat
2572 = reinterpret_cast<const flat_binder_object*>(mData + mObjects[i]);
2573 if (flat->type == BINDER_TYPE_FD) {
2582 size_t Parcel::getBlobAshmemSize() const
2584 // This used to return the size of all blobs that were written to ashmem, now we're returning
2585 // the ashmem currently referenced by this Parcel, which should be equivalent.
2586 // TODO: Remove method once ABI can be changed.
2587 return mOpenAshmemSize;
2590 size_t Parcel::getOpenAshmemSize() const
2592 return mOpenAshmemSize;
2595 // --- Parcel::Blob ---
2597 Parcel::Blob::Blob() :
2598 mFd(-1), mData(NULL), mSize(0), mMutable(false) {
2601 Parcel::Blob::~Blob() {
2605 void Parcel::Blob::release() {
2606 if (mFd != -1 && mData) {
2607 ::munmap(mData, mSize);
2612 void Parcel::Blob::init(int fd, void* data, size_t size, bool isMutable) {
2616 mMutable = isMutable;
2619 void Parcel::Blob::clear() {
2626 }; // namespace android