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