Parcel.cpp revision 499127eab812088ca24421b59ebfac6f47ea850f
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 <binder/Parcel.h>
21
22#include <binder/IPCThreadState.h>
23#include <binder/Binder.h>
24#include <binder/BpBinder.h>
25#include <binder/ProcessState.h>
26#include <binder/TextOutput.h>
27
28#include <errno.h>
29#include <utils/Debug.h>
30#include <utils/Log.h>
31#include <utils/String8.h>
32#include <utils/String16.h>
33#include <utils/misc.h>
34#include <utils/Flattenable.h>
35#include <cutils/ashmem.h>
36
37#include <private/binder/binder_module.h>
38#include <private/binder/Static.h>
39
40#include <inttypes.h>
41#include <stdio.h>
42#include <stdlib.h>
43#include <stdint.h>
44#include <sys/mman.h>
45
46#ifndef INT32_MAX
47#define INT32_MAX ((int32_t)(2147483647))
48#endif
49
50#define LOG_REFS(...)
51//#define LOG_REFS(...) ALOG(LOG_DEBUG, "Parcel", __VA_ARGS__)
52#define LOG_ALLOC(...)
53//#define LOG_ALLOC(...) ALOG(LOG_DEBUG, "Parcel", __VA_ARGS__)
54
55// ---------------------------------------------------------------------------
56
57#define PAD_SIZE(s) (((s)+3)&~3)
58
59// Note: must be kept in sync with android/os/StrictMode.java's PENALTY_GATHER
60#define STRICT_MODE_PENALTY_GATHER (0x40 << 16)
61
62// Note: must be kept in sync with android/os/Parcel.java's EX_HAS_REPLY_HEADER
63#define EX_HAS_REPLY_HEADER -128
64
65// Maximum size of a blob to transfer in-place.
66static const size_t IN_PLACE_BLOB_LIMIT = 40 * 1024;
67
68// XXX This can be made public if we want to provide
69// support for typed data.
70struct small_flat_data
71{
72    uint32_t type;
73    uint32_t data;
74};
75
76namespace android {
77
78static pthread_mutex_t gParcelGlobalAllocSizeLock = PTHREAD_MUTEX_INITIALIZER;
79static size_t gParcelGlobalAllocSize = 0;
80static size_t gParcelGlobalAllocCount = 0;
81
82void acquire_object(const sp<ProcessState>& proc,
83    const flat_binder_object& obj, const void* who)
84{
85    switch (obj.type) {
86        case BINDER_TYPE_BINDER:
87            if (obj.binder) {
88                LOG_REFS("Parcel %p acquiring reference on local %p", who, obj.cookie);
89                reinterpret_cast<IBinder*>(obj.cookie)->incStrong(who);
90            }
91            return;
92        case BINDER_TYPE_WEAK_BINDER:
93            if (obj.binder)
94                reinterpret_cast<RefBase::weakref_type*>(obj.binder)->incWeak(who);
95            return;
96        case BINDER_TYPE_HANDLE: {
97            const sp<IBinder> b = proc->getStrongProxyForHandle(obj.handle);
98            if (b != NULL) {
99                LOG_REFS("Parcel %p acquiring reference on remote %p", who, b.get());
100                b->incStrong(who);
101            }
102            return;
103        }
104        case BINDER_TYPE_WEAK_HANDLE: {
105            const wp<IBinder> b = proc->getWeakProxyForHandle(obj.handle);
106            if (b != NULL) b.get_refs()->incWeak(who);
107            return;
108        }
109        case BINDER_TYPE_FD: {
110            // intentionally blank -- nothing to do to acquire this, but we do
111            // recognize it as a legitimate object type.
112            return;
113        }
114    }
115
116    ALOGD("Invalid object type 0x%08x", obj.type);
117}
118
119void release_object(const sp<ProcessState>& proc,
120    const flat_binder_object& obj, const void* who)
121{
122    switch (obj.type) {
123        case BINDER_TYPE_BINDER:
124            if (obj.binder) {
125                LOG_REFS("Parcel %p releasing reference on local %p", who, obj.cookie);
126                reinterpret_cast<IBinder*>(obj.cookie)->decStrong(who);
127            }
128            return;
129        case BINDER_TYPE_WEAK_BINDER:
130            if (obj.binder)
131                reinterpret_cast<RefBase::weakref_type*>(obj.binder)->decWeak(who);
132            return;
133        case BINDER_TYPE_HANDLE: {
134            const sp<IBinder> b = proc->getStrongProxyForHandle(obj.handle);
135            if (b != NULL) {
136                LOG_REFS("Parcel %p releasing reference on remote %p", who, b.get());
137                b->decStrong(who);
138            }
139            return;
140        }
141        case BINDER_TYPE_WEAK_HANDLE: {
142            const wp<IBinder> b = proc->getWeakProxyForHandle(obj.handle);
143            if (b != NULL) b.get_refs()->decWeak(who);
144            return;
145        }
146        case BINDER_TYPE_FD: {
147            if (obj.cookie != 0) close(obj.handle);
148            return;
149        }
150    }
151
152    ALOGE("Invalid object type 0x%08x", obj.type);
153}
154
155inline static status_t finish_flatten_binder(
156    const sp<IBinder>& /*binder*/, const flat_binder_object& flat, Parcel* out)
157{
158    return out->writeObject(flat, false);
159}
160
161status_t flatten_binder(const sp<ProcessState>& /*proc*/,
162    const sp<IBinder>& binder, Parcel* out)
163{
164    flat_binder_object obj;
165
166    obj.flags = 0x7f | FLAT_BINDER_FLAG_ACCEPTS_FDS;
167    if (binder != NULL) {
168        IBinder *local = binder->localBinder();
169        if (!local) {
170            BpBinder *proxy = binder->remoteBinder();
171            if (proxy == NULL) {
172                ALOGE("null proxy");
173            }
174            const int32_t handle = proxy ? proxy->handle() : 0;
175            obj.type = BINDER_TYPE_HANDLE;
176            obj.binder = 0; /* Don't pass uninitialized stack data to a remote process */
177            obj.handle = handle;
178            obj.cookie = 0;
179        } else {
180            obj.type = BINDER_TYPE_BINDER;
181            obj.binder = reinterpret_cast<uintptr_t>(local->getWeakRefs());
182            obj.cookie = reinterpret_cast<uintptr_t>(local);
183        }
184    } else {
185        obj.type = BINDER_TYPE_BINDER;
186        obj.binder = 0;
187        obj.cookie = 0;
188    }
189
190    return finish_flatten_binder(binder, obj, out);
191}
192
193status_t flatten_binder(const sp<ProcessState>& /*proc*/,
194    const wp<IBinder>& binder, Parcel* out)
195{
196    flat_binder_object obj;
197
198    obj.flags = 0x7f | FLAT_BINDER_FLAG_ACCEPTS_FDS;
199    if (binder != NULL) {
200        sp<IBinder> real = binder.promote();
201        if (real != NULL) {
202            IBinder *local = real->localBinder();
203            if (!local) {
204                BpBinder *proxy = real->remoteBinder();
205                if (proxy == NULL) {
206                    ALOGE("null proxy");
207                }
208                const int32_t handle = proxy ? proxy->handle() : 0;
209                obj.type = BINDER_TYPE_WEAK_HANDLE;
210                obj.binder = 0; /* Don't pass uninitialized stack data to a remote process */
211                obj.handle = handle;
212                obj.cookie = 0;
213            } else {
214                obj.type = BINDER_TYPE_WEAK_BINDER;
215                obj.binder = reinterpret_cast<uintptr_t>(binder.get_refs());
216                obj.cookie = reinterpret_cast<uintptr_t>(binder.unsafe_get());
217            }
218            return finish_flatten_binder(real, obj, out);
219        }
220
221        // XXX How to deal?  In order to flatten the given binder,
222        // we need to probe it for information, which requires a primary
223        // reference...  but we don't have one.
224        //
225        // The OpenBinder implementation uses a dynamic_cast<> here,
226        // but we can't do that with the different reference counting
227        // implementation we are using.
228        ALOGE("Unable to unflatten Binder weak reference!");
229        obj.type = BINDER_TYPE_BINDER;
230        obj.binder = 0;
231        obj.cookie = 0;
232        return finish_flatten_binder(NULL, obj, out);
233
234    } else {
235        obj.type = BINDER_TYPE_BINDER;
236        obj.binder = 0;
237        obj.cookie = 0;
238        return finish_flatten_binder(NULL, obj, out);
239    }
240}
241
242inline static status_t finish_unflatten_binder(
243    BpBinder* /*proxy*/, const flat_binder_object& /*flat*/,
244    const Parcel& /*in*/)
245{
246    return NO_ERROR;
247}
248
249status_t unflatten_binder(const sp<ProcessState>& proc,
250    const Parcel& in, sp<IBinder>* out)
251{
252    const flat_binder_object* flat = in.readObject(false);
253
254    if (flat) {
255        switch (flat->type) {
256            case BINDER_TYPE_BINDER:
257                *out = reinterpret_cast<IBinder*>(flat->cookie);
258                return finish_unflatten_binder(NULL, *flat, in);
259            case BINDER_TYPE_HANDLE:
260                *out = proc->getStrongProxyForHandle(flat->handle);
261                return finish_unflatten_binder(
262                    static_cast<BpBinder*>(out->get()), *flat, in);
263        }
264    }
265    return BAD_TYPE;
266}
267
268status_t unflatten_binder(const sp<ProcessState>& proc,
269    const Parcel& in, wp<IBinder>* out)
270{
271    const flat_binder_object* flat = in.readObject(false);
272
273    if (flat) {
274        switch (flat->type) {
275            case BINDER_TYPE_BINDER:
276                *out = reinterpret_cast<IBinder*>(flat->cookie);
277                return finish_unflatten_binder(NULL, *flat, in);
278            case BINDER_TYPE_WEAK_BINDER:
279                if (flat->binder != 0) {
280                    out->set_object_and_refs(
281                        reinterpret_cast<IBinder*>(flat->cookie),
282                        reinterpret_cast<RefBase::weakref_type*>(flat->binder));
283                } else {
284                    *out = NULL;
285                }
286                return finish_unflatten_binder(NULL, *flat, in);
287            case BINDER_TYPE_HANDLE:
288            case BINDER_TYPE_WEAK_HANDLE:
289                *out = proc->getWeakProxyForHandle(flat->handle);
290                return finish_unflatten_binder(
291                    static_cast<BpBinder*>(out->unsafe_get()), *flat, in);
292        }
293    }
294    return BAD_TYPE;
295}
296
297// ---------------------------------------------------------------------------
298
299Parcel::Parcel()
300{
301    LOG_ALLOC("Parcel %p: constructing", this);
302    initState();
303}
304
305Parcel::~Parcel()
306{
307    freeDataNoInit();
308    LOG_ALLOC("Parcel %p: destroyed", this);
309}
310
311size_t Parcel::getGlobalAllocSize() {
312    pthread_mutex_lock(&gParcelGlobalAllocSizeLock);
313    size_t size = gParcelGlobalAllocSize;
314    pthread_mutex_unlock(&gParcelGlobalAllocSizeLock);
315    return size;
316}
317
318size_t Parcel::getGlobalAllocCount() {
319    pthread_mutex_lock(&gParcelGlobalAllocSizeLock);
320    size_t count = gParcelGlobalAllocCount;
321    pthread_mutex_unlock(&gParcelGlobalAllocSizeLock);
322    return count;
323}
324
325const uint8_t* Parcel::data() const
326{
327    return mData;
328}
329
330size_t Parcel::dataSize() const
331{
332    return (mDataSize > mDataPos ? mDataSize : mDataPos);
333}
334
335size_t Parcel::dataAvail() const
336{
337    // TODO: decide what to do about the possibility that this can
338    // report an available-data size that exceeds a Java int's max
339    // positive value, causing havoc.  Fortunately this will only
340    // happen if someone constructs a Parcel containing more than two
341    // gigabytes of data, which on typical phone hardware is simply
342    // not possible.
343    return dataSize() - dataPosition();
344}
345
346size_t Parcel::dataPosition() const
347{
348    return mDataPos;
349}
350
351size_t Parcel::dataCapacity() const
352{
353    return mDataCapacity;
354}
355
356status_t Parcel::setDataSize(size_t size)
357{
358    status_t err;
359    err = continueWrite(size);
360    if (err == NO_ERROR) {
361        mDataSize = size;
362        ALOGV("setDataSize Setting data size of %p to %zu", this, mDataSize);
363    }
364    return err;
365}
366
367void Parcel::setDataPosition(size_t pos) const
368{
369    mDataPos = pos;
370    mNextObjectHint = 0;
371}
372
373status_t Parcel::setDataCapacity(size_t size)
374{
375    if (size > mDataCapacity) return continueWrite(size);
376    return NO_ERROR;
377}
378
379status_t Parcel::setData(const uint8_t* buffer, size_t len)
380{
381    status_t err = restartWrite(len);
382    if (err == NO_ERROR) {
383        memcpy(const_cast<uint8_t*>(data()), buffer, len);
384        mDataSize = len;
385        mFdsKnown = false;
386    }
387    return err;
388}
389
390status_t Parcel::appendFrom(const Parcel *parcel, size_t offset, size_t len)
391{
392    const sp<ProcessState> proc(ProcessState::self());
393    status_t err;
394    const uint8_t *data = parcel->mData;
395    const binder_size_t *objects = parcel->mObjects;
396    size_t size = parcel->mObjectsSize;
397    int startPos = mDataPos;
398    int firstIndex = -1, lastIndex = -2;
399
400    if (len == 0) {
401        return NO_ERROR;
402    }
403
404    // range checks against the source parcel size
405    if ((offset > parcel->mDataSize)
406            || (len > parcel->mDataSize)
407            || (offset + len > parcel->mDataSize)) {
408        return BAD_VALUE;
409    }
410
411    // Count objects in range
412    for (int i = 0; i < (int) size; i++) {
413        size_t off = objects[i];
414        if ((off >= offset) && (off < offset + len)) {
415            if (firstIndex == -1) {
416                firstIndex = i;
417            }
418            lastIndex = i;
419        }
420    }
421    int numObjects = lastIndex - firstIndex + 1;
422
423    if ((mDataSize+len) > mDataCapacity) {
424        // grow data
425        err = growData(len);
426        if (err != NO_ERROR) {
427            return err;
428        }
429    }
430
431    // append data
432    memcpy(mData + mDataPos, data + offset, len);
433    mDataPos += len;
434    mDataSize += len;
435
436    err = NO_ERROR;
437
438    if (numObjects > 0) {
439        // grow objects
440        if (mObjectsCapacity < mObjectsSize + numObjects) {
441            int newSize = ((mObjectsSize + numObjects)*3)/2;
442            binder_size_t *objects =
443                (binder_size_t*)realloc(mObjects, newSize*sizeof(binder_size_t));
444            if (objects == (binder_size_t*)0) {
445                return NO_MEMORY;
446            }
447            mObjects = objects;
448            mObjectsCapacity = newSize;
449        }
450
451        // append and acquire objects
452        int idx = mObjectsSize;
453        for (int i = firstIndex; i <= lastIndex; i++) {
454            size_t off = objects[i] - offset + startPos;
455            mObjects[idx++] = off;
456            mObjectsSize++;
457
458            flat_binder_object* flat
459                = reinterpret_cast<flat_binder_object*>(mData + off);
460            acquire_object(proc, *flat, this);
461
462            if (flat->type == BINDER_TYPE_FD) {
463                // If this is a file descriptor, we need to dup it so the
464                // new Parcel now owns its own fd, and can declare that we
465                // officially know we have fds.
466                flat->handle = dup(flat->handle);
467                flat->cookie = 1;
468                mHasFds = mFdsKnown = true;
469                if (!mAllowFds) {
470                    err = FDS_NOT_ALLOWED;
471                }
472            }
473        }
474    }
475
476    return err;
477}
478
479bool Parcel::pushAllowFds(bool allowFds)
480{
481    const bool origValue = mAllowFds;
482    if (!allowFds) {
483        mAllowFds = false;
484    }
485    return origValue;
486}
487
488void Parcel::restoreAllowFds(bool lastValue)
489{
490    mAllowFds = lastValue;
491}
492
493bool Parcel::hasFileDescriptors() const
494{
495    if (!mFdsKnown) {
496        scanForFds();
497    }
498    return mHasFds;
499}
500
501// Write RPC headers.  (previously just the interface token)
502status_t Parcel::writeInterfaceToken(const String16& interface)
503{
504    writeInt32(IPCThreadState::self()->getStrictModePolicy() |
505               STRICT_MODE_PENALTY_GATHER);
506    // currently the interface identification token is just its name as a string
507    return writeString16(interface);
508}
509
510bool Parcel::checkInterface(IBinder* binder) const
511{
512    return enforceInterface(binder->getInterfaceDescriptor());
513}
514
515bool Parcel::enforceInterface(const String16& interface,
516                              IPCThreadState* threadState) const
517{
518    int32_t strictPolicy = readInt32();
519    if (threadState == NULL) {
520        threadState = IPCThreadState::self();
521    }
522    if ((threadState->getLastTransactionBinderFlags() &
523         IBinder::FLAG_ONEWAY) != 0) {
524      // For one-way calls, the callee is running entirely
525      // disconnected from the caller, so disable StrictMode entirely.
526      // Not only does disk/network usage not impact the caller, but
527      // there's no way to commuicate back any violations anyway.
528      threadState->setStrictModePolicy(0);
529    } else {
530      threadState->setStrictModePolicy(strictPolicy);
531    }
532    const String16 str(readString16());
533    if (str == interface) {
534        return true;
535    } else {
536        ALOGW("**** enforceInterface() expected '%s' but read '%s'",
537                String8(interface).string(), String8(str).string());
538        return false;
539    }
540}
541
542const binder_size_t* Parcel::objects() const
543{
544    return mObjects;
545}
546
547size_t Parcel::objectsCount() const
548{
549    return mObjectsSize;
550}
551
552status_t Parcel::errorCheck() const
553{
554    return mError;
555}
556
557void Parcel::setError(status_t err)
558{
559    mError = err;
560}
561
562status_t Parcel::finishWrite(size_t len)
563{
564    //printf("Finish write of %d\n", len);
565    mDataPos += len;
566    ALOGV("finishWrite Setting data pos of %p to %zu", this, mDataPos);
567    if (mDataPos > mDataSize) {
568        mDataSize = mDataPos;
569        ALOGV("finishWrite Setting data size of %p to %zu", this, mDataSize);
570    }
571    //printf("New pos=%d, size=%d\n", mDataPos, mDataSize);
572    return NO_ERROR;
573}
574
575status_t Parcel::writeUnpadded(const void* data, size_t len)
576{
577    size_t end = mDataPos + len;
578    if (end < mDataPos) {
579        // integer overflow
580        return BAD_VALUE;
581    }
582
583    if (end <= mDataCapacity) {
584restart_write:
585        memcpy(mData+mDataPos, data, len);
586        return finishWrite(len);
587    }
588
589    status_t err = growData(len);
590    if (err == NO_ERROR) goto restart_write;
591    return err;
592}
593
594status_t Parcel::write(const void* data, size_t len)
595{
596    void* const d = writeInplace(len);
597    if (d) {
598        memcpy(d, data, len);
599        return NO_ERROR;
600    }
601    return mError;
602}
603
604void* Parcel::writeInplace(size_t len)
605{
606    const size_t padded = PAD_SIZE(len);
607
608    // sanity check for integer overflow
609    if (mDataPos+padded < mDataPos) {
610        return NULL;
611    }
612
613    if ((mDataPos+padded) <= mDataCapacity) {
614restart_write:
615        //printf("Writing %ld bytes, padded to %ld\n", len, padded);
616        uint8_t* const data = mData+mDataPos;
617
618        // Need to pad at end?
619        if (padded != len) {
620#if BYTE_ORDER == BIG_ENDIAN
621            static const uint32_t mask[4] = {
622                0x00000000, 0xffffff00, 0xffff0000, 0xff000000
623            };
624#endif
625#if BYTE_ORDER == LITTLE_ENDIAN
626            static const uint32_t mask[4] = {
627                0x00000000, 0x00ffffff, 0x0000ffff, 0x000000ff
628            };
629#endif
630            //printf("Applying pad mask: %p to %p\n", (void*)mask[padded-len],
631            //    *reinterpret_cast<void**>(data+padded-4));
632            *reinterpret_cast<uint32_t*>(data+padded-4) &= mask[padded-len];
633        }
634
635        finishWrite(padded);
636        return data;
637    }
638
639    status_t err = growData(padded);
640    if (err == NO_ERROR) goto restart_write;
641    return NULL;
642}
643
644status_t Parcel::writeInt32(int32_t val)
645{
646    return writeAligned(val);
647}
648
649status_t Parcel::writeUint32(uint32_t val)
650{
651    return writeAligned(val);
652}
653
654status_t Parcel::writeInt32Array(size_t len, const int32_t *val) {
655    if (!val) {
656        return writeAligned(-1);
657    }
658    status_t ret = writeAligned(len);
659    if (ret == NO_ERROR) {
660        ret = write(val, len * sizeof(*val));
661    }
662    return ret;
663}
664status_t Parcel::writeByteArray(size_t len, const uint8_t *val) {
665    if (!val) {
666        return writeAligned(-1);
667    }
668    status_t ret = writeAligned(len);
669    if (ret == NO_ERROR) {
670        ret = write(val, len * sizeof(*val));
671    }
672    return ret;
673}
674
675status_t Parcel::writeInt64(int64_t val)
676{
677    return writeAligned(val);
678}
679
680status_t Parcel::writePointer(uintptr_t val)
681{
682    return writeAligned<binder_uintptr_t>(val);
683}
684
685status_t Parcel::writeFloat(float val)
686{
687    return writeAligned(val);
688}
689
690#if defined(__mips__) && defined(__mips_hard_float)
691
692status_t Parcel::writeDouble(double val)
693{
694    union {
695        double d;
696        unsigned long long ll;
697    } u;
698    u.d = val;
699    return writeAligned(u.ll);
700}
701
702#else
703
704status_t Parcel::writeDouble(double val)
705{
706    return writeAligned(val);
707}
708
709#endif
710
711status_t Parcel::writeCString(const char* str)
712{
713    return write(str, strlen(str)+1);
714}
715
716status_t Parcel::writeString8(const String8& str)
717{
718    status_t err = writeInt32(str.bytes());
719    // only write string if its length is more than zero characters,
720    // as readString8 will only read if the length field is non-zero.
721    // this is slightly different from how writeString16 works.
722    if (str.bytes() > 0 && err == NO_ERROR) {
723        err = write(str.string(), str.bytes()+1);
724    }
725    return err;
726}
727
728status_t Parcel::writeString16(const String16& str)
729{
730    return writeString16(str.string(), str.size());
731}
732
733status_t Parcel::writeString16(const char16_t* str, size_t len)
734{
735    if (str == NULL) return writeInt32(-1);
736
737    status_t err = writeInt32(len);
738    if (err == NO_ERROR) {
739        len *= sizeof(char16_t);
740        uint8_t* data = (uint8_t*)writeInplace(len+sizeof(char16_t));
741        if (data) {
742            memcpy(data, str, len);
743            *reinterpret_cast<char16_t*>(data+len) = 0;
744            return NO_ERROR;
745        }
746        err = mError;
747    }
748    return err;
749}
750
751status_t Parcel::writeStrongBinder(const sp<IBinder>& val)
752{
753    return flatten_binder(ProcessState::self(), val, this);
754}
755
756status_t Parcel::writeWeakBinder(const wp<IBinder>& val)
757{
758    return flatten_binder(ProcessState::self(), val, this);
759}
760
761status_t Parcel::writeNativeHandle(const native_handle* handle)
762{
763    if (!handle || handle->version != sizeof(native_handle))
764        return BAD_TYPE;
765
766    status_t err;
767    err = writeInt32(handle->numFds);
768    if (err != NO_ERROR) return err;
769
770    err = writeInt32(handle->numInts);
771    if (err != NO_ERROR) return err;
772
773    for (int i=0 ; err==NO_ERROR && i<handle->numFds ; i++)
774        err = writeDupFileDescriptor(handle->data[i]);
775
776    if (err != NO_ERROR) {
777        ALOGD("write native handle, write dup fd failed");
778        return err;
779    }
780    err = write(handle->data + handle->numFds, sizeof(int)*handle->numInts);
781    return err;
782}
783
784status_t Parcel::writeFileDescriptor(int fd, bool takeOwnership)
785{
786    flat_binder_object obj;
787    obj.type = BINDER_TYPE_FD;
788    obj.flags = 0x7f | FLAT_BINDER_FLAG_ACCEPTS_FDS;
789    obj.binder = 0; /* Don't pass uninitialized stack data to a remote process */
790    obj.handle = fd;
791    obj.cookie = takeOwnership ? 1 : 0;
792    return writeObject(obj, true);
793}
794
795status_t Parcel::writeDupFileDescriptor(int fd)
796{
797    int dupFd = dup(fd);
798    if (dupFd < 0) {
799        return -errno;
800    }
801    status_t err = writeFileDescriptor(dupFd, true /*takeOwnership*/);
802    if (err) {
803        close(dupFd);
804    }
805    return err;
806}
807
808// WARNING: This method must stay in sync with
809// Parcelable.Creator<ParcelFileDescriptor> CREATOR
810// in frameworks/base/core/java/android/os/ParcelFileDescriptor.java
811status_t Parcel::writeParcelFileDescriptor(int fd, int commChannel) {
812    status_t status;
813
814    if (fd < 0) {
815        status = writeInt32(0); // ParcelFileDescriptor is null
816        if (status) return status;
817    } else {
818        status = writeInt32(1); // ParcelFileDescriptor is not null
819        if (status) return status;
820        status = writeDupFileDescriptor(fd);
821        if (status) return status;
822        if (commChannel < 0) {
823            status = writeInt32(0); // commChannel is null
824            if (status) return status;
825        } else {
826            status = writeInt32(1); // commChannel is not null
827            if (status) return status;
828            status = writeDupFileDescriptor(commChannel);
829        }
830    }
831    return status;
832}
833
834status_t Parcel::writeBlob(size_t len, WritableBlob* outBlob)
835{
836    status_t status;
837
838    if (!mAllowFds || len <= IN_PLACE_BLOB_LIMIT) {
839        ALOGV("writeBlob: write in place");
840        status = writeInt32(0);
841        if (status) return status;
842
843        void* ptr = writeInplace(len);
844        if (!ptr) return NO_MEMORY;
845
846        outBlob->init(false /*mapped*/, ptr, len);
847        return NO_ERROR;
848    }
849
850    ALOGV("writeBlob: write to ashmem");
851    int fd = ashmem_create_region("Parcel Blob", len);
852    if (fd < 0) return NO_MEMORY;
853
854    int result = ashmem_set_prot_region(fd, PROT_READ | PROT_WRITE);
855    if (result < 0) {
856        status = result;
857    } else {
858        void* ptr = ::mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
859        if (ptr == MAP_FAILED) {
860            status = -errno;
861        } else {
862            result = ashmem_set_prot_region(fd, PROT_READ);
863            if (result < 0) {
864                status = result;
865            } else {
866                status = writeInt32(1);
867                if (!status) {
868                    status = writeFileDescriptor(fd, true /*takeOwnership*/);
869                    if (!status) {
870                        outBlob->init(true /*mapped*/, ptr, len);
871                        return NO_ERROR;
872                    }
873                }
874            }
875        }
876        ::munmap(ptr, len);
877    }
878    ::close(fd);
879    return status;
880}
881
882status_t Parcel::write(const FlattenableHelperInterface& val)
883{
884    status_t err;
885
886    // size if needed
887    const size_t len = val.getFlattenedSize();
888    const size_t fd_count = val.getFdCount();
889
890    err = this->writeInt32(len);
891    if (err) return err;
892
893    err = this->writeInt32(fd_count);
894    if (err) return err;
895
896    // payload
897    void* const buf = this->writeInplace(PAD_SIZE(len));
898    if (buf == NULL)
899        return BAD_VALUE;
900
901    int* fds = NULL;
902    if (fd_count) {
903        fds = new int[fd_count];
904    }
905
906    err = val.flatten(buf, len, fds, fd_count);
907    for (size_t i=0 ; i<fd_count && err==NO_ERROR ; i++) {
908        err = this->writeDupFileDescriptor( fds[i] );
909    }
910
911    if (fd_count) {
912        delete [] fds;
913    }
914
915    return err;
916}
917
918status_t Parcel::writeObject(const flat_binder_object& val, bool nullMetaData)
919{
920    const bool enoughData = (mDataPos+sizeof(val)) <= mDataCapacity;
921    const bool enoughObjects = mObjectsSize < mObjectsCapacity;
922    if (enoughData && enoughObjects) {
923restart_write:
924        *reinterpret_cast<flat_binder_object*>(mData+mDataPos) = val;
925
926        // Need to write meta-data?
927        if (nullMetaData || val.binder != 0) {
928            mObjects[mObjectsSize] = mDataPos;
929            acquire_object(ProcessState::self(), val, this);
930            mObjectsSize++;
931        }
932
933        // remember if it's a file descriptor
934        if (val.type == BINDER_TYPE_FD) {
935            if (!mAllowFds) {
936                return FDS_NOT_ALLOWED;
937            }
938            mHasFds = mFdsKnown = true;
939        }
940
941        return finishWrite(sizeof(flat_binder_object));
942    }
943
944    if (!enoughData) {
945        const status_t err = growData(sizeof(val));
946        if (err != NO_ERROR) return err;
947    }
948    if (!enoughObjects) {
949        size_t newSize = ((mObjectsSize+2)*3)/2;
950        binder_size_t* objects = (binder_size_t*)realloc(mObjects, newSize*sizeof(binder_size_t));
951        if (objects == NULL) return NO_MEMORY;
952        mObjects = objects;
953        mObjectsCapacity = newSize;
954    }
955
956    goto restart_write;
957}
958
959status_t Parcel::writeNoException()
960{
961    return writeInt32(0);
962}
963
964void Parcel::remove(size_t /*start*/, size_t /*amt*/)
965{
966    LOG_ALWAYS_FATAL("Parcel::remove() not yet implemented!");
967}
968
969status_t Parcel::read(void* outData, size_t len) const
970{
971    if ((mDataPos+PAD_SIZE(len)) >= mDataPos && (mDataPos+PAD_SIZE(len)) <= mDataSize
972            && len <= PAD_SIZE(len)) {
973        memcpy(outData, mData+mDataPos, len);
974        mDataPos += PAD_SIZE(len);
975        ALOGV("read Setting data pos of %p to %zu", this, mDataPos);
976        return NO_ERROR;
977    }
978    return NOT_ENOUGH_DATA;
979}
980
981const void* Parcel::readInplace(size_t len) const
982{
983    if ((mDataPos+PAD_SIZE(len)) >= mDataPos && (mDataPos+PAD_SIZE(len)) <= mDataSize
984            && len <= PAD_SIZE(len)) {
985        const void* data = mData+mDataPos;
986        mDataPos += PAD_SIZE(len);
987        ALOGV("readInplace Setting data pos of %p to %zu", this, mDataPos);
988        return data;
989    }
990    return NULL;
991}
992
993template<class T>
994status_t Parcel::readAligned(T *pArg) const {
995    COMPILE_TIME_ASSERT_FUNCTION_SCOPE(PAD_SIZE(sizeof(T)) == sizeof(T));
996
997    if ((mDataPos+sizeof(T)) <= mDataSize) {
998        const void* data = mData+mDataPos;
999        mDataPos += sizeof(T);
1000        *pArg =  *reinterpret_cast<const T*>(data);
1001        return NO_ERROR;
1002    } else {
1003        return NOT_ENOUGH_DATA;
1004    }
1005}
1006
1007template<class T>
1008T Parcel::readAligned() const {
1009    T result;
1010    if (readAligned(&result) != NO_ERROR) {
1011        result = 0;
1012    }
1013
1014    return result;
1015}
1016
1017template<class T>
1018status_t Parcel::writeAligned(T val) {
1019    COMPILE_TIME_ASSERT_FUNCTION_SCOPE(PAD_SIZE(sizeof(T)) == sizeof(T));
1020
1021    if ((mDataPos+sizeof(val)) <= mDataCapacity) {
1022restart_write:
1023        *reinterpret_cast<T*>(mData+mDataPos) = val;
1024        return finishWrite(sizeof(val));
1025    }
1026
1027    status_t err = growData(sizeof(val));
1028    if (err == NO_ERROR) goto restart_write;
1029    return err;
1030}
1031
1032status_t Parcel::readInt32(int32_t *pArg) const
1033{
1034    return readAligned(pArg);
1035}
1036
1037int32_t Parcel::readInt32() const
1038{
1039    return readAligned<int32_t>();
1040}
1041
1042status_t Parcel::readUint32(uint32_t *pArg) const
1043{
1044    return readAligned(pArg);
1045}
1046
1047uint32_t Parcel::readUint32() const
1048{
1049    return readAligned<uint32_t>();
1050}
1051
1052status_t Parcel::readInt64(int64_t *pArg) const
1053{
1054    return readAligned(pArg);
1055}
1056
1057
1058int64_t Parcel::readInt64() const
1059{
1060    return readAligned<int64_t>();
1061}
1062
1063status_t Parcel::readPointer(uintptr_t *pArg) const
1064{
1065    status_t ret;
1066    binder_uintptr_t ptr;
1067    ret = readAligned(&ptr);
1068    if (!ret)
1069        *pArg = ptr;
1070    return ret;
1071}
1072
1073uintptr_t Parcel::readPointer() const
1074{
1075    return readAligned<binder_uintptr_t>();
1076}
1077
1078
1079status_t Parcel::readFloat(float *pArg) const
1080{
1081    return readAligned(pArg);
1082}
1083
1084
1085float Parcel::readFloat() const
1086{
1087    return readAligned<float>();
1088}
1089
1090#if defined(__mips__) && defined(__mips_hard_float)
1091
1092status_t Parcel::readDouble(double *pArg) const
1093{
1094    union {
1095      double d;
1096      unsigned long long ll;
1097    } u;
1098    u.d = 0;
1099    status_t status;
1100    status = readAligned(&u.ll);
1101    *pArg = u.d;
1102    return status;
1103}
1104
1105double Parcel::readDouble() const
1106{
1107    union {
1108      double d;
1109      unsigned long long ll;
1110    } u;
1111    u.ll = readAligned<unsigned long long>();
1112    return u.d;
1113}
1114
1115#else
1116
1117status_t Parcel::readDouble(double *pArg) const
1118{
1119    return readAligned(pArg);
1120}
1121
1122double Parcel::readDouble() const
1123{
1124    return readAligned<double>();
1125}
1126
1127#endif
1128
1129status_t Parcel::readIntPtr(intptr_t *pArg) const
1130{
1131    return readAligned(pArg);
1132}
1133
1134
1135intptr_t Parcel::readIntPtr() const
1136{
1137    return readAligned<intptr_t>();
1138}
1139
1140
1141const char* Parcel::readCString() const
1142{
1143    const size_t avail = mDataSize-mDataPos;
1144    if (avail > 0) {
1145        const char* str = reinterpret_cast<const char*>(mData+mDataPos);
1146        // is the string's trailing NUL within the parcel's valid bounds?
1147        const char* eos = reinterpret_cast<const char*>(memchr(str, 0, avail));
1148        if (eos) {
1149            const size_t len = eos - str;
1150            mDataPos += PAD_SIZE(len+1);
1151            ALOGV("readCString Setting data pos of %p to %zu", this, mDataPos);
1152            return str;
1153        }
1154    }
1155    return NULL;
1156}
1157
1158String8 Parcel::readString8() const
1159{
1160    int32_t size = readInt32();
1161    // watch for potential int overflow adding 1 for trailing NUL
1162    if (size > 0 && size < INT32_MAX) {
1163        const char* str = (const char*)readInplace(size+1);
1164        if (str) return String8(str, size);
1165    }
1166    return String8();
1167}
1168
1169String16 Parcel::readString16() const
1170{
1171    size_t len;
1172    const char16_t* str = readString16Inplace(&len);
1173    if (str) return String16(str, len);
1174    ALOGE("Reading a NULL string not supported here.");
1175    return String16();
1176}
1177
1178const char16_t* Parcel::readString16Inplace(size_t* outLen) const
1179{
1180    int32_t size = readInt32();
1181    // watch for potential int overflow from size+1
1182    if (size >= 0 && size < INT32_MAX) {
1183        *outLen = size;
1184        const char16_t* str = (const char16_t*)readInplace((size+1)*sizeof(char16_t));
1185        if (str != NULL) {
1186            return str;
1187        }
1188    }
1189    *outLen = 0;
1190    return NULL;
1191}
1192
1193sp<IBinder> Parcel::readStrongBinder() const
1194{
1195    sp<IBinder> val;
1196    unflatten_binder(ProcessState::self(), *this, &val);
1197    return val;
1198}
1199
1200wp<IBinder> Parcel::readWeakBinder() const
1201{
1202    wp<IBinder> val;
1203    unflatten_binder(ProcessState::self(), *this, &val);
1204    return val;
1205}
1206
1207int32_t Parcel::readExceptionCode() const
1208{
1209  int32_t exception_code = readAligned<int32_t>();
1210  if (exception_code == EX_HAS_REPLY_HEADER) {
1211    int32_t header_start = dataPosition();
1212    int32_t header_size = readAligned<int32_t>();
1213    // Skip over fat responses headers.  Not used (or propagated) in
1214    // native code
1215    setDataPosition(header_start + header_size);
1216    // And fat response headers are currently only used when there are no
1217    // exceptions, so return no error:
1218    return 0;
1219  }
1220  return exception_code;
1221}
1222
1223native_handle* Parcel::readNativeHandle() const
1224{
1225    int numFds, numInts;
1226    status_t err;
1227    err = readInt32(&numFds);
1228    if (err != NO_ERROR) return 0;
1229    err = readInt32(&numInts);
1230    if (err != NO_ERROR) return 0;
1231
1232    native_handle* h = native_handle_create(numFds, numInts);
1233    for (int i=0 ; err==NO_ERROR && i<numFds ; i++) {
1234        h->data[i] = dup(readFileDescriptor());
1235        if (h->data[i] < 0) err = BAD_VALUE;
1236    }
1237    err = read(h->data + numFds, sizeof(int)*numInts);
1238    if (err != NO_ERROR) {
1239        native_handle_close(h);
1240        native_handle_delete(h);
1241        h = 0;
1242    }
1243    return h;
1244}
1245
1246
1247int Parcel::readFileDescriptor() const
1248{
1249    const flat_binder_object* flat = readObject(true);
1250    if (flat) {
1251        switch (flat->type) {
1252            case BINDER_TYPE_FD:
1253                //ALOGI("Returning file descriptor %ld from parcel %p", flat->handle, this);
1254                return flat->handle;
1255        }
1256    }
1257    return BAD_TYPE;
1258}
1259
1260// WARNING: This method must stay in sync with writeToParcel()
1261// in frameworks/base/core/java/android/os/ParcelFileDescriptor.java
1262int Parcel::readParcelFileDescriptor(int& outCommChannel) const {
1263    int fd;
1264    outCommChannel = -1;
1265
1266    if (readInt32() == 0) {
1267        fd = -1;
1268    } else {
1269        fd = readFileDescriptor();
1270        if (fd >= 0 && readInt32() != 0) {
1271            outCommChannel = readFileDescriptor();
1272        }
1273    }
1274    return fd;
1275}
1276
1277status_t Parcel::readBlob(size_t len, ReadableBlob* outBlob) const
1278{
1279    int32_t useAshmem;
1280    status_t status = readInt32(&useAshmem);
1281    if (status) return status;
1282
1283    if (!useAshmem) {
1284        ALOGV("readBlob: read in place");
1285        const void* ptr = readInplace(len);
1286        if (!ptr) return BAD_VALUE;
1287
1288        outBlob->init(false /*mapped*/, const_cast<void*>(ptr), len);
1289        return NO_ERROR;
1290    }
1291
1292    ALOGV("readBlob: read from ashmem");
1293    int fd = readFileDescriptor();
1294    if (fd == int(BAD_TYPE)) return BAD_VALUE;
1295
1296    void* ptr = ::mmap(NULL, len, PROT_READ, MAP_SHARED, fd, 0);
1297    if (ptr == MAP_FAILED) return NO_MEMORY;
1298
1299    outBlob->init(true /*mapped*/, ptr, len);
1300    return NO_ERROR;
1301}
1302
1303status_t Parcel::read(FlattenableHelperInterface& val) const
1304{
1305    // size
1306    const size_t len = this->readInt32();
1307    const size_t fd_count = this->readInt32();
1308
1309    // payload
1310    void const* const buf = this->readInplace(PAD_SIZE(len));
1311    if (buf == NULL)
1312        return BAD_VALUE;
1313
1314    int* fds = NULL;
1315    if (fd_count) {
1316        fds = new int[fd_count];
1317    }
1318
1319    status_t err = NO_ERROR;
1320    for (size_t i=0 ; i<fd_count && err==NO_ERROR ; i++) {
1321        fds[i] = dup(this->readFileDescriptor());
1322        if (fds[i] < 0) {
1323            err = BAD_VALUE;
1324            ALOGE("dup() failed in Parcel::read, i is %zu, fds[i] is %d, fd_count is %zu, error: %s",
1325                i, fds[i], fd_count, strerror(errno));
1326        }
1327    }
1328
1329    if (err == NO_ERROR) {
1330        err = val.unflatten(buf, len, fds, fd_count);
1331    }
1332
1333    if (fd_count) {
1334        delete [] fds;
1335    }
1336
1337    return err;
1338}
1339const flat_binder_object* Parcel::readObject(bool nullMetaData) const
1340{
1341    const size_t DPOS = mDataPos;
1342    if ((DPOS+sizeof(flat_binder_object)) <= mDataSize) {
1343        const flat_binder_object* obj
1344                = reinterpret_cast<const flat_binder_object*>(mData+DPOS);
1345        mDataPos = DPOS + sizeof(flat_binder_object);
1346        if (!nullMetaData && (obj->cookie == 0 && obj->binder == 0)) {
1347            // When transferring a NULL object, we don't write it into
1348            // the object list, so we don't want to check for it when
1349            // reading.
1350            ALOGV("readObject Setting data pos of %p to %zu", this, mDataPos);
1351            return obj;
1352        }
1353
1354        // Ensure that this object is valid...
1355        binder_size_t* const OBJS = mObjects;
1356        const size_t N = mObjectsSize;
1357        size_t opos = mNextObjectHint;
1358
1359        if (N > 0) {
1360            ALOGV("Parcel %p looking for obj at %zu, hint=%zu",
1361                 this, DPOS, opos);
1362
1363            // Start at the current hint position, looking for an object at
1364            // the current data position.
1365            if (opos < N) {
1366                while (opos < (N-1) && OBJS[opos] < DPOS) {
1367                    opos++;
1368                }
1369            } else {
1370                opos = N-1;
1371            }
1372            if (OBJS[opos] == DPOS) {
1373                // Found it!
1374                ALOGV("Parcel %p found obj %zu at index %zu with forward search",
1375                     this, DPOS, opos);
1376                mNextObjectHint = opos+1;
1377                ALOGV("readObject Setting data pos of %p to %zu", this, mDataPos);
1378                return obj;
1379            }
1380
1381            // Look backwards for it...
1382            while (opos > 0 && OBJS[opos] > DPOS) {
1383                opos--;
1384            }
1385            if (OBJS[opos] == DPOS) {
1386                // Found it!
1387                ALOGV("Parcel %p found obj %zu at index %zu with backward search",
1388                     this, DPOS, opos);
1389                mNextObjectHint = opos+1;
1390                ALOGV("readObject Setting data pos of %p to %zu", this, mDataPos);
1391                return obj;
1392            }
1393        }
1394        ALOGW("Attempt to read object from Parcel %p at offset %zu that is not in the object list",
1395             this, DPOS);
1396    }
1397    return NULL;
1398}
1399
1400void Parcel::closeFileDescriptors()
1401{
1402    size_t i = mObjectsSize;
1403    if (i > 0) {
1404        //ALOGI("Closing file descriptors for %zu objects...", i);
1405    }
1406    while (i > 0) {
1407        i--;
1408        const flat_binder_object* flat
1409            = reinterpret_cast<flat_binder_object*>(mData+mObjects[i]);
1410        if (flat->type == BINDER_TYPE_FD) {
1411            //ALOGI("Closing fd: %ld", flat->handle);
1412            close(flat->handle);
1413        }
1414    }
1415}
1416
1417uintptr_t Parcel::ipcData() const
1418{
1419    return reinterpret_cast<uintptr_t>(mData);
1420}
1421
1422size_t Parcel::ipcDataSize() const
1423{
1424    return (mDataSize > mDataPos ? mDataSize : mDataPos);
1425}
1426
1427uintptr_t Parcel::ipcObjects() const
1428{
1429    return reinterpret_cast<uintptr_t>(mObjects);
1430}
1431
1432size_t Parcel::ipcObjectsCount() const
1433{
1434    return mObjectsSize;
1435}
1436
1437void Parcel::ipcSetDataReference(const uint8_t* data, size_t dataSize,
1438    const binder_size_t* objects, size_t objectsCount, release_func relFunc, void* relCookie)
1439{
1440    binder_size_t minOffset = 0;
1441    freeDataNoInit();
1442    mError = NO_ERROR;
1443    mData = const_cast<uint8_t*>(data);
1444    mDataSize = mDataCapacity = dataSize;
1445    //ALOGI("setDataReference Setting data size of %p to %lu (pid=%d)", this, mDataSize, getpid());
1446    mDataPos = 0;
1447    ALOGV("setDataReference Setting data pos of %p to %zu", this, mDataPos);
1448    mObjects = const_cast<binder_size_t*>(objects);
1449    mObjectsSize = mObjectsCapacity = objectsCount;
1450    mNextObjectHint = 0;
1451    mOwner = relFunc;
1452    mOwnerCookie = relCookie;
1453    for (size_t i = 0; i < mObjectsSize; i++) {
1454        binder_size_t offset = mObjects[i];
1455        if (offset < minOffset) {
1456            ALOGE("%s: bad object offset %" PRIu64 " < %" PRIu64 "\n",
1457                  __func__, (uint64_t)offset, (uint64_t)minOffset);
1458            mObjectsSize = 0;
1459            break;
1460        }
1461        minOffset = offset + sizeof(flat_binder_object);
1462    }
1463    scanForFds();
1464}
1465
1466void Parcel::print(TextOutput& to, uint32_t /*flags*/) const
1467{
1468    to << "Parcel(";
1469
1470    if (errorCheck() != NO_ERROR) {
1471        const status_t err = errorCheck();
1472        to << "Error: " << (void*)(intptr_t)err << " \"" << strerror(-err) << "\"";
1473    } else if (dataSize() > 0) {
1474        const uint8_t* DATA = data();
1475        to << indent << HexDump(DATA, dataSize()) << dedent;
1476        const binder_size_t* OBJS = objects();
1477        const size_t N = objectsCount();
1478        for (size_t i=0; i<N; i++) {
1479            const flat_binder_object* flat
1480                = reinterpret_cast<const flat_binder_object*>(DATA+OBJS[i]);
1481            to << endl << "Object #" << i << " @ " << (void*)OBJS[i] << ": "
1482                << TypeCode(flat->type & 0x7f7f7f00)
1483                << " = " << flat->binder;
1484        }
1485    } else {
1486        to << "NULL";
1487    }
1488
1489    to << ")";
1490}
1491
1492void Parcel::releaseObjects()
1493{
1494    const sp<ProcessState> proc(ProcessState::self());
1495    size_t i = mObjectsSize;
1496    uint8_t* const data = mData;
1497    binder_size_t* const objects = mObjects;
1498    while (i > 0) {
1499        i--;
1500        const flat_binder_object* flat
1501            = reinterpret_cast<flat_binder_object*>(data+objects[i]);
1502        release_object(proc, *flat, this);
1503    }
1504}
1505
1506void Parcel::acquireObjects()
1507{
1508    const sp<ProcessState> proc(ProcessState::self());
1509    size_t i = mObjectsSize;
1510    uint8_t* const data = mData;
1511    binder_size_t* const objects = mObjects;
1512    while (i > 0) {
1513        i--;
1514        const flat_binder_object* flat
1515            = reinterpret_cast<flat_binder_object*>(data+objects[i]);
1516        acquire_object(proc, *flat, this);
1517    }
1518}
1519
1520void Parcel::freeData()
1521{
1522    freeDataNoInit();
1523    initState();
1524}
1525
1526void Parcel::freeDataNoInit()
1527{
1528    if (mOwner) {
1529        LOG_ALLOC("Parcel %p: freeing other owner data", this);
1530        //ALOGI("Freeing data ref of %p (pid=%d)", this, getpid());
1531        mOwner(this, mData, mDataSize, mObjects, mObjectsSize, mOwnerCookie);
1532    } else {
1533        LOG_ALLOC("Parcel %p: freeing allocated data", this);
1534        releaseObjects();
1535        if (mData) {
1536            LOG_ALLOC("Parcel %p: freeing with %zu capacity", this, mDataCapacity);
1537            pthread_mutex_lock(&gParcelGlobalAllocSizeLock);
1538            gParcelGlobalAllocSize -= mDataCapacity;
1539            gParcelGlobalAllocCount--;
1540            pthread_mutex_unlock(&gParcelGlobalAllocSizeLock);
1541            free(mData);
1542        }
1543        if (mObjects) free(mObjects);
1544    }
1545}
1546
1547status_t Parcel::growData(size_t len)
1548{
1549    size_t newSize = ((mDataSize+len)*3)/2;
1550    return (newSize <= mDataSize)
1551            ? (status_t) NO_MEMORY
1552            : continueWrite(newSize);
1553}
1554
1555status_t Parcel::restartWrite(size_t desired)
1556{
1557    if (mOwner) {
1558        freeData();
1559        return continueWrite(desired);
1560    }
1561
1562    uint8_t* data = (uint8_t*)realloc(mData, desired);
1563    if (!data && desired > mDataCapacity) {
1564        mError = NO_MEMORY;
1565        return NO_MEMORY;
1566    }
1567
1568    releaseObjects();
1569
1570    if (data) {
1571        LOG_ALLOC("Parcel %p: restart from %zu to %zu capacity", this, mDataCapacity, desired);
1572        pthread_mutex_lock(&gParcelGlobalAllocSizeLock);
1573        gParcelGlobalAllocSize += desired;
1574        gParcelGlobalAllocSize -= mDataCapacity;
1575        pthread_mutex_unlock(&gParcelGlobalAllocSizeLock);
1576        mData = data;
1577        mDataCapacity = desired;
1578    }
1579
1580    mDataSize = mDataPos = 0;
1581    ALOGV("restartWrite Setting data size of %p to %zu", this, mDataSize);
1582    ALOGV("restartWrite Setting data pos of %p to %zu", this, mDataPos);
1583
1584    free(mObjects);
1585    mObjects = NULL;
1586    mObjectsSize = mObjectsCapacity = 0;
1587    mNextObjectHint = 0;
1588    mHasFds = false;
1589    mFdsKnown = true;
1590    mAllowFds = true;
1591
1592    return NO_ERROR;
1593}
1594
1595status_t Parcel::continueWrite(size_t desired)
1596{
1597    // If shrinking, first adjust for any objects that appear
1598    // after the new data size.
1599    size_t objectsSize = mObjectsSize;
1600    if (desired < mDataSize) {
1601        if (desired == 0) {
1602            objectsSize = 0;
1603        } else {
1604            while (objectsSize > 0) {
1605                if (mObjects[objectsSize-1] < desired)
1606                    break;
1607                objectsSize--;
1608            }
1609        }
1610    }
1611
1612    if (mOwner) {
1613        // If the size is going to zero, just release the owner's data.
1614        if (desired == 0) {
1615            freeData();
1616            return NO_ERROR;
1617        }
1618
1619        // If there is a different owner, we need to take
1620        // posession.
1621        uint8_t* data = (uint8_t*)malloc(desired);
1622        if (!data) {
1623            mError = NO_MEMORY;
1624            return NO_MEMORY;
1625        }
1626        binder_size_t* objects = NULL;
1627
1628        if (objectsSize) {
1629            objects = (binder_size_t*)malloc(objectsSize*sizeof(binder_size_t));
1630            if (!objects) {
1631                free(data);
1632
1633                mError = NO_MEMORY;
1634                return NO_MEMORY;
1635            }
1636
1637            // Little hack to only acquire references on objects
1638            // we will be keeping.
1639            size_t oldObjectsSize = mObjectsSize;
1640            mObjectsSize = objectsSize;
1641            acquireObjects();
1642            mObjectsSize = oldObjectsSize;
1643        }
1644
1645        if (mData) {
1646            memcpy(data, mData, mDataSize < desired ? mDataSize : desired);
1647        }
1648        if (objects && mObjects) {
1649            memcpy(objects, mObjects, objectsSize*sizeof(binder_size_t));
1650        }
1651        //ALOGI("Freeing data ref of %p (pid=%d)", this, getpid());
1652        mOwner(this, mData, mDataSize, mObjects, mObjectsSize, mOwnerCookie);
1653        mOwner = NULL;
1654
1655        LOG_ALLOC("Parcel %p: taking ownership of %zu capacity", this, desired);
1656        pthread_mutex_lock(&gParcelGlobalAllocSizeLock);
1657        gParcelGlobalAllocSize += desired;
1658        gParcelGlobalAllocCount++;
1659        pthread_mutex_unlock(&gParcelGlobalAllocSizeLock);
1660
1661        mData = data;
1662        mObjects = objects;
1663        mDataSize = (mDataSize < desired) ? mDataSize : desired;
1664        ALOGV("continueWrite Setting data size of %p to %zu", this, mDataSize);
1665        mDataCapacity = desired;
1666        mObjectsSize = mObjectsCapacity = objectsSize;
1667        mNextObjectHint = 0;
1668
1669    } else if (mData) {
1670        if (objectsSize < mObjectsSize) {
1671            // Need to release refs on any objects we are dropping.
1672            const sp<ProcessState> proc(ProcessState::self());
1673            for (size_t i=objectsSize; i<mObjectsSize; i++) {
1674                const flat_binder_object* flat
1675                    = reinterpret_cast<flat_binder_object*>(mData+mObjects[i]);
1676                if (flat->type == BINDER_TYPE_FD) {
1677                    // will need to rescan because we may have lopped off the only FDs
1678                    mFdsKnown = false;
1679                }
1680                release_object(proc, *flat, this);
1681            }
1682            binder_size_t* objects =
1683                (binder_size_t*)realloc(mObjects, objectsSize*sizeof(binder_size_t));
1684            if (objects) {
1685                mObjects = objects;
1686            }
1687            mObjectsSize = objectsSize;
1688            mNextObjectHint = 0;
1689        }
1690
1691        // We own the data, so we can just do a realloc().
1692        if (desired > mDataCapacity) {
1693            uint8_t* data = (uint8_t*)realloc(mData, desired);
1694            if (data) {
1695                LOG_ALLOC("Parcel %p: continue from %zu to %zu capacity", this, mDataCapacity,
1696                        desired);
1697                pthread_mutex_lock(&gParcelGlobalAllocSizeLock);
1698                gParcelGlobalAllocSize += desired;
1699                gParcelGlobalAllocSize -= mDataCapacity;
1700                pthread_mutex_unlock(&gParcelGlobalAllocSizeLock);
1701                mData = data;
1702                mDataCapacity = desired;
1703            } else if (desired > mDataCapacity) {
1704                mError = NO_MEMORY;
1705                return NO_MEMORY;
1706            }
1707        } else {
1708            if (mDataSize > desired) {
1709                mDataSize = desired;
1710                ALOGV("continueWrite Setting data size of %p to %zu", this, mDataSize);
1711            }
1712            if (mDataPos > desired) {
1713                mDataPos = desired;
1714                ALOGV("continueWrite Setting data pos of %p to %zu", this, mDataPos);
1715            }
1716        }
1717
1718    } else {
1719        // This is the first data.  Easy!
1720        uint8_t* data = (uint8_t*)malloc(desired);
1721        if (!data) {
1722            mError = NO_MEMORY;
1723            return NO_MEMORY;
1724        }
1725
1726        if(!(mDataCapacity == 0 && mObjects == NULL
1727             && mObjectsCapacity == 0)) {
1728            ALOGE("continueWrite: %zu/%p/%zu/%zu", mDataCapacity, mObjects, mObjectsCapacity, desired);
1729        }
1730
1731        LOG_ALLOC("Parcel %p: allocating with %zu capacity", this, desired);
1732        pthread_mutex_lock(&gParcelGlobalAllocSizeLock);
1733        gParcelGlobalAllocSize += desired;
1734        gParcelGlobalAllocCount++;
1735        pthread_mutex_unlock(&gParcelGlobalAllocSizeLock);
1736
1737        mData = data;
1738        mDataSize = mDataPos = 0;
1739        ALOGV("continueWrite Setting data size of %p to %zu", this, mDataSize);
1740        ALOGV("continueWrite Setting data pos of %p to %zu", this, mDataPos);
1741        mDataCapacity = desired;
1742    }
1743
1744    return NO_ERROR;
1745}
1746
1747void Parcel::initState()
1748{
1749    LOG_ALLOC("Parcel %p: initState", this);
1750    mError = NO_ERROR;
1751    mData = 0;
1752    mDataSize = 0;
1753    mDataCapacity = 0;
1754    mDataPos = 0;
1755    ALOGV("initState Setting data size of %p to %zu", this, mDataSize);
1756    ALOGV("initState Setting data pos of %p to %zu", this, mDataPos);
1757    mObjects = NULL;
1758    mObjectsSize = 0;
1759    mObjectsCapacity = 0;
1760    mNextObjectHint = 0;
1761    mHasFds = false;
1762    mFdsKnown = true;
1763    mAllowFds = true;
1764    mOwner = NULL;
1765}
1766
1767void Parcel::scanForFds() const
1768{
1769    bool hasFds = false;
1770    for (size_t i=0; i<mObjectsSize; i++) {
1771        const flat_binder_object* flat
1772            = reinterpret_cast<const flat_binder_object*>(mData + mObjects[i]);
1773        if (flat->type == BINDER_TYPE_FD) {
1774            hasFds = true;
1775            break;
1776        }
1777    }
1778    mHasFds = hasFds;
1779    mFdsKnown = true;
1780}
1781
1782// --- Parcel::Blob ---
1783
1784Parcel::Blob::Blob() :
1785        mMapped(false), mData(NULL), mSize(0) {
1786}
1787
1788Parcel::Blob::~Blob() {
1789    release();
1790}
1791
1792void Parcel::Blob::release() {
1793    if (mMapped && mData) {
1794        ::munmap(mData, mSize);
1795    }
1796    clear();
1797}
1798
1799void Parcel::Blob::init(bool mapped, void* data, size_t size) {
1800    mMapped = mapped;
1801    mData = data;
1802    mSize = size;
1803}
1804
1805void Parcel::Blob::clear() {
1806    mMapped = false;
1807    mData = NULL;
1808    mSize = 0;
1809}
1810
1811}; // namespace android
1812