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