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