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