Parcel.cpp revision 13de7f1defd259f41da9d1044c8aec779c60c1c4
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}
635status_t Parcel::writeByteArray(size_t len, const uint8_t *val) {
636    if (!val) {
637        return writeAligned(-1);
638    }
639    status_t ret = writeAligned(len);
640    if (ret == NO_ERROR) {
641        ret = write(val, len * sizeof(*val));
642    }
643    return ret;
644}
645
646status_t Parcel::writeInt64(int64_t val)
647{
648    return writeAligned(val);
649}
650
651status_t Parcel::writePointer(uintptr_t val)
652{
653    return writeAligned<binder_uintptr_t>(val);
654}
655
656status_t Parcel::writeFloat(float val)
657{
658    return writeAligned(val);
659}
660
661#if defined(__mips__) && defined(__mips_hard_float)
662
663status_t Parcel::writeDouble(double val)
664{
665    union {
666        double d;
667        unsigned long long ll;
668    } u;
669    u.d = val;
670    return writeAligned(u.ll);
671}
672
673#else
674
675status_t Parcel::writeDouble(double val)
676{
677    return writeAligned(val);
678}
679
680#endif
681
682status_t Parcel::writeIntPtr(intptr_t val)
683{
684    return writeAligned(val);
685}
686
687status_t Parcel::writeCString(const char* str)
688{
689    return write(str, strlen(str)+1);
690}
691
692status_t Parcel::writeString8(const String8& str)
693{
694    status_t err = writeInt32(str.bytes());
695    // only write string if its length is more than zero characters,
696    // as readString8 will only read if the length field is non-zero.
697    // this is slightly different from how writeString16 works.
698    if (str.bytes() > 0 && err == NO_ERROR) {
699        err = write(str.string(), str.bytes()+1);
700    }
701    return err;
702}
703
704status_t Parcel::writeString16(const String16& str)
705{
706    return writeString16(str.string(), str.size());
707}
708
709status_t Parcel::writeString16(const char16_t* str, size_t len)
710{
711    if (str == NULL) return writeInt32(-1);
712
713    status_t err = writeInt32(len);
714    if (err == NO_ERROR) {
715        len *= sizeof(char16_t);
716        uint8_t* data = (uint8_t*)writeInplace(len+sizeof(char16_t));
717        if (data) {
718            memcpy(data, str, len);
719            *reinterpret_cast<char16_t*>(data+len) = 0;
720            return NO_ERROR;
721        }
722        err = mError;
723    }
724    return err;
725}
726
727status_t Parcel::writeStrongBinder(const sp<IBinder>& val)
728{
729    return flatten_binder(ProcessState::self(), val, this);
730}
731
732status_t Parcel::writeWeakBinder(const wp<IBinder>& val)
733{
734    return flatten_binder(ProcessState::self(), val, this);
735}
736
737status_t Parcel::writeNativeHandle(const native_handle* handle)
738{
739    if (!handle || handle->version != sizeof(native_handle))
740        return BAD_TYPE;
741
742    status_t err;
743    err = writeInt32(handle->numFds);
744    if (err != NO_ERROR) return err;
745
746    err = writeInt32(handle->numInts);
747    if (err != NO_ERROR) return err;
748
749    for (int i=0 ; err==NO_ERROR && i<handle->numFds ; i++)
750        err = writeDupFileDescriptor(handle->data[i]);
751
752    if (err != NO_ERROR) {
753        ALOGD("write native handle, write dup fd failed");
754        return err;
755    }
756    err = write(handle->data + handle->numFds, sizeof(int)*handle->numInts);
757    return err;
758}
759
760status_t Parcel::writeFileDescriptor(int fd, bool takeOwnership)
761{
762    flat_binder_object obj;
763    obj.type = BINDER_TYPE_FD;
764    obj.flags = 0x7f | FLAT_BINDER_FLAG_ACCEPTS_FDS;
765    obj.binder = 0; /* Don't pass uninitialized stack data to a remote process */
766    obj.handle = fd;
767    obj.cookie = takeOwnership ? 1 : 0;
768    return writeObject(obj, true);
769}
770
771status_t Parcel::writeDupFileDescriptor(int fd)
772{
773    int dupFd = dup(fd);
774    if (dupFd < 0) {
775        return -errno;
776    }
777    status_t err = writeFileDescriptor(dupFd, true /*takeOwnership*/);
778    if (err) {
779        close(dupFd);
780    }
781    return err;
782}
783
784// WARNING: This method must stay in sync with
785// Parcelable.Creator<ParcelFileDescriptor> CREATOR
786// in frameworks/base/core/java/android/os/ParcelFileDescriptor.java
787status_t Parcel::writeParcelFileDescriptor(int fd, int commChannel) {
788    status_t status;
789
790    if (fd < 0) {
791        status = writeInt32(0); // ParcelFileDescriptor is null
792        if (status) return status;
793    } else {
794        status = writeInt32(1); // ParcelFileDescriptor is not null
795        if (status) return status;
796        status = writeDupFileDescriptor(fd);
797        if (status) return status;
798        if (commChannel < 0) {
799            status = writeInt32(0); // commChannel is null
800            if (status) return status;
801        } else {
802            status = writeInt32(1); // commChannel is not null
803            if (status) return status;
804            status = writeDupFileDescriptor(commChannel);
805        }
806    }
807    return status;
808}
809
810status_t Parcel::writeBlob(size_t len, WritableBlob* outBlob)
811{
812    status_t status;
813
814    if (!mAllowFds || len <= IN_PLACE_BLOB_LIMIT) {
815        ALOGV("writeBlob: write in place");
816        status = writeInt32(0);
817        if (status) return status;
818
819        void* ptr = writeInplace(len);
820        if (!ptr) return NO_MEMORY;
821
822        outBlob->init(false /*mapped*/, ptr, len);
823        return NO_ERROR;
824    }
825
826    ALOGV("writeBlob: write to ashmem");
827    int fd = ashmem_create_region("Parcel Blob", len);
828    if (fd < 0) return NO_MEMORY;
829
830    int result = ashmem_set_prot_region(fd, PROT_READ | PROT_WRITE);
831    if (result < 0) {
832        status = result;
833    } else {
834        void* ptr = ::mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
835        if (ptr == MAP_FAILED) {
836            status = -errno;
837        } else {
838            result = ashmem_set_prot_region(fd, PROT_READ);
839            if (result < 0) {
840                status = result;
841            } else {
842                status = writeInt32(1);
843                if (!status) {
844                    status = writeFileDescriptor(fd, true /*takeOwnership*/);
845                    if (!status) {
846                        outBlob->init(true /*mapped*/, ptr, len);
847                        return NO_ERROR;
848                    }
849                }
850            }
851        }
852        ::munmap(ptr, len);
853    }
854    ::close(fd);
855    return status;
856}
857
858status_t Parcel::write(const FlattenableHelperInterface& val)
859{
860    status_t err;
861
862    // size if needed
863    const size_t len = val.getFlattenedSize();
864    const size_t fd_count = val.getFdCount();
865
866    err = this->writeInt32(len);
867    if (err) return err;
868
869    err = this->writeInt32(fd_count);
870    if (err) return err;
871
872    // payload
873    void* const buf = this->writeInplace(PAD_SIZE(len));
874    if (buf == NULL)
875        return BAD_VALUE;
876
877    int* fds = NULL;
878    if (fd_count) {
879        fds = new int[fd_count];
880    }
881
882    err = val.flatten(buf, len, fds, fd_count);
883    for (size_t i=0 ; i<fd_count && err==NO_ERROR ; i++) {
884        err = this->writeDupFileDescriptor( fds[i] );
885    }
886
887    if (fd_count) {
888        delete [] fds;
889    }
890
891    return err;
892}
893
894status_t Parcel::writeObject(const flat_binder_object& val, bool nullMetaData)
895{
896    const bool enoughData = (mDataPos+sizeof(val)) <= mDataCapacity;
897    const bool enoughObjects = mObjectsSize < mObjectsCapacity;
898    if (enoughData && enoughObjects) {
899restart_write:
900        *reinterpret_cast<flat_binder_object*>(mData+mDataPos) = val;
901
902        // Need to write meta-data?
903        if (nullMetaData || val.binder != 0) {
904            mObjects[mObjectsSize] = mDataPos;
905            acquire_object(ProcessState::self(), val, this);
906            mObjectsSize++;
907        }
908
909        // remember if it's a file descriptor
910        if (val.type == BINDER_TYPE_FD) {
911            if (!mAllowFds) {
912                return FDS_NOT_ALLOWED;
913            }
914            mHasFds = mFdsKnown = true;
915        }
916
917        return finishWrite(sizeof(flat_binder_object));
918    }
919
920    if (!enoughData) {
921        const status_t err = growData(sizeof(val));
922        if (err != NO_ERROR) return err;
923    }
924    if (!enoughObjects) {
925        size_t newSize = ((mObjectsSize+2)*3)/2;
926        binder_size_t* objects = (binder_size_t*)realloc(mObjects, newSize*sizeof(binder_size_t));
927        if (objects == NULL) return NO_MEMORY;
928        mObjects = objects;
929        mObjectsCapacity = newSize;
930    }
931
932    goto restart_write;
933}
934
935status_t Parcel::writeNoException()
936{
937    return writeInt32(0);
938}
939
940void Parcel::remove(size_t /*start*/, size_t /*amt*/)
941{
942    LOG_ALWAYS_FATAL("Parcel::remove() not yet implemented!");
943}
944
945status_t Parcel::read(void* outData, size_t len) const
946{
947    if ((mDataPos+PAD_SIZE(len)) >= mDataPos && (mDataPos+PAD_SIZE(len)) <= mDataSize
948            && len <= PAD_SIZE(len)) {
949        memcpy(outData, mData+mDataPos, len);
950        mDataPos += PAD_SIZE(len);
951        ALOGV("read Setting data pos of %p to %d\n", this, mDataPos);
952        return NO_ERROR;
953    }
954    return NOT_ENOUGH_DATA;
955}
956
957const void* Parcel::readInplace(size_t len) const
958{
959    if ((mDataPos+PAD_SIZE(len)) >= mDataPos && (mDataPos+PAD_SIZE(len)) <= mDataSize
960            && len <= PAD_SIZE(len)) {
961        const void* data = mData+mDataPos;
962        mDataPos += PAD_SIZE(len);
963        ALOGV("readInplace Setting data pos of %p to %d\n", this, mDataPos);
964        return data;
965    }
966    return NULL;
967}
968
969template<class T>
970status_t Parcel::readAligned(T *pArg) const {
971    COMPILE_TIME_ASSERT_FUNCTION_SCOPE(PAD_SIZE(sizeof(T)) == sizeof(T));
972
973    if ((mDataPos+sizeof(T)) <= mDataSize) {
974        const void* data = mData+mDataPos;
975        mDataPos += sizeof(T);
976        *pArg =  *reinterpret_cast<const T*>(data);
977        return NO_ERROR;
978    } else {
979        return NOT_ENOUGH_DATA;
980    }
981}
982
983template<class T>
984T Parcel::readAligned() const {
985    T result;
986    if (readAligned(&result) != NO_ERROR) {
987        result = 0;
988    }
989
990    return result;
991}
992
993template<class T>
994status_t Parcel::writeAligned(T val) {
995    COMPILE_TIME_ASSERT_FUNCTION_SCOPE(PAD_SIZE(sizeof(T)) == sizeof(T));
996
997    if ((mDataPos+sizeof(val)) <= mDataCapacity) {
998restart_write:
999        *reinterpret_cast<T*>(mData+mDataPos) = val;
1000        return finishWrite(sizeof(val));
1001    }
1002
1003    status_t err = growData(sizeof(val));
1004    if (err == NO_ERROR) goto restart_write;
1005    return err;
1006}
1007
1008status_t Parcel::readInt32(int32_t *pArg) const
1009{
1010    return readAligned(pArg);
1011}
1012
1013int32_t Parcel::readInt32() const
1014{
1015    return readAligned<int32_t>();
1016}
1017
1018
1019status_t Parcel::readInt64(int64_t *pArg) const
1020{
1021    return readAligned(pArg);
1022}
1023
1024
1025int64_t Parcel::readInt64() const
1026{
1027    return readAligned<int64_t>();
1028}
1029
1030status_t Parcel::readPointer(uintptr_t *pArg) const
1031{
1032    status_t ret;
1033    binder_uintptr_t ptr;
1034    ret = readAligned(&ptr);
1035    if (!ret)
1036        *pArg = ptr;
1037    return ret;
1038}
1039
1040uintptr_t Parcel::readPointer() const
1041{
1042    return readAligned<binder_uintptr_t>();
1043}
1044
1045
1046status_t Parcel::readFloat(float *pArg) const
1047{
1048    return readAligned(pArg);
1049}
1050
1051
1052float Parcel::readFloat() const
1053{
1054    return readAligned<float>();
1055}
1056
1057#if defined(__mips__) && defined(__mips_hard_float)
1058
1059status_t Parcel::readDouble(double *pArg) const
1060{
1061    union {
1062      double d;
1063      unsigned long long ll;
1064    } u;
1065    status_t status;
1066    status = readAligned(&u.ll);
1067    *pArg = u.d;
1068    return status;
1069}
1070
1071double Parcel::readDouble() const
1072{
1073    union {
1074      double d;
1075      unsigned long long ll;
1076    } u;
1077    u.ll = readAligned<unsigned long long>();
1078    return u.d;
1079}
1080
1081#else
1082
1083status_t Parcel::readDouble(double *pArg) const
1084{
1085    return readAligned(pArg);
1086}
1087
1088double Parcel::readDouble() const
1089{
1090    return readAligned<double>();
1091}
1092
1093#endif
1094
1095status_t Parcel::readIntPtr(intptr_t *pArg) const
1096{
1097    return readAligned(pArg);
1098}
1099
1100
1101intptr_t Parcel::readIntPtr() const
1102{
1103    return readAligned<intptr_t>();
1104}
1105
1106
1107const char* Parcel::readCString() const
1108{
1109    const size_t avail = mDataSize-mDataPos;
1110    if (avail > 0) {
1111        const char* str = reinterpret_cast<const char*>(mData+mDataPos);
1112        // is the string's trailing NUL within the parcel's valid bounds?
1113        const char* eos = reinterpret_cast<const char*>(memchr(str, 0, avail));
1114        if (eos) {
1115            const size_t len = eos - str;
1116            mDataPos += PAD_SIZE(len+1);
1117            ALOGV("readCString Setting data pos of %p to %d\n", this, mDataPos);
1118            return str;
1119        }
1120    }
1121    return NULL;
1122}
1123
1124String8 Parcel::readString8() const
1125{
1126    int32_t size = readInt32();
1127    // watch for potential int overflow adding 1 for trailing NUL
1128    if (size > 0 && size < INT32_MAX) {
1129        const char* str = (const char*)readInplace(size+1);
1130        if (str) return String8(str, size);
1131    }
1132    return String8();
1133}
1134
1135String16 Parcel::readString16() const
1136{
1137    size_t len;
1138    const char16_t* str = readString16Inplace(&len);
1139    if (str) return String16(str, len);
1140    ALOGE("Reading a NULL string not supported here.");
1141    return String16();
1142}
1143
1144const char16_t* Parcel::readString16Inplace(size_t* outLen) const
1145{
1146    int32_t size = readInt32();
1147    // watch for potential int overflow from size+1
1148    if (size >= 0 && size < INT32_MAX) {
1149        *outLen = size;
1150        const char16_t* str = (const char16_t*)readInplace((size+1)*sizeof(char16_t));
1151        if (str != NULL) {
1152            return str;
1153        }
1154    }
1155    *outLen = 0;
1156    return NULL;
1157}
1158
1159sp<IBinder> Parcel::readStrongBinder() const
1160{
1161    sp<IBinder> val;
1162    unflatten_binder(ProcessState::self(), *this, &val);
1163    return val;
1164}
1165
1166wp<IBinder> Parcel::readWeakBinder() const
1167{
1168    wp<IBinder> val;
1169    unflatten_binder(ProcessState::self(), *this, &val);
1170    return val;
1171}
1172
1173int32_t Parcel::readExceptionCode() const
1174{
1175  int32_t exception_code = readAligned<int32_t>();
1176  if (exception_code == EX_HAS_REPLY_HEADER) {
1177    int32_t header_start = dataPosition();
1178    int32_t header_size = readAligned<int32_t>();
1179    // Skip over fat responses headers.  Not used (or propagated) in
1180    // native code
1181    setDataPosition(header_start + header_size);
1182    // And fat response headers are currently only used when there are no
1183    // exceptions, so return no error:
1184    return 0;
1185  }
1186  return exception_code;
1187}
1188
1189native_handle* Parcel::readNativeHandle() const
1190{
1191    int numFds, numInts;
1192    status_t err;
1193    err = readInt32(&numFds);
1194    if (err != NO_ERROR) return 0;
1195    err = readInt32(&numInts);
1196    if (err != NO_ERROR) return 0;
1197
1198    native_handle* h = native_handle_create(numFds, numInts);
1199    for (int i=0 ; err==NO_ERROR && i<numFds ; i++) {
1200        h->data[i] = dup(readFileDescriptor());
1201        if (h->data[i] < 0) err = BAD_VALUE;
1202    }
1203    err = read(h->data + numFds, sizeof(int)*numInts);
1204    if (err != NO_ERROR) {
1205        native_handle_close(h);
1206        native_handle_delete(h);
1207        h = 0;
1208    }
1209    return h;
1210}
1211
1212
1213int Parcel::readFileDescriptor() const
1214{
1215    const flat_binder_object* flat = readObject(true);
1216    if (flat) {
1217        switch (flat->type) {
1218            case BINDER_TYPE_FD:
1219                //ALOGI("Returning file descriptor %ld from parcel %p\n", flat->handle, this);
1220                return flat->handle;
1221        }
1222    }
1223    return BAD_TYPE;
1224}
1225
1226// WARNING: This method must stay in sync with writeToParcel()
1227// in frameworks/base/core/java/android/os/ParcelFileDescriptor.java
1228int Parcel::readParcelFileDescriptor(int& outCommChannel) const {
1229    int fd;
1230    outCommChannel = -1;
1231
1232    if (readInt32() == 0) {
1233        fd = -1;
1234    } else {
1235        fd = readFileDescriptor();
1236        if (fd >= 0 && readInt32() != 0) {
1237            outCommChannel = readFileDescriptor();
1238        }
1239    }
1240    return fd;
1241}
1242
1243status_t Parcel::readBlob(size_t len, ReadableBlob* outBlob) const
1244{
1245    int32_t useAshmem;
1246    status_t status = readInt32(&useAshmem);
1247    if (status) return status;
1248
1249    if (!useAshmem) {
1250        ALOGV("readBlob: read in place");
1251        const void* ptr = readInplace(len);
1252        if (!ptr) return BAD_VALUE;
1253
1254        outBlob->init(false /*mapped*/, const_cast<void*>(ptr), len);
1255        return NO_ERROR;
1256    }
1257
1258    ALOGV("readBlob: read from ashmem");
1259    int fd = readFileDescriptor();
1260    if (fd == int(BAD_TYPE)) return BAD_VALUE;
1261
1262    void* ptr = ::mmap(NULL, len, PROT_READ, MAP_SHARED, fd, 0);
1263    if (!ptr) return NO_MEMORY;
1264
1265    outBlob->init(true /*mapped*/, ptr, len);
1266    return NO_ERROR;
1267}
1268
1269status_t Parcel::read(FlattenableHelperInterface& val) const
1270{
1271    // size
1272    const size_t len = this->readInt32();
1273    const size_t fd_count = this->readInt32();
1274
1275    // payload
1276    void const* const buf = this->readInplace(PAD_SIZE(len));
1277    if (buf == NULL)
1278        return BAD_VALUE;
1279
1280    int* fds = NULL;
1281    if (fd_count) {
1282        fds = new int[fd_count];
1283    }
1284
1285    status_t err = NO_ERROR;
1286    for (size_t i=0 ; i<fd_count && err==NO_ERROR ; i++) {
1287        fds[i] = dup(this->readFileDescriptor());
1288        if (fds[i] < 0) {
1289            err = BAD_VALUE;
1290            ALOGE("dup() failed in Parcel::read, i is %d, fds[i] is %d, fd_count is %d, error: %s",
1291                i, fds[i], fd_count, strerror(errno));
1292        }
1293    }
1294
1295    if (err == NO_ERROR) {
1296        err = val.unflatten(buf, len, fds, fd_count);
1297    }
1298
1299    if (fd_count) {
1300        delete [] fds;
1301    }
1302
1303    return err;
1304}
1305const flat_binder_object* Parcel::readObject(bool nullMetaData) const
1306{
1307    const size_t DPOS = mDataPos;
1308    if ((DPOS+sizeof(flat_binder_object)) <= mDataSize) {
1309        const flat_binder_object* obj
1310                = reinterpret_cast<const flat_binder_object*>(mData+DPOS);
1311        mDataPos = DPOS + sizeof(flat_binder_object);
1312        if (!nullMetaData && (obj->cookie == 0 && obj->binder == 0)) {
1313            // When transferring a NULL object, we don't write it into
1314            // the object list, so we don't want to check for it when
1315            // reading.
1316            ALOGV("readObject Setting data pos of %p to %d\n", this, mDataPos);
1317            return obj;
1318        }
1319
1320        // Ensure that this object is valid...
1321        binder_size_t* const OBJS = mObjects;
1322        const size_t N = mObjectsSize;
1323        size_t opos = mNextObjectHint;
1324
1325        if (N > 0) {
1326            ALOGV("Parcel %p looking for obj at %d, hint=%d\n",
1327                 this, DPOS, opos);
1328
1329            // Start at the current hint position, looking for an object at
1330            // the current data position.
1331            if (opos < N) {
1332                while (opos < (N-1) && OBJS[opos] < DPOS) {
1333                    opos++;
1334                }
1335            } else {
1336                opos = N-1;
1337            }
1338            if (OBJS[opos] == DPOS) {
1339                // Found it!
1340                ALOGV("Parcel found obj %d at index %d with forward search",
1341                     this, DPOS, opos);
1342                mNextObjectHint = opos+1;
1343                ALOGV("readObject Setting data pos of %p to %d\n", this, mDataPos);
1344                return obj;
1345            }
1346
1347            // Look backwards for it...
1348            while (opos > 0 && OBJS[opos] > DPOS) {
1349                opos--;
1350            }
1351            if (OBJS[opos] == DPOS) {
1352                // Found it!
1353                ALOGV("Parcel found obj %d at index %d with backward search",
1354                     this, DPOS, opos);
1355                mNextObjectHint = opos+1;
1356                ALOGV("readObject Setting data pos of %p to %d\n", this, mDataPos);
1357                return obj;
1358            }
1359        }
1360        ALOGW("Attempt to read object from Parcel %p at offset %zu that is not in the object list",
1361             this, DPOS);
1362    }
1363    return NULL;
1364}
1365
1366void Parcel::closeFileDescriptors()
1367{
1368    size_t i = mObjectsSize;
1369    if (i > 0) {
1370        //ALOGI("Closing file descriptors for %d objects...", mObjectsSize);
1371    }
1372    while (i > 0) {
1373        i--;
1374        const flat_binder_object* flat
1375            = reinterpret_cast<flat_binder_object*>(mData+mObjects[i]);
1376        if (flat->type == BINDER_TYPE_FD) {
1377            //ALOGI("Closing fd: %ld\n", flat->handle);
1378            close(flat->handle);
1379        }
1380    }
1381}
1382
1383uintptr_t Parcel::ipcData() const
1384{
1385    return reinterpret_cast<uintptr_t>(mData);
1386}
1387
1388size_t Parcel::ipcDataSize() const
1389{
1390    return (mDataSize > mDataPos ? mDataSize : mDataPos);
1391}
1392
1393uintptr_t Parcel::ipcObjects() const
1394{
1395    return reinterpret_cast<uintptr_t>(mObjects);
1396}
1397
1398size_t Parcel::ipcObjectsCount() const
1399{
1400    return mObjectsSize;
1401}
1402
1403void Parcel::ipcSetDataReference(const uint8_t* data, size_t dataSize,
1404    const binder_size_t* objects, size_t objectsCount, release_func relFunc, void* relCookie)
1405{
1406    binder_size_t minOffset = 0;
1407    freeDataNoInit();
1408    mError = NO_ERROR;
1409    mData = const_cast<uint8_t*>(data);
1410    mDataSize = mDataCapacity = dataSize;
1411    //ALOGI("setDataReference Setting data size of %p to %lu (pid=%d)\n", this, mDataSize, getpid());
1412    mDataPos = 0;
1413    ALOGV("setDataReference Setting data pos of %p to %d\n", this, mDataPos);
1414    mObjects = const_cast<binder_size_t*>(objects);
1415    mObjectsSize = mObjectsCapacity = objectsCount;
1416    mNextObjectHint = 0;
1417    mOwner = relFunc;
1418    mOwnerCookie = relCookie;
1419    for (size_t i = 0; i < mObjectsSize; i++) {
1420        binder_size_t offset = mObjects[i];
1421        if (offset < minOffset) {
1422            ALOGE("%s: bad object offset %"PRIu64" < %"PRIu64"\n",
1423                  __func__, (uint64_t)offset, (uint64_t)minOffset);
1424            mObjectsSize = 0;
1425            break;
1426        }
1427        minOffset = offset + sizeof(flat_binder_object);
1428    }
1429    scanForFds();
1430}
1431
1432void Parcel::print(TextOutput& to, uint32_t /*flags*/) const
1433{
1434    to << "Parcel(";
1435
1436    if (errorCheck() != NO_ERROR) {
1437        const status_t err = errorCheck();
1438        to << "Error: " << (void*)(intptr_t)err << " \"" << strerror(-err) << "\"";
1439    } else if (dataSize() > 0) {
1440        const uint8_t* DATA = data();
1441        to << indent << HexDump(DATA, dataSize()) << dedent;
1442        const binder_size_t* OBJS = objects();
1443        const size_t N = objectsCount();
1444        for (size_t i=0; i<N; i++) {
1445            const flat_binder_object* flat
1446                = reinterpret_cast<const flat_binder_object*>(DATA+OBJS[i]);
1447            to << endl << "Object #" << i << " @ " << (void*)OBJS[i] << ": "
1448                << TypeCode(flat->type & 0x7f7f7f00)
1449                << " = " << flat->binder;
1450        }
1451    } else {
1452        to << "NULL";
1453    }
1454
1455    to << ")";
1456}
1457
1458void Parcel::releaseObjects()
1459{
1460    const sp<ProcessState> proc(ProcessState::self());
1461    size_t i = mObjectsSize;
1462    uint8_t* const data = mData;
1463    binder_size_t* const objects = mObjects;
1464    while (i > 0) {
1465        i--;
1466        const flat_binder_object* flat
1467            = reinterpret_cast<flat_binder_object*>(data+objects[i]);
1468        release_object(proc, *flat, this);
1469    }
1470}
1471
1472void Parcel::acquireObjects()
1473{
1474    const sp<ProcessState> proc(ProcessState::self());
1475    size_t i = mObjectsSize;
1476    uint8_t* const data = mData;
1477    binder_size_t* const objects = mObjects;
1478    while (i > 0) {
1479        i--;
1480        const flat_binder_object* flat
1481            = reinterpret_cast<flat_binder_object*>(data+objects[i]);
1482        acquire_object(proc, *flat, this);
1483    }
1484}
1485
1486void Parcel::freeData()
1487{
1488    freeDataNoInit();
1489    initState();
1490}
1491
1492void Parcel::freeDataNoInit()
1493{
1494    if (mOwner) {
1495        //ALOGI("Freeing data ref of %p (pid=%d)\n", this, getpid());
1496        mOwner(this, mData, mDataSize, mObjects, mObjectsSize, mOwnerCookie);
1497    } else {
1498        releaseObjects();
1499        if (mData) free(mData);
1500        if (mObjects) free(mObjects);
1501    }
1502}
1503
1504status_t Parcel::growData(size_t len)
1505{
1506    size_t newSize = ((mDataSize+len)*3)/2;
1507    return (newSize <= mDataSize)
1508            ? (status_t) NO_MEMORY
1509            : continueWrite(newSize);
1510}
1511
1512status_t Parcel::restartWrite(size_t desired)
1513{
1514    if (mOwner) {
1515        freeData();
1516        return continueWrite(desired);
1517    }
1518
1519    uint8_t* data = (uint8_t*)realloc(mData, desired);
1520    if (!data && desired > mDataCapacity) {
1521        mError = NO_MEMORY;
1522        return NO_MEMORY;
1523    }
1524
1525    releaseObjects();
1526
1527    if (data) {
1528        mData = data;
1529        mDataCapacity = desired;
1530    }
1531
1532    mDataSize = mDataPos = 0;
1533    ALOGV("restartWrite Setting data size of %p to %d\n", this, mDataSize);
1534    ALOGV("restartWrite Setting data pos of %p to %d\n", this, mDataPos);
1535
1536    free(mObjects);
1537    mObjects = NULL;
1538    mObjectsSize = mObjectsCapacity = 0;
1539    mNextObjectHint = 0;
1540    mHasFds = false;
1541    mFdsKnown = true;
1542    mAllowFds = true;
1543
1544    return NO_ERROR;
1545}
1546
1547status_t Parcel::continueWrite(size_t desired)
1548{
1549    // If shrinking, first adjust for any objects that appear
1550    // after the new data size.
1551    size_t objectsSize = mObjectsSize;
1552    if (desired < mDataSize) {
1553        if (desired == 0) {
1554            objectsSize = 0;
1555        } else {
1556            while (objectsSize > 0) {
1557                if (mObjects[objectsSize-1] < desired)
1558                    break;
1559                objectsSize--;
1560            }
1561        }
1562    }
1563
1564    if (mOwner) {
1565        // If the size is going to zero, just release the owner's data.
1566        if (desired == 0) {
1567            freeData();
1568            return NO_ERROR;
1569        }
1570
1571        // If there is a different owner, we need to take
1572        // posession.
1573        uint8_t* data = (uint8_t*)malloc(desired);
1574        if (!data) {
1575            mError = NO_MEMORY;
1576            return NO_MEMORY;
1577        }
1578        binder_size_t* objects = NULL;
1579
1580        if (objectsSize) {
1581            objects = (binder_size_t*)malloc(objectsSize*sizeof(binder_size_t));
1582            if (!objects) {
1583                free(data);
1584
1585                mError = NO_MEMORY;
1586                return NO_MEMORY;
1587            }
1588
1589            // Little hack to only acquire references on objects
1590            // we will be keeping.
1591            size_t oldObjectsSize = mObjectsSize;
1592            mObjectsSize = objectsSize;
1593            acquireObjects();
1594            mObjectsSize = oldObjectsSize;
1595        }
1596
1597        if (mData) {
1598            memcpy(data, mData, mDataSize < desired ? mDataSize : desired);
1599        }
1600        if (objects && mObjects) {
1601            memcpy(objects, mObjects, objectsSize*sizeof(binder_size_t));
1602        }
1603        //ALOGI("Freeing data ref of %p (pid=%d)\n", this, getpid());
1604        mOwner(this, mData, mDataSize, mObjects, mObjectsSize, mOwnerCookie);
1605        mOwner = NULL;
1606
1607        mData = data;
1608        mObjects = objects;
1609        mDataSize = (mDataSize < desired) ? mDataSize : desired;
1610        ALOGV("continueWrite Setting data size of %p to %d\n", this, mDataSize);
1611        mDataCapacity = desired;
1612        mObjectsSize = mObjectsCapacity = objectsSize;
1613        mNextObjectHint = 0;
1614
1615    } else if (mData) {
1616        if (objectsSize < mObjectsSize) {
1617            // Need to release refs on any objects we are dropping.
1618            const sp<ProcessState> proc(ProcessState::self());
1619            for (size_t i=objectsSize; i<mObjectsSize; i++) {
1620                const flat_binder_object* flat
1621                    = reinterpret_cast<flat_binder_object*>(mData+mObjects[i]);
1622                if (flat->type == BINDER_TYPE_FD) {
1623                    // will need to rescan because we may have lopped off the only FDs
1624                    mFdsKnown = false;
1625                }
1626                release_object(proc, *flat, this);
1627            }
1628            binder_size_t* objects =
1629                (binder_size_t*)realloc(mObjects, objectsSize*sizeof(binder_size_t));
1630            if (objects) {
1631                mObjects = objects;
1632            }
1633            mObjectsSize = objectsSize;
1634            mNextObjectHint = 0;
1635        }
1636
1637        // We own the data, so we can just do a realloc().
1638        if (desired > mDataCapacity) {
1639            uint8_t* data = (uint8_t*)realloc(mData, desired);
1640            if (data) {
1641                mData = data;
1642                mDataCapacity = desired;
1643            } else if (desired > mDataCapacity) {
1644                mError = NO_MEMORY;
1645                return NO_MEMORY;
1646            }
1647        } else {
1648            if (mDataSize > desired) {
1649                mDataSize = desired;
1650                ALOGV("continueWrite Setting data size of %p to %d\n", this, mDataSize);
1651            }
1652            if (mDataPos > desired) {
1653                mDataPos = desired;
1654                ALOGV("continueWrite Setting data pos of %p to %d\n", this, mDataPos);
1655            }
1656        }
1657
1658    } else {
1659        // This is the first data.  Easy!
1660        uint8_t* data = (uint8_t*)malloc(desired);
1661        if (!data) {
1662            mError = NO_MEMORY;
1663            return NO_MEMORY;
1664        }
1665
1666        if(!(mDataCapacity == 0 && mObjects == NULL
1667             && mObjectsCapacity == 0)) {
1668            ALOGE("continueWrite: %zu/%p/%zu/%zu", mDataCapacity, mObjects, mObjectsCapacity, desired);
1669        }
1670
1671        mData = data;
1672        mDataSize = mDataPos = 0;
1673        ALOGV("continueWrite Setting data size of %p to %d\n", this, mDataSize);
1674        ALOGV("continueWrite Setting data pos of %p to %d\n", this, mDataPos);
1675        mDataCapacity = desired;
1676    }
1677
1678    return NO_ERROR;
1679}
1680
1681void Parcel::initState()
1682{
1683    mError = NO_ERROR;
1684    mData = 0;
1685    mDataSize = 0;
1686    mDataCapacity = 0;
1687    mDataPos = 0;
1688    ALOGV("initState Setting data size of %p to %d\n", this, mDataSize);
1689    ALOGV("initState Setting data pos of %p to %d\n", this, mDataPos);
1690    mObjects = NULL;
1691    mObjectsSize = 0;
1692    mObjectsCapacity = 0;
1693    mNextObjectHint = 0;
1694    mHasFds = false;
1695    mFdsKnown = true;
1696    mAllowFds = true;
1697    mOwner = NULL;
1698}
1699
1700void Parcel::scanForFds() const
1701{
1702    bool hasFds = false;
1703    for (size_t i=0; i<mObjectsSize; i++) {
1704        const flat_binder_object* flat
1705            = reinterpret_cast<const flat_binder_object*>(mData + mObjects[i]);
1706        if (flat->type == BINDER_TYPE_FD) {
1707            hasFds = true;
1708            break;
1709        }
1710    }
1711    mHasFds = hasFds;
1712    mFdsKnown = true;
1713}
1714
1715// --- Parcel::Blob ---
1716
1717Parcel::Blob::Blob() :
1718        mMapped(false), mData(NULL), mSize(0) {
1719}
1720
1721Parcel::Blob::~Blob() {
1722    release();
1723}
1724
1725void Parcel::Blob::release() {
1726    if (mMapped && mData) {
1727        ::munmap(mData, mSize);
1728    }
1729    clear();
1730}
1731
1732void Parcel::Blob::init(bool mapped, void* data, size_t size) {
1733    mMapped = mapped;
1734    mData = data;
1735    mSize = size;
1736}
1737
1738void Parcel::Blob::clear() {
1739    mMapped = false;
1740    mData = NULL;
1741    mSize = 0;
1742}
1743
1744}; // namespace android
1745