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