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