Parcel.cpp revision 14f8cf12e2764ff554dd0e3b72cc8711b14adffe
1/*
2 * Copyright (C) 2005 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "Parcel"
18//#define LOG_NDEBUG 0
19
20#include <binder/Parcel.h>
21
22#include <binder/IPCThreadState.h>
23#include <binder/Binder.h>
24#include <binder/BpBinder.h>
25#include <binder/ProcessState.h>
26#include <binder/TextOutput.h>
27
28#include <errno.h>
29#include <utils/Debug.h>
30#include <utils/Log.h>
31#include <utils/String8.h>
32#include <utils/String16.h>
33#include <utils/misc.h>
34#include <utils/Flattenable.h>
35#include <cutils/ashmem.h>
36
37#include <private/binder/binder_module.h>
38#include <private/binder/Static.h>
39
40#include <inttypes.h>
41#include <stdio.h>
42#include <stdlib.h>
43#include <stdint.h>
44#include <sys/mman.h>
45
46#ifndef INT32_MAX
47#define INT32_MAX ((int32_t)(2147483647))
48#endif
49
50#define LOG_REFS(...)
51//#define LOG_REFS(...) ALOG(LOG_DEBUG, "Parcel", __VA_ARGS__)
52#define LOG_ALLOC(...)
53//#define LOG_ALLOC(...) ALOG(LOG_DEBUG, "Parcel", __VA_ARGS__)
54
55// ---------------------------------------------------------------------------
56
57// This macro should never be used at runtime, as a too large value
58// of s could cause an integer overflow. Instead, you should always
59// use the wrapper function pad_size()
60#define PAD_SIZE_UNSAFE(s) (((s)+3)&~3)
61
62static size_t pad_size(size_t s) {
63    if (s > (SIZE_T_MAX - 3)) {
64        abort();
65    }
66    return PAD_SIZE_UNSAFE(s);
67}
68
69// Note: must be kept in sync with android/os/StrictMode.java's PENALTY_GATHER
70#define STRICT_MODE_PENALTY_GATHER (0x40 << 16)
71
72// Note: must be kept in sync with android/os/Parcel.java's EX_HAS_REPLY_HEADER
73#define EX_HAS_REPLY_HEADER -128
74
75// XXX This can be made public if we want to provide
76// support for typed data.
77struct small_flat_data
78{
79    uint32_t type;
80    uint32_t data;
81};
82
83namespace android {
84
85static pthread_mutex_t gParcelGlobalAllocSizeLock = PTHREAD_MUTEX_INITIALIZER;
86static size_t gParcelGlobalAllocSize = 0;
87static size_t gParcelGlobalAllocCount = 0;
88
89// Maximum size of a blob to transfer in-place.
90static const size_t BLOB_INPLACE_LIMIT = 16 * 1024;
91
92enum {
93    BLOB_INPLACE = 0,
94    BLOB_ASHMEM_IMMUTABLE = 1,
95    BLOB_ASHMEM_MUTABLE = 2,
96};
97
98void acquire_object(const sp<ProcessState>& proc,
99    const flat_binder_object& obj, const void* who, size_t* outAshmemSize)
100{
101    switch (obj.type) {
102        case BINDER_TYPE_BINDER:
103            if (obj.binder) {
104                LOG_REFS("Parcel %p acquiring reference on local %p", who, obj.cookie);
105                reinterpret_cast<IBinder*>(obj.cookie)->incStrong(who);
106            }
107            return;
108        case BINDER_TYPE_WEAK_BINDER:
109            if (obj.binder)
110                reinterpret_cast<RefBase::weakref_type*>(obj.binder)->incWeak(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 acquiring reference on remote %p", who, b.get());
116                b->incStrong(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()->incWeak(who);
123            return;
124        }
125        case BINDER_TYPE_FD: {
126            if (obj.cookie != 0) {
127                if (outAshmemSize != NULL) {
128                    // If we own an ashmem fd, keep track of how much memory it refers to.
129                    int size = ashmem_get_size_region(obj.handle);
130                    if (size > 0) {
131                        *outAshmemSize += size;
132                    }
133                }
134            }
135            return;
136        }
137    }
138
139    ALOGD("Invalid object type 0x%08x", obj.type);
140}
141
142void acquire_object(const sp<ProcessState>& proc,
143    const flat_binder_object& obj, const void* who)
144{
145    acquire_object(proc, obj, who, NULL);
146}
147
148static void release_object(const sp<ProcessState>& proc,
149    const flat_binder_object& obj, const void* who, size_t* outAshmemSize)
150{
151    switch (obj.type) {
152        case BINDER_TYPE_BINDER:
153            if (obj.binder) {
154                LOG_REFS("Parcel %p releasing reference on local %p", who, obj.cookie);
155                reinterpret_cast<IBinder*>(obj.cookie)->decStrong(who);
156            }
157            return;
158        case BINDER_TYPE_WEAK_BINDER:
159            if (obj.binder)
160                reinterpret_cast<RefBase::weakref_type*>(obj.binder)->decWeak(who);
161            return;
162        case BINDER_TYPE_HANDLE: {
163            const sp<IBinder> b = proc->getStrongProxyForHandle(obj.handle);
164            if (b != NULL) {
165                LOG_REFS("Parcel %p releasing reference on remote %p", who, b.get());
166                b->decStrong(who);
167            }
168            return;
169        }
170        case BINDER_TYPE_WEAK_HANDLE: {
171            const wp<IBinder> b = proc->getWeakProxyForHandle(obj.handle);
172            if (b != NULL) b.get_refs()->decWeak(who);
173            return;
174        }
175        case BINDER_TYPE_FD: {
176            if (outAshmemSize != NULL) {
177                if (obj.cookie != 0) {
178                    int size = ashmem_get_size_region(obj.handle);
179                    if (size > 0) {
180                        *outAshmemSize -= size;
181                    }
182
183                    close(obj.handle);
184                }
185            }
186            return;
187        }
188    }
189
190    ALOGE("Invalid object type 0x%08x", obj.type);
191}
192
193void release_object(const sp<ProcessState>& proc,
194    const flat_binder_object& obj, const void* who)
195{
196    release_object(proc, obj, who, NULL);
197}
198
199inline static status_t finish_flatten_binder(
200    const sp<IBinder>& /*binder*/, const flat_binder_object& flat, Parcel* out)
201{
202    return out->writeObject(flat, false);
203}
204
205status_t flatten_binder(const sp<ProcessState>& /*proc*/,
206    const sp<IBinder>& binder, Parcel* out)
207{
208    flat_binder_object obj;
209
210    obj.flags = 0x7f | FLAT_BINDER_FLAG_ACCEPTS_FDS;
211    if (binder != NULL) {
212        IBinder *local = binder->localBinder();
213        if (!local) {
214            BpBinder *proxy = binder->remoteBinder();
215            if (proxy == NULL) {
216                ALOGE("null proxy");
217            }
218            const int32_t handle = proxy ? proxy->handle() : 0;
219            obj.type = BINDER_TYPE_HANDLE;
220            obj.binder = 0; /* Don't pass uninitialized stack data to a remote process */
221            obj.handle = handle;
222            obj.cookie = 0;
223        } else {
224            obj.type = BINDER_TYPE_BINDER;
225            obj.binder = reinterpret_cast<uintptr_t>(local->getWeakRefs());
226            obj.cookie = reinterpret_cast<uintptr_t>(local);
227        }
228    } else {
229        obj.type = BINDER_TYPE_BINDER;
230        obj.binder = 0;
231        obj.cookie = 0;
232    }
233
234    return finish_flatten_binder(binder, obj, out);
235}
236
237status_t flatten_binder(const sp<ProcessState>& /*proc*/,
238    const wp<IBinder>& binder, Parcel* out)
239{
240    flat_binder_object obj;
241
242    obj.flags = 0x7f | FLAT_BINDER_FLAG_ACCEPTS_FDS;
243    if (binder != NULL) {
244        sp<IBinder> real = binder.promote();
245        if (real != NULL) {
246            IBinder *local = real->localBinder();
247            if (!local) {
248                BpBinder *proxy = real->remoteBinder();
249                if (proxy == NULL) {
250                    ALOGE("null proxy");
251                }
252                const int32_t handle = proxy ? proxy->handle() : 0;
253                obj.type = BINDER_TYPE_WEAK_HANDLE;
254                obj.binder = 0; /* Don't pass uninitialized stack data to a remote process */
255                obj.handle = handle;
256                obj.cookie = 0;
257            } else {
258                obj.type = BINDER_TYPE_WEAK_BINDER;
259                obj.binder = reinterpret_cast<uintptr_t>(binder.get_refs());
260                obj.cookie = reinterpret_cast<uintptr_t>(binder.unsafe_get());
261            }
262            return finish_flatten_binder(real, obj, out);
263        }
264
265        // XXX How to deal?  In order to flatten the given binder,
266        // we need to probe it for information, which requires a primary
267        // reference...  but we don't have one.
268        //
269        // The OpenBinder implementation uses a dynamic_cast<> here,
270        // but we can't do that with the different reference counting
271        // implementation we are using.
272        ALOGE("Unable to unflatten Binder weak reference!");
273        obj.type = BINDER_TYPE_BINDER;
274        obj.binder = 0;
275        obj.cookie = 0;
276        return finish_flatten_binder(NULL, obj, out);
277
278    } else {
279        obj.type = BINDER_TYPE_BINDER;
280        obj.binder = 0;
281        obj.cookie = 0;
282        return finish_flatten_binder(NULL, obj, out);
283    }
284}
285
286inline static status_t finish_unflatten_binder(
287    BpBinder* /*proxy*/, const flat_binder_object& /*flat*/,
288    const Parcel& /*in*/)
289{
290    return NO_ERROR;
291}
292
293status_t unflatten_binder(const sp<ProcessState>& proc,
294    const Parcel& in, sp<IBinder>* out)
295{
296    const flat_binder_object* flat = in.readObject(false);
297
298    if (flat) {
299        switch (flat->type) {
300            case BINDER_TYPE_BINDER:
301                *out = reinterpret_cast<IBinder*>(flat->cookie);
302                return finish_unflatten_binder(NULL, *flat, in);
303            case BINDER_TYPE_HANDLE:
304                *out = proc->getStrongProxyForHandle(flat->handle);
305                return finish_unflatten_binder(
306                    static_cast<BpBinder*>(out->get()), *flat, in);
307        }
308    }
309    return BAD_TYPE;
310}
311
312status_t unflatten_binder(const sp<ProcessState>& proc,
313    const Parcel& in, wp<IBinder>* out)
314{
315    const flat_binder_object* flat = in.readObject(false);
316
317    if (flat) {
318        switch (flat->type) {
319            case BINDER_TYPE_BINDER:
320                *out = reinterpret_cast<IBinder*>(flat->cookie);
321                return finish_unflatten_binder(NULL, *flat, in);
322            case BINDER_TYPE_WEAK_BINDER:
323                if (flat->binder != 0) {
324                    out->set_object_and_refs(
325                        reinterpret_cast<IBinder*>(flat->cookie),
326                        reinterpret_cast<RefBase::weakref_type*>(flat->binder));
327                } else {
328                    *out = NULL;
329                }
330                return finish_unflatten_binder(NULL, *flat, in);
331            case BINDER_TYPE_HANDLE:
332            case BINDER_TYPE_WEAK_HANDLE:
333                *out = proc->getWeakProxyForHandle(flat->handle);
334                return finish_unflatten_binder(
335                    static_cast<BpBinder*>(out->unsafe_get()), *flat, in);
336        }
337    }
338    return BAD_TYPE;
339}
340
341// ---------------------------------------------------------------------------
342
343Parcel::Parcel()
344{
345    LOG_ALLOC("Parcel %p: constructing", this);
346    initState();
347}
348
349Parcel::~Parcel()
350{
351    freeDataNoInit();
352    LOG_ALLOC("Parcel %p: destroyed", this);
353}
354
355size_t Parcel::getGlobalAllocSize() {
356    pthread_mutex_lock(&gParcelGlobalAllocSizeLock);
357    size_t size = gParcelGlobalAllocSize;
358    pthread_mutex_unlock(&gParcelGlobalAllocSizeLock);
359    return size;
360}
361
362size_t Parcel::getGlobalAllocCount() {
363    pthread_mutex_lock(&gParcelGlobalAllocSizeLock);
364    size_t count = gParcelGlobalAllocCount;
365    pthread_mutex_unlock(&gParcelGlobalAllocSizeLock);
366    return count;
367}
368
369const uint8_t* Parcel::data() const
370{
371    return mData;
372}
373
374size_t Parcel::dataSize() const
375{
376    return (mDataSize > mDataPos ? mDataSize : mDataPos);
377}
378
379size_t Parcel::dataAvail() const
380{
381    // TODO: decide what to do about the possibility that this can
382    // report an available-data size that exceeds a Java int's max
383    // positive value, causing havoc.  Fortunately this will only
384    // happen if someone constructs a Parcel containing more than two
385    // gigabytes of data, which on typical phone hardware is simply
386    // not possible.
387    return dataSize() - dataPosition();
388}
389
390size_t Parcel::dataPosition() const
391{
392    return mDataPos;
393}
394
395size_t Parcel::dataCapacity() const
396{
397    return mDataCapacity;
398}
399
400status_t Parcel::setDataSize(size_t size)
401{
402    if (size > INT32_MAX) {
403        // don't accept size_t values which may have come from an
404        // inadvertent conversion from a negative int.
405        return BAD_VALUE;
406    }
407
408    status_t err;
409    err = continueWrite(size);
410    if (err == NO_ERROR) {
411        mDataSize = size;
412        ALOGV("setDataSize Setting data size of %p to %zu", this, mDataSize);
413    }
414    return err;
415}
416
417void Parcel::setDataPosition(size_t pos) const
418{
419    if (pos > INT32_MAX) {
420        // don't accept size_t values which may have come from an
421        // inadvertent conversion from a negative int.
422        abort();
423    }
424
425    mDataPos = pos;
426    mNextObjectHint = 0;
427}
428
429status_t Parcel::setDataCapacity(size_t size)
430{
431    if (size > INT32_MAX) {
432        // don't accept size_t values which may have come from an
433        // inadvertent conversion from a negative int.
434        return BAD_VALUE;
435    }
436
437    if (size > mDataCapacity) return continueWrite(size);
438    return NO_ERROR;
439}
440
441status_t Parcel::setData(const uint8_t* buffer, size_t len)
442{
443    if (len > INT32_MAX) {
444        // don't accept size_t values which may have come from an
445        // inadvertent conversion from a negative int.
446        return BAD_VALUE;
447    }
448
449    status_t err = restartWrite(len);
450    if (err == NO_ERROR) {
451        memcpy(const_cast<uint8_t*>(data()), buffer, len);
452        mDataSize = len;
453        mFdsKnown = false;
454    }
455    return err;
456}
457
458status_t Parcel::appendFrom(const Parcel *parcel, size_t offset, size_t len)
459{
460    const sp<ProcessState> proc(ProcessState::self());
461    status_t err;
462    const uint8_t *data = parcel->mData;
463    const binder_size_t *objects = parcel->mObjects;
464    size_t size = parcel->mObjectsSize;
465    int startPos = mDataPos;
466    int firstIndex = -1, lastIndex = -2;
467
468    if (len == 0) {
469        return NO_ERROR;
470    }
471
472    if (len > INT32_MAX) {
473        // don't accept size_t values which may have come from an
474        // inadvertent conversion from a negative int.
475        return BAD_VALUE;
476    }
477
478    // range checks against the source parcel size
479    if ((offset > parcel->mDataSize)
480            || (len > parcel->mDataSize)
481            || (offset + len > parcel->mDataSize)) {
482        return BAD_VALUE;
483    }
484
485    // Count objects in range
486    for (int i = 0; i < (int) size; i++) {
487        size_t off = objects[i];
488        if ((off >= offset) && (off + sizeof(flat_binder_object) <= offset + len)) {
489            if (firstIndex == -1) {
490                firstIndex = i;
491            }
492            lastIndex = i;
493        }
494    }
495    int numObjects = lastIndex - firstIndex + 1;
496
497    if ((mDataSize+len) > mDataCapacity) {
498        // grow data
499        err = growData(len);
500        if (err != NO_ERROR) {
501            return err;
502        }
503    }
504
505    // append data
506    memcpy(mData + mDataPos, data + offset, len);
507    mDataPos += len;
508    mDataSize += len;
509
510    err = NO_ERROR;
511
512    if (numObjects > 0) {
513        // grow objects
514        if (mObjectsCapacity < mObjectsSize + numObjects) {
515            size_t newSize = ((mObjectsSize + numObjects)*3)/2;
516            if (newSize < mObjectsSize) return NO_MEMORY;   // overflow
517            binder_size_t *objects =
518                (binder_size_t*)realloc(mObjects, newSize*sizeof(binder_size_t));
519            if (objects == (binder_size_t*)0) {
520                return NO_MEMORY;
521            }
522            mObjects = objects;
523            mObjectsCapacity = newSize;
524        }
525
526        // append and acquire objects
527        int idx = mObjectsSize;
528        for (int i = firstIndex; i <= lastIndex; i++) {
529            size_t off = objects[i] - offset + startPos;
530            mObjects[idx++] = off;
531            mObjectsSize++;
532
533            flat_binder_object* flat
534                = reinterpret_cast<flat_binder_object*>(mData + off);
535            acquire_object(proc, *flat, this, &mOpenAshmemSize);
536
537            if (flat->type == BINDER_TYPE_FD) {
538                // If this is a file descriptor, we need to dup it so the
539                // new Parcel now owns its own fd, and can declare that we
540                // officially know we have fds.
541                flat->handle = dup(flat->handle);
542                flat->cookie = 1;
543                mHasFds = mFdsKnown = true;
544                if (!mAllowFds) {
545                    err = FDS_NOT_ALLOWED;
546                }
547            }
548        }
549    }
550
551    return err;
552}
553
554bool Parcel::allowFds() const
555{
556    return mAllowFds;
557}
558
559bool Parcel::pushAllowFds(bool allowFds)
560{
561    const bool origValue = mAllowFds;
562    if (!allowFds) {
563        mAllowFds = false;
564    }
565    return origValue;
566}
567
568void Parcel::restoreAllowFds(bool lastValue)
569{
570    mAllowFds = lastValue;
571}
572
573bool Parcel::hasFileDescriptors() const
574{
575    if (!mFdsKnown) {
576        scanForFds();
577    }
578    return mHasFds;
579}
580
581// Write RPC headers.  (previously just the interface token)
582status_t Parcel::writeInterfaceToken(const String16& interface)
583{
584    writeInt32(IPCThreadState::self()->getStrictModePolicy() |
585               STRICT_MODE_PENALTY_GATHER);
586    // currently the interface identification token is just its name as a string
587    return writeString16(interface);
588}
589
590bool Parcel::checkInterface(IBinder* binder) const
591{
592    return enforceInterface(binder->getInterfaceDescriptor());
593}
594
595bool Parcel::enforceInterface(const String16& interface,
596                              IPCThreadState* threadState) const
597{
598    int32_t strictPolicy = readInt32();
599    if (threadState == NULL) {
600        threadState = IPCThreadState::self();
601    }
602    if ((threadState->getLastTransactionBinderFlags() &
603         IBinder::FLAG_ONEWAY) != 0) {
604      // For one-way calls, the callee is running entirely
605      // disconnected from the caller, so disable StrictMode entirely.
606      // Not only does disk/network usage not impact the caller, but
607      // there's no way to commuicate back any violations anyway.
608      threadState->setStrictModePolicy(0);
609    } else {
610      threadState->setStrictModePolicy(strictPolicy);
611    }
612    const String16 str(readString16());
613    if (str == interface) {
614        return true;
615    } else {
616        ALOGW("**** enforceInterface() expected '%s' but read '%s'",
617                String8(interface).string(), String8(str).string());
618        return false;
619    }
620}
621
622const binder_size_t* Parcel::objects() const
623{
624    return mObjects;
625}
626
627size_t Parcel::objectsCount() const
628{
629    return mObjectsSize;
630}
631
632status_t Parcel::errorCheck() const
633{
634    return mError;
635}
636
637void Parcel::setError(status_t err)
638{
639    mError = err;
640}
641
642status_t Parcel::finishWrite(size_t len)
643{
644    if (len > INT32_MAX) {
645        // don't accept size_t values which may have come from an
646        // inadvertent conversion from a negative int.
647        return BAD_VALUE;
648    }
649
650    //printf("Finish write of %d\n", len);
651    mDataPos += len;
652    ALOGV("finishWrite Setting data pos of %p to %zu", this, mDataPos);
653    if (mDataPos > mDataSize) {
654        mDataSize = mDataPos;
655        ALOGV("finishWrite Setting data size of %p to %zu", this, mDataSize);
656    }
657    //printf("New pos=%d, size=%d\n", mDataPos, mDataSize);
658    return NO_ERROR;
659}
660
661status_t Parcel::writeUnpadded(const void* data, size_t len)
662{
663    if (len > INT32_MAX) {
664        // don't accept size_t values which may have come from an
665        // inadvertent conversion from a negative int.
666        return BAD_VALUE;
667    }
668
669    size_t end = mDataPos + len;
670    if (end < mDataPos) {
671        // integer overflow
672        return BAD_VALUE;
673    }
674
675    if (end <= mDataCapacity) {
676restart_write:
677        memcpy(mData+mDataPos, data, len);
678        return finishWrite(len);
679    }
680
681    status_t err = growData(len);
682    if (err == NO_ERROR) goto restart_write;
683    return err;
684}
685
686status_t Parcel::write(const void* data, size_t len)
687{
688    if (len > INT32_MAX) {
689        // don't accept size_t values which may have come from an
690        // inadvertent conversion from a negative int.
691        return BAD_VALUE;
692    }
693
694    void* const d = writeInplace(len);
695    if (d) {
696        memcpy(d, data, len);
697        return NO_ERROR;
698    }
699    return mError;
700}
701
702void* Parcel::writeInplace(size_t len)
703{
704    if (len > INT32_MAX) {
705        // don't accept size_t values which may have come from an
706        // inadvertent conversion from a negative int.
707        return NULL;
708    }
709
710    const size_t padded = pad_size(len);
711
712    // sanity check for integer overflow
713    if (mDataPos+padded < mDataPos) {
714        return NULL;
715    }
716
717    if ((mDataPos+padded) <= mDataCapacity) {
718restart_write:
719        //printf("Writing %ld bytes, padded to %ld\n", len, padded);
720        uint8_t* const data = mData+mDataPos;
721
722        // Need to pad at end?
723        if (padded != len) {
724#if BYTE_ORDER == BIG_ENDIAN
725            static const uint32_t mask[4] = {
726                0x00000000, 0xffffff00, 0xffff0000, 0xff000000
727            };
728#endif
729#if BYTE_ORDER == LITTLE_ENDIAN
730            static const uint32_t mask[4] = {
731                0x00000000, 0x00ffffff, 0x0000ffff, 0x000000ff
732            };
733#endif
734            //printf("Applying pad mask: %p to %p\n", (void*)mask[padded-len],
735            //    *reinterpret_cast<void**>(data+padded-4));
736            *reinterpret_cast<uint32_t*>(data+padded-4) &= mask[padded-len];
737        }
738
739        finishWrite(padded);
740        return data;
741    }
742
743    status_t err = growData(padded);
744    if (err == NO_ERROR) goto restart_write;
745    return NULL;
746}
747
748status_t Parcel::writeByteVector(const std::vector<int8_t>& val)
749{
750    status_t status;
751    if (val.size() > std::numeric_limits<int32_t>::max()) {
752        status = BAD_VALUE;
753        return status;
754    }
755
756    status = writeInt32(val.size());
757    if (status != OK) {
758        return status;
759    }
760
761    void* data = writeInplace(val.size());
762    if (!data) {
763        status = BAD_VALUE;
764        return status;
765    }
766
767    memcpy(data, val.data(), val.size());
768    return status;
769}
770
771status_t Parcel::writeInt32Vector(const std::vector<int32_t>& val)
772{
773    if (val.size() > std::numeric_limits<int32_t>::max()) {
774        return BAD_VALUE;
775    }
776
777    status_t status = writeInt32(val.size());
778
779    if (status != OK) {
780        return status;
781    }
782
783    for (const auto& item : val) {
784        status = writeInt32(item);
785
786        if (status != OK) {
787            return status;
788        }
789    }
790
791    return OK;
792}
793
794status_t Parcel::writeInt64Vector(const std::vector<int64_t>& val)
795{
796    if (val.size() > std::numeric_limits<int32_t>::max()) {
797        return BAD_VALUE;
798    }
799
800    status_t status = writeInt32(val.size());
801
802    if (status != OK) {
803        return status;
804    }
805
806    for (const auto& item : val) {
807        status = writeInt64(item);
808
809        if (status != OK) {
810            return status;
811        }
812    }
813
814    return OK;
815}
816
817status_t Parcel::writeFloatVector(const std::vector<float>& val)
818{
819    if (val.size() > std::numeric_limits<int32_t>::max()) {
820        return BAD_VALUE;
821    }
822
823    status_t status = writeInt32(val.size());
824
825    if (status != OK) {
826        return status;
827    }
828
829    for (const auto& item : val) {
830        status = writeFloat(item);
831
832        if (status != OK) {
833            return status;
834        }
835    }
836
837    return OK;
838}
839
840status_t Parcel::writeDoubleVector(const std::vector<double>& val)
841{
842    if (val.size() > std::numeric_limits<int32_t>::max()) {
843        return BAD_VALUE;
844    }
845
846    status_t status = writeInt32(val.size());
847
848    if (status != OK) {
849        return status;
850    }
851
852    for (const auto& item : val) {
853        status = writeDouble(item);
854
855        if (status != OK) {
856            return status;
857        }
858    }
859
860    return OK;
861}
862
863status_t Parcel::writeBoolVector(const std::vector<bool>& val)
864{
865    if (val.size() > std::numeric_limits<int32_t>::max()) {
866        return BAD_VALUE;
867    }
868
869    status_t status = writeInt32(val.size());
870
871    if (status != OK) {
872        return status;
873    }
874
875    for (const auto& item : val) {
876        status = writeBool(item);
877
878        if (status != OK) {
879            return status;
880        }
881    }
882
883    return OK;
884}
885
886status_t Parcel::writeCharVector(const std::vector<char16_t>& val)
887{
888    if (val.size() > std::numeric_limits<int32_t>::max()) {
889        return BAD_VALUE;
890    }
891
892    status_t status = writeInt32(val.size());
893
894    if (status != OK) {
895        return status;
896    }
897
898    for (const auto& item : val) {
899        status = writeChar(item);
900
901        if (status != OK) {
902            return status;
903        }
904    }
905
906    return OK;
907}
908
909status_t Parcel::writeString16Vector(const std::vector<String16>& val)
910{
911    if (val.size() > std::numeric_limits<int32_t>::max()) {
912        return BAD_VALUE;
913    }
914
915    status_t status = writeInt32(val.size());
916
917    if (status != OK) {
918        return status;
919    }
920
921    for (const auto& item : val) {
922        status = writeString16(item);
923
924        if (status != OK) {
925            return status;
926        }
927    }
928
929    return OK;
930}
931
932status_t Parcel::writeInt32(int32_t val)
933{
934    return writeAligned(val);
935}
936
937status_t Parcel::writeUint32(uint32_t val)
938{
939    return writeAligned(val);
940}
941
942status_t Parcel::writeInt32Array(size_t len, const int32_t *val) {
943    if (len > INT32_MAX) {
944        // don't accept size_t values which may have come from an
945        // inadvertent conversion from a negative int.
946        return BAD_VALUE;
947    }
948
949    if (!val) {
950        return writeInt32(-1);
951    }
952    status_t ret = writeInt32(static_cast<uint32_t>(len));
953    if (ret == NO_ERROR) {
954        ret = write(val, len * sizeof(*val));
955    }
956    return ret;
957}
958status_t Parcel::writeByteArray(size_t len, const uint8_t *val) {
959    if (len > INT32_MAX) {
960        // don't accept size_t values which may have come from an
961        // inadvertent conversion from a negative int.
962        return BAD_VALUE;
963    }
964
965    if (!val) {
966        return writeInt32(-1);
967    }
968    status_t ret = writeInt32(static_cast<uint32_t>(len));
969    if (ret == NO_ERROR) {
970        ret = write(val, len * sizeof(*val));
971    }
972    return ret;
973}
974
975status_t Parcel::writeBool(bool val)
976{
977    return writeInt32(int32_t(val));
978}
979
980status_t Parcel::writeChar(char16_t val)
981{
982    return writeInt32(int32_t(val));
983}
984
985status_t Parcel::writeByte(int8_t val)
986{
987    return writeInt32(int32_t(val));
988}
989
990status_t Parcel::writeInt64(int64_t val)
991{
992    return writeAligned(val);
993}
994
995status_t Parcel::writeUint64(uint64_t val)
996{
997    return writeAligned(val);
998}
999
1000status_t Parcel::writePointer(uintptr_t val)
1001{
1002    return writeAligned<binder_uintptr_t>(val);
1003}
1004
1005status_t Parcel::writeFloat(float val)
1006{
1007    return writeAligned(val);
1008}
1009
1010#if defined(__mips__) && defined(__mips_hard_float)
1011
1012status_t Parcel::writeDouble(double val)
1013{
1014    union {
1015        double d;
1016        unsigned long long ll;
1017    } u;
1018    u.d = val;
1019    return writeAligned(u.ll);
1020}
1021
1022#else
1023
1024status_t Parcel::writeDouble(double val)
1025{
1026    return writeAligned(val);
1027}
1028
1029#endif
1030
1031status_t Parcel::writeCString(const char* str)
1032{
1033    return write(str, strlen(str)+1);
1034}
1035
1036status_t Parcel::writeString8(const String8& str)
1037{
1038    status_t err = writeInt32(str.bytes());
1039    // only write string if its length is more than zero characters,
1040    // as readString8 will only read if the length field is non-zero.
1041    // this is slightly different from how writeString16 works.
1042    if (str.bytes() > 0 && err == NO_ERROR) {
1043        err = write(str.string(), str.bytes()+1);
1044    }
1045    return err;
1046}
1047
1048status_t Parcel::writeString16(const String16& str)
1049{
1050    return writeString16(str.string(), str.size());
1051}
1052
1053status_t Parcel::writeString16(const char16_t* str, size_t len)
1054{
1055    if (str == NULL) return writeInt32(-1);
1056
1057    status_t err = writeInt32(len);
1058    if (err == NO_ERROR) {
1059        len *= sizeof(char16_t);
1060        uint8_t* data = (uint8_t*)writeInplace(len+sizeof(char16_t));
1061        if (data) {
1062            memcpy(data, str, len);
1063            *reinterpret_cast<char16_t*>(data+len) = 0;
1064            return NO_ERROR;
1065        }
1066        err = mError;
1067    }
1068    return err;
1069}
1070
1071status_t Parcel::writeStrongBinder(const sp<IBinder>& val)
1072{
1073    return flatten_binder(ProcessState::self(), val, this);
1074}
1075
1076status_t Parcel::writeWeakBinder(const wp<IBinder>& val)
1077{
1078    return flatten_binder(ProcessState::self(), val, this);
1079}
1080
1081status_t Parcel::writeNativeHandle(const native_handle* handle)
1082{
1083    if (!handle || handle->version != sizeof(native_handle))
1084        return BAD_TYPE;
1085
1086    status_t err;
1087    err = writeInt32(handle->numFds);
1088    if (err != NO_ERROR) return err;
1089
1090    err = writeInt32(handle->numInts);
1091    if (err != NO_ERROR) return err;
1092
1093    for (int i=0 ; err==NO_ERROR && i<handle->numFds ; i++)
1094        err = writeDupFileDescriptor(handle->data[i]);
1095
1096    if (err != NO_ERROR) {
1097        ALOGD("write native handle, write dup fd failed");
1098        return err;
1099    }
1100    err = write(handle->data + handle->numFds, sizeof(int)*handle->numInts);
1101    return err;
1102}
1103
1104status_t Parcel::writeFileDescriptor(int fd, bool takeOwnership)
1105{
1106    flat_binder_object obj;
1107    obj.type = BINDER_TYPE_FD;
1108    obj.flags = 0x7f | FLAT_BINDER_FLAG_ACCEPTS_FDS;
1109    obj.binder = 0; /* Don't pass uninitialized stack data to a remote process */
1110    obj.handle = fd;
1111    obj.cookie = takeOwnership ? 1 : 0;
1112    return writeObject(obj, true);
1113}
1114
1115status_t Parcel::writeDupFileDescriptor(int fd)
1116{
1117    int dupFd = dup(fd);
1118    if (dupFd < 0) {
1119        return -errno;
1120    }
1121    status_t err = writeFileDescriptor(dupFd, true /*takeOwnership*/);
1122    if (err) {
1123        close(dupFd);
1124    }
1125    return err;
1126}
1127
1128status_t Parcel::writeBlob(size_t len, bool mutableCopy, WritableBlob* outBlob)
1129{
1130    if (len > INT32_MAX) {
1131        // don't accept size_t values which may have come from an
1132        // inadvertent conversion from a negative int.
1133        return BAD_VALUE;
1134    }
1135
1136    status_t status;
1137    if (!mAllowFds || len <= BLOB_INPLACE_LIMIT) {
1138        ALOGV("writeBlob: write in place");
1139        status = writeInt32(BLOB_INPLACE);
1140        if (status) return status;
1141
1142        void* ptr = writeInplace(len);
1143        if (!ptr) return NO_MEMORY;
1144
1145        outBlob->init(-1, ptr, len, false);
1146        return NO_ERROR;
1147    }
1148
1149    ALOGV("writeBlob: write to ashmem");
1150    int fd = ashmem_create_region("Parcel Blob", len);
1151    if (fd < 0) return NO_MEMORY;
1152
1153    int result = ashmem_set_prot_region(fd, PROT_READ | PROT_WRITE);
1154    if (result < 0) {
1155        status = result;
1156    } else {
1157        void* ptr = ::mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
1158        if (ptr == MAP_FAILED) {
1159            status = -errno;
1160        } else {
1161            if (!mutableCopy) {
1162                result = ashmem_set_prot_region(fd, PROT_READ);
1163            }
1164            if (result < 0) {
1165                status = result;
1166            } else {
1167                status = writeInt32(mutableCopy ? BLOB_ASHMEM_MUTABLE : BLOB_ASHMEM_IMMUTABLE);
1168                if (!status) {
1169                    status = writeFileDescriptor(fd, true /*takeOwnership*/);
1170                    if (!status) {
1171                        outBlob->init(fd, ptr, len, mutableCopy);
1172                        return NO_ERROR;
1173                    }
1174                }
1175            }
1176        }
1177        ::munmap(ptr, len);
1178    }
1179    ::close(fd);
1180    return status;
1181}
1182
1183status_t Parcel::writeDupImmutableBlobFileDescriptor(int fd)
1184{
1185    // Must match up with what's done in writeBlob.
1186    if (!mAllowFds) return FDS_NOT_ALLOWED;
1187    status_t status = writeInt32(BLOB_ASHMEM_IMMUTABLE);
1188    if (status) return status;
1189    return writeDupFileDescriptor(fd);
1190}
1191
1192status_t Parcel::write(const FlattenableHelperInterface& val)
1193{
1194    status_t err;
1195
1196    // size if needed
1197    const size_t len = val.getFlattenedSize();
1198    const size_t fd_count = val.getFdCount();
1199
1200    if ((len > INT32_MAX) || (fd_count > INT32_MAX)) {
1201        // don't accept size_t values which may have come from an
1202        // inadvertent conversion from a negative int.
1203        return BAD_VALUE;
1204    }
1205
1206    err = this->writeInt32(len);
1207    if (err) return err;
1208
1209    err = this->writeInt32(fd_count);
1210    if (err) return err;
1211
1212    // payload
1213    void* const buf = this->writeInplace(pad_size(len));
1214    if (buf == NULL)
1215        return BAD_VALUE;
1216
1217    int* fds = NULL;
1218    if (fd_count) {
1219        fds = new int[fd_count];
1220    }
1221
1222    err = val.flatten(buf, len, fds, fd_count);
1223    for (size_t i=0 ; i<fd_count && err==NO_ERROR ; i++) {
1224        err = this->writeDupFileDescriptor( fds[i] );
1225    }
1226
1227    if (fd_count) {
1228        delete [] fds;
1229    }
1230
1231    return err;
1232}
1233
1234status_t Parcel::writeObject(const flat_binder_object& val, bool nullMetaData)
1235{
1236    const bool enoughData = (mDataPos+sizeof(val)) <= mDataCapacity;
1237    const bool enoughObjects = mObjectsSize < mObjectsCapacity;
1238    if (enoughData && enoughObjects) {
1239restart_write:
1240        *reinterpret_cast<flat_binder_object*>(mData+mDataPos) = val;
1241
1242        // remember if it's a file descriptor
1243        if (val.type == BINDER_TYPE_FD) {
1244            if (!mAllowFds) {
1245                // fail before modifying our object index
1246                return FDS_NOT_ALLOWED;
1247            }
1248            mHasFds = mFdsKnown = true;
1249        }
1250
1251        // Need to write meta-data?
1252        if (nullMetaData || val.binder != 0) {
1253            mObjects[mObjectsSize] = mDataPos;
1254            acquire_object(ProcessState::self(), val, this, &mOpenAshmemSize);
1255            mObjectsSize++;
1256        }
1257
1258        return finishWrite(sizeof(flat_binder_object));
1259    }
1260
1261    if (!enoughData) {
1262        const status_t err = growData(sizeof(val));
1263        if (err != NO_ERROR) return err;
1264    }
1265    if (!enoughObjects) {
1266        size_t newSize = ((mObjectsSize+2)*3)/2;
1267        if (newSize < mObjectsSize) return NO_MEMORY;   // overflow
1268        binder_size_t* objects = (binder_size_t*)realloc(mObjects, newSize*sizeof(binder_size_t));
1269        if (objects == NULL) return NO_MEMORY;
1270        mObjects = objects;
1271        mObjectsCapacity = newSize;
1272    }
1273
1274    goto restart_write;
1275}
1276
1277status_t Parcel::writeNoException()
1278{
1279    return writeInt32(0);
1280}
1281
1282void Parcel::remove(size_t /*start*/, size_t /*amt*/)
1283{
1284    LOG_ALWAYS_FATAL("Parcel::remove() not yet implemented!");
1285}
1286
1287status_t Parcel::read(void* outData, size_t len) const
1288{
1289    if (len > INT32_MAX) {
1290        // don't accept size_t values which may have come from an
1291        // inadvertent conversion from a negative int.
1292        return BAD_VALUE;
1293    }
1294
1295    if ((mDataPos+pad_size(len)) >= mDataPos && (mDataPos+pad_size(len)) <= mDataSize
1296            && len <= pad_size(len)) {
1297        memcpy(outData, mData+mDataPos, len);
1298        mDataPos += pad_size(len);
1299        ALOGV("read Setting data pos of %p to %zu", this, mDataPos);
1300        return NO_ERROR;
1301    }
1302    return NOT_ENOUGH_DATA;
1303}
1304
1305const void* Parcel::readInplace(size_t len) const
1306{
1307    if (len > INT32_MAX) {
1308        // don't accept size_t values which may have come from an
1309        // inadvertent conversion from a negative int.
1310        return NULL;
1311    }
1312
1313    if ((mDataPos+pad_size(len)) >= mDataPos && (mDataPos+pad_size(len)) <= mDataSize
1314            && len <= pad_size(len)) {
1315        const void* data = mData+mDataPos;
1316        mDataPos += pad_size(len);
1317        ALOGV("readInplace Setting data pos of %p to %zu", this, mDataPos);
1318        return data;
1319    }
1320    return NULL;
1321}
1322
1323template<class T>
1324status_t Parcel::readAligned(T *pArg) const {
1325    COMPILE_TIME_ASSERT_FUNCTION_SCOPE(PAD_SIZE_UNSAFE(sizeof(T)) == sizeof(T));
1326
1327    if ((mDataPos+sizeof(T)) <= mDataSize) {
1328        const void* data = mData+mDataPos;
1329        mDataPos += sizeof(T);
1330        *pArg =  *reinterpret_cast<const T*>(data);
1331        return NO_ERROR;
1332    } else {
1333        return NOT_ENOUGH_DATA;
1334    }
1335}
1336
1337template<class T>
1338T Parcel::readAligned() const {
1339    T result;
1340    if (readAligned(&result) != NO_ERROR) {
1341        result = 0;
1342    }
1343
1344    return result;
1345}
1346
1347template<class T>
1348status_t Parcel::writeAligned(T val) {
1349    COMPILE_TIME_ASSERT_FUNCTION_SCOPE(PAD_SIZE_UNSAFE(sizeof(T)) == sizeof(T));
1350
1351    if ((mDataPos+sizeof(val)) <= mDataCapacity) {
1352restart_write:
1353        *reinterpret_cast<T*>(mData+mDataPos) = val;
1354        return finishWrite(sizeof(val));
1355    }
1356
1357    status_t err = growData(sizeof(val));
1358    if (err == NO_ERROR) goto restart_write;
1359    return err;
1360}
1361
1362status_t Parcel::readByteVector(std::vector<int8_t>* val) const {
1363    val->clear();
1364
1365    int32_t size;
1366    status_t status = readInt32(&size);
1367
1368    if (status != OK) {
1369        return status;
1370    }
1371
1372    if (size < 0 || size_t(size) > dataAvail()) {
1373        status = BAD_VALUE;
1374        return status;
1375    }
1376    const void* data = readInplace(size);
1377    if (!data) {
1378        status = BAD_VALUE;
1379        return status;
1380    }
1381    val->resize(size);
1382    memcpy(val->data(), data, size);
1383
1384    return status;
1385}
1386
1387status_t Parcel::readInt32Vector(std::vector<int32_t>* val) const {
1388    val->clear();
1389
1390    int32_t size;
1391    status_t status = readInt32(&size);
1392
1393    if (status != OK) {
1394        return status;
1395    }
1396
1397    if (size < 0) {
1398        return BAD_VALUE;
1399    }
1400
1401    val->resize(size);
1402
1403    for (auto& v: *val) {
1404        status = readInt32(&v);
1405
1406        if (status != OK) {
1407            return status;
1408        }
1409    }
1410
1411    return OK;
1412}
1413
1414status_t Parcel::readInt64Vector(std::vector<int64_t>* val) const {
1415    val->clear();
1416
1417    int32_t size;
1418    status_t status = readInt32(&size);
1419
1420    if (status != OK) {
1421        return status;
1422    }
1423
1424    if (size < 0) {
1425        return BAD_VALUE;
1426    }
1427
1428    val->resize(size);
1429
1430    for (auto& v : *val) {
1431        status = readInt64(&v);
1432
1433        if (status != OK) {
1434            return status;
1435        }
1436    }
1437
1438    return OK;
1439}
1440
1441status_t Parcel::readFloatVector(std::vector<float>* val) const {
1442    val->clear();
1443
1444    int32_t size;
1445    status_t status = readInt32(&size);
1446
1447    if (status != OK) {
1448        return status;
1449    }
1450
1451    if (size < 0) {
1452        return BAD_VALUE;
1453    }
1454
1455    val->resize(size);
1456
1457    for (auto& v : *val) {
1458        status = readFloat(&v);
1459
1460        if (status != OK) {
1461            return status;
1462        }
1463    }
1464
1465    return OK;
1466}
1467
1468status_t Parcel::readDoubleVector(std::vector<double>* val) const {
1469    val->clear();
1470
1471    int32_t size;
1472    status_t status = readInt32(&size);
1473
1474    if (status != OK) {
1475        return status;
1476    }
1477
1478    if (size < 0) {
1479        return BAD_VALUE;
1480    }
1481
1482    val->resize(size);
1483
1484    for (auto& v : *val) {
1485        status = readDouble(&v);
1486
1487        if (status != OK) {
1488            return status;
1489        }
1490    }
1491
1492    return OK;
1493}
1494
1495status_t Parcel::readBoolVector(std::vector<bool>* val) const {
1496    val->clear();
1497
1498    int32_t size;
1499    status_t status = readInt32(&size);
1500
1501    if (status != OK) {
1502        return status;
1503    }
1504
1505    if (size < 0) {
1506        return BAD_VALUE;
1507    }
1508
1509    val->resize(size);
1510
1511    /* C++ bool handling means a vector of bools isn't necessarily addressable
1512     * (we might use individual bits)
1513     */
1514    bool data;
1515    for (int32_t i = 0; i < size; ++i) {
1516        status = readBool(&data);
1517        (*val)[i] = data;
1518
1519        if (status != OK) {
1520            return status;
1521        }
1522    }
1523
1524    return OK;
1525}
1526
1527status_t Parcel::readCharVector(std::vector<char16_t>* val) const {
1528    val->clear();
1529
1530    int32_t size;
1531    status_t status = readInt32(&size);
1532
1533    if (status != OK) {
1534        return status;
1535    }
1536
1537    if (size < 0) {
1538        return BAD_VALUE;
1539    }
1540
1541    val->resize(size);
1542
1543    for (auto& v : *val) {
1544        status = readChar(&v);
1545
1546        if (status != OK) {
1547            return status;
1548        }
1549    }
1550
1551    return OK;
1552}
1553
1554status_t Parcel::readString16Vector(std::vector<String16>* val) const {
1555    val->clear();
1556
1557    int32_t size;
1558    status_t status = readInt32(&size);
1559
1560    if (status != OK) {
1561        return status;
1562    }
1563
1564    if (size < 0) {
1565        return BAD_VALUE;
1566    }
1567
1568    val->reserve(size);
1569
1570    while (size-- > 0) {
1571        const char16_t *data;
1572        size_t size;
1573        data = readString16Inplace(&size);
1574
1575        if (data == nullptr) {
1576            return UNKNOWN_ERROR;
1577        }
1578
1579        val->emplace_back(data, size);
1580    }
1581
1582    return OK;
1583}
1584
1585
1586status_t Parcel::readInt32(int32_t *pArg) const
1587{
1588    return readAligned(pArg);
1589}
1590
1591int32_t Parcel::readInt32() const
1592{
1593    return readAligned<int32_t>();
1594}
1595
1596status_t Parcel::readUint32(uint32_t *pArg) const
1597{
1598    return readAligned(pArg);
1599}
1600
1601uint32_t Parcel::readUint32() const
1602{
1603    return readAligned<uint32_t>();
1604}
1605
1606status_t Parcel::readInt64(int64_t *pArg) const
1607{
1608    return readAligned(pArg);
1609}
1610
1611
1612int64_t Parcel::readInt64() const
1613{
1614    return readAligned<int64_t>();
1615}
1616
1617status_t Parcel::readUint64(uint64_t *pArg) const
1618{
1619    return readAligned(pArg);
1620}
1621
1622uint64_t Parcel::readUint64() const
1623{
1624    return readAligned<uint64_t>();
1625}
1626
1627status_t Parcel::readPointer(uintptr_t *pArg) const
1628{
1629    status_t ret;
1630    binder_uintptr_t ptr;
1631    ret = readAligned(&ptr);
1632    if (!ret)
1633        *pArg = ptr;
1634    return ret;
1635}
1636
1637uintptr_t Parcel::readPointer() const
1638{
1639    return readAligned<binder_uintptr_t>();
1640}
1641
1642
1643status_t Parcel::readFloat(float *pArg) const
1644{
1645    return readAligned(pArg);
1646}
1647
1648
1649float Parcel::readFloat() const
1650{
1651    return readAligned<float>();
1652}
1653
1654#if defined(__mips__) && defined(__mips_hard_float)
1655
1656status_t Parcel::readDouble(double *pArg) const
1657{
1658    union {
1659      double d;
1660      unsigned long long ll;
1661    } u;
1662    u.d = 0;
1663    status_t status;
1664    status = readAligned(&u.ll);
1665    *pArg = u.d;
1666    return status;
1667}
1668
1669double Parcel::readDouble() const
1670{
1671    union {
1672      double d;
1673      unsigned long long ll;
1674    } u;
1675    u.ll = readAligned<unsigned long long>();
1676    return u.d;
1677}
1678
1679#else
1680
1681status_t Parcel::readDouble(double *pArg) const
1682{
1683    return readAligned(pArg);
1684}
1685
1686double Parcel::readDouble() const
1687{
1688    return readAligned<double>();
1689}
1690
1691#endif
1692
1693status_t Parcel::readIntPtr(intptr_t *pArg) const
1694{
1695    return readAligned(pArg);
1696}
1697
1698
1699intptr_t Parcel::readIntPtr() const
1700{
1701    return readAligned<intptr_t>();
1702}
1703
1704status_t Parcel::readBool(bool *pArg) const
1705{
1706    int32_t tmp;
1707    status_t ret = readInt32(&tmp);
1708    *pArg = (tmp != 0);
1709    return ret;
1710}
1711
1712bool Parcel::readBool() const
1713{
1714    return readInt32() != 0;
1715}
1716
1717status_t Parcel::readChar(char16_t *pArg) const
1718{
1719    int32_t tmp;
1720    status_t ret = readInt32(&tmp);
1721    *pArg = char16_t(tmp);
1722    return ret;
1723}
1724
1725char16_t Parcel::readChar() const
1726{
1727    return char16_t(readInt32());
1728}
1729
1730status_t Parcel::readByte(int8_t *pArg) const
1731{
1732    int32_t tmp;
1733    status_t ret = readInt32(&tmp);
1734    *pArg = int8_t(tmp);
1735    return ret;
1736}
1737
1738int8_t Parcel::readByte() const
1739{
1740    return int8_t(readInt32());
1741}
1742
1743const char* Parcel::readCString() const
1744{
1745    const size_t avail = mDataSize-mDataPos;
1746    if (avail > 0) {
1747        const char* str = reinterpret_cast<const char*>(mData+mDataPos);
1748        // is the string's trailing NUL within the parcel's valid bounds?
1749        const char* eos = reinterpret_cast<const char*>(memchr(str, 0, avail));
1750        if (eos) {
1751            const size_t len = eos - str;
1752            mDataPos += pad_size(len+1);
1753            ALOGV("readCString Setting data pos of %p to %zu", this, mDataPos);
1754            return str;
1755        }
1756    }
1757    return NULL;
1758}
1759
1760String8 Parcel::readString8() const
1761{
1762    int32_t size = readInt32();
1763    // watch for potential int overflow adding 1 for trailing NUL
1764    if (size > 0 && size < INT32_MAX) {
1765        const char* str = (const char*)readInplace(size+1);
1766        if (str) return String8(str, size);
1767    }
1768    return String8();
1769}
1770
1771String16 Parcel::readString16() const
1772{
1773    size_t len;
1774    const char16_t* str = readString16Inplace(&len);
1775    if (str) return String16(str, len);
1776    ALOGE("Reading a NULL string not supported here.");
1777    return String16();
1778}
1779
1780status_t Parcel::readString16(String16* pArg) const
1781{
1782    size_t len;
1783    const char16_t* str = readString16Inplace(&len);
1784    if (str) {
1785        pArg->setTo(str, len);
1786        return 0;
1787    } else {
1788        *pArg = String16();
1789        return UNKNOWN_ERROR;
1790    }
1791}
1792
1793const char16_t* Parcel::readString16Inplace(size_t* outLen) const
1794{
1795    int32_t size = readInt32();
1796    // watch for potential int overflow from size+1
1797    if (size >= 0 && size < INT32_MAX) {
1798        *outLen = size;
1799        const char16_t* str = (const char16_t*)readInplace((size+1)*sizeof(char16_t));
1800        if (str != NULL) {
1801            return str;
1802        }
1803    }
1804    *outLen = 0;
1805    return NULL;
1806}
1807
1808status_t Parcel::readStrongBinder(sp<IBinder>* val) const
1809{
1810    return unflatten_binder(ProcessState::self(), *this, val);
1811}
1812
1813sp<IBinder> Parcel::readStrongBinder() const
1814{
1815    sp<IBinder> val;
1816    readStrongBinder(&val);
1817    return val;
1818}
1819
1820wp<IBinder> Parcel::readWeakBinder() const
1821{
1822    wp<IBinder> val;
1823    unflatten_binder(ProcessState::self(), *this, &val);
1824    return val;
1825}
1826
1827int32_t Parcel::readExceptionCode() const
1828{
1829  int32_t exception_code = readAligned<int32_t>();
1830  if (exception_code == EX_HAS_REPLY_HEADER) {
1831    int32_t header_start = dataPosition();
1832    int32_t header_size = readAligned<int32_t>();
1833    // Skip over fat responses headers.  Not used (or propagated) in
1834    // native code
1835    setDataPosition(header_start + header_size);
1836    // And fat response headers are currently only used when there are no
1837    // exceptions, so return no error:
1838    return 0;
1839  }
1840  return exception_code;
1841}
1842
1843native_handle* Parcel::readNativeHandle() const
1844{
1845    int numFds, numInts;
1846    status_t err;
1847    err = readInt32(&numFds);
1848    if (err != NO_ERROR) return 0;
1849    err = readInt32(&numInts);
1850    if (err != NO_ERROR) return 0;
1851
1852    native_handle* h = native_handle_create(numFds, numInts);
1853    if (!h) {
1854        return 0;
1855    }
1856
1857    for (int i=0 ; err==NO_ERROR && i<numFds ; i++) {
1858        h->data[i] = dup(readFileDescriptor());
1859        if (h->data[i] < 0) err = BAD_VALUE;
1860    }
1861    err = read(h->data + numFds, sizeof(int)*numInts);
1862    if (err != NO_ERROR) {
1863        native_handle_close(h);
1864        native_handle_delete(h);
1865        h = 0;
1866    }
1867    return h;
1868}
1869
1870
1871int Parcel::readFileDescriptor() const
1872{
1873    const flat_binder_object* flat = readObject(true);
1874    if (flat) {
1875        switch (flat->type) {
1876            case BINDER_TYPE_FD:
1877                //ALOGI("Returning file descriptor %ld from parcel %p", flat->handle, this);
1878                return flat->handle;
1879        }
1880    }
1881    return BAD_TYPE;
1882}
1883
1884status_t Parcel::readBlob(size_t len, ReadableBlob* outBlob) const
1885{
1886    int32_t blobType;
1887    status_t status = readInt32(&blobType);
1888    if (status) return status;
1889
1890    if (blobType == BLOB_INPLACE) {
1891        ALOGV("readBlob: read in place");
1892        const void* ptr = readInplace(len);
1893        if (!ptr) return BAD_VALUE;
1894
1895        outBlob->init(-1, const_cast<void*>(ptr), len, false);
1896        return NO_ERROR;
1897    }
1898
1899    ALOGV("readBlob: read from ashmem");
1900    bool isMutable = (blobType == BLOB_ASHMEM_MUTABLE);
1901    int fd = readFileDescriptor();
1902    if (fd == int(BAD_TYPE)) return BAD_VALUE;
1903
1904    void* ptr = ::mmap(NULL, len, isMutable ? PROT_READ | PROT_WRITE : PROT_READ,
1905            MAP_SHARED, fd, 0);
1906    if (ptr == MAP_FAILED) return NO_MEMORY;
1907
1908    outBlob->init(fd, ptr, len, isMutable);
1909    return NO_ERROR;
1910}
1911
1912status_t Parcel::read(FlattenableHelperInterface& val) const
1913{
1914    // size
1915    const size_t len = this->readInt32();
1916    const size_t fd_count = this->readInt32();
1917
1918    if (len > INT32_MAX) {
1919        // don't accept size_t values which may have come from an
1920        // inadvertent conversion from a negative int.
1921        return BAD_VALUE;
1922    }
1923
1924    // payload
1925    void const* const buf = this->readInplace(pad_size(len));
1926    if (buf == NULL)
1927        return BAD_VALUE;
1928
1929    int* fds = NULL;
1930    if (fd_count) {
1931        fds = new int[fd_count];
1932    }
1933
1934    status_t err = NO_ERROR;
1935    for (size_t i=0 ; i<fd_count && err==NO_ERROR ; i++) {
1936        fds[i] = dup(this->readFileDescriptor());
1937        if (fds[i] < 0) {
1938            err = BAD_VALUE;
1939            ALOGE("dup() failed in Parcel::read, i is %zu, fds[i] is %d, fd_count is %zu, error: %s",
1940                i, fds[i], fd_count, strerror(errno));
1941        }
1942    }
1943
1944    if (err == NO_ERROR) {
1945        err = val.unflatten(buf, len, fds, fd_count);
1946    }
1947
1948    if (fd_count) {
1949        delete [] fds;
1950    }
1951
1952    return err;
1953}
1954const flat_binder_object* Parcel::readObject(bool nullMetaData) const
1955{
1956    const size_t DPOS = mDataPos;
1957    if ((DPOS+sizeof(flat_binder_object)) <= mDataSize) {
1958        const flat_binder_object* obj
1959                = reinterpret_cast<const flat_binder_object*>(mData+DPOS);
1960        mDataPos = DPOS + sizeof(flat_binder_object);
1961        if (!nullMetaData && (obj->cookie == 0 && obj->binder == 0)) {
1962            // When transferring a NULL object, we don't write it into
1963            // the object list, so we don't want to check for it when
1964            // reading.
1965            ALOGV("readObject Setting data pos of %p to %zu", this, mDataPos);
1966            return obj;
1967        }
1968
1969        // Ensure that this object is valid...
1970        binder_size_t* const OBJS = mObjects;
1971        const size_t N = mObjectsSize;
1972        size_t opos = mNextObjectHint;
1973
1974        if (N > 0) {
1975            ALOGV("Parcel %p looking for obj at %zu, hint=%zu",
1976                 this, DPOS, opos);
1977
1978            // Start at the current hint position, looking for an object at
1979            // the current data position.
1980            if (opos < N) {
1981                while (opos < (N-1) && OBJS[opos] < DPOS) {
1982                    opos++;
1983                }
1984            } else {
1985                opos = N-1;
1986            }
1987            if (OBJS[opos] == DPOS) {
1988                // Found it!
1989                ALOGV("Parcel %p found obj %zu at index %zu with forward search",
1990                     this, DPOS, opos);
1991                mNextObjectHint = opos+1;
1992                ALOGV("readObject Setting data pos of %p to %zu", this, mDataPos);
1993                return obj;
1994            }
1995
1996            // Look backwards for it...
1997            while (opos > 0 && OBJS[opos] > DPOS) {
1998                opos--;
1999            }
2000            if (OBJS[opos] == DPOS) {
2001                // Found it!
2002                ALOGV("Parcel %p found obj %zu at index %zu with backward search",
2003                     this, DPOS, opos);
2004                mNextObjectHint = opos+1;
2005                ALOGV("readObject Setting data pos of %p to %zu", this, mDataPos);
2006                return obj;
2007            }
2008        }
2009        ALOGW("Attempt to read object from Parcel %p at offset %zu that is not in the object list",
2010             this, DPOS);
2011    }
2012    return NULL;
2013}
2014
2015void Parcel::closeFileDescriptors()
2016{
2017    size_t i = mObjectsSize;
2018    if (i > 0) {
2019        //ALOGI("Closing file descriptors for %zu objects...", i);
2020    }
2021    while (i > 0) {
2022        i--;
2023        const flat_binder_object* flat
2024            = reinterpret_cast<flat_binder_object*>(mData+mObjects[i]);
2025        if (flat->type == BINDER_TYPE_FD) {
2026            //ALOGI("Closing fd: %ld", flat->handle);
2027            close(flat->handle);
2028        }
2029    }
2030}
2031
2032uintptr_t Parcel::ipcData() const
2033{
2034    return reinterpret_cast<uintptr_t>(mData);
2035}
2036
2037size_t Parcel::ipcDataSize() const
2038{
2039    return (mDataSize > mDataPos ? mDataSize : mDataPos);
2040}
2041
2042uintptr_t Parcel::ipcObjects() const
2043{
2044    return reinterpret_cast<uintptr_t>(mObjects);
2045}
2046
2047size_t Parcel::ipcObjectsCount() const
2048{
2049    return mObjectsSize;
2050}
2051
2052void Parcel::ipcSetDataReference(const uint8_t* data, size_t dataSize,
2053    const binder_size_t* objects, size_t objectsCount, release_func relFunc, void* relCookie)
2054{
2055    binder_size_t minOffset = 0;
2056    freeDataNoInit();
2057    mError = NO_ERROR;
2058    mData = const_cast<uint8_t*>(data);
2059    mDataSize = mDataCapacity = dataSize;
2060    //ALOGI("setDataReference Setting data size of %p to %lu (pid=%d)", this, mDataSize, getpid());
2061    mDataPos = 0;
2062    ALOGV("setDataReference Setting data pos of %p to %zu", this, mDataPos);
2063    mObjects = const_cast<binder_size_t*>(objects);
2064    mObjectsSize = mObjectsCapacity = objectsCount;
2065    mNextObjectHint = 0;
2066    mOwner = relFunc;
2067    mOwnerCookie = relCookie;
2068    for (size_t i = 0; i < mObjectsSize; i++) {
2069        binder_size_t offset = mObjects[i];
2070        if (offset < minOffset) {
2071            ALOGE("%s: bad object offset %" PRIu64 " < %" PRIu64 "\n",
2072                  __func__, (uint64_t)offset, (uint64_t)minOffset);
2073            mObjectsSize = 0;
2074            break;
2075        }
2076        minOffset = offset + sizeof(flat_binder_object);
2077    }
2078    scanForFds();
2079}
2080
2081void Parcel::print(TextOutput& to, uint32_t /*flags*/) const
2082{
2083    to << "Parcel(";
2084
2085    if (errorCheck() != NO_ERROR) {
2086        const status_t err = errorCheck();
2087        to << "Error: " << (void*)(intptr_t)err << " \"" << strerror(-err) << "\"";
2088    } else if (dataSize() > 0) {
2089        const uint8_t* DATA = data();
2090        to << indent << HexDump(DATA, dataSize()) << dedent;
2091        const binder_size_t* OBJS = objects();
2092        const size_t N = objectsCount();
2093        for (size_t i=0; i<N; i++) {
2094            const flat_binder_object* flat
2095                = reinterpret_cast<const flat_binder_object*>(DATA+OBJS[i]);
2096            to << endl << "Object #" << i << " @ " << (void*)OBJS[i] << ": "
2097                << TypeCode(flat->type & 0x7f7f7f00)
2098                << " = " << flat->binder;
2099        }
2100    } else {
2101        to << "NULL";
2102    }
2103
2104    to << ")";
2105}
2106
2107void Parcel::releaseObjects()
2108{
2109    const sp<ProcessState> proc(ProcessState::self());
2110    size_t i = mObjectsSize;
2111    uint8_t* const data = mData;
2112    binder_size_t* const objects = mObjects;
2113    while (i > 0) {
2114        i--;
2115        const flat_binder_object* flat
2116            = reinterpret_cast<flat_binder_object*>(data+objects[i]);
2117        release_object(proc, *flat, this, &mOpenAshmemSize);
2118    }
2119}
2120
2121void Parcel::acquireObjects()
2122{
2123    const sp<ProcessState> proc(ProcessState::self());
2124    size_t i = mObjectsSize;
2125    uint8_t* const data = mData;
2126    binder_size_t* const objects = mObjects;
2127    while (i > 0) {
2128        i--;
2129        const flat_binder_object* flat
2130            = reinterpret_cast<flat_binder_object*>(data+objects[i]);
2131        acquire_object(proc, *flat, this, &mOpenAshmemSize);
2132    }
2133}
2134
2135void Parcel::freeData()
2136{
2137    freeDataNoInit();
2138    initState();
2139}
2140
2141void Parcel::freeDataNoInit()
2142{
2143    if (mOwner) {
2144        LOG_ALLOC("Parcel %p: freeing other owner data", this);
2145        //ALOGI("Freeing data ref of %p (pid=%d)", this, getpid());
2146        mOwner(this, mData, mDataSize, mObjects, mObjectsSize, mOwnerCookie);
2147    } else {
2148        LOG_ALLOC("Parcel %p: freeing allocated data", this);
2149        releaseObjects();
2150        if (mData) {
2151            LOG_ALLOC("Parcel %p: freeing with %zu capacity", this, mDataCapacity);
2152            pthread_mutex_lock(&gParcelGlobalAllocSizeLock);
2153            if (mDataCapacity <= gParcelGlobalAllocSize) {
2154              gParcelGlobalAllocSize = gParcelGlobalAllocSize - mDataCapacity;
2155            } else {
2156              gParcelGlobalAllocSize = 0;
2157            }
2158            if (gParcelGlobalAllocCount > 0) {
2159              gParcelGlobalAllocCount--;
2160            }
2161            pthread_mutex_unlock(&gParcelGlobalAllocSizeLock);
2162            free(mData);
2163        }
2164        if (mObjects) free(mObjects);
2165    }
2166}
2167
2168status_t Parcel::growData(size_t len)
2169{
2170    if (len > INT32_MAX) {
2171        // don't accept size_t values which may have come from an
2172        // inadvertent conversion from a negative int.
2173        return BAD_VALUE;
2174    }
2175
2176    size_t newSize = ((mDataSize+len)*3)/2;
2177    return (newSize <= mDataSize)
2178            ? (status_t) NO_MEMORY
2179            : continueWrite(newSize);
2180}
2181
2182status_t Parcel::restartWrite(size_t desired)
2183{
2184    if (desired > INT32_MAX) {
2185        // don't accept size_t values which may have come from an
2186        // inadvertent conversion from a negative int.
2187        return BAD_VALUE;
2188    }
2189
2190    if (mOwner) {
2191        freeData();
2192        return continueWrite(desired);
2193    }
2194
2195    uint8_t* data = (uint8_t*)realloc(mData, desired);
2196    if (!data && desired > mDataCapacity) {
2197        mError = NO_MEMORY;
2198        return NO_MEMORY;
2199    }
2200
2201    releaseObjects();
2202
2203    if (data) {
2204        LOG_ALLOC("Parcel %p: restart from %zu to %zu capacity", this, mDataCapacity, desired);
2205        pthread_mutex_lock(&gParcelGlobalAllocSizeLock);
2206        gParcelGlobalAllocSize += desired;
2207        gParcelGlobalAllocSize -= mDataCapacity;
2208        pthread_mutex_unlock(&gParcelGlobalAllocSizeLock);
2209        mData = data;
2210        mDataCapacity = desired;
2211    }
2212
2213    mDataSize = mDataPos = 0;
2214    ALOGV("restartWrite Setting data size of %p to %zu", this, mDataSize);
2215    ALOGV("restartWrite Setting data pos of %p to %zu", this, mDataPos);
2216
2217    free(mObjects);
2218    mObjects = NULL;
2219    mObjectsSize = mObjectsCapacity = 0;
2220    mNextObjectHint = 0;
2221    mHasFds = false;
2222    mFdsKnown = true;
2223    mAllowFds = true;
2224
2225    return NO_ERROR;
2226}
2227
2228status_t Parcel::continueWrite(size_t desired)
2229{
2230    if (desired > INT32_MAX) {
2231        // don't accept size_t values which may have come from an
2232        // inadvertent conversion from a negative int.
2233        return BAD_VALUE;
2234    }
2235
2236    // If shrinking, first adjust for any objects that appear
2237    // after the new data size.
2238    size_t objectsSize = mObjectsSize;
2239    if (desired < mDataSize) {
2240        if (desired == 0) {
2241            objectsSize = 0;
2242        } else {
2243            while (objectsSize > 0) {
2244                if (mObjects[objectsSize-1] < desired)
2245                    break;
2246                objectsSize--;
2247            }
2248        }
2249    }
2250
2251    if (mOwner) {
2252        // If the size is going to zero, just release the owner's data.
2253        if (desired == 0) {
2254            freeData();
2255            return NO_ERROR;
2256        }
2257
2258        // If there is a different owner, we need to take
2259        // posession.
2260        uint8_t* data = (uint8_t*)malloc(desired);
2261        if (!data) {
2262            mError = NO_MEMORY;
2263            return NO_MEMORY;
2264        }
2265        binder_size_t* objects = NULL;
2266
2267        if (objectsSize) {
2268            objects = (binder_size_t*)calloc(objectsSize, sizeof(binder_size_t));
2269            if (!objects) {
2270                free(data);
2271
2272                mError = NO_MEMORY;
2273                return NO_MEMORY;
2274            }
2275
2276            // Little hack to only acquire references on objects
2277            // we will be keeping.
2278            size_t oldObjectsSize = mObjectsSize;
2279            mObjectsSize = objectsSize;
2280            acquireObjects();
2281            mObjectsSize = oldObjectsSize;
2282        }
2283
2284        if (mData) {
2285            memcpy(data, mData, mDataSize < desired ? mDataSize : desired);
2286        }
2287        if (objects && mObjects) {
2288            memcpy(objects, mObjects, objectsSize*sizeof(binder_size_t));
2289        }
2290        //ALOGI("Freeing data ref of %p (pid=%d)", this, getpid());
2291        mOwner(this, mData, mDataSize, mObjects, mObjectsSize, mOwnerCookie);
2292        mOwner = NULL;
2293
2294        LOG_ALLOC("Parcel %p: taking ownership of %zu capacity", this, desired);
2295        pthread_mutex_lock(&gParcelGlobalAllocSizeLock);
2296        gParcelGlobalAllocSize += desired;
2297        gParcelGlobalAllocCount++;
2298        pthread_mutex_unlock(&gParcelGlobalAllocSizeLock);
2299
2300        mData = data;
2301        mObjects = objects;
2302        mDataSize = (mDataSize < desired) ? mDataSize : desired;
2303        ALOGV("continueWrite Setting data size of %p to %zu", this, mDataSize);
2304        mDataCapacity = desired;
2305        mObjectsSize = mObjectsCapacity = objectsSize;
2306        mNextObjectHint = 0;
2307
2308    } else if (mData) {
2309        if (objectsSize < mObjectsSize) {
2310            // Need to release refs on any objects we are dropping.
2311            const sp<ProcessState> proc(ProcessState::self());
2312            for (size_t i=objectsSize; i<mObjectsSize; i++) {
2313                const flat_binder_object* flat
2314                    = reinterpret_cast<flat_binder_object*>(mData+mObjects[i]);
2315                if (flat->type == BINDER_TYPE_FD) {
2316                    // will need to rescan because we may have lopped off the only FDs
2317                    mFdsKnown = false;
2318                }
2319                release_object(proc, *flat, this, &mOpenAshmemSize);
2320            }
2321            binder_size_t* objects =
2322                (binder_size_t*)realloc(mObjects, objectsSize*sizeof(binder_size_t));
2323            if (objects) {
2324                mObjects = objects;
2325            }
2326            mObjectsSize = objectsSize;
2327            mNextObjectHint = 0;
2328        }
2329
2330        // We own the data, so we can just do a realloc().
2331        if (desired > mDataCapacity) {
2332            uint8_t* data = (uint8_t*)realloc(mData, desired);
2333            if (data) {
2334                LOG_ALLOC("Parcel %p: continue from %zu to %zu capacity", this, mDataCapacity,
2335                        desired);
2336                pthread_mutex_lock(&gParcelGlobalAllocSizeLock);
2337                gParcelGlobalAllocSize += desired;
2338                gParcelGlobalAllocSize -= mDataCapacity;
2339                gParcelGlobalAllocCount++;
2340                pthread_mutex_unlock(&gParcelGlobalAllocSizeLock);
2341                mData = data;
2342                mDataCapacity = desired;
2343            } else if (desired > mDataCapacity) {
2344                mError = NO_MEMORY;
2345                return NO_MEMORY;
2346            }
2347        } else {
2348            if (mDataSize > desired) {
2349                mDataSize = desired;
2350                ALOGV("continueWrite Setting data size of %p to %zu", this, mDataSize);
2351            }
2352            if (mDataPos > desired) {
2353                mDataPos = desired;
2354                ALOGV("continueWrite Setting data pos of %p to %zu", this, mDataPos);
2355            }
2356        }
2357
2358    } else {
2359        // This is the first data.  Easy!
2360        uint8_t* data = (uint8_t*)malloc(desired);
2361        if (!data) {
2362            mError = NO_MEMORY;
2363            return NO_MEMORY;
2364        }
2365
2366        if(!(mDataCapacity == 0 && mObjects == NULL
2367             && mObjectsCapacity == 0)) {
2368            ALOGE("continueWrite: %zu/%p/%zu/%zu", mDataCapacity, mObjects, mObjectsCapacity, desired);
2369        }
2370
2371        LOG_ALLOC("Parcel %p: allocating with %zu capacity", this, desired);
2372        pthread_mutex_lock(&gParcelGlobalAllocSizeLock);
2373        gParcelGlobalAllocSize += desired;
2374        gParcelGlobalAllocCount++;
2375        pthread_mutex_unlock(&gParcelGlobalAllocSizeLock);
2376
2377        mData = data;
2378        mDataSize = mDataPos = 0;
2379        ALOGV("continueWrite Setting data size of %p to %zu", this, mDataSize);
2380        ALOGV("continueWrite Setting data pos of %p to %zu", this, mDataPos);
2381        mDataCapacity = desired;
2382    }
2383
2384    return NO_ERROR;
2385}
2386
2387void Parcel::initState()
2388{
2389    LOG_ALLOC("Parcel %p: initState", this);
2390    mError = NO_ERROR;
2391    mData = 0;
2392    mDataSize = 0;
2393    mDataCapacity = 0;
2394    mDataPos = 0;
2395    ALOGV("initState Setting data size of %p to %zu", this, mDataSize);
2396    ALOGV("initState Setting data pos of %p to %zu", this, mDataPos);
2397    mObjects = NULL;
2398    mObjectsSize = 0;
2399    mObjectsCapacity = 0;
2400    mNextObjectHint = 0;
2401    mHasFds = false;
2402    mFdsKnown = true;
2403    mAllowFds = true;
2404    mOwner = NULL;
2405    mOpenAshmemSize = 0;
2406}
2407
2408void Parcel::scanForFds() const
2409{
2410    bool hasFds = false;
2411    for (size_t i=0; i<mObjectsSize; i++) {
2412        const flat_binder_object* flat
2413            = reinterpret_cast<const flat_binder_object*>(mData + mObjects[i]);
2414        if (flat->type == BINDER_TYPE_FD) {
2415            hasFds = true;
2416            break;
2417        }
2418    }
2419    mHasFds = hasFds;
2420    mFdsKnown = true;
2421}
2422
2423size_t Parcel::getBlobAshmemSize() const
2424{
2425    // This used to return the size of all blobs that were written to ashmem, now we're returning
2426    // the ashmem currently referenced by this Parcel, which should be equivalent.
2427    // TODO: Remove method once ABI can be changed.
2428    return mOpenAshmemSize;
2429}
2430
2431size_t Parcel::getOpenAshmemSize() const
2432{
2433    return mOpenAshmemSize;
2434}
2435
2436// --- Parcel::Blob ---
2437
2438Parcel::Blob::Blob() :
2439        mFd(-1), mData(NULL), mSize(0), mMutable(false) {
2440}
2441
2442Parcel::Blob::~Blob() {
2443    release();
2444}
2445
2446void Parcel::Blob::release() {
2447    if (mFd != -1 && mData) {
2448        ::munmap(mData, mSize);
2449    }
2450    clear();
2451}
2452
2453void Parcel::Blob::init(int fd, void* data, size_t size, bool isMutable) {
2454    mFd = fd;
2455    mData = data;
2456    mSize = size;
2457    mMutable = isMutable;
2458}
2459
2460void Parcel::Blob::clear() {
2461    mFd = -1;
2462    mData = NULL;
2463    mSize = 0;
2464    mMutable = false;
2465}
2466
2467}; // namespace android
2468