Parcel.cpp revision 702ea9d42f52fc145090c0f0bfbe64993e4b8b33
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
757void Parcel::remove(size_t start, size_t amt)
758{
759    LOG_ALWAYS_FATAL("Parcel::remove() not yet implemented!");
760}
761
762status_t Parcel::read(void* outData, size_t len) const
763{
764    if ((mDataPos+PAD_SIZE(len)) >= mDataPos && (mDataPos+PAD_SIZE(len)) <= mDataSize) {
765        memcpy(outData, mData+mDataPos, len);
766        mDataPos += PAD_SIZE(len);
767        LOGV("read Setting data pos of %p to %d\n", this, mDataPos);
768        return NO_ERROR;
769    }
770    return NOT_ENOUGH_DATA;
771}
772
773const void* Parcel::readInplace(size_t len) const
774{
775    if ((mDataPos+PAD_SIZE(len)) >= mDataPos && (mDataPos+PAD_SIZE(len)) <= mDataSize) {
776        const void* data = mData+mDataPos;
777        mDataPos += PAD_SIZE(len);
778        LOGV("readInplace Setting data pos of %p to %d\n", this, mDataPos);
779        return data;
780    }
781    return NULL;
782}
783
784template<class T>
785status_t Parcel::readAligned(T *pArg) const {
786    COMPILE_TIME_ASSERT_FUNCTION_SCOPE(PAD_SIZE(sizeof(T)) == sizeof(T));
787
788    if ((mDataPos+sizeof(T)) <= mDataSize) {
789        const void* data = mData+mDataPos;
790        mDataPos += sizeof(T);
791        *pArg =  *reinterpret_cast<const T*>(data);
792        return NO_ERROR;
793    } else {
794        return NOT_ENOUGH_DATA;
795    }
796}
797
798template<class T>
799T Parcel::readAligned() const {
800    T result;
801    if (readAligned(&result) != NO_ERROR) {
802        result = 0;
803    }
804
805    return result;
806}
807
808template<class T>
809status_t Parcel::writeAligned(T val) {
810    COMPILE_TIME_ASSERT_FUNCTION_SCOPE(PAD_SIZE(sizeof(T)) == sizeof(T));
811
812    if ((mDataPos+sizeof(val)) <= mDataCapacity) {
813restart_write:
814        *reinterpret_cast<T*>(mData+mDataPos) = val;
815        return finishWrite(sizeof(val));
816    }
817
818    status_t err = growData(sizeof(val));
819    if (err == NO_ERROR) goto restart_write;
820    return err;
821}
822
823status_t Parcel::readInt32(int32_t *pArg) const
824{
825    return readAligned(pArg);
826}
827
828int32_t Parcel::readInt32() const
829{
830    return readAligned<int32_t>();
831}
832
833
834status_t Parcel::readInt64(int64_t *pArg) const
835{
836    return readAligned(pArg);
837}
838
839
840int64_t Parcel::readInt64() const
841{
842    return readAligned<int64_t>();
843}
844
845status_t Parcel::readFloat(float *pArg) const
846{
847    return readAligned(pArg);
848}
849
850
851float Parcel::readFloat() const
852{
853    return readAligned<float>();
854}
855
856status_t Parcel::readDouble(double *pArg) const
857{
858    return readAligned(pArg);
859}
860
861
862double Parcel::readDouble() const
863{
864    return readAligned<double>();
865}
866
867status_t Parcel::readIntPtr(intptr_t *pArg) const
868{
869    return readAligned(pArg);
870}
871
872
873intptr_t Parcel::readIntPtr() const
874{
875    return readAligned<intptr_t>();
876}
877
878
879const char* Parcel::readCString() const
880{
881    const size_t avail = mDataSize-mDataPos;
882    if (avail > 0) {
883        const char* str = reinterpret_cast<const char*>(mData+mDataPos);
884        // is the string's trailing NUL within the parcel's valid bounds?
885        const char* eos = reinterpret_cast<const char*>(memchr(str, 0, avail));
886        if (eos) {
887            const size_t len = eos - str;
888            mDataPos += PAD_SIZE(len+1);
889            LOGV("readCString Setting data pos of %p to %d\n", this, mDataPos);
890            return str;
891        }
892    }
893    return NULL;
894}
895
896String8 Parcel::readString8() const
897{
898    int32_t size = readInt32();
899    // watch for potential int overflow adding 1 for trailing NUL
900    if (size > 0 && size < INT32_MAX) {
901        const char* str = (const char*)readInplace(size+1);
902        if (str) return String8(str, size);
903    }
904    return String8();
905}
906
907String16 Parcel::readString16() const
908{
909    size_t len;
910    const char16_t* str = readString16Inplace(&len);
911    if (str) return String16(str, len);
912    LOGE("Reading a NULL string not supported here.");
913    return String16();
914}
915
916const char16_t* Parcel::readString16Inplace(size_t* outLen) const
917{
918    int32_t size = readInt32();
919    // watch for potential int overflow from size+1
920    if (size >= 0 && size < INT32_MAX) {
921        *outLen = size;
922        const char16_t* str = (const char16_t*)readInplace((size+1)*sizeof(char16_t));
923        if (str != NULL) {
924            return str;
925        }
926    }
927    *outLen = 0;
928    return NULL;
929}
930
931sp<IBinder> Parcel::readStrongBinder() const
932{
933    sp<IBinder> val;
934    unflatten_binder(ProcessState::self(), *this, &val);
935    return val;
936}
937
938wp<IBinder> Parcel::readWeakBinder() const
939{
940    wp<IBinder> val;
941    unflatten_binder(ProcessState::self(), *this, &val);
942    return val;
943}
944
945
946native_handle* Parcel::readNativeHandle() const
947{
948    int numFds, numInts;
949    status_t err;
950    err = readInt32(&numFds);
951    if (err != NO_ERROR) return 0;
952    err = readInt32(&numInts);
953    if (err != NO_ERROR) return 0;
954
955    native_handle* h = native_handle_create(numFds, numInts);
956    for (int i=0 ; err==NO_ERROR && i<numFds ; i++) {
957        h->data[i] = dup(readFileDescriptor());
958        if (h->data[i] < 0) err = BAD_VALUE;
959    }
960    err = read(h->data + numFds, sizeof(int)*numInts);
961    if (err != NO_ERROR) {
962        native_handle_close(h);
963        native_handle_delete(h);
964        h = 0;
965    }
966    return h;
967}
968
969
970int Parcel::readFileDescriptor() const
971{
972    const flat_binder_object* flat = readObject(true);
973    if (flat) {
974        switch (flat->type) {
975            case BINDER_TYPE_FD:
976                //LOGI("Returning file descriptor %ld from parcel %p\n", flat->handle, this);
977                return flat->handle;
978        }
979    }
980    return BAD_TYPE;
981}
982
983status_t Parcel::read(Flattenable& val) const
984{
985    // size
986    const size_t len = this->readInt32();
987    const size_t fd_count = this->readInt32();
988
989    // payload
990    void const* buf = this->readInplace(PAD_SIZE(len));
991    if (buf == NULL)
992        return BAD_VALUE;
993
994    int* fds = NULL;
995    if (fd_count) {
996        fds = new int[fd_count];
997    }
998
999    status_t err = NO_ERROR;
1000    for (size_t i=0 ; i<fd_count && err==NO_ERROR ; i++) {
1001        fds[i] = dup(this->readFileDescriptor());
1002        if (fds[i] < 0) err = BAD_VALUE;
1003    }
1004
1005    if (err == NO_ERROR) {
1006        err = val.unflatten(buf, len, fds, fd_count);
1007    }
1008
1009    if (fd_count) {
1010        delete [] fds;
1011    }
1012
1013    return err;
1014}
1015const flat_binder_object* Parcel::readObject(bool nullMetaData) const
1016{
1017    const size_t DPOS = mDataPos;
1018    if ((DPOS+sizeof(flat_binder_object)) <= mDataSize) {
1019        const flat_binder_object* obj
1020                = reinterpret_cast<const flat_binder_object*>(mData+DPOS);
1021        mDataPos = DPOS + sizeof(flat_binder_object);
1022        if (!nullMetaData && (obj->cookie == NULL && obj->binder == NULL)) {
1023            // When transferring a NULL object, we don't write it into
1024            // the object list, so we don't want to check for it when
1025            // reading.
1026            LOGV("readObject Setting data pos of %p to %d\n", this, mDataPos);
1027            return obj;
1028        }
1029
1030        // Ensure that this object is valid...
1031        size_t* const OBJS = mObjects;
1032        const size_t N = mObjectsSize;
1033        size_t opos = mNextObjectHint;
1034
1035        if (N > 0) {
1036            LOGV("Parcel %p looking for obj at %d, hint=%d\n",
1037                 this, DPOS, opos);
1038
1039            // Start at the current hint position, looking for an object at
1040            // the current data position.
1041            if (opos < N) {
1042                while (opos < (N-1) && OBJS[opos] < DPOS) {
1043                    opos++;
1044                }
1045            } else {
1046                opos = N-1;
1047            }
1048            if (OBJS[opos] == DPOS) {
1049                // Found it!
1050                LOGV("Parcel found obj %d at index %d with forward search",
1051                     this, DPOS, opos);
1052                mNextObjectHint = opos+1;
1053                LOGV("readObject Setting data pos of %p to %d\n", this, mDataPos);
1054                return obj;
1055            }
1056
1057            // Look backwards for it...
1058            while (opos > 0 && OBJS[opos] > DPOS) {
1059                opos--;
1060            }
1061            if (OBJS[opos] == DPOS) {
1062                // Found it!
1063                LOGV("Parcel found obj %d at index %d with backward search",
1064                     this, DPOS, opos);
1065                mNextObjectHint = opos+1;
1066                LOGV("readObject Setting data pos of %p to %d\n", this, mDataPos);
1067                return obj;
1068            }
1069        }
1070        LOGW("Attempt to read object from Parcel %p at offset %d that is not in the object list",
1071             this, DPOS);
1072    }
1073    return NULL;
1074}
1075
1076void Parcel::closeFileDescriptors()
1077{
1078    size_t i = mObjectsSize;
1079    if (i > 0) {
1080        //LOGI("Closing file descriptors for %d objects...", mObjectsSize);
1081    }
1082    while (i > 0) {
1083        i--;
1084        const flat_binder_object* flat
1085            = reinterpret_cast<flat_binder_object*>(mData+mObjects[i]);
1086        if (flat->type == BINDER_TYPE_FD) {
1087            //LOGI("Closing fd: %ld\n", flat->handle);
1088            close(flat->handle);
1089        }
1090    }
1091}
1092
1093const uint8_t* Parcel::ipcData() const
1094{
1095    return mData;
1096}
1097
1098size_t Parcel::ipcDataSize() const
1099{
1100    return (mDataSize > mDataPos ? mDataSize : mDataPos);
1101}
1102
1103const size_t* Parcel::ipcObjects() const
1104{
1105    return mObjects;
1106}
1107
1108size_t Parcel::ipcObjectsCount() const
1109{
1110    return mObjectsSize;
1111}
1112
1113void Parcel::ipcSetDataReference(const uint8_t* data, size_t dataSize,
1114    const size_t* objects, size_t objectsCount, release_func relFunc, void* relCookie)
1115{
1116    freeDataNoInit();
1117    mError = NO_ERROR;
1118    mData = const_cast<uint8_t*>(data);
1119    mDataSize = mDataCapacity = dataSize;
1120    //LOGI("setDataReference Setting data size of %p to %lu (pid=%d)\n", this, mDataSize, getpid());
1121    mDataPos = 0;
1122    LOGV("setDataReference Setting data pos of %p to %d\n", this, mDataPos);
1123    mObjects = const_cast<size_t*>(objects);
1124    mObjectsSize = mObjectsCapacity = objectsCount;
1125    mNextObjectHint = 0;
1126    mOwner = relFunc;
1127    mOwnerCookie = relCookie;
1128    scanForFds();
1129}
1130
1131void Parcel::print(TextOutput& to, uint32_t flags) const
1132{
1133    to << "Parcel(";
1134
1135    if (errorCheck() != NO_ERROR) {
1136        const status_t err = errorCheck();
1137        to << "Error: " << (void*)err << " \"" << strerror(-err) << "\"";
1138    } else if (dataSize() > 0) {
1139        const uint8_t* DATA = data();
1140        to << indent << HexDump(DATA, dataSize()) << dedent;
1141        const size_t* OBJS = objects();
1142        const size_t N = objectsCount();
1143        for (size_t i=0; i<N; i++) {
1144            const flat_binder_object* flat
1145                = reinterpret_cast<const flat_binder_object*>(DATA+OBJS[i]);
1146            to << endl << "Object #" << i << " @ " << (void*)OBJS[i] << ": "
1147                << TypeCode(flat->type & 0x7f7f7f00)
1148                << " = " << flat->binder;
1149        }
1150    } else {
1151        to << "NULL";
1152    }
1153
1154    to << ")";
1155}
1156
1157void Parcel::releaseObjects()
1158{
1159    const sp<ProcessState> proc(ProcessState::self());
1160    size_t i = mObjectsSize;
1161    uint8_t* const data = mData;
1162    size_t* const objects = mObjects;
1163    while (i > 0) {
1164        i--;
1165        const flat_binder_object* flat
1166            = reinterpret_cast<flat_binder_object*>(data+objects[i]);
1167        release_object(proc, *flat, this);
1168    }
1169}
1170
1171void Parcel::acquireObjects()
1172{
1173    const sp<ProcessState> proc(ProcessState::self());
1174    size_t i = mObjectsSize;
1175    uint8_t* const data = mData;
1176    size_t* const objects = mObjects;
1177    while (i > 0) {
1178        i--;
1179        const flat_binder_object* flat
1180            = reinterpret_cast<flat_binder_object*>(data+objects[i]);
1181        acquire_object(proc, *flat, this);
1182    }
1183}
1184
1185void Parcel::freeData()
1186{
1187    freeDataNoInit();
1188    initState();
1189}
1190
1191void Parcel::freeDataNoInit()
1192{
1193    if (mOwner) {
1194        //LOGI("Freeing data ref of %p (pid=%d)\n", this, getpid());
1195        mOwner(this, mData, mDataSize, mObjects, mObjectsSize, mOwnerCookie);
1196    } else {
1197        releaseObjects();
1198        if (mData) free(mData);
1199        if (mObjects) free(mObjects);
1200    }
1201}
1202
1203status_t Parcel::growData(size_t len)
1204{
1205    size_t newSize = ((mDataSize+len)*3)/2;
1206    return (newSize <= mDataSize)
1207            ? (status_t) NO_MEMORY
1208            : continueWrite(newSize);
1209}
1210
1211status_t Parcel::restartWrite(size_t desired)
1212{
1213    if (mOwner) {
1214        freeData();
1215        return continueWrite(desired);
1216    }
1217
1218    uint8_t* data = (uint8_t*)realloc(mData, desired);
1219    if (!data && desired > mDataCapacity) {
1220        mError = NO_MEMORY;
1221        return NO_MEMORY;
1222    }
1223
1224    releaseObjects();
1225
1226    if (data) {
1227        mData = data;
1228        mDataCapacity = desired;
1229    }
1230
1231    mDataSize = mDataPos = 0;
1232    LOGV("restartWrite Setting data size of %p to %d\n", this, mDataSize);
1233    LOGV("restartWrite Setting data pos of %p to %d\n", this, mDataPos);
1234
1235    free(mObjects);
1236    mObjects = NULL;
1237    mObjectsSize = mObjectsCapacity = 0;
1238    mNextObjectHint = 0;
1239    mHasFds = false;
1240    mFdsKnown = true;
1241
1242    return NO_ERROR;
1243}
1244
1245status_t Parcel::continueWrite(size_t desired)
1246{
1247    // If shrinking, first adjust for any objects that appear
1248    // after the new data size.
1249    size_t objectsSize = mObjectsSize;
1250    if (desired < mDataSize) {
1251        if (desired == 0) {
1252            objectsSize = 0;
1253        } else {
1254            while (objectsSize > 0) {
1255                if (mObjects[objectsSize-1] < desired)
1256                    break;
1257                objectsSize--;
1258            }
1259        }
1260    }
1261
1262    if (mOwner) {
1263        // If the size is going to zero, just release the owner's data.
1264        if (desired == 0) {
1265            freeData();
1266            return NO_ERROR;
1267        }
1268
1269        // If there is a different owner, we need to take
1270        // posession.
1271        uint8_t* data = (uint8_t*)malloc(desired);
1272        if (!data) {
1273            mError = NO_MEMORY;
1274            return NO_MEMORY;
1275        }
1276        size_t* objects = NULL;
1277
1278        if (objectsSize) {
1279            objects = (size_t*)malloc(objectsSize*sizeof(size_t));
1280            if (!objects) {
1281                mError = NO_MEMORY;
1282                return NO_MEMORY;
1283            }
1284
1285            // Little hack to only acquire references on objects
1286            // we will be keeping.
1287            size_t oldObjectsSize = mObjectsSize;
1288            mObjectsSize = objectsSize;
1289            acquireObjects();
1290            mObjectsSize = oldObjectsSize;
1291        }
1292
1293        if (mData) {
1294            memcpy(data, mData, mDataSize < desired ? mDataSize : desired);
1295        }
1296        if (objects && mObjects) {
1297            memcpy(objects, mObjects, objectsSize*sizeof(size_t));
1298        }
1299        //LOGI("Freeing data ref of %p (pid=%d)\n", this, getpid());
1300        mOwner(this, mData, mDataSize, mObjects, mObjectsSize, mOwnerCookie);
1301        mOwner = NULL;
1302
1303        mData = data;
1304        mObjects = objects;
1305        mDataSize = (mDataSize < desired) ? mDataSize : desired;
1306        LOGV("continueWrite Setting data size of %p to %d\n", this, mDataSize);
1307        mDataCapacity = desired;
1308        mObjectsSize = mObjectsCapacity = objectsSize;
1309        mNextObjectHint = 0;
1310
1311    } else if (mData) {
1312        if (objectsSize < mObjectsSize) {
1313            // Need to release refs on any objects we are dropping.
1314            const sp<ProcessState> proc(ProcessState::self());
1315            for (size_t i=objectsSize; i<mObjectsSize; i++) {
1316                const flat_binder_object* flat
1317                    = reinterpret_cast<flat_binder_object*>(mData+mObjects[i]);
1318                if (flat->type == BINDER_TYPE_FD) {
1319                    // will need to rescan because we may have lopped off the only FDs
1320                    mFdsKnown = false;
1321                }
1322                release_object(proc, *flat, this);
1323            }
1324            size_t* objects =
1325                (size_t*)realloc(mObjects, objectsSize*sizeof(size_t));
1326            if (objects) {
1327                mObjects = objects;
1328            }
1329            mObjectsSize = objectsSize;
1330            mNextObjectHint = 0;
1331        }
1332
1333        // We own the data, so we can just do a realloc().
1334        if (desired > mDataCapacity) {
1335            uint8_t* data = (uint8_t*)realloc(mData, desired);
1336            if (data) {
1337                mData = data;
1338                mDataCapacity = desired;
1339            } else if (desired > mDataCapacity) {
1340                mError = NO_MEMORY;
1341                return NO_MEMORY;
1342            }
1343        } else {
1344            mDataSize = desired;
1345            LOGV("continueWrite Setting data size of %p to %d\n", this, mDataSize);
1346            if (mDataPos > desired) {
1347                mDataPos = desired;
1348                LOGV("continueWrite Setting data pos of %p to %d\n", this, mDataPos);
1349            }
1350        }
1351
1352    } else {
1353        // This is the first data.  Easy!
1354        uint8_t* data = (uint8_t*)malloc(desired);
1355        if (!data) {
1356            mError = NO_MEMORY;
1357            return NO_MEMORY;
1358        }
1359
1360        if(!(mDataCapacity == 0 && mObjects == NULL
1361             && mObjectsCapacity == 0)) {
1362            LOGE("continueWrite: %d/%p/%d/%d", mDataCapacity, mObjects, mObjectsCapacity, desired);
1363        }
1364
1365        mData = data;
1366        mDataSize = mDataPos = 0;
1367        LOGV("continueWrite Setting data size of %p to %d\n", this, mDataSize);
1368        LOGV("continueWrite Setting data pos of %p to %d\n", this, mDataPos);
1369        mDataCapacity = desired;
1370    }
1371
1372    return NO_ERROR;
1373}
1374
1375void Parcel::initState()
1376{
1377    mError = NO_ERROR;
1378    mData = 0;
1379    mDataSize = 0;
1380    mDataCapacity = 0;
1381    mDataPos = 0;
1382    LOGV("initState Setting data size of %p to %d\n", this, mDataSize);
1383    LOGV("initState Setting data pos of %p to %d\n", this, mDataPos);
1384    mObjects = NULL;
1385    mObjectsSize = 0;
1386    mObjectsCapacity = 0;
1387    mNextObjectHint = 0;
1388    mHasFds = false;
1389    mFdsKnown = true;
1390    mOwner = NULL;
1391}
1392
1393void Parcel::scanForFds() const
1394{
1395    bool hasFds = false;
1396    for (size_t i=0; i<mObjectsSize; i++) {
1397        const flat_binder_object* flat
1398            = reinterpret_cast<const flat_binder_object*>(mData + mObjects[i]);
1399        if (flat->type == BINDER_TYPE_FD) {
1400            hasFds = true;
1401            break;
1402        }
1403    }
1404    mHasFds = hasFds;
1405    mFdsKnown = true;
1406}
1407
1408}; // namespace android
1409