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