Parcel.cpp revision 70f3665f8272b2f6d05e77ff0c17683b4b7f82b7
1/*
2 * Copyright (C) 2005 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "Parcel"
18//#define LOG_NDEBUG 0
19
20#include <errno.h>
21#include <fcntl.h>
22#include <inttypes.h>
23#include <pthread.h>
24#include <stdint.h>
25#include <stdio.h>
26#include <stdlib.h>
27#include <sys/mman.h>
28#include <sys/stat.h>
29#include <sys/types.h>
30#include <unistd.h>
31
32#include <binder/Binder.h>
33#include <binder/BpBinder.h>
34#include <binder/IPCThreadState.h>
35#include <binder/Parcel.h>
36#include <binder/ProcessState.h>
37#include <binder/Status.h>
38#include <binder/TextOutput.h>
39
40#include <cutils/ashmem.h>
41#include <utils/Debug.h>
42#include <utils/Flattenable.h>
43#include <utils/Log.h>
44#include <utils/misc.h>
45#include <utils/String8.h>
46#include <utils/String16.h>
47
48#include <private/binder/binder_module.h>
49#include <private/binder/Static.h>
50
51#ifndef INT32_MAX
52#define INT32_MAX ((int32_t)(2147483647))
53#endif
54
55#define LOG_REFS(...)
56//#define LOG_REFS(...) ALOG(LOG_DEBUG, LOG_TAG, __VA_ARGS__)
57#define LOG_ALLOC(...)
58//#define LOG_ALLOC(...) ALOG(LOG_DEBUG, LOG_TAG, __VA_ARGS__)
59
60// ---------------------------------------------------------------------------
61
62// This macro should never be used at runtime, as a too large value
63// of s could cause an integer overflow. Instead, you should always
64// use the wrapper function pad_size()
65#define PAD_SIZE_UNSAFE(s) (((s)+3)&~3)
66
67static size_t pad_size(size_t s) {
68    if (s > (SIZE_T_MAX - 3)) {
69        abort();
70    }
71    return PAD_SIZE_UNSAFE(s);
72}
73
74// Note: must be kept in sync with android/os/StrictMode.java's PENALTY_GATHER
75#define STRICT_MODE_PENALTY_GATHER (0x40 << 16)
76
77// XXX This can be made public if we want to provide
78// support for typed data.
79struct small_flat_data
80{
81    uint32_t type;
82    uint32_t data;
83};
84
85namespace android {
86
87static pthread_mutex_t gParcelGlobalAllocSizeLock = PTHREAD_MUTEX_INITIALIZER;
88static size_t gParcelGlobalAllocSize = 0;
89static size_t gParcelGlobalAllocCount = 0;
90
91// Maximum size of a blob to transfer in-place.
92static const size_t BLOB_INPLACE_LIMIT = 16 * 1024;
93
94enum {
95    BLOB_INPLACE = 0,
96    BLOB_ASHMEM_IMMUTABLE = 1,
97    BLOB_ASHMEM_MUTABLE = 2,
98};
99
100static dev_t ashmem_rdev()
101{
102    static dev_t __ashmem_rdev;
103    static pthread_mutex_t __ashmem_rdev_lock = PTHREAD_MUTEX_INITIALIZER;
104
105    pthread_mutex_lock(&__ashmem_rdev_lock);
106
107    dev_t rdev = __ashmem_rdev;
108    if (!rdev) {
109        int fd = TEMP_FAILURE_RETRY(open("/dev/ashmem", O_RDONLY));
110        if (fd >= 0) {
111            struct stat st;
112
113            int ret = TEMP_FAILURE_RETRY(fstat(fd, &st));
114            close(fd);
115            if ((ret >= 0) && S_ISCHR(st.st_mode)) {
116                rdev = __ashmem_rdev = st.st_rdev;
117            }
118        }
119    }
120
121    pthread_mutex_unlock(&__ashmem_rdev_lock);
122
123    return rdev;
124}
125
126void acquire_object(const sp<ProcessState>& proc,
127    const flat_binder_object& obj, const void* who, size_t* outAshmemSize)
128{
129    switch (obj.type) {
130        case BINDER_TYPE_BINDER:
131            if (obj.binder) {
132                LOG_REFS("Parcel %p acquiring reference on local %p", who, obj.cookie);
133                reinterpret_cast<IBinder*>(obj.cookie)->incStrong(who);
134            }
135            return;
136        case BINDER_TYPE_WEAK_BINDER:
137            if (obj.binder)
138                reinterpret_cast<RefBase::weakref_type*>(obj.binder)->incWeak(who);
139            return;
140        case BINDER_TYPE_HANDLE: {
141            const sp<IBinder> b = proc->getStrongProxyForHandle(obj.handle);
142            if (b != NULL) {
143                LOG_REFS("Parcel %p acquiring reference on remote %p", who, b.get());
144                b->incStrong(who);
145            }
146            return;
147        }
148        case BINDER_TYPE_WEAK_HANDLE: {
149            const wp<IBinder> b = proc->getWeakProxyForHandle(obj.handle);
150            if (b != NULL) b.get_refs()->incWeak(who);
151            return;
152        }
153        case BINDER_TYPE_FD: {
154            if ((obj.cookie != 0) && (outAshmemSize != NULL)) {
155                struct stat st;
156                int ret = fstat(obj.handle, &st);
157                if (!ret && S_ISCHR(st.st_mode) && (st.st_rdev == ashmem_rdev())) {
158                    // If we own an ashmem fd, keep track of how much memory it refers to.
159                    int size = ashmem_get_size_region(obj.handle);
160                    if (size > 0) {
161                        *outAshmemSize += size;
162                    }
163                }
164            }
165            return;
166        }
167    }
168
169    ALOGD("Invalid object type 0x%08x", obj.type);
170}
171
172void acquire_object(const sp<ProcessState>& proc,
173    const flat_binder_object& obj, const void* who)
174{
175    acquire_object(proc, obj, who, NULL);
176}
177
178static void release_object(const sp<ProcessState>& proc,
179    const flat_binder_object& obj, const void* who, size_t* outAshmemSize)
180{
181    switch (obj.type) {
182        case BINDER_TYPE_BINDER:
183            if (obj.binder) {
184                LOG_REFS("Parcel %p releasing reference on local %p", who, obj.cookie);
185                reinterpret_cast<IBinder*>(obj.cookie)->decStrong(who);
186            }
187            return;
188        case BINDER_TYPE_WEAK_BINDER:
189            if (obj.binder)
190                reinterpret_cast<RefBase::weakref_type*>(obj.binder)->decWeak(who);
191            return;
192        case BINDER_TYPE_HANDLE: {
193            const sp<IBinder> b = proc->getStrongProxyForHandle(obj.handle);
194            if (b != NULL) {
195                LOG_REFS("Parcel %p releasing reference on remote %p", who, b.get());
196                b->decStrong(who);
197            }
198            return;
199        }
200        case BINDER_TYPE_WEAK_HANDLE: {
201            const wp<IBinder> b = proc->getWeakProxyForHandle(obj.handle);
202            if (b != NULL) b.get_refs()->decWeak(who);
203            return;
204        }
205        case BINDER_TYPE_FD: {
206            if (obj.cookie != 0) { // owned
207                if (outAshmemSize != NULL) {
208                    struct stat st;
209                    int ret = fstat(obj.handle, &st);
210                    if (!ret && S_ISCHR(st.st_mode) && (st.st_rdev == ashmem_rdev())) {
211                        int size = ashmem_get_size_region(obj.handle);
212                        if (size > 0) {
213                            *outAshmemSize -= size;
214                        }
215                    }
216                }
217
218                close(obj.handle);
219            }
220            return;
221        }
222    }
223
224    ALOGE("Invalid object type 0x%08x", obj.type);
225}
226
227void release_object(const sp<ProcessState>& proc,
228    const flat_binder_object& obj, const void* who)
229{
230    release_object(proc, obj, who, NULL);
231}
232
233inline static status_t finish_flatten_binder(
234    const sp<IBinder>& /*binder*/, const flat_binder_object& flat, Parcel* out)
235{
236    return out->writeObject(flat, false);
237}
238
239status_t flatten_binder(const sp<ProcessState>& /*proc*/,
240    const sp<IBinder>& binder, Parcel* out)
241{
242    flat_binder_object obj;
243
244    obj.flags = 0x7f | FLAT_BINDER_FLAG_ACCEPTS_FDS;
245    if (binder != NULL) {
246        IBinder *local = binder->localBinder();
247        if (!local) {
248            BpBinder *proxy = binder->remoteBinder();
249            if (proxy == NULL) {
250                ALOGE("null proxy");
251            }
252            const int32_t handle = proxy ? proxy->handle() : 0;
253            obj.type = BINDER_TYPE_HANDLE;
254            obj.binder = 0; /* Don't pass uninitialized stack data to a remote process */
255            obj.handle = handle;
256            obj.cookie = 0;
257        } else {
258            obj.type = BINDER_TYPE_BINDER;
259            obj.binder = reinterpret_cast<uintptr_t>(local->getWeakRefs());
260            obj.cookie = reinterpret_cast<uintptr_t>(local);
261        }
262    } else {
263        obj.type = BINDER_TYPE_BINDER;
264        obj.binder = 0;
265        obj.cookie = 0;
266    }
267
268    return finish_flatten_binder(binder, obj, out);
269}
270
271status_t flatten_binder(const sp<ProcessState>& /*proc*/,
272    const wp<IBinder>& binder, Parcel* out)
273{
274    flat_binder_object obj;
275
276    obj.flags = 0x7f | FLAT_BINDER_FLAG_ACCEPTS_FDS;
277    if (binder != NULL) {
278        sp<IBinder> real = binder.promote();
279        if (real != NULL) {
280            IBinder *local = real->localBinder();
281            if (!local) {
282                BpBinder *proxy = real->remoteBinder();
283                if (proxy == NULL) {
284                    ALOGE("null proxy");
285                }
286                const int32_t handle = proxy ? proxy->handle() : 0;
287                obj.type = BINDER_TYPE_WEAK_HANDLE;
288                obj.binder = 0; /* Don't pass uninitialized stack data to a remote process */
289                obj.handle = handle;
290                obj.cookie = 0;
291            } else {
292                obj.type = BINDER_TYPE_WEAK_BINDER;
293                obj.binder = reinterpret_cast<uintptr_t>(binder.get_refs());
294                obj.cookie = reinterpret_cast<uintptr_t>(binder.unsafe_get());
295            }
296            return finish_flatten_binder(real, obj, out);
297        }
298
299        // XXX How to deal?  In order to flatten the given binder,
300        // we need to probe it for information, which requires a primary
301        // reference...  but we don't have one.
302        //
303        // The OpenBinder implementation uses a dynamic_cast<> here,
304        // but we can't do that with the different reference counting
305        // implementation we are using.
306        ALOGE("Unable to unflatten Binder weak reference!");
307        obj.type = BINDER_TYPE_BINDER;
308        obj.binder = 0;
309        obj.cookie = 0;
310        return finish_flatten_binder(NULL, obj, out);
311
312    } else {
313        obj.type = BINDER_TYPE_BINDER;
314        obj.binder = 0;
315        obj.cookie = 0;
316        return finish_flatten_binder(NULL, obj, out);
317    }
318}
319
320inline static status_t finish_unflatten_binder(
321    BpBinder* /*proxy*/, const flat_binder_object& /*flat*/,
322    const Parcel& /*in*/)
323{
324    return NO_ERROR;
325}
326
327status_t unflatten_binder(const sp<ProcessState>& proc,
328    const Parcel& in, sp<IBinder>* out)
329{
330    const flat_binder_object* flat = in.readObject(false);
331
332    if (flat) {
333        switch (flat->type) {
334            case BINDER_TYPE_BINDER:
335                *out = reinterpret_cast<IBinder*>(flat->cookie);
336                return finish_unflatten_binder(NULL, *flat, in);
337            case BINDER_TYPE_HANDLE:
338                *out = proc->getStrongProxyForHandle(flat->handle);
339                return finish_unflatten_binder(
340                    static_cast<BpBinder*>(out->get()), *flat, in);
341        }
342    }
343    return BAD_TYPE;
344}
345
346status_t unflatten_binder(const sp<ProcessState>& proc,
347    const Parcel& in, wp<IBinder>* out)
348{
349    const flat_binder_object* flat = in.readObject(false);
350
351    if (flat) {
352        switch (flat->type) {
353            case BINDER_TYPE_BINDER:
354                *out = reinterpret_cast<IBinder*>(flat->cookie);
355                return finish_unflatten_binder(NULL, *flat, in);
356            case BINDER_TYPE_WEAK_BINDER:
357                if (flat->binder != 0) {
358                    out->set_object_and_refs(
359                        reinterpret_cast<IBinder*>(flat->cookie),
360                        reinterpret_cast<RefBase::weakref_type*>(flat->binder));
361                } else {
362                    *out = NULL;
363                }
364                return finish_unflatten_binder(NULL, *flat, in);
365            case BINDER_TYPE_HANDLE:
366            case BINDER_TYPE_WEAK_HANDLE:
367                *out = proc->getWeakProxyForHandle(flat->handle);
368                return finish_unflatten_binder(
369                    static_cast<BpBinder*>(out->unsafe_get()), *flat, in);
370        }
371    }
372    return BAD_TYPE;
373}
374
375// ---------------------------------------------------------------------------
376
377Parcel::Parcel()
378{
379    LOG_ALLOC("Parcel %p: constructing", this);
380    initState();
381}
382
383Parcel::~Parcel()
384{
385    freeDataNoInit();
386    LOG_ALLOC("Parcel %p: destroyed", this);
387}
388
389size_t Parcel::getGlobalAllocSize() {
390    pthread_mutex_lock(&gParcelGlobalAllocSizeLock);
391    size_t size = gParcelGlobalAllocSize;
392    pthread_mutex_unlock(&gParcelGlobalAllocSizeLock);
393    return size;
394}
395
396size_t Parcel::getGlobalAllocCount() {
397    pthread_mutex_lock(&gParcelGlobalAllocSizeLock);
398    size_t count = gParcelGlobalAllocCount;
399    pthread_mutex_unlock(&gParcelGlobalAllocSizeLock);
400    return count;
401}
402
403const uint8_t* Parcel::data() const
404{
405    return mData;
406}
407
408size_t Parcel::dataSize() const
409{
410    return (mDataSize > mDataPos ? mDataSize : mDataPos);
411}
412
413size_t Parcel::dataAvail() const
414{
415    // TODO: decide what to do about the possibility that this can
416    // report an available-data size that exceeds a Java int's max
417    // positive value, causing havoc.  Fortunately this will only
418    // happen if someone constructs a Parcel containing more than two
419    // gigabytes of data, which on typical phone hardware is simply
420    // not possible.
421    return dataSize() - dataPosition();
422}
423
424size_t Parcel::dataPosition() const
425{
426    return mDataPos;
427}
428
429size_t Parcel::dataCapacity() const
430{
431    return mDataCapacity;
432}
433
434status_t Parcel::setDataSize(size_t size)
435{
436    if (size > INT32_MAX) {
437        // don't accept size_t values which may have come from an
438        // inadvertent conversion from a negative int.
439        return BAD_VALUE;
440    }
441
442    status_t err;
443    err = continueWrite(size);
444    if (err == NO_ERROR) {
445        mDataSize = size;
446        ALOGV("setDataSize Setting data size of %p to %zu", this, mDataSize);
447    }
448    return err;
449}
450
451void Parcel::setDataPosition(size_t pos) const
452{
453    if (pos > INT32_MAX) {
454        // don't accept size_t values which may have come from an
455        // inadvertent conversion from a negative int.
456        abort();
457    }
458
459    mDataPos = pos;
460    mNextObjectHint = 0;
461}
462
463status_t Parcel::setDataCapacity(size_t size)
464{
465    if (size > INT32_MAX) {
466        // don't accept size_t values which may have come from an
467        // inadvertent conversion from a negative int.
468        return BAD_VALUE;
469    }
470
471    if (size > mDataCapacity) return continueWrite(size);
472    return NO_ERROR;
473}
474
475status_t Parcel::setData(const uint8_t* buffer, size_t len)
476{
477    if (len > INT32_MAX) {
478        // don't accept size_t values which may have come from an
479        // inadvertent conversion from a negative int.
480        return BAD_VALUE;
481    }
482
483    status_t err = restartWrite(len);
484    if (err == NO_ERROR) {
485        memcpy(const_cast<uint8_t*>(data()), buffer, len);
486        mDataSize = len;
487        mFdsKnown = false;
488    }
489    return err;
490}
491
492status_t Parcel::appendFrom(const Parcel *parcel, size_t offset, size_t len)
493{
494    const sp<ProcessState> proc(ProcessState::self());
495    status_t err;
496    const uint8_t *data = parcel->mData;
497    const binder_size_t *objects = parcel->mObjects;
498    size_t size = parcel->mObjectsSize;
499    int startPos = mDataPos;
500    int firstIndex = -1, lastIndex = -2;
501
502    if (len == 0) {
503        return NO_ERROR;
504    }
505
506    if (len > INT32_MAX) {
507        // don't accept size_t values which may have come from an
508        // inadvertent conversion from a negative int.
509        return BAD_VALUE;
510    }
511
512    // range checks against the source parcel size
513    if ((offset > parcel->mDataSize)
514            || (len > parcel->mDataSize)
515            || (offset + len > parcel->mDataSize)) {
516        return BAD_VALUE;
517    }
518
519    // Count objects in range
520    for (int i = 0; i < (int) size; i++) {
521        size_t off = objects[i];
522        if ((off >= offset) && (off + sizeof(flat_binder_object) <= offset + len)) {
523            if (firstIndex == -1) {
524                firstIndex = i;
525            }
526            lastIndex = i;
527        }
528    }
529    int numObjects = lastIndex - firstIndex + 1;
530
531    if ((mDataSize+len) > mDataCapacity) {
532        // grow data
533        err = growData(len);
534        if (err != NO_ERROR) {
535            return err;
536        }
537    }
538
539    // append data
540    memcpy(mData + mDataPos, data + offset, len);
541    mDataPos += len;
542    mDataSize += len;
543
544    err = NO_ERROR;
545
546    if (numObjects > 0) {
547        // grow objects
548        if (mObjectsCapacity < mObjectsSize + numObjects) {
549            size_t newSize = ((mObjectsSize + numObjects)*3)/2;
550            if (newSize < mObjectsSize) return NO_MEMORY;   // overflow
551            binder_size_t *objects =
552                (binder_size_t*)realloc(mObjects, newSize*sizeof(binder_size_t));
553            if (objects == (binder_size_t*)0) {
554                return NO_MEMORY;
555            }
556            mObjects = objects;
557            mObjectsCapacity = newSize;
558        }
559
560        // append and acquire objects
561        int idx = mObjectsSize;
562        for (int i = firstIndex; i <= lastIndex; i++) {
563            size_t off = objects[i] - offset + startPos;
564            mObjects[idx++] = off;
565            mObjectsSize++;
566
567            flat_binder_object* flat
568                = reinterpret_cast<flat_binder_object*>(mData + off);
569            acquire_object(proc, *flat, this, &mOpenAshmemSize);
570
571            if (flat->type == BINDER_TYPE_FD) {
572                // If this is a file descriptor, we need to dup it so the
573                // new Parcel now owns its own fd, and can declare that we
574                // officially know we have fds.
575                flat->handle = dup(flat->handle);
576                flat->cookie = 1;
577                mHasFds = mFdsKnown = true;
578                if (!mAllowFds) {
579                    err = FDS_NOT_ALLOWED;
580                }
581            }
582        }
583    }
584
585    return err;
586}
587
588bool Parcel::allowFds() const
589{
590    return mAllowFds;
591}
592
593bool Parcel::pushAllowFds(bool allowFds)
594{
595    const bool origValue = mAllowFds;
596    if (!allowFds) {
597        mAllowFds = false;
598    }
599    return origValue;
600}
601
602void Parcel::restoreAllowFds(bool lastValue)
603{
604    mAllowFds = lastValue;
605}
606
607bool Parcel::hasFileDescriptors() const
608{
609    if (!mFdsKnown) {
610        scanForFds();
611    }
612    return mHasFds;
613}
614
615// Write RPC headers.  (previously just the interface token)
616status_t Parcel::writeInterfaceToken(const String16& interface)
617{
618    writeInt32(IPCThreadState::self()->getStrictModePolicy() |
619               STRICT_MODE_PENALTY_GATHER);
620    // currently the interface identification token is just its name as a string
621    return writeString16(interface);
622}
623
624bool Parcel::checkInterface(IBinder* binder) const
625{
626    return enforceInterface(binder->getInterfaceDescriptor());
627}
628
629bool Parcel::enforceInterface(const String16& interface,
630                              IPCThreadState* threadState) const
631{
632    int32_t strictPolicy = readInt32();
633    if (threadState == NULL) {
634        threadState = IPCThreadState::self();
635    }
636    if ((threadState->getLastTransactionBinderFlags() &
637         IBinder::FLAG_ONEWAY) != 0) {
638      // For one-way calls, the callee is running entirely
639      // disconnected from the caller, so disable StrictMode entirely.
640      // Not only does disk/network usage not impact the caller, but
641      // there's no way to commuicate back any violations anyway.
642      threadState->setStrictModePolicy(0);
643    } else {
644      threadState->setStrictModePolicy(strictPolicy);
645    }
646    const String16 str(readString16());
647    if (str == interface) {
648        return true;
649    } else {
650        ALOGW("**** enforceInterface() expected '%s' but read '%s'",
651                String8(interface).string(), String8(str).string());
652        return false;
653    }
654}
655
656const binder_size_t* Parcel::objects() const
657{
658    return mObjects;
659}
660
661size_t Parcel::objectsCount() const
662{
663    return mObjectsSize;
664}
665
666status_t Parcel::errorCheck() const
667{
668    return mError;
669}
670
671void Parcel::setError(status_t err)
672{
673    mError = err;
674}
675
676status_t Parcel::finishWrite(size_t len)
677{
678    if (len > INT32_MAX) {
679        // don't accept size_t values which may have come from an
680        // inadvertent conversion from a negative int.
681        return BAD_VALUE;
682    }
683
684    //printf("Finish write of %d\n", len);
685    mDataPos += len;
686    ALOGV("finishWrite Setting data pos of %p to %zu", this, mDataPos);
687    if (mDataPos > mDataSize) {
688        mDataSize = mDataPos;
689        ALOGV("finishWrite Setting data size of %p to %zu", this, mDataSize);
690    }
691    //printf("New pos=%d, size=%d\n", mDataPos, mDataSize);
692    return NO_ERROR;
693}
694
695status_t Parcel::writeUnpadded(const void* data, size_t len)
696{
697    if (len > INT32_MAX) {
698        // don't accept size_t values which may have come from an
699        // inadvertent conversion from a negative int.
700        return BAD_VALUE;
701    }
702
703    size_t end = mDataPos + len;
704    if (end < mDataPos) {
705        // integer overflow
706        return BAD_VALUE;
707    }
708
709    if (end <= mDataCapacity) {
710restart_write:
711        memcpy(mData+mDataPos, data, len);
712        return finishWrite(len);
713    }
714
715    status_t err = growData(len);
716    if (err == NO_ERROR) goto restart_write;
717    return err;
718}
719
720status_t Parcel::write(const void* data, size_t len)
721{
722    if (len > INT32_MAX) {
723        // don't accept size_t values which may have come from an
724        // inadvertent conversion from a negative int.
725        return BAD_VALUE;
726    }
727
728    void* const d = writeInplace(len);
729    if (d) {
730        memcpy(d, data, len);
731        return NO_ERROR;
732    }
733    return mError;
734}
735
736void* Parcel::writeInplace(size_t len)
737{
738    if (len > INT32_MAX) {
739        // don't accept size_t values which may have come from an
740        // inadvertent conversion from a negative int.
741        return NULL;
742    }
743
744    const size_t padded = pad_size(len);
745
746    // sanity check for integer overflow
747    if (mDataPos+padded < mDataPos) {
748        return NULL;
749    }
750
751    if ((mDataPos+padded) <= mDataCapacity) {
752restart_write:
753        //printf("Writing %ld bytes, padded to %ld\n", len, padded);
754        uint8_t* const data = mData+mDataPos;
755
756        // Need to pad at end?
757        if (padded != len) {
758#if BYTE_ORDER == BIG_ENDIAN
759            static const uint32_t mask[4] = {
760                0x00000000, 0xffffff00, 0xffff0000, 0xff000000
761            };
762#endif
763#if BYTE_ORDER == LITTLE_ENDIAN
764            static const uint32_t mask[4] = {
765                0x00000000, 0x00ffffff, 0x0000ffff, 0x000000ff
766            };
767#endif
768            //printf("Applying pad mask: %p to %p\n", (void*)mask[padded-len],
769            //    *reinterpret_cast<void**>(data+padded-4));
770            *reinterpret_cast<uint32_t*>(data+padded-4) &= mask[padded-len];
771        }
772
773        finishWrite(padded);
774        return data;
775    }
776
777    status_t err = growData(padded);
778    if (err == NO_ERROR) goto restart_write;
779    return NULL;
780}
781
782status_t Parcel::writeUtf8AsUtf16(const std::string& str) {
783    const uint8_t* strData = (uint8_t*)str.data();
784    const size_t strLen= str.length();
785    const ssize_t utf16Len = utf8_to_utf16_length(strData, strLen);
786    if (utf16Len < 0 || utf16Len> std::numeric_limits<int32_t>::max()) {
787        return BAD_VALUE;
788    }
789
790    status_t err = writeInt32(utf16Len);
791    if (err) {
792        return err;
793    }
794
795    // Allocate enough bytes to hold our converted string and its terminating NULL.
796    void* dst = writeInplace((utf16Len + 1) * sizeof(char16_t));
797    if (!dst) {
798        return NO_MEMORY;
799    }
800
801    utf8_to_utf16(strData, strLen, (char16_t*)dst);
802
803    return NO_ERROR;
804}
805
806status_t Parcel::writeUtf8AsUtf16(const std::unique_ptr<std::string>& str) {
807  if (!str) {
808    return writeInt32(-1);
809  }
810  return writeUtf8AsUtf16(*str);
811}
812
813status_t Parcel::writeByteVector(const std::unique_ptr<std::vector<int8_t>>& val)
814{
815    if (!val) {
816        return writeInt32(-1);
817    }
818
819    return writeByteVector(*val);
820}
821
822status_t Parcel::writeByteVector(const std::vector<int8_t>& val)
823{
824    status_t status;
825    if (val.size() > std::numeric_limits<int32_t>::max()) {
826        status = BAD_VALUE;
827        return status;
828    }
829
830    status = writeInt32(val.size());
831    if (status != OK) {
832        return status;
833    }
834
835    void* data = writeInplace(val.size());
836    if (!data) {
837        status = BAD_VALUE;
838        return status;
839    }
840
841    memcpy(data, val.data(), val.size());
842    return status;
843}
844
845status_t Parcel::writeInt32Vector(const std::vector<int32_t>& val)
846{
847    return writeTypedVector(val, &Parcel::writeInt32);
848}
849
850status_t Parcel::writeInt32Vector(const std::unique_ptr<std::vector<int32_t>>& val)
851{
852    return writeNullableTypedVector(val, &Parcel::writeInt32);
853}
854
855status_t Parcel::writeInt64Vector(const std::vector<int64_t>& val)
856{
857    return writeTypedVector(val, &Parcel::writeInt64);
858}
859
860status_t Parcel::writeInt64Vector(const std::unique_ptr<std::vector<int64_t>>& val)
861{
862    return writeNullableTypedVector(val, &Parcel::writeInt64);
863}
864
865status_t Parcel::writeFloatVector(const std::vector<float>& val)
866{
867    return writeTypedVector(val, &Parcel::writeFloat);
868}
869
870status_t Parcel::writeFloatVector(const std::unique_ptr<std::vector<float>>& val)
871{
872    return writeNullableTypedVector(val, &Parcel::writeFloat);
873}
874
875status_t Parcel::writeDoubleVector(const std::vector<double>& val)
876{
877    return writeTypedVector(val, &Parcel::writeDouble);
878}
879
880status_t Parcel::writeDoubleVector(const std::unique_ptr<std::vector<double>>& val)
881{
882    return writeNullableTypedVector(val, &Parcel::writeDouble);
883}
884
885status_t Parcel::writeBoolVector(const std::vector<bool>& val)
886{
887    return writeTypedVector(val, &Parcel::writeBool);
888}
889
890status_t Parcel::writeBoolVector(const std::unique_ptr<std::vector<bool>>& val)
891{
892    return writeNullableTypedVector(val, &Parcel::writeBool);
893}
894
895status_t Parcel::writeCharVector(const std::vector<char16_t>& val)
896{
897    return writeTypedVector(val, &Parcel::writeChar);
898}
899
900status_t Parcel::writeCharVector(const std::unique_ptr<std::vector<char16_t>>& val)
901{
902    return writeNullableTypedVector(val, &Parcel::writeChar);
903}
904
905status_t Parcel::writeString16Vector(const std::vector<String16>& val)
906{
907    return writeTypedVector(val, &Parcel::writeString16);
908}
909
910status_t Parcel::writeString16Vector(
911        const std::unique_ptr<std::vector<std::unique_ptr<String16>>>& val)
912{
913    return writeNullableTypedVector(val, &Parcel::writeString16);
914}
915
916status_t Parcel::writeUtf8VectorAsUtf16Vector(
917                        const std::unique_ptr<std::vector<std::unique_ptr<std::string>>>& val) {
918    return writeNullableTypedVector(val, &Parcel::writeUtf8AsUtf16);
919}
920
921status_t Parcel::writeUtf8VectorAsUtf16Vector(const std::vector<std::string>& val) {
922    return writeTypedVector(val, &Parcel::writeUtf8AsUtf16);
923}
924
925status_t Parcel::writeInt32(int32_t val)
926{
927    return writeAligned(val);
928}
929
930status_t Parcel::writeUint32(uint32_t val)
931{
932    return writeAligned(val);
933}
934
935status_t Parcel::writeInt32Array(size_t len, const int32_t *val) {
936    if (len > INT32_MAX) {
937        // don't accept size_t values which may have come from an
938        // inadvertent conversion from a negative int.
939        return BAD_VALUE;
940    }
941
942    if (!val) {
943        return writeInt32(-1);
944    }
945    status_t ret = writeInt32(static_cast<uint32_t>(len));
946    if (ret == NO_ERROR) {
947        ret = write(val, len * sizeof(*val));
948    }
949    return ret;
950}
951status_t Parcel::writeByteArray(size_t len, const uint8_t *val) {
952    if (len > INT32_MAX) {
953        // don't accept size_t values which may have come from an
954        // inadvertent conversion from a negative int.
955        return BAD_VALUE;
956    }
957
958    if (!val) {
959        return writeInt32(-1);
960    }
961    status_t ret = writeInt32(static_cast<uint32_t>(len));
962    if (ret == NO_ERROR) {
963        ret = write(val, len * sizeof(*val));
964    }
965    return ret;
966}
967
968status_t Parcel::writeBool(bool val)
969{
970    return writeInt32(int32_t(val));
971}
972
973status_t Parcel::writeChar(char16_t val)
974{
975    return writeInt32(int32_t(val));
976}
977
978status_t Parcel::writeByte(int8_t val)
979{
980    return writeInt32(int32_t(val));
981}
982
983status_t Parcel::writeInt64(int64_t val)
984{
985    return writeAligned(val);
986}
987
988status_t Parcel::writeUint64(uint64_t val)
989{
990    return writeAligned(val);
991}
992
993status_t Parcel::writePointer(uintptr_t val)
994{
995    return writeAligned<binder_uintptr_t>(val);
996}
997
998status_t Parcel::writeFloat(float val)
999{
1000    return writeAligned(val);
1001}
1002
1003#if defined(__mips__) && defined(__mips_hard_float)
1004
1005status_t Parcel::writeDouble(double val)
1006{
1007    union {
1008        double d;
1009        unsigned long long ll;
1010    } u;
1011    u.d = val;
1012    return writeAligned(u.ll);
1013}
1014
1015#else
1016
1017status_t Parcel::writeDouble(double val)
1018{
1019    return writeAligned(val);
1020}
1021
1022#endif
1023
1024status_t Parcel::writeCString(const char* str)
1025{
1026    return write(str, strlen(str)+1);
1027}
1028
1029status_t Parcel::writeString8(const String8& str)
1030{
1031    status_t err = writeInt32(str.bytes());
1032    // only write string if its length is more than zero characters,
1033    // as readString8 will only read if the length field is non-zero.
1034    // this is slightly different from how writeString16 works.
1035    if (str.bytes() > 0 && err == NO_ERROR) {
1036        err = write(str.string(), str.bytes()+1);
1037    }
1038    return err;
1039}
1040
1041status_t Parcel::writeString16(const std::unique_ptr<String16>& str)
1042{
1043    if (!str) {
1044        return writeInt32(-1);
1045    }
1046
1047    return writeString16(*str);
1048}
1049
1050status_t Parcel::writeString16(const String16& str)
1051{
1052    return writeString16(str.string(), str.size());
1053}
1054
1055status_t Parcel::writeString16(const char16_t* str, size_t len)
1056{
1057    if (str == NULL) return writeInt32(-1);
1058
1059    status_t err = writeInt32(len);
1060    if (err == NO_ERROR) {
1061        len *= sizeof(char16_t);
1062        uint8_t* data = (uint8_t*)writeInplace(len+sizeof(char16_t));
1063        if (data) {
1064            memcpy(data, str, len);
1065            *reinterpret_cast<char16_t*>(data+len) = 0;
1066            return NO_ERROR;
1067        }
1068        err = mError;
1069    }
1070    return err;
1071}
1072
1073status_t Parcel::writeStrongBinder(const sp<IBinder>& val)
1074{
1075    return flatten_binder(ProcessState::self(), val, this);
1076}
1077
1078status_t Parcel::writeStrongBinderVector(const std::vector<sp<IBinder>>& val)
1079{
1080    return writeTypedVector(val, &Parcel::writeStrongBinder);
1081}
1082
1083status_t Parcel::writeStrongBinderVector(const std::unique_ptr<std::vector<sp<IBinder>>>& val)
1084{
1085    return writeNullableTypedVector(val, &Parcel::writeStrongBinder);
1086}
1087
1088status_t Parcel::readStrongBinderVector(std::unique_ptr<std::vector<sp<IBinder>>>* val) const {
1089    return readNullableTypedVector(val, &Parcel::readStrongBinder);
1090}
1091
1092status_t Parcel::readStrongBinderVector(std::vector<sp<IBinder>>* val) const {
1093    return readTypedVector(val, &Parcel::readStrongBinder);
1094}
1095
1096status_t Parcel::writeWeakBinder(const wp<IBinder>& val)
1097{
1098    return flatten_binder(ProcessState::self(), val, this);
1099}
1100
1101status_t Parcel::writeRawNullableParcelable(const Parcelable* parcelable) {
1102    if (!parcelable) {
1103        return writeInt32(0);
1104    }
1105
1106    return writeParcelable(*parcelable);
1107}
1108
1109status_t Parcel::writeParcelable(const Parcelable& parcelable) {
1110    status_t status = writeInt32(1);  // parcelable is not null.
1111    if (status != OK) {
1112        return status;
1113    }
1114    return parcelable.writeToParcel(this);
1115}
1116
1117status_t Parcel::writeNativeHandle(const native_handle* handle)
1118{
1119    if (!handle || handle->version != sizeof(native_handle))
1120        return BAD_TYPE;
1121
1122    status_t err;
1123    err = writeInt32(handle->numFds);
1124    if (err != NO_ERROR) return err;
1125
1126    err = writeInt32(handle->numInts);
1127    if (err != NO_ERROR) return err;
1128
1129    for (int i=0 ; err==NO_ERROR && i<handle->numFds ; i++)
1130        err = writeDupFileDescriptor(handle->data[i]);
1131
1132    if (err != NO_ERROR) {
1133        ALOGD("write native handle, write dup fd failed");
1134        return err;
1135    }
1136    err = write(handle->data + handle->numFds, sizeof(int)*handle->numInts);
1137    return err;
1138}
1139
1140status_t Parcel::writeFileDescriptor(int fd, bool takeOwnership)
1141{
1142    flat_binder_object obj;
1143    obj.type = BINDER_TYPE_FD;
1144    obj.flags = 0x7f | FLAT_BINDER_FLAG_ACCEPTS_FDS;
1145    obj.binder = 0; /* Don't pass uninitialized stack data to a remote process */
1146    obj.handle = fd;
1147    obj.cookie = takeOwnership ? 1 : 0;
1148    return writeObject(obj, true);
1149}
1150
1151status_t Parcel::writeDupFileDescriptor(int fd)
1152{
1153    int dupFd = dup(fd);
1154    if (dupFd < 0) {
1155        return -errno;
1156    }
1157    status_t err = writeFileDescriptor(dupFd, true /*takeOwnership*/);
1158    if (err != OK) {
1159        close(dupFd);
1160    }
1161    return err;
1162}
1163
1164status_t Parcel::writeUniqueFileDescriptor(const ScopedFd& fd) {
1165    return writeDupFileDescriptor(fd.get());
1166}
1167
1168status_t Parcel::writeUniqueFileDescriptorVector(const std::vector<ScopedFd>& val) {
1169    return writeTypedVector(val, &Parcel::writeUniqueFileDescriptor);
1170}
1171
1172status_t Parcel::writeUniqueFileDescriptorVector(const std::unique_ptr<std::vector<ScopedFd>>& val) {
1173    return writeNullableTypedVector(val, &Parcel::writeUniqueFileDescriptor);
1174}
1175
1176status_t Parcel::writeBlob(size_t len, bool mutableCopy, WritableBlob* outBlob)
1177{
1178    if (len > INT32_MAX) {
1179        // don't accept size_t values which may have come from an
1180        // inadvertent conversion from a negative int.
1181        return BAD_VALUE;
1182    }
1183
1184    status_t status;
1185    if (!mAllowFds || len <= BLOB_INPLACE_LIMIT) {
1186        ALOGV("writeBlob: write in place");
1187        status = writeInt32(BLOB_INPLACE);
1188        if (status) return status;
1189
1190        void* ptr = writeInplace(len);
1191        if (!ptr) return NO_MEMORY;
1192
1193        outBlob->init(-1, ptr, len, false);
1194        return NO_ERROR;
1195    }
1196
1197    ALOGV("writeBlob: write to ashmem");
1198    int fd = ashmem_create_region("Parcel Blob", len);
1199    if (fd < 0) return NO_MEMORY;
1200
1201    int result = ashmem_set_prot_region(fd, PROT_READ | PROT_WRITE);
1202    if (result < 0) {
1203        status = result;
1204    } else {
1205        void* ptr = ::mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
1206        if (ptr == MAP_FAILED) {
1207            status = -errno;
1208        } else {
1209            if (!mutableCopy) {
1210                result = ashmem_set_prot_region(fd, PROT_READ);
1211            }
1212            if (result < 0) {
1213                status = result;
1214            } else {
1215                status = writeInt32(mutableCopy ? BLOB_ASHMEM_MUTABLE : BLOB_ASHMEM_IMMUTABLE);
1216                if (!status) {
1217                    status = writeFileDescriptor(fd, true /*takeOwnership*/);
1218                    if (!status) {
1219                        outBlob->init(fd, ptr, len, mutableCopy);
1220                        return NO_ERROR;
1221                    }
1222                }
1223            }
1224        }
1225        ::munmap(ptr, len);
1226    }
1227    ::close(fd);
1228    return status;
1229}
1230
1231status_t Parcel::writeDupImmutableBlobFileDescriptor(int fd)
1232{
1233    // Must match up with what's done in writeBlob.
1234    if (!mAllowFds) return FDS_NOT_ALLOWED;
1235    status_t status = writeInt32(BLOB_ASHMEM_IMMUTABLE);
1236    if (status) return status;
1237    return writeDupFileDescriptor(fd);
1238}
1239
1240status_t Parcel::write(const FlattenableHelperInterface& val)
1241{
1242    status_t err;
1243
1244    // size if needed
1245    const size_t len = val.getFlattenedSize();
1246    const size_t fd_count = val.getFdCount();
1247
1248    if ((len > INT32_MAX) || (fd_count > INT32_MAX)) {
1249        // don't accept size_t values which may have come from an
1250        // inadvertent conversion from a negative int.
1251        return BAD_VALUE;
1252    }
1253
1254    err = this->writeInt32(len);
1255    if (err) return err;
1256
1257    err = this->writeInt32(fd_count);
1258    if (err) return err;
1259
1260    // payload
1261    void* const buf = this->writeInplace(pad_size(len));
1262    if (buf == NULL)
1263        return BAD_VALUE;
1264
1265    int* fds = NULL;
1266    if (fd_count) {
1267        fds = new int[fd_count];
1268    }
1269
1270    err = val.flatten(buf, len, fds, fd_count);
1271    for (size_t i=0 ; i<fd_count && err==NO_ERROR ; i++) {
1272        err = this->writeDupFileDescriptor( fds[i] );
1273    }
1274
1275    if (fd_count) {
1276        delete [] fds;
1277    }
1278
1279    return err;
1280}
1281
1282status_t Parcel::writeObject(const flat_binder_object& val, bool nullMetaData)
1283{
1284    const bool enoughData = (mDataPos+sizeof(val)) <= mDataCapacity;
1285    const bool enoughObjects = mObjectsSize < mObjectsCapacity;
1286    if (enoughData && enoughObjects) {
1287restart_write:
1288        *reinterpret_cast<flat_binder_object*>(mData+mDataPos) = val;
1289
1290        // remember if it's a file descriptor
1291        if (val.type == BINDER_TYPE_FD) {
1292            if (!mAllowFds) {
1293                // fail before modifying our object index
1294                return FDS_NOT_ALLOWED;
1295            }
1296            mHasFds = mFdsKnown = true;
1297        }
1298
1299        // Need to write meta-data?
1300        if (nullMetaData || val.binder != 0) {
1301            mObjects[mObjectsSize] = mDataPos;
1302            acquire_object(ProcessState::self(), val, this, &mOpenAshmemSize);
1303            mObjectsSize++;
1304        }
1305
1306        return finishWrite(sizeof(flat_binder_object));
1307    }
1308
1309    if (!enoughData) {
1310        const status_t err = growData(sizeof(val));
1311        if (err != NO_ERROR) return err;
1312    }
1313    if (!enoughObjects) {
1314        size_t newSize = ((mObjectsSize+2)*3)/2;
1315        if (newSize < mObjectsSize) return NO_MEMORY;   // overflow
1316        binder_size_t* objects = (binder_size_t*)realloc(mObjects, newSize*sizeof(binder_size_t));
1317        if (objects == NULL) return NO_MEMORY;
1318        mObjects = objects;
1319        mObjectsCapacity = newSize;
1320    }
1321
1322    goto restart_write;
1323}
1324
1325status_t Parcel::writeNoException()
1326{
1327    binder::Status status;
1328    return status.writeToParcel(this);
1329}
1330
1331void Parcel::remove(size_t /*start*/, size_t /*amt*/)
1332{
1333    LOG_ALWAYS_FATAL("Parcel::remove() not yet implemented!");
1334}
1335
1336status_t Parcel::read(void* outData, size_t len) const
1337{
1338    if (len > INT32_MAX) {
1339        // don't accept size_t values which may have come from an
1340        // inadvertent conversion from a negative int.
1341        return BAD_VALUE;
1342    }
1343
1344    if ((mDataPos+pad_size(len)) >= mDataPos && (mDataPos+pad_size(len)) <= mDataSize
1345            && len <= pad_size(len)) {
1346        memcpy(outData, mData+mDataPos, len);
1347        mDataPos += pad_size(len);
1348        ALOGV("read Setting data pos of %p to %zu", this, mDataPos);
1349        return NO_ERROR;
1350    }
1351    return NOT_ENOUGH_DATA;
1352}
1353
1354const void* Parcel::readInplace(size_t len) const
1355{
1356    if (len > INT32_MAX) {
1357        // don't accept size_t values which may have come from an
1358        // inadvertent conversion from a negative int.
1359        return NULL;
1360    }
1361
1362    if ((mDataPos+pad_size(len)) >= mDataPos && (mDataPos+pad_size(len)) <= mDataSize
1363            && len <= pad_size(len)) {
1364        const void* data = mData+mDataPos;
1365        mDataPos += pad_size(len);
1366        ALOGV("readInplace Setting data pos of %p to %zu", this, mDataPos);
1367        return data;
1368    }
1369    return NULL;
1370}
1371
1372template<class T>
1373status_t Parcel::readAligned(T *pArg) const {
1374    COMPILE_TIME_ASSERT_FUNCTION_SCOPE(PAD_SIZE_UNSAFE(sizeof(T)) == sizeof(T));
1375
1376    if ((mDataPos+sizeof(T)) <= mDataSize) {
1377        const void* data = mData+mDataPos;
1378        mDataPos += sizeof(T);
1379        *pArg =  *reinterpret_cast<const T*>(data);
1380        return NO_ERROR;
1381    } else {
1382        return NOT_ENOUGH_DATA;
1383    }
1384}
1385
1386template<class T>
1387T Parcel::readAligned() const {
1388    T result;
1389    if (readAligned(&result) != NO_ERROR) {
1390        result = 0;
1391    }
1392
1393    return result;
1394}
1395
1396template<class T>
1397status_t Parcel::writeAligned(T val) {
1398    COMPILE_TIME_ASSERT_FUNCTION_SCOPE(PAD_SIZE_UNSAFE(sizeof(T)) == sizeof(T));
1399
1400    if ((mDataPos+sizeof(val)) <= mDataCapacity) {
1401restart_write:
1402        *reinterpret_cast<T*>(mData+mDataPos) = val;
1403        return finishWrite(sizeof(val));
1404    }
1405
1406    status_t err = growData(sizeof(val));
1407    if (err == NO_ERROR) goto restart_write;
1408    return err;
1409}
1410
1411status_t Parcel::readByteVector(std::vector<int8_t>* val) const {
1412    val->clear();
1413
1414    int32_t size;
1415    status_t status = readInt32(&size);
1416
1417    if (status != OK) {
1418        return status;
1419    }
1420
1421    if (size < 0) {
1422        status = UNEXPECTED_NULL;
1423        return status;
1424    }
1425    if (size_t(size) > dataAvail()) {
1426        status = BAD_VALUE;
1427        return status;
1428    }
1429
1430    const void* data = readInplace(size);
1431    if (!data) {
1432        status = BAD_VALUE;
1433        return status;
1434    }
1435    val->resize(size);
1436    memcpy(val->data(), data, size);
1437
1438    return status;
1439}
1440
1441status_t Parcel::readByteVector(std::unique_ptr<std::vector<int8_t>>* val) const {
1442    const int32_t start = dataPosition();
1443    int32_t size;
1444    status_t status = readInt32(&size);
1445    val->reset();
1446
1447    if (status != OK || size < 0) {
1448        return status;
1449    }
1450
1451    setDataPosition(start);
1452    val->reset(new std::vector<int8_t>());
1453
1454    status = readByteVector(val->get());
1455
1456    if (status != OK) {
1457        val->reset();
1458    }
1459
1460    return status;
1461}
1462
1463status_t Parcel::readInt32Vector(std::unique_ptr<std::vector<int32_t>>* val) const {
1464    return readNullableTypedVector(val, &Parcel::readInt32);
1465}
1466
1467status_t Parcel::readInt32Vector(std::vector<int32_t>* val) const {
1468    return readTypedVector(val, &Parcel::readInt32);
1469}
1470
1471status_t Parcel::readInt64Vector(std::unique_ptr<std::vector<int64_t>>* val) const {
1472    return readNullableTypedVector(val, &Parcel::readInt64);
1473}
1474
1475status_t Parcel::readInt64Vector(std::vector<int64_t>* val) const {
1476    return readTypedVector(val, &Parcel::readInt64);
1477}
1478
1479status_t Parcel::readFloatVector(std::unique_ptr<std::vector<float>>* val) const {
1480    return readNullableTypedVector(val, &Parcel::readFloat);
1481}
1482
1483status_t Parcel::readFloatVector(std::vector<float>* val) const {
1484    return readTypedVector(val, &Parcel::readFloat);
1485}
1486
1487status_t Parcel::readDoubleVector(std::unique_ptr<std::vector<double>>* val) const {
1488    return readNullableTypedVector(val, &Parcel::readDouble);
1489}
1490
1491status_t Parcel::readDoubleVector(std::vector<double>* val) const {
1492    return readTypedVector(val, &Parcel::readDouble);
1493}
1494
1495status_t Parcel::readBoolVector(std::unique_ptr<std::vector<bool>>* val) const {
1496    const int32_t start = dataPosition();
1497    int32_t size;
1498    status_t status = readInt32(&size);
1499    val->reset();
1500
1501    if (status != OK || size < 0) {
1502        return status;
1503    }
1504
1505    setDataPosition(start);
1506    val->reset(new std::vector<bool>());
1507
1508    status = readBoolVector(val->get());
1509
1510    if (status != OK) {
1511        val->reset();
1512    }
1513
1514    return status;
1515}
1516
1517status_t Parcel::readBoolVector(std::vector<bool>* val) const {
1518    int32_t size;
1519    status_t status = readInt32(&size);
1520
1521    if (status != OK) {
1522        return status;
1523    }
1524
1525    if (size < 0) {
1526        return UNEXPECTED_NULL;
1527    }
1528
1529    val->resize(size);
1530
1531    /* C++ bool handling means a vector of bools isn't necessarily addressable
1532     * (we might use individual bits)
1533     */
1534    bool data;
1535    for (int32_t i = 0; i < size; ++i) {
1536        status = readBool(&data);
1537        (*val)[i] = data;
1538
1539        if (status != OK) {
1540            return status;
1541        }
1542    }
1543
1544    return OK;
1545}
1546
1547status_t Parcel::readCharVector(std::unique_ptr<std::vector<char16_t>>* val) const {
1548    return readNullableTypedVector(val, &Parcel::readChar);
1549}
1550
1551status_t Parcel::readCharVector(std::vector<char16_t>* val) const {
1552    return readTypedVector(val, &Parcel::readChar);
1553}
1554
1555status_t Parcel::readString16Vector(
1556        std::unique_ptr<std::vector<std::unique_ptr<String16>>>* val) const {
1557    return readNullableTypedVector(val, &Parcel::readString16);
1558}
1559
1560status_t Parcel::readString16Vector(std::vector<String16>* val) const {
1561    return readTypedVector(val, &Parcel::readString16);
1562}
1563
1564status_t Parcel::readUtf8VectorFromUtf16Vector(
1565        std::unique_ptr<std::vector<std::unique_ptr<std::string>>>* val) const {
1566    return readNullableTypedVector(val, &Parcel::readUtf8FromUtf16);
1567}
1568
1569status_t Parcel::readUtf8VectorFromUtf16Vector(std::vector<std::string>* val) const {
1570    return readTypedVector(val, &Parcel::readUtf8FromUtf16);
1571}
1572
1573status_t Parcel::readInt32(int32_t *pArg) const
1574{
1575    return readAligned(pArg);
1576}
1577
1578int32_t Parcel::readInt32() const
1579{
1580    return readAligned<int32_t>();
1581}
1582
1583status_t Parcel::readUint32(uint32_t *pArg) const
1584{
1585    return readAligned(pArg);
1586}
1587
1588uint32_t Parcel::readUint32() const
1589{
1590    return readAligned<uint32_t>();
1591}
1592
1593status_t Parcel::readInt64(int64_t *pArg) const
1594{
1595    return readAligned(pArg);
1596}
1597
1598
1599int64_t Parcel::readInt64() const
1600{
1601    return readAligned<int64_t>();
1602}
1603
1604status_t Parcel::readUint64(uint64_t *pArg) const
1605{
1606    return readAligned(pArg);
1607}
1608
1609uint64_t Parcel::readUint64() const
1610{
1611    return readAligned<uint64_t>();
1612}
1613
1614status_t Parcel::readPointer(uintptr_t *pArg) const
1615{
1616    status_t ret;
1617    binder_uintptr_t ptr;
1618    ret = readAligned(&ptr);
1619    if (!ret)
1620        *pArg = ptr;
1621    return ret;
1622}
1623
1624uintptr_t Parcel::readPointer() const
1625{
1626    return readAligned<binder_uintptr_t>();
1627}
1628
1629
1630status_t Parcel::readFloat(float *pArg) const
1631{
1632    return readAligned(pArg);
1633}
1634
1635
1636float Parcel::readFloat() const
1637{
1638    return readAligned<float>();
1639}
1640
1641#if defined(__mips__) && defined(__mips_hard_float)
1642
1643status_t Parcel::readDouble(double *pArg) const
1644{
1645    union {
1646      double d;
1647      unsigned long long ll;
1648    } u;
1649    u.d = 0;
1650    status_t status;
1651    status = readAligned(&u.ll);
1652    *pArg = u.d;
1653    return status;
1654}
1655
1656double Parcel::readDouble() const
1657{
1658    union {
1659      double d;
1660      unsigned long long ll;
1661    } u;
1662    u.ll = readAligned<unsigned long long>();
1663    return u.d;
1664}
1665
1666#else
1667
1668status_t Parcel::readDouble(double *pArg) const
1669{
1670    return readAligned(pArg);
1671}
1672
1673double Parcel::readDouble() const
1674{
1675    return readAligned<double>();
1676}
1677
1678#endif
1679
1680status_t Parcel::readIntPtr(intptr_t *pArg) const
1681{
1682    return readAligned(pArg);
1683}
1684
1685
1686intptr_t Parcel::readIntPtr() const
1687{
1688    return readAligned<intptr_t>();
1689}
1690
1691status_t Parcel::readBool(bool *pArg) const
1692{
1693    int32_t tmp;
1694    status_t ret = readInt32(&tmp);
1695    *pArg = (tmp != 0);
1696    return ret;
1697}
1698
1699bool Parcel::readBool() const
1700{
1701    return readInt32() != 0;
1702}
1703
1704status_t Parcel::readChar(char16_t *pArg) const
1705{
1706    int32_t tmp;
1707    status_t ret = readInt32(&tmp);
1708    *pArg = char16_t(tmp);
1709    return ret;
1710}
1711
1712char16_t Parcel::readChar() const
1713{
1714    return char16_t(readInt32());
1715}
1716
1717status_t Parcel::readByte(int8_t *pArg) const
1718{
1719    int32_t tmp;
1720    status_t ret = readInt32(&tmp);
1721    *pArg = int8_t(tmp);
1722    return ret;
1723}
1724
1725int8_t Parcel::readByte() const
1726{
1727    return int8_t(readInt32());
1728}
1729
1730status_t Parcel::readUtf8FromUtf16(std::string* str) const {
1731    size_t utf16Size = 0;
1732    const char16_t* src = readString16Inplace(&utf16Size);
1733    if (!src) {
1734        return UNEXPECTED_NULL;
1735    }
1736
1737    // Save ourselves the trouble, we're done.
1738    if (utf16Size == 0u) {
1739        str->clear();
1740       return NO_ERROR;
1741    }
1742
1743    ssize_t utf8Size = utf16_to_utf8_length(src, utf16Size);
1744    if (utf8Size < 0) {
1745        return BAD_VALUE;
1746    }
1747    // Note that while it is probably safe to assume string::resize keeps a
1748    // spare byte around for the trailing null, we're going to be explicit.
1749    str->resize(utf8Size + 1);
1750    utf16_to_utf8(src, utf16Size, &((*str)[0]));
1751    str->resize(utf8Size);
1752    return NO_ERROR;
1753}
1754
1755status_t Parcel::readUtf8FromUtf16(std::unique_ptr<std::string>* str) const {
1756    const int32_t start = dataPosition();
1757    int32_t size;
1758    status_t status = readInt32(&size);
1759    str->reset();
1760
1761    if (status != OK || size < 0) {
1762        return status;
1763    }
1764
1765    setDataPosition(start);
1766    str->reset(new std::string());
1767    return readUtf8FromUtf16(str->get());
1768}
1769
1770const char* Parcel::readCString() const
1771{
1772    const size_t avail = mDataSize-mDataPos;
1773    if (avail > 0) {
1774        const char* str = reinterpret_cast<const char*>(mData+mDataPos);
1775        // is the string's trailing NUL within the parcel's valid bounds?
1776        const char* eos = reinterpret_cast<const char*>(memchr(str, 0, avail));
1777        if (eos) {
1778            const size_t len = eos - str;
1779            mDataPos += pad_size(len+1);
1780            ALOGV("readCString Setting data pos of %p to %zu", this, mDataPos);
1781            return str;
1782        }
1783    }
1784    return NULL;
1785}
1786
1787String8 Parcel::readString8() const
1788{
1789    int32_t size = readInt32();
1790    // watch for potential int overflow adding 1 for trailing NUL
1791    if (size > 0 && size < INT32_MAX) {
1792        const char* str = (const char*)readInplace(size+1);
1793        if (str) return String8(str, size);
1794    }
1795    return String8();
1796}
1797
1798String16 Parcel::readString16() const
1799{
1800    size_t len;
1801    const char16_t* str = readString16Inplace(&len);
1802    if (str) return String16(str, len);
1803    ALOGE("Reading a NULL string not supported here.");
1804    return String16();
1805}
1806
1807status_t Parcel::readString16(std::unique_ptr<String16>* pArg) const
1808{
1809    const int32_t start = dataPosition();
1810    int32_t size;
1811    status_t status = readInt32(&size);
1812    pArg->reset();
1813
1814    if (status != OK || size < 0) {
1815        return status;
1816    }
1817
1818    setDataPosition(start);
1819    pArg->reset(new String16());
1820
1821    status = readString16(pArg->get());
1822
1823    if (status != OK) {
1824        pArg->reset();
1825    }
1826
1827    return status;
1828}
1829
1830status_t Parcel::readString16(String16* pArg) const
1831{
1832    size_t len;
1833    const char16_t* str = readString16Inplace(&len);
1834    if (str) {
1835        pArg->setTo(str, len);
1836        return 0;
1837    } else {
1838        *pArg = String16();
1839        return UNEXPECTED_NULL;
1840    }
1841}
1842
1843const char16_t* Parcel::readString16Inplace(size_t* outLen) const
1844{
1845    int32_t size = readInt32();
1846    // watch for potential int overflow from size+1
1847    if (size >= 0 && size < INT32_MAX) {
1848        *outLen = size;
1849        const char16_t* str = (const char16_t*)readInplace((size+1)*sizeof(char16_t));
1850        if (str != NULL) {
1851            return str;
1852        }
1853    }
1854    *outLen = 0;
1855    return NULL;
1856}
1857
1858status_t Parcel::readStrongBinder(sp<IBinder>* val) const
1859{
1860    return unflatten_binder(ProcessState::self(), *this, val);
1861}
1862
1863sp<IBinder> Parcel::readStrongBinder() const
1864{
1865    sp<IBinder> val;
1866    readStrongBinder(&val);
1867    return val;
1868}
1869
1870wp<IBinder> Parcel::readWeakBinder() const
1871{
1872    wp<IBinder> val;
1873    unflatten_binder(ProcessState::self(), *this, &val);
1874    return val;
1875}
1876
1877status_t Parcel::readParcelable(Parcelable* parcelable) const {
1878    int32_t have_parcelable = 0;
1879    status_t status = readInt32(&have_parcelable);
1880    if (status != OK) {
1881        return status;
1882    }
1883    if (!have_parcelable) {
1884        return UNEXPECTED_NULL;
1885    }
1886    return parcelable->readFromParcel(this);
1887}
1888
1889int32_t Parcel::readExceptionCode() const
1890{
1891    binder::Status status;
1892    status.readFromParcel(*this);
1893    return status.exceptionCode();
1894}
1895
1896native_handle* Parcel::readNativeHandle() const
1897{
1898    int numFds, numInts;
1899    status_t err;
1900    err = readInt32(&numFds);
1901    if (err != NO_ERROR) return 0;
1902    err = readInt32(&numInts);
1903    if (err != NO_ERROR) return 0;
1904
1905    native_handle* h = native_handle_create(numFds, numInts);
1906    if (!h) {
1907        return 0;
1908    }
1909
1910    for (int i=0 ; err==NO_ERROR && i<numFds ; i++) {
1911        h->data[i] = dup(readFileDescriptor());
1912        if (h->data[i] < 0) err = BAD_VALUE;
1913    }
1914    err = read(h->data + numFds, sizeof(int)*numInts);
1915    if (err != NO_ERROR) {
1916        native_handle_close(h);
1917        native_handle_delete(h);
1918        h = 0;
1919    }
1920    return h;
1921}
1922
1923
1924int Parcel::readFileDescriptor() const
1925{
1926    const flat_binder_object* flat = readObject(true);
1927
1928    if (flat && flat->type == BINDER_TYPE_FD) {
1929        return flat->handle;
1930    }
1931
1932    return BAD_TYPE;
1933}
1934
1935status_t Parcel::readUniqueFileDescriptor(ScopedFd* val) const
1936{
1937    int got = readFileDescriptor();
1938
1939    if (got == BAD_TYPE) {
1940        return BAD_TYPE;
1941    }
1942
1943    val->reset(dup(got));
1944
1945    if (val->get() < 0) {
1946        return BAD_VALUE;
1947    }
1948
1949    return OK;
1950}
1951
1952
1953status_t Parcel::readUniqueFileDescriptorVector(std::unique_ptr<std::vector<ScopedFd>>* val) const {
1954    return readNullableTypedVector(val, &Parcel::readUniqueFileDescriptor);
1955}
1956
1957status_t Parcel::readUniqueFileDescriptorVector(std::vector<ScopedFd>* val) const {
1958    return readTypedVector(val, &Parcel::readUniqueFileDescriptor);
1959}
1960
1961status_t Parcel::readBlob(size_t len, ReadableBlob* outBlob) const
1962{
1963    int32_t blobType;
1964    status_t status = readInt32(&blobType);
1965    if (status) return status;
1966
1967    if (blobType == BLOB_INPLACE) {
1968        ALOGV("readBlob: read in place");
1969        const void* ptr = readInplace(len);
1970        if (!ptr) return BAD_VALUE;
1971
1972        outBlob->init(-1, const_cast<void*>(ptr), len, false);
1973        return NO_ERROR;
1974    }
1975
1976    ALOGV("readBlob: read from ashmem");
1977    bool isMutable = (blobType == BLOB_ASHMEM_MUTABLE);
1978    int fd = readFileDescriptor();
1979    if (fd == int(BAD_TYPE)) return BAD_VALUE;
1980
1981    void* ptr = ::mmap(NULL, len, isMutable ? PROT_READ | PROT_WRITE : PROT_READ,
1982            MAP_SHARED, fd, 0);
1983    if (ptr == MAP_FAILED) return NO_MEMORY;
1984
1985    outBlob->init(fd, ptr, len, isMutable);
1986    return NO_ERROR;
1987}
1988
1989status_t Parcel::read(FlattenableHelperInterface& val) const
1990{
1991    // size
1992    const size_t len = this->readInt32();
1993    const size_t fd_count = this->readInt32();
1994
1995    if (len > INT32_MAX) {
1996        // don't accept size_t values which may have come from an
1997        // inadvertent conversion from a negative int.
1998        return BAD_VALUE;
1999    }
2000
2001    // payload
2002    void const* const buf = this->readInplace(pad_size(len));
2003    if (buf == NULL)
2004        return BAD_VALUE;
2005
2006    int* fds = NULL;
2007    if (fd_count) {
2008        fds = new int[fd_count];
2009    }
2010
2011    status_t err = NO_ERROR;
2012    for (size_t i=0 ; i<fd_count && err==NO_ERROR ; i++) {
2013        fds[i] = dup(this->readFileDescriptor());
2014        if (fds[i] < 0) {
2015            err = BAD_VALUE;
2016            ALOGE("dup() failed in Parcel::read, i is %zu, fds[i] is %d, fd_count is %zu, error: %s",
2017                i, fds[i], fd_count, strerror(errno));
2018        }
2019    }
2020
2021    if (err == NO_ERROR) {
2022        err = val.unflatten(buf, len, fds, fd_count);
2023    }
2024
2025    if (fd_count) {
2026        delete [] fds;
2027    }
2028
2029    return err;
2030}
2031const flat_binder_object* Parcel::readObject(bool nullMetaData) const
2032{
2033    const size_t DPOS = mDataPos;
2034    if ((DPOS+sizeof(flat_binder_object)) <= mDataSize) {
2035        const flat_binder_object* obj
2036                = reinterpret_cast<const flat_binder_object*>(mData+DPOS);
2037        mDataPos = DPOS + sizeof(flat_binder_object);
2038        if (!nullMetaData && (obj->cookie == 0 && obj->binder == 0)) {
2039            // When transferring a NULL object, we don't write it into
2040            // the object list, so we don't want to check for it when
2041            // reading.
2042            ALOGV("readObject Setting data pos of %p to %zu", this, mDataPos);
2043            return obj;
2044        }
2045
2046        // Ensure that this object is valid...
2047        binder_size_t* const OBJS = mObjects;
2048        const size_t N = mObjectsSize;
2049        size_t opos = mNextObjectHint;
2050
2051        if (N > 0) {
2052            ALOGV("Parcel %p looking for obj at %zu, hint=%zu",
2053                 this, DPOS, opos);
2054
2055            // Start at the current hint position, looking for an object at
2056            // the current data position.
2057            if (opos < N) {
2058                while (opos < (N-1) && OBJS[opos] < DPOS) {
2059                    opos++;
2060                }
2061            } else {
2062                opos = N-1;
2063            }
2064            if (OBJS[opos] == DPOS) {
2065                // Found it!
2066                ALOGV("Parcel %p found obj %zu at index %zu with forward search",
2067                     this, DPOS, opos);
2068                mNextObjectHint = opos+1;
2069                ALOGV("readObject Setting data pos of %p to %zu", this, mDataPos);
2070                return obj;
2071            }
2072
2073            // Look backwards for it...
2074            while (opos > 0 && OBJS[opos] > DPOS) {
2075                opos--;
2076            }
2077            if (OBJS[opos] == DPOS) {
2078                // Found it!
2079                ALOGV("Parcel %p found obj %zu at index %zu with backward search",
2080                     this, DPOS, opos);
2081                mNextObjectHint = opos+1;
2082                ALOGV("readObject Setting data pos of %p to %zu", this, mDataPos);
2083                return obj;
2084            }
2085        }
2086        ALOGW("Attempt to read object from Parcel %p at offset %zu that is not in the object list",
2087             this, DPOS);
2088    }
2089    return NULL;
2090}
2091
2092void Parcel::closeFileDescriptors()
2093{
2094    size_t i = mObjectsSize;
2095    if (i > 0) {
2096        //ALOGI("Closing file descriptors for %zu objects...", i);
2097    }
2098    while (i > 0) {
2099        i--;
2100        const flat_binder_object* flat
2101            = reinterpret_cast<flat_binder_object*>(mData+mObjects[i]);
2102        if (flat->type == BINDER_TYPE_FD) {
2103            //ALOGI("Closing fd: %ld", flat->handle);
2104            close(flat->handle);
2105        }
2106    }
2107}
2108
2109uintptr_t Parcel::ipcData() const
2110{
2111    return reinterpret_cast<uintptr_t>(mData);
2112}
2113
2114size_t Parcel::ipcDataSize() const
2115{
2116    return (mDataSize > mDataPos ? mDataSize : mDataPos);
2117}
2118
2119uintptr_t Parcel::ipcObjects() const
2120{
2121    return reinterpret_cast<uintptr_t>(mObjects);
2122}
2123
2124size_t Parcel::ipcObjectsCount() const
2125{
2126    return mObjectsSize;
2127}
2128
2129void Parcel::ipcSetDataReference(const uint8_t* data, size_t dataSize,
2130    const binder_size_t* objects, size_t objectsCount, release_func relFunc, void* relCookie)
2131{
2132    binder_size_t minOffset = 0;
2133    freeDataNoInit();
2134    mError = NO_ERROR;
2135    mData = const_cast<uint8_t*>(data);
2136    mDataSize = mDataCapacity = dataSize;
2137    //ALOGI("setDataReference Setting data size of %p to %lu (pid=%d)", this, mDataSize, getpid());
2138    mDataPos = 0;
2139    ALOGV("setDataReference Setting data pos of %p to %zu", this, mDataPos);
2140    mObjects = const_cast<binder_size_t*>(objects);
2141    mObjectsSize = mObjectsCapacity = objectsCount;
2142    mNextObjectHint = 0;
2143    mOwner = relFunc;
2144    mOwnerCookie = relCookie;
2145    for (size_t i = 0; i < mObjectsSize; i++) {
2146        binder_size_t offset = mObjects[i];
2147        if (offset < minOffset) {
2148            ALOGE("%s: bad object offset %" PRIu64 " < %" PRIu64 "\n",
2149                  __func__, (uint64_t)offset, (uint64_t)minOffset);
2150            mObjectsSize = 0;
2151            break;
2152        }
2153        minOffset = offset + sizeof(flat_binder_object);
2154    }
2155    scanForFds();
2156}
2157
2158void Parcel::print(TextOutput& to, uint32_t /*flags*/) const
2159{
2160    to << "Parcel(";
2161
2162    if (errorCheck() != NO_ERROR) {
2163        const status_t err = errorCheck();
2164        to << "Error: " << (void*)(intptr_t)err << " \"" << strerror(-err) << "\"";
2165    } else if (dataSize() > 0) {
2166        const uint8_t* DATA = data();
2167        to << indent << HexDump(DATA, dataSize()) << dedent;
2168        const binder_size_t* OBJS = objects();
2169        const size_t N = objectsCount();
2170        for (size_t i=0; i<N; i++) {
2171            const flat_binder_object* flat
2172                = reinterpret_cast<const flat_binder_object*>(DATA+OBJS[i]);
2173            to << endl << "Object #" << i << " @ " << (void*)OBJS[i] << ": "
2174                << TypeCode(flat->type & 0x7f7f7f00)
2175                << " = " << flat->binder;
2176        }
2177    } else {
2178        to << "NULL";
2179    }
2180
2181    to << ")";
2182}
2183
2184void Parcel::releaseObjects()
2185{
2186    const sp<ProcessState> proc(ProcessState::self());
2187    size_t i = mObjectsSize;
2188    uint8_t* const data = mData;
2189    binder_size_t* const objects = mObjects;
2190    while (i > 0) {
2191        i--;
2192        const flat_binder_object* flat
2193            = reinterpret_cast<flat_binder_object*>(data+objects[i]);
2194        release_object(proc, *flat, this, &mOpenAshmemSize);
2195    }
2196}
2197
2198void Parcel::acquireObjects()
2199{
2200    const sp<ProcessState> proc(ProcessState::self());
2201    size_t i = mObjectsSize;
2202    uint8_t* const data = mData;
2203    binder_size_t* const objects = mObjects;
2204    while (i > 0) {
2205        i--;
2206        const flat_binder_object* flat
2207            = reinterpret_cast<flat_binder_object*>(data+objects[i]);
2208        acquire_object(proc, *flat, this, &mOpenAshmemSize);
2209    }
2210}
2211
2212void Parcel::freeData()
2213{
2214    freeDataNoInit();
2215    initState();
2216}
2217
2218void Parcel::freeDataNoInit()
2219{
2220    if (mOwner) {
2221        LOG_ALLOC("Parcel %p: freeing other owner data", this);
2222        //ALOGI("Freeing data ref of %p (pid=%d)", this, getpid());
2223        mOwner(this, mData, mDataSize, mObjects, mObjectsSize, mOwnerCookie);
2224    } else {
2225        LOG_ALLOC("Parcel %p: freeing allocated data", this);
2226        releaseObjects();
2227        if (mData) {
2228            LOG_ALLOC("Parcel %p: freeing with %zu capacity", this, mDataCapacity);
2229            pthread_mutex_lock(&gParcelGlobalAllocSizeLock);
2230            if (mDataCapacity <= gParcelGlobalAllocSize) {
2231              gParcelGlobalAllocSize = gParcelGlobalAllocSize - mDataCapacity;
2232            } else {
2233              gParcelGlobalAllocSize = 0;
2234            }
2235            if (gParcelGlobalAllocCount > 0) {
2236              gParcelGlobalAllocCount--;
2237            }
2238            pthread_mutex_unlock(&gParcelGlobalAllocSizeLock);
2239            free(mData);
2240        }
2241        if (mObjects) free(mObjects);
2242    }
2243}
2244
2245status_t Parcel::growData(size_t len)
2246{
2247    if (len > INT32_MAX) {
2248        // don't accept size_t values which may have come from an
2249        // inadvertent conversion from a negative int.
2250        return BAD_VALUE;
2251    }
2252
2253    size_t newSize = ((mDataSize+len)*3)/2;
2254    return (newSize <= mDataSize)
2255            ? (status_t) NO_MEMORY
2256            : continueWrite(newSize);
2257}
2258
2259status_t Parcel::restartWrite(size_t desired)
2260{
2261    if (desired > INT32_MAX) {
2262        // don't accept size_t values which may have come from an
2263        // inadvertent conversion from a negative int.
2264        return BAD_VALUE;
2265    }
2266
2267    if (mOwner) {
2268        freeData();
2269        return continueWrite(desired);
2270    }
2271
2272    uint8_t* data = (uint8_t*)realloc(mData, desired);
2273    if (!data && desired > mDataCapacity) {
2274        mError = NO_MEMORY;
2275        return NO_MEMORY;
2276    }
2277
2278    releaseObjects();
2279
2280    if (data) {
2281        LOG_ALLOC("Parcel %p: restart from %zu to %zu capacity", this, mDataCapacity, desired);
2282        pthread_mutex_lock(&gParcelGlobalAllocSizeLock);
2283        gParcelGlobalAllocSize += desired;
2284        gParcelGlobalAllocSize -= mDataCapacity;
2285        if (!mData) {
2286            gParcelGlobalAllocCount++;
2287        }
2288        pthread_mutex_unlock(&gParcelGlobalAllocSizeLock);
2289        mData = data;
2290        mDataCapacity = desired;
2291    }
2292
2293    mDataSize = mDataPos = 0;
2294    ALOGV("restartWrite Setting data size of %p to %zu", this, mDataSize);
2295    ALOGV("restartWrite Setting data pos of %p to %zu", this, mDataPos);
2296
2297    free(mObjects);
2298    mObjects = NULL;
2299    mObjectsSize = mObjectsCapacity = 0;
2300    mNextObjectHint = 0;
2301    mHasFds = false;
2302    mFdsKnown = true;
2303    mAllowFds = true;
2304
2305    return NO_ERROR;
2306}
2307
2308status_t Parcel::continueWrite(size_t desired)
2309{
2310    if (desired > INT32_MAX) {
2311        // don't accept size_t values which may have come from an
2312        // inadvertent conversion from a negative int.
2313        return BAD_VALUE;
2314    }
2315
2316    // If shrinking, first adjust for any objects that appear
2317    // after the new data size.
2318    size_t objectsSize = mObjectsSize;
2319    if (desired < mDataSize) {
2320        if (desired == 0) {
2321            objectsSize = 0;
2322        } else {
2323            while (objectsSize > 0) {
2324                if (mObjects[objectsSize-1] < desired)
2325                    break;
2326                objectsSize--;
2327            }
2328        }
2329    }
2330
2331    if (mOwner) {
2332        // If the size is going to zero, just release the owner's data.
2333        if (desired == 0) {
2334            freeData();
2335            return NO_ERROR;
2336        }
2337
2338        // If there is a different owner, we need to take
2339        // posession.
2340        uint8_t* data = (uint8_t*)malloc(desired);
2341        if (!data) {
2342            mError = NO_MEMORY;
2343            return NO_MEMORY;
2344        }
2345        binder_size_t* objects = NULL;
2346
2347        if (objectsSize) {
2348            objects = (binder_size_t*)calloc(objectsSize, sizeof(binder_size_t));
2349            if (!objects) {
2350                free(data);
2351
2352                mError = NO_MEMORY;
2353                return NO_MEMORY;
2354            }
2355
2356            // Little hack to only acquire references on objects
2357            // we will be keeping.
2358            size_t oldObjectsSize = mObjectsSize;
2359            mObjectsSize = objectsSize;
2360            acquireObjects();
2361            mObjectsSize = oldObjectsSize;
2362        }
2363
2364        if (mData) {
2365            memcpy(data, mData, mDataSize < desired ? mDataSize : desired);
2366        }
2367        if (objects && mObjects) {
2368            memcpy(objects, mObjects, objectsSize*sizeof(binder_size_t));
2369        }
2370        //ALOGI("Freeing data ref of %p (pid=%d)", this, getpid());
2371        mOwner(this, mData, mDataSize, mObjects, mObjectsSize, mOwnerCookie);
2372        mOwner = NULL;
2373
2374        LOG_ALLOC("Parcel %p: taking ownership of %zu capacity", this, desired);
2375        pthread_mutex_lock(&gParcelGlobalAllocSizeLock);
2376        gParcelGlobalAllocSize += desired;
2377        gParcelGlobalAllocCount++;
2378        pthread_mutex_unlock(&gParcelGlobalAllocSizeLock);
2379
2380        mData = data;
2381        mObjects = objects;
2382        mDataSize = (mDataSize < desired) ? mDataSize : desired;
2383        ALOGV("continueWrite Setting data size of %p to %zu", this, mDataSize);
2384        mDataCapacity = desired;
2385        mObjectsSize = mObjectsCapacity = objectsSize;
2386        mNextObjectHint = 0;
2387
2388    } else if (mData) {
2389        if (objectsSize < mObjectsSize) {
2390            // Need to release refs on any objects we are dropping.
2391            const sp<ProcessState> proc(ProcessState::self());
2392            for (size_t i=objectsSize; i<mObjectsSize; i++) {
2393                const flat_binder_object* flat
2394                    = reinterpret_cast<flat_binder_object*>(mData+mObjects[i]);
2395                if (flat->type == BINDER_TYPE_FD) {
2396                    // will need to rescan because we may have lopped off the only FDs
2397                    mFdsKnown = false;
2398                }
2399                release_object(proc, *flat, this, &mOpenAshmemSize);
2400            }
2401            binder_size_t* objects =
2402                (binder_size_t*)realloc(mObjects, objectsSize*sizeof(binder_size_t));
2403            if (objects) {
2404                mObjects = objects;
2405            }
2406            mObjectsSize = objectsSize;
2407            mNextObjectHint = 0;
2408        }
2409
2410        // We own the data, so we can just do a realloc().
2411        if (desired > mDataCapacity) {
2412            uint8_t* data = (uint8_t*)realloc(mData, desired);
2413            if (data) {
2414                LOG_ALLOC("Parcel %p: continue from %zu to %zu capacity", this, mDataCapacity,
2415                        desired);
2416                pthread_mutex_lock(&gParcelGlobalAllocSizeLock);
2417                gParcelGlobalAllocSize += desired;
2418                gParcelGlobalAllocSize -= mDataCapacity;
2419                pthread_mutex_unlock(&gParcelGlobalAllocSizeLock);
2420                mData = data;
2421                mDataCapacity = desired;
2422            } else if (desired > mDataCapacity) {
2423                mError = NO_MEMORY;
2424                return NO_MEMORY;
2425            }
2426        } else {
2427            if (mDataSize > desired) {
2428                mDataSize = desired;
2429                ALOGV("continueWrite Setting data size of %p to %zu", this, mDataSize);
2430            }
2431            if (mDataPos > desired) {
2432                mDataPos = desired;
2433                ALOGV("continueWrite Setting data pos of %p to %zu", this, mDataPos);
2434            }
2435        }
2436
2437    } else {
2438        // This is the first data.  Easy!
2439        uint8_t* data = (uint8_t*)malloc(desired);
2440        if (!data) {
2441            mError = NO_MEMORY;
2442            return NO_MEMORY;
2443        }
2444
2445        if(!(mDataCapacity == 0 && mObjects == NULL
2446             && mObjectsCapacity == 0)) {
2447            ALOGE("continueWrite: %zu/%p/%zu/%zu", mDataCapacity, mObjects, mObjectsCapacity, desired);
2448        }
2449
2450        LOG_ALLOC("Parcel %p: allocating with %zu capacity", this, desired);
2451        pthread_mutex_lock(&gParcelGlobalAllocSizeLock);
2452        gParcelGlobalAllocSize += desired;
2453        gParcelGlobalAllocCount++;
2454        pthread_mutex_unlock(&gParcelGlobalAllocSizeLock);
2455
2456        mData = data;
2457        mDataSize = mDataPos = 0;
2458        ALOGV("continueWrite Setting data size of %p to %zu", this, mDataSize);
2459        ALOGV("continueWrite Setting data pos of %p to %zu", this, mDataPos);
2460        mDataCapacity = desired;
2461    }
2462
2463    return NO_ERROR;
2464}
2465
2466void Parcel::initState()
2467{
2468    LOG_ALLOC("Parcel %p: initState", this);
2469    mError = NO_ERROR;
2470    mData = 0;
2471    mDataSize = 0;
2472    mDataCapacity = 0;
2473    mDataPos = 0;
2474    ALOGV("initState Setting data size of %p to %zu", this, mDataSize);
2475    ALOGV("initState Setting data pos of %p to %zu", this, mDataPos);
2476    mObjects = NULL;
2477    mObjectsSize = 0;
2478    mObjectsCapacity = 0;
2479    mNextObjectHint = 0;
2480    mHasFds = false;
2481    mFdsKnown = true;
2482    mAllowFds = true;
2483    mOwner = NULL;
2484    mOpenAshmemSize = 0;
2485}
2486
2487void Parcel::scanForFds() const
2488{
2489    bool hasFds = false;
2490    for (size_t i=0; i<mObjectsSize; i++) {
2491        const flat_binder_object* flat
2492            = reinterpret_cast<const flat_binder_object*>(mData + mObjects[i]);
2493        if (flat->type == BINDER_TYPE_FD) {
2494            hasFds = true;
2495            break;
2496        }
2497    }
2498    mHasFds = hasFds;
2499    mFdsKnown = true;
2500}
2501
2502size_t Parcel::getBlobAshmemSize() const
2503{
2504    // This used to return the size of all blobs that were written to ashmem, now we're returning
2505    // the ashmem currently referenced by this Parcel, which should be equivalent.
2506    // TODO: Remove method once ABI can be changed.
2507    return mOpenAshmemSize;
2508}
2509
2510size_t Parcel::getOpenAshmemSize() const
2511{
2512    return mOpenAshmemSize;
2513}
2514
2515// --- Parcel::Blob ---
2516
2517Parcel::Blob::Blob() :
2518        mFd(-1), mData(NULL), mSize(0), mMutable(false) {
2519}
2520
2521Parcel::Blob::~Blob() {
2522    release();
2523}
2524
2525void Parcel::Blob::release() {
2526    if (mFd != -1 && mData) {
2527        ::munmap(mData, mSize);
2528    }
2529    clear();
2530}
2531
2532void Parcel::Blob::init(int fd, void* data, size_t size, bool isMutable) {
2533    mFd = fd;
2534    mData = data;
2535    mSize = size;
2536    mMutable = isMutable;
2537}
2538
2539void Parcel::Blob::clear() {
2540    mFd = -1;
2541    mData = NULL;
2542    mSize = 0;
2543    mMutable = false;
2544}
2545
2546}; // namespace android
2547