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