Home | History | Annotate | Download | only in binder
      1 /*
      2  * Copyright (C) 2005 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 #define LOG_TAG "Parcel"
     18 //#define LOG_NDEBUG 0
     19 
     20 #include <binder/Parcel.h>
     21 
     22 #include <binder/IPCThreadState.h>
     23 #include <binder/Binder.h>
     24 #include <binder/BpBinder.h>
     25 #include <binder/ProcessState.h>
     26 #include <binder/TextOutput.h>
     27 
     28 #include <utils/Debug.h>
     29 #include <utils/Log.h>
     30 #include <utils/String8.h>
     31 #include <utils/String16.h>
     32 #include <utils/misc.h>
     33 #include <utils/Flattenable.h>
     34 #include <cutils/ashmem.h>
     35 
     36 #include <private/binder/binder_module.h>
     37 
     38 #include <inttypes.h>
     39 #include <stdio.h>
     40 #include <stdlib.h>
     41 #include <stdint.h>
     42 #include <sys/mman.h>
     43 
     44 #ifndef INT32_MAX
     45 #define INT32_MAX ((int32_t)(2147483647))
     46 #endif
     47 
     48 #define LOG_REFS(...)
     49 //#define LOG_REFS(...) ALOG(LOG_DEBUG, "Parcel", __VA_ARGS__)
     50 
     51 // ---------------------------------------------------------------------------
     52 
     53 #define PAD_SIZE(s) (((s)+3)&~3)
     54 
     55 // Note: must be kept in sync with android/os/StrictMode.java's PENALTY_GATHER
     56 #define STRICT_MODE_PENALTY_GATHER 0x100
     57 
     58 // Note: must be kept in sync with android/os/Parcel.java's EX_HAS_REPLY_HEADER
     59 #define EX_HAS_REPLY_HEADER -128
     60 
     61 // Maximum size of a blob to transfer in-place.
     62 static const size_t IN_PLACE_BLOB_LIMIT = 40 * 1024;
     63 
     64 // XXX This can be made public if we want to provide
     65 // support for typed data.
     66 struct small_flat_data
     67 {
     68     uint32_t type;
     69     uint32_t data;
     70 };
     71 
     72 namespace android {
     73 
     74 void acquire_object(const sp<ProcessState>& proc,
     75     const flat_binder_object& obj, const void* who)
     76 {
     77     switch (obj.type) {
     78         case BINDER_TYPE_BINDER:
     79             if (obj.binder) {
     80                 LOG_REFS("Parcel %p acquiring reference on local %p", who, obj.cookie);
     81                 static_cast<IBinder*>(obj.cookie)->incStrong(who);
     82             }
     83             return;
     84         case BINDER_TYPE_WEAK_BINDER:
     85             if (obj.binder)
     86                 static_cast<RefBase::weakref_type*>(obj.binder)->incWeak(who);
     87             return;
     88         case BINDER_TYPE_HANDLE: {
     89             const sp<IBinder> b = proc->getStrongProxyForHandle(obj.handle);
     90             if (b != NULL) {
     91                 LOG_REFS("Parcel %p acquiring reference on remote %p", who, b.get());
     92                 b->incStrong(who);
     93             }
     94             return;
     95         }
     96         case BINDER_TYPE_WEAK_HANDLE: {
     97             const wp<IBinder> b = proc->getWeakProxyForHandle(obj.handle);
     98             if (b != NULL) b.get_refs()->incWeak(who);
     99             return;
    100         }
    101         case BINDER_TYPE_FD: {
    102             // intentionally blank -- nothing to do to acquire this, but we do
    103             // recognize it as a legitimate object type.
    104             return;
    105         }
    106     }
    107 
    108     ALOGD("Invalid object type 0x%08lx", obj.type);
    109 }
    110 
    111 void release_object(const sp<ProcessState>& proc,
    112     const flat_binder_object& obj, const void* who)
    113 {
    114     switch (obj.type) {
    115         case BINDER_TYPE_BINDER:
    116             if (obj.binder) {
    117                 LOG_REFS("Parcel %p releasing reference on local %p", who, obj.cookie);
    118                 static_cast<IBinder*>(obj.cookie)->decStrong(who);
    119             }
    120             return;
    121         case BINDER_TYPE_WEAK_BINDER:
    122             if (obj.binder)
    123                 static_cast<RefBase::weakref_type*>(obj.binder)->decWeak(who);
    124             return;
    125         case BINDER_TYPE_HANDLE: {
    126             const sp<IBinder> b = proc->getStrongProxyForHandle(obj.handle);
    127             if (b != NULL) {
    128                 LOG_REFS("Parcel %p releasing reference on remote %p", who, b.get());
    129                 b->decStrong(who);
    130             }
    131             return;
    132         }
    133         case BINDER_TYPE_WEAK_HANDLE: {
    134             const wp<IBinder> b = proc->getWeakProxyForHandle(obj.handle);
    135             if (b != NULL) b.get_refs()->decWeak(who);
    136             return;
    137         }
    138         case BINDER_TYPE_FD: {
    139             if (obj.cookie != (void*)0) close(obj.handle);
    140             return;
    141         }
    142     }
    143 
    144     ALOGE("Invalid object type 0x%08lx", obj.type);
    145 }
    146 
    147 inline static status_t finish_flatten_binder(
    148     const sp<IBinder>& binder, const flat_binder_object& flat, Parcel* out)
    149 {
    150     return out->writeObject(flat, false);
    151 }
    152 
    153 status_t flatten_binder(const sp<ProcessState>& proc,
    154     const sp<IBinder>& binder, Parcel* out)
    155 {
    156     flat_binder_object obj;
    157 
    158     obj.flags = 0x7f | FLAT_BINDER_FLAG_ACCEPTS_FDS;
    159     if (binder != NULL) {
    160         IBinder *local = binder->localBinder();
    161         if (!local) {
    162             BpBinder *proxy = binder->remoteBinder();
    163             if (proxy == NULL) {
    164                 ALOGE("null proxy");
    165             }
    166             const int32_t handle = proxy ? proxy->handle() : 0;
    167             obj.type = BINDER_TYPE_HANDLE;
    168             obj.handle = handle;
    169             obj.cookie = NULL;
    170         } else {
    171             obj.type = BINDER_TYPE_BINDER;
    172             obj.binder = local->getWeakRefs();
    173             obj.cookie = local;
    174         }
    175     } else {
    176         obj.type = BINDER_TYPE_BINDER;
    177         obj.binder = NULL;
    178         obj.cookie = NULL;
    179     }
    180 
    181     return finish_flatten_binder(binder, obj, out);
    182 }
    183 
    184 status_t flatten_binder(const sp<ProcessState>& proc,
    185     const wp<IBinder>& binder, Parcel* out)
    186 {
    187     flat_binder_object obj;
    188 
    189     obj.flags = 0x7f | FLAT_BINDER_FLAG_ACCEPTS_FDS;
    190     if (binder != NULL) {
    191         sp<IBinder> real = binder.promote();
    192         if (real != NULL) {
    193             IBinder *local = real->localBinder();
    194             if (!local) {
    195                 BpBinder *proxy = real->remoteBinder();
    196                 if (proxy == NULL) {
    197                     ALOGE("null proxy");
    198                 }
    199                 const int32_t handle = proxy ? proxy->handle() : 0;
    200                 obj.type = BINDER_TYPE_WEAK_HANDLE;
    201                 obj.handle = handle;
    202                 obj.cookie = NULL;
    203             } else {
    204                 obj.type = BINDER_TYPE_WEAK_BINDER;
    205                 obj.binder = binder.get_refs();
    206                 obj.cookie = binder.unsafe_get();
    207             }
    208             return finish_flatten_binder(real, obj, out);
    209         }
    210 
    211         // XXX How to deal?  In order to flatten the given binder,
    212         // we need to probe it for information, which requires a primary
    213         // reference...  but we don't have one.
    214         //
    215         // The OpenBinder implementation uses a dynamic_cast<> here,
    216         // but we can't do that with the different reference counting
    217         // implementation we are using.
    218         ALOGE("Unable to unflatten Binder weak reference!");
    219         obj.type = BINDER_TYPE_BINDER;
    220         obj.binder = NULL;
    221         obj.cookie = NULL;
    222         return finish_flatten_binder(NULL, obj, out);
    223 
    224     } else {
    225         obj.type = BINDER_TYPE_BINDER;
    226         obj.binder = NULL;
    227         obj.cookie = NULL;
    228         return finish_flatten_binder(NULL, obj, out);
    229     }
    230 }
    231 
    232 inline static status_t finish_unflatten_binder(
    233     BpBinder* proxy, const flat_binder_object& flat, const Parcel& in)
    234 {
    235     return NO_ERROR;
    236 }
    237 
    238 status_t unflatten_binder(const sp<ProcessState>& proc,
    239     const Parcel& in, sp<IBinder>* out)
    240 {
    241     const flat_binder_object* flat = in.readObject(false);
    242 
    243     if (flat) {
    244         switch (flat->type) {
    245             case BINDER_TYPE_BINDER:
    246                 *out = static_cast<IBinder*>(flat->cookie);
    247                 return finish_unflatten_binder(NULL, *flat, in);
    248             case BINDER_TYPE_HANDLE:
    249                 *out = proc->getStrongProxyForHandle(flat->handle);
    250                 return finish_unflatten_binder(
    251                     static_cast<BpBinder*>(out->get()), *flat, in);
    252         }
    253     }
    254     return BAD_TYPE;
    255 }
    256 
    257 status_t unflatten_binder(const sp<ProcessState>& proc,
    258     const Parcel& in, wp<IBinder>* out)
    259 {
    260     const flat_binder_object* flat = in.readObject(false);
    261 
    262     if (flat) {
    263         switch (flat->type) {
    264             case BINDER_TYPE_BINDER:
    265                 *out = static_cast<IBinder*>(flat->cookie);
    266                 return finish_unflatten_binder(NULL, *flat, in);
    267             case BINDER_TYPE_WEAK_BINDER:
    268                 if (flat->binder != NULL) {
    269                     out->set_object_and_refs(
    270                         static_cast<IBinder*>(flat->cookie),
    271                         static_cast<RefBase::weakref_type*>(flat->binder));
    272                 } else {
    273                     *out = NULL;
    274                 }
    275                 return finish_unflatten_binder(NULL, *flat, in);
    276             case BINDER_TYPE_HANDLE:
    277             case BINDER_TYPE_WEAK_HANDLE:
    278                 *out = proc->getWeakProxyForHandle(flat->handle);
    279                 return finish_unflatten_binder(
    280                     static_cast<BpBinder*>(out->unsafe_get()), *flat, in);
    281         }
    282     }
    283     return BAD_TYPE;
    284 }
    285 
    286 // ---------------------------------------------------------------------------
    287 
    288 Parcel::Parcel()
    289 {
    290     initState();
    291 }
    292 
    293 Parcel::~Parcel()
    294 {
    295     freeDataNoInit();
    296 }
    297 
    298 const uint8_t* Parcel::data() const
    299 {
    300     return mData;
    301 }
    302 
    303 size_t Parcel::dataSize() const
    304 {
    305     return (mDataSize > mDataPos ? mDataSize : mDataPos);
    306 }
    307 
    308 size_t Parcel::dataAvail() const
    309 {
    310     // TODO: decide what to do about the possibility that this can
    311     // report an available-data size that exceeds a Java int's max
    312     // positive value, causing havoc.  Fortunately this will only
    313     // happen if someone constructs a Parcel containing more than two
    314     // gigabytes of data, which on typical phone hardware is simply
    315     // not possible.
    316     return dataSize() - dataPosition();
    317 }
    318 
    319 size_t Parcel::dataPosition() const
    320 {
    321     return mDataPos;
    322 }
    323 
    324 size_t Parcel::dataCapacity() const
    325 {
    326     return mDataCapacity;
    327 }
    328 
    329 status_t Parcel::setDataSize(size_t size)
    330 {
    331     status_t err;
    332     err = continueWrite(size);
    333     if (err == NO_ERROR) {
    334         mDataSize = size;
    335         ALOGV("setDataSize Setting data size of %p to %d\n", this, mDataSize);
    336     }
    337     return err;
    338 }
    339 
    340 void Parcel::setDataPosition(size_t pos) const
    341 {
    342     mDataPos = pos;
    343     mNextObjectHint = 0;
    344 }
    345 
    346 status_t Parcel::setDataCapacity(size_t size)
    347 {
    348     if (size > mDataCapacity) return continueWrite(size);
    349     return NO_ERROR;
    350 }
    351 
    352 status_t Parcel::setData(const uint8_t* buffer, size_t len)
    353 {
    354     status_t err = restartWrite(len);
    355     if (err == NO_ERROR) {
    356         memcpy(const_cast<uint8_t*>(data()), buffer, len);
    357         mDataSize = len;
    358         mFdsKnown = false;
    359     }
    360     return err;
    361 }
    362 
    363 status_t Parcel::appendFrom(const Parcel *parcel, size_t offset, size_t len)
    364 {
    365     const sp<ProcessState> proc(ProcessState::self());
    366     status_t err;
    367     const uint8_t *data = parcel->mData;
    368     const size_t *objects = parcel->mObjects;
    369     size_t size = parcel->mObjectsSize;
    370     int startPos = mDataPos;
    371     int firstIndex = -1, lastIndex = -2;
    372 
    373     if (len == 0) {
    374         return NO_ERROR;
    375     }
    376 
    377     // range checks against the source parcel size
    378     if ((offset > parcel->mDataSize)
    379             || (len > parcel->mDataSize)
    380             || (offset + len > parcel->mDataSize)) {
    381         return BAD_VALUE;
    382     }
    383 
    384     // Count objects in range
    385     for (int i = 0; i < (int) size; i++) {
    386         size_t off = objects[i];
    387         if ((off >= offset) && (off < offset + len)) {
    388             if (firstIndex == -1) {
    389                 firstIndex = i;
    390             }
    391             lastIndex = i;
    392         }
    393     }
    394     int numObjects = lastIndex - firstIndex + 1;
    395 
    396     if ((mDataSize+len) > mDataCapacity) {
    397         // grow data
    398         err = growData(len);
    399         if (err != NO_ERROR) {
    400             return err;
    401         }
    402     }
    403 
    404     // append data
    405     memcpy(mData + mDataPos, data + offset, len);
    406     mDataPos += len;
    407     mDataSize += len;
    408 
    409     err = NO_ERROR;
    410 
    411     if (numObjects > 0) {
    412         // grow objects
    413         if (mObjectsCapacity < mObjectsSize + numObjects) {
    414             int newSize = ((mObjectsSize + numObjects)*3)/2;
    415             size_t *objects =
    416                 (size_t*)realloc(mObjects, newSize*sizeof(size_t));
    417             if (objects == (size_t*)0) {
    418                 return NO_MEMORY;
    419             }
    420             mObjects = objects;
    421             mObjectsCapacity = newSize;
    422         }
    423 
    424         // append and acquire objects
    425         int idx = mObjectsSize;
    426         for (int i = firstIndex; i <= lastIndex; i++) {
    427             size_t off = objects[i] - offset + startPos;
    428             mObjects[idx++] = off;
    429             mObjectsSize++;
    430 
    431             flat_binder_object* flat
    432                 = reinterpret_cast<flat_binder_object*>(mData + off);
    433             acquire_object(proc, *flat, this);
    434 
    435             if (flat->type == BINDER_TYPE_FD) {
    436                 // If this is a file descriptor, we need to dup it so the
    437                 // new Parcel now owns its own fd, and can declare that we
    438                 // officially know we have fds.
    439                 flat->handle = dup(flat->handle);
    440                 flat->cookie = (void*)1;
    441                 mHasFds = mFdsKnown = true;
    442                 if (!mAllowFds) {
    443                     err = FDS_NOT_ALLOWED;
    444                 }
    445             }
    446         }
    447     }
    448 
    449     return err;
    450 }
    451 
    452 bool Parcel::pushAllowFds(bool allowFds)
    453 {
    454     const bool origValue = mAllowFds;
    455     if (!allowFds) {
    456         mAllowFds = false;
    457     }
    458     return origValue;
    459 }
    460 
    461 void Parcel::restoreAllowFds(bool lastValue)
    462 {
    463     mAllowFds = lastValue;
    464 }
    465 
    466 bool Parcel::hasFileDescriptors() const
    467 {
    468     if (!mFdsKnown) {
    469         scanForFds();
    470     }
    471     return mHasFds;
    472 }
    473 
    474 // Write RPC headers.  (previously just the interface token)
    475 status_t Parcel::writeInterfaceToken(const String16& interface)
    476 {
    477     writeInt32(IPCThreadState::self()->getStrictModePolicy() |
    478                STRICT_MODE_PENALTY_GATHER);
    479     // currently the interface identification token is just its name as a string
    480     return writeString16(interface);
    481 }
    482 
    483 bool Parcel::checkInterface(IBinder* binder) const
    484 {
    485     return enforceInterface(binder->getInterfaceDescriptor());
    486 }
    487 
    488 bool Parcel::enforceInterface(const String16& interface,
    489                               IPCThreadState* threadState) const
    490 {
    491     int32_t strictPolicy = readInt32();
    492     if (threadState == NULL) {
    493         threadState = IPCThreadState::self();
    494     }
    495     if ((threadState->getLastTransactionBinderFlags() &
    496          IBinder::FLAG_ONEWAY) != 0) {
    497       // For one-way calls, the callee is running entirely
    498       // disconnected from the caller, so disable StrictMode entirely.
    499       // Not only does disk/network usage not impact the caller, but
    500       // there's no way to commuicate back any violations anyway.
    501       threadState->setStrictModePolicy(0);
    502     } else {
    503       threadState->setStrictModePolicy(strictPolicy);
    504     }
    505     const String16 str(readString16());
    506     if (str == interface) {
    507         return true;
    508     } else {
    509         ALOGW("**** enforceInterface() expected '%s' but read '%s'\n",
    510                 String8(interface).string(), String8(str).string());
    511         return false;
    512     }
    513 }
    514 
    515 const size_t* Parcel::objects() const
    516 {
    517     return mObjects;
    518 }
    519 
    520 size_t Parcel::objectsCount() const
    521 {
    522     return mObjectsSize;
    523 }
    524 
    525 status_t Parcel::errorCheck() const
    526 {
    527     return mError;
    528 }
    529 
    530 void Parcel::setError(status_t err)
    531 {
    532     mError = err;
    533 }
    534 
    535 status_t Parcel::finishWrite(size_t len)
    536 {
    537     //printf("Finish write of %d\n", len);
    538     mDataPos += len;
    539     ALOGV("finishWrite Setting data pos of %p to %d\n", this, mDataPos);
    540     if (mDataPos > mDataSize) {
    541         mDataSize = mDataPos;
    542         ALOGV("finishWrite Setting data size of %p to %d\n", this, mDataSize);
    543     }
    544     //printf("New pos=%d, size=%d\n", mDataPos, mDataSize);
    545     return NO_ERROR;
    546 }
    547 
    548 status_t Parcel::writeUnpadded(const void* data, size_t len)
    549 {
    550     size_t end = mDataPos + len;
    551     if (end < mDataPos) {
    552         // integer overflow
    553         return BAD_VALUE;
    554     }
    555 
    556     if (end <= mDataCapacity) {
    557 restart_write:
    558         memcpy(mData+mDataPos, data, len);
    559         return finishWrite(len);
    560     }
    561 
    562     status_t err = growData(len);
    563     if (err == NO_ERROR) goto restart_write;
    564     return err;
    565 }
    566 
    567 status_t Parcel::write(const void* data, size_t len)
    568 {
    569     void* const d = writeInplace(len);
    570     if (d) {
    571         memcpy(d, data, len);
    572         return NO_ERROR;
    573     }
    574     return mError;
    575 }
    576 
    577 void* Parcel::writeInplace(size_t len)
    578 {
    579     const size_t padded = PAD_SIZE(len);
    580 
    581     // sanity check for integer overflow
    582     if (mDataPos+padded < mDataPos) {
    583         return NULL;
    584     }
    585 
    586     if ((mDataPos+padded) <= mDataCapacity) {
    587 restart_write:
    588         //printf("Writing %ld bytes, padded to %ld\n", len, padded);
    589         uint8_t* const data = mData+mDataPos;
    590 
    591         // Need to pad at end?
    592         if (padded != len) {
    593 #if BYTE_ORDER == BIG_ENDIAN
    594             static const uint32_t mask[4] = {
    595                 0x00000000, 0xffffff00, 0xffff0000, 0xff000000
    596             };
    597 #endif
    598 #if BYTE_ORDER == LITTLE_ENDIAN
    599             static const uint32_t mask[4] = {
    600                 0x00000000, 0x00ffffff, 0x0000ffff, 0x000000ff
    601             };
    602 #endif
    603             //printf("Applying pad mask: %p to %p\n", (void*)mask[padded-len],
    604             //    *reinterpret_cast<void**>(data+padded-4));
    605             *reinterpret_cast<uint32_t*>(data+padded-4) &= mask[padded-len];
    606         }
    607 
    608         finishWrite(padded);
    609         return data;
    610     }
    611 
    612     status_t err = growData(padded);
    613     if (err == NO_ERROR) goto restart_write;
    614     return NULL;
    615 }
    616 
    617 status_t Parcel::writeInt32(int32_t val)
    618 {
    619     return writeAligned(val);
    620 }
    621 status_t Parcel::writeInt32Array(size_t len, const int32_t *val) {
    622     if (!val) {
    623         return writeAligned(-1);
    624     }
    625     status_t ret = writeAligned(len);
    626     if (ret == NO_ERROR) {
    627         ret = write(val, len * sizeof(*val));
    628     }
    629     return ret;
    630 }
    631 status_t Parcel::writeByteArray(size_t len, const uint8_t *val) {
    632     if (!val) {
    633         return writeAligned(-1);
    634     }
    635     status_t ret = writeAligned(len);
    636     if (ret == NO_ERROR) {
    637         ret = write(val, len * sizeof(*val));
    638     }
    639     return ret;
    640 }
    641 
    642 status_t Parcel::writeInt64(int64_t val)
    643 {
    644     return writeAligned(val);
    645 }
    646 
    647 status_t Parcel::writeFloat(float val)
    648 {
    649     return writeAligned(val);
    650 }
    651 
    652 #if defined(__mips__) && defined(__mips_hard_float)
    653 
    654 status_t Parcel::writeDouble(double val)
    655 {
    656     union {
    657         double d;
    658         unsigned long long ll;
    659     } u;
    660     u.d = val;
    661     return writeAligned(u.ll);
    662 }
    663 
    664 #else
    665 
    666 status_t Parcel::writeDouble(double val)
    667 {
    668     return writeAligned(val);
    669 }
    670 
    671 #endif
    672 
    673 status_t Parcel::writeIntPtr(intptr_t val)
    674 {
    675     return writeAligned(val);
    676 }
    677 
    678 status_t Parcel::writeCString(const char* str)
    679 {
    680     return write(str, strlen(str)+1);
    681 }
    682 
    683 status_t Parcel::writeString8(const String8& str)
    684 {
    685     status_t err = writeInt32(str.bytes());
    686     // only write string if its length is more than zero characters,
    687     // as readString8 will only read if the length field is non-zero.
    688     // this is slightly different from how writeString16 works.
    689     if (str.bytes() > 0 && err == NO_ERROR) {
    690         err = write(str.string(), str.bytes()+1);
    691     }
    692     return err;
    693 }
    694 
    695 status_t Parcel::writeString16(const String16& str)
    696 {
    697     return writeString16(str.string(), str.size());
    698 }
    699 
    700 status_t Parcel::writeString16(const char16_t* str, size_t len)
    701 {
    702     if (str == NULL) return writeInt32(-1);
    703 
    704     status_t err = writeInt32(len);
    705     if (err == NO_ERROR) {
    706         len *= sizeof(char16_t);
    707         uint8_t* data = (uint8_t*)writeInplace(len+sizeof(char16_t));
    708         if (data) {
    709             memcpy(data, str, len);
    710             *reinterpret_cast<char16_t*>(data+len) = 0;
    711             return NO_ERROR;
    712         }
    713         err = mError;
    714     }
    715     return err;
    716 }
    717 
    718 status_t Parcel::writeStrongBinder(const sp<IBinder>& val)
    719 {
    720     return flatten_binder(ProcessState::self(), val, this);
    721 }
    722 
    723 status_t Parcel::writeWeakBinder(const wp<IBinder>& val)
    724 {
    725     return flatten_binder(ProcessState::self(), val, this);
    726 }
    727 
    728 status_t Parcel::writeNativeHandle(const native_handle* handle)
    729 {
    730     if (!handle || handle->version != sizeof(native_handle))
    731         return BAD_TYPE;
    732 
    733     status_t err;
    734     err = writeInt32(handle->numFds);
    735     if (err != NO_ERROR) return err;
    736 
    737     err = writeInt32(handle->numInts);
    738     if (err != NO_ERROR) return err;
    739 
    740     for (int i=0 ; err==NO_ERROR && i<handle->numFds ; i++)
    741         err = writeDupFileDescriptor(handle->data[i]);
    742 
    743     if (err != NO_ERROR) {
    744         ALOGD("write native handle, write dup fd failed");
    745         return err;
    746     }
    747     err = write(handle->data + handle->numFds, sizeof(int)*handle->numInts);
    748     return err;
    749 }
    750 
    751 status_t Parcel::writeFileDescriptor(int fd, bool takeOwnership)
    752 {
    753     flat_binder_object obj;
    754     obj.type = BINDER_TYPE_FD;
    755     obj.flags = 0x7f | FLAT_BINDER_FLAG_ACCEPTS_FDS;
    756     obj.handle = fd;
    757     obj.cookie = (void*) (takeOwnership ? 1 : 0);
    758     return writeObject(obj, true);
    759 }
    760 
    761 status_t Parcel::writeDupFileDescriptor(int fd)
    762 {
    763     int dupFd = dup(fd);
    764     if (dupFd < 0) {
    765         return -errno;
    766     }
    767     status_t err = writeFileDescriptor(dupFd, true /*takeOwnership*/);
    768     if (err) {
    769         close(dupFd);
    770     }
    771     return err;
    772 }
    773 
    774 status_t Parcel::writeBlob(size_t len, WritableBlob* outBlob)
    775 {
    776     status_t status;
    777 
    778     if (!mAllowFds || len <= IN_PLACE_BLOB_LIMIT) {
    779         ALOGV("writeBlob: write in place");
    780         status = writeInt32(0);
    781         if (status) return status;
    782 
    783         void* ptr = writeInplace(len);
    784         if (!ptr) return NO_MEMORY;
    785 
    786         outBlob->init(false /*mapped*/, ptr, len);
    787         return NO_ERROR;
    788     }
    789 
    790     ALOGV("writeBlob: write to ashmem");
    791     int fd = ashmem_create_region("Parcel Blob", len);
    792     if (fd < 0) return NO_MEMORY;
    793 
    794     int result = ashmem_set_prot_region(fd, PROT_READ | PROT_WRITE);
    795     if (result < 0) {
    796         status = result;
    797     } else {
    798         void* ptr = ::mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    799         if (ptr == MAP_FAILED) {
    800             status = -errno;
    801         } else {
    802             result = ashmem_set_prot_region(fd, PROT_READ);
    803             if (result < 0) {
    804                 status = result;
    805             } else {
    806                 status = writeInt32(1);
    807                 if (!status) {
    808                     status = writeFileDescriptor(fd, true /*takeOwnership*/);
    809                     if (!status) {
    810                         outBlob->init(true /*mapped*/, ptr, len);
    811                         return NO_ERROR;
    812                     }
    813                 }
    814             }
    815         }
    816         ::munmap(ptr, len);
    817     }
    818     ::close(fd);
    819     return status;
    820 }
    821 
    822 status_t Parcel::write(const FlattenableHelperInterface& val)
    823 {
    824     status_t err;
    825 
    826     // size if needed
    827     const size_t len = val.getFlattenedSize();
    828     const size_t fd_count = val.getFdCount();
    829 
    830     err = this->writeInt32(len);
    831     if (err) return err;
    832 
    833     err = this->writeInt32(fd_count);
    834     if (err) return err;
    835 
    836     // payload
    837     void* const buf = this->writeInplace(PAD_SIZE(len));
    838     if (buf == NULL)
    839         return BAD_VALUE;
    840 
    841     int* fds = NULL;
    842     if (fd_count) {
    843         fds = new int[fd_count];
    844     }
    845 
    846     err = val.flatten(buf, len, fds, fd_count);
    847     for (size_t i=0 ; i<fd_count && err==NO_ERROR ; i++) {
    848         err = this->writeDupFileDescriptor( fds[i] );
    849     }
    850 
    851     if (fd_count) {
    852         delete [] fds;
    853     }
    854 
    855     return err;
    856 }
    857 
    858 status_t Parcel::writeObject(const flat_binder_object& val, bool nullMetaData)
    859 {
    860     const bool enoughData = (mDataPos+sizeof(val)) <= mDataCapacity;
    861     const bool enoughObjects = mObjectsSize < mObjectsCapacity;
    862     if (enoughData && enoughObjects) {
    863 restart_write:
    864         *reinterpret_cast<flat_binder_object*>(mData+mDataPos) = val;
    865 
    866         // Need to write meta-data?
    867         if (nullMetaData || val.binder != NULL) {
    868             mObjects[mObjectsSize] = mDataPos;
    869             acquire_object(ProcessState::self(), val, this);
    870             mObjectsSize++;
    871         }
    872 
    873         // remember if it's a file descriptor
    874         if (val.type == BINDER_TYPE_FD) {
    875             if (!mAllowFds) {
    876                 return FDS_NOT_ALLOWED;
    877             }
    878             mHasFds = mFdsKnown = true;
    879         }
    880 
    881         return finishWrite(sizeof(flat_binder_object));
    882     }
    883 
    884     if (!enoughData) {
    885         const status_t err = growData(sizeof(val));
    886         if (err != NO_ERROR) return err;
    887     }
    888     if (!enoughObjects) {
    889         size_t newSize = ((mObjectsSize+2)*3)/2;
    890         size_t* objects = (size_t*)realloc(mObjects, newSize*sizeof(size_t));
    891         if (objects == NULL) return NO_MEMORY;
    892         mObjects = objects;
    893         mObjectsCapacity = newSize;
    894     }
    895 
    896     goto restart_write;
    897 }
    898 
    899 status_t Parcel::writeNoException()
    900 {
    901     return writeInt32(0);
    902 }
    903 
    904 void Parcel::remove(size_t start, size_t amt)
    905 {
    906     LOG_ALWAYS_FATAL("Parcel::remove() not yet implemented!");
    907 }
    908 
    909 status_t Parcel::read(void* outData, size_t len) const
    910 {
    911     if ((mDataPos+PAD_SIZE(len)) >= mDataPos && (mDataPos+PAD_SIZE(len)) <= mDataSize
    912             && len <= PAD_SIZE(len)) {
    913         memcpy(outData, mData+mDataPos, len);
    914         mDataPos += PAD_SIZE(len);
    915         ALOGV("read Setting data pos of %p to %d\n", this, mDataPos);
    916         return NO_ERROR;
    917     }
    918     return NOT_ENOUGH_DATA;
    919 }
    920 
    921 const void* Parcel::readInplace(size_t len) const
    922 {
    923     if ((mDataPos+PAD_SIZE(len)) >= mDataPos && (mDataPos+PAD_SIZE(len)) <= mDataSize
    924             && len <= PAD_SIZE(len)) {
    925         const void* data = mData+mDataPos;
    926         mDataPos += PAD_SIZE(len);
    927         ALOGV("readInplace Setting data pos of %p to %d\n", this, mDataPos);
    928         return data;
    929     }
    930     return NULL;
    931 }
    932 
    933 template<class T>
    934 status_t Parcel::readAligned(T *pArg) const {
    935     COMPILE_TIME_ASSERT_FUNCTION_SCOPE(PAD_SIZE(sizeof(T)) == sizeof(T));
    936 
    937     if ((mDataPos+sizeof(T)) <= mDataSize) {
    938         const void* data = mData+mDataPos;
    939         mDataPos += sizeof(T);
    940         *pArg =  *reinterpret_cast<const T*>(data);
    941         return NO_ERROR;
    942     } else {
    943         return NOT_ENOUGH_DATA;
    944     }
    945 }
    946 
    947 template<class T>
    948 T Parcel::readAligned() const {
    949     T result;
    950     if (readAligned(&result) != NO_ERROR) {
    951         result = 0;
    952     }
    953 
    954     return result;
    955 }
    956 
    957 template<class T>
    958 status_t Parcel::writeAligned(T val) {
    959     COMPILE_TIME_ASSERT_FUNCTION_SCOPE(PAD_SIZE(sizeof(T)) == sizeof(T));
    960 
    961     if ((mDataPos+sizeof(val)) <= mDataCapacity) {
    962 restart_write:
    963         *reinterpret_cast<T*>(mData+mDataPos) = val;
    964         return finishWrite(sizeof(val));
    965     }
    966 
    967     status_t err = growData(sizeof(val));
    968     if (err == NO_ERROR) goto restart_write;
    969     return err;
    970 }
    971 
    972 status_t Parcel::readInt32(int32_t *pArg) const
    973 {
    974     return readAligned(pArg);
    975 }
    976 
    977 int32_t Parcel::readInt32() const
    978 {
    979     return readAligned<int32_t>();
    980 }
    981 
    982 
    983 status_t Parcel::readInt64(int64_t *pArg) const
    984 {
    985     return readAligned(pArg);
    986 }
    987 
    988 
    989 int64_t Parcel::readInt64() const
    990 {
    991     return readAligned<int64_t>();
    992 }
    993 
    994 status_t Parcel::readFloat(float *pArg) const
    995 {
    996     return readAligned(pArg);
    997 }
    998 
    999 
   1000 float Parcel::readFloat() const
   1001 {
   1002     return readAligned<float>();
   1003 }
   1004 
   1005 #if defined(__mips__) && defined(__mips_hard_float)
   1006 
   1007 status_t Parcel::readDouble(double *pArg) const
   1008 {
   1009     union {
   1010       double d;
   1011       unsigned long long ll;
   1012     } u;
   1013     status_t status;
   1014     status = readAligned(&u.ll);
   1015     *pArg = u.d;
   1016     return status;
   1017 }
   1018 
   1019 double Parcel::readDouble() const
   1020 {
   1021     union {
   1022       double d;
   1023       unsigned long long ll;
   1024     } u;
   1025     u.ll = readAligned<unsigned long long>();
   1026     return u.d;
   1027 }
   1028 
   1029 #else
   1030 
   1031 status_t Parcel::readDouble(double *pArg) const
   1032 {
   1033     return readAligned(pArg);
   1034 }
   1035 
   1036 double Parcel::readDouble() const
   1037 {
   1038     return readAligned<double>();
   1039 }
   1040 
   1041 #endif
   1042 
   1043 status_t Parcel::readIntPtr(intptr_t *pArg) const
   1044 {
   1045     return readAligned(pArg);
   1046 }
   1047 
   1048 
   1049 intptr_t Parcel::readIntPtr() const
   1050 {
   1051     return readAligned<intptr_t>();
   1052 }
   1053 
   1054 
   1055 const char* Parcel::readCString() const
   1056 {
   1057     const size_t avail = mDataSize-mDataPos;
   1058     if (avail > 0) {
   1059         const char* str = reinterpret_cast<const char*>(mData+mDataPos);
   1060         // is the string's trailing NUL within the parcel's valid bounds?
   1061         const char* eos = reinterpret_cast<const char*>(memchr(str, 0, avail));
   1062         if (eos) {
   1063             const size_t len = eos - str;
   1064             mDataPos += PAD_SIZE(len+1);
   1065             ALOGV("readCString Setting data pos of %p to %d\n", this, mDataPos);
   1066             return str;
   1067         }
   1068     }
   1069     return NULL;
   1070 }
   1071 
   1072 String8 Parcel::readString8() const
   1073 {
   1074     int32_t size = readInt32();
   1075     // watch for potential int overflow adding 1 for trailing NUL
   1076     if (size > 0 && size < INT32_MAX) {
   1077         const char* str = (const char*)readInplace(size+1);
   1078         if (str) return String8(str, size);
   1079     }
   1080     return String8();
   1081 }
   1082 
   1083 String16 Parcel::readString16() const
   1084 {
   1085     size_t len;
   1086     const char16_t* str = readString16Inplace(&len);
   1087     if (str) return String16(str, len);
   1088     ALOGE("Reading a NULL string not supported here.");
   1089     return String16();
   1090 }
   1091 
   1092 const char16_t* Parcel::readString16Inplace(size_t* outLen) const
   1093 {
   1094     int32_t size = readInt32();
   1095     // watch for potential int overflow from size+1
   1096     if (size >= 0 && size < INT32_MAX) {
   1097         *outLen = size;
   1098         const char16_t* str = (const char16_t*)readInplace((size+1)*sizeof(char16_t));
   1099         if (str != NULL) {
   1100             return str;
   1101         }
   1102     }
   1103     *outLen = 0;
   1104     return NULL;
   1105 }
   1106 
   1107 sp<IBinder> Parcel::readStrongBinder() const
   1108 {
   1109     sp<IBinder> val;
   1110     unflatten_binder(ProcessState::self(), *this, &val);
   1111     return val;
   1112 }
   1113 
   1114 wp<IBinder> Parcel::readWeakBinder() const
   1115 {
   1116     wp<IBinder> val;
   1117     unflatten_binder(ProcessState::self(), *this, &val);
   1118     return val;
   1119 }
   1120 
   1121 int32_t Parcel::readExceptionCode() const
   1122 {
   1123   int32_t exception_code = readAligned<int32_t>();
   1124   if (exception_code == EX_HAS_REPLY_HEADER) {
   1125     int32_t header_start = dataPosition();
   1126     int32_t header_size = readAligned<int32_t>();
   1127     // Skip over fat responses headers.  Not used (or propagated) in
   1128     // native code
   1129     setDataPosition(header_start + header_size);
   1130     // And fat response headers are currently only used when there are no
   1131     // exceptions, so return no error:
   1132     return 0;
   1133   }
   1134   return exception_code;
   1135 }
   1136 
   1137 native_handle* Parcel::readNativeHandle() const
   1138 {
   1139     int numFds, numInts;
   1140     status_t err;
   1141     err = readInt32(&numFds);
   1142     if (err != NO_ERROR) return 0;
   1143     err = readInt32(&numInts);
   1144     if (err != NO_ERROR) return 0;
   1145 
   1146     native_handle* h = native_handle_create(numFds, numInts);
   1147     for (int i=0 ; err==NO_ERROR && i<numFds ; i++) {
   1148         h->data[i] = dup(readFileDescriptor());
   1149         if (h->data[i] < 0) err = BAD_VALUE;
   1150     }
   1151     err = read(h->data + numFds, sizeof(int)*numInts);
   1152     if (err != NO_ERROR) {
   1153         native_handle_close(h);
   1154         native_handle_delete(h);
   1155         h = 0;
   1156     }
   1157     return h;
   1158 }
   1159 
   1160 
   1161 int Parcel::readFileDescriptor() const
   1162 {
   1163     const flat_binder_object* flat = readObject(true);
   1164     if (flat) {
   1165         switch (flat->type) {
   1166             case BINDER_TYPE_FD:
   1167                 //ALOGI("Returning file descriptor %ld from parcel %p\n", flat->handle, this);
   1168                 return flat->handle;
   1169         }
   1170     }
   1171     return BAD_TYPE;
   1172 }
   1173 
   1174 status_t Parcel::readBlob(size_t len, ReadableBlob* outBlob) const
   1175 {
   1176     int32_t useAshmem;
   1177     status_t status = readInt32(&useAshmem);
   1178     if (status) return status;
   1179 
   1180     if (!useAshmem) {
   1181         ALOGV("readBlob: read in place");
   1182         const void* ptr = readInplace(len);
   1183         if (!ptr) return BAD_VALUE;
   1184 
   1185         outBlob->init(false /*mapped*/, const_cast<void*>(ptr), len);
   1186         return NO_ERROR;
   1187     }
   1188 
   1189     ALOGV("readBlob: read from ashmem");
   1190     int fd = readFileDescriptor();
   1191     if (fd == int(BAD_TYPE)) return BAD_VALUE;
   1192 
   1193     void* ptr = ::mmap(NULL, len, PROT_READ, MAP_SHARED, fd, 0);
   1194     if (!ptr) return NO_MEMORY;
   1195 
   1196     outBlob->init(true /*mapped*/, ptr, len);
   1197     return NO_ERROR;
   1198 }
   1199 
   1200 status_t Parcel::read(FlattenableHelperInterface& val) const
   1201 {
   1202     // size
   1203     const size_t len = this->readInt32();
   1204     const size_t fd_count = this->readInt32();
   1205 
   1206     // payload
   1207     void const* const buf = this->readInplace(PAD_SIZE(len));
   1208     if (buf == NULL)
   1209         return BAD_VALUE;
   1210 
   1211     int* fds = NULL;
   1212     if (fd_count) {
   1213         fds = new int[fd_count];
   1214     }
   1215 
   1216     status_t err = NO_ERROR;
   1217     for (size_t i=0 ; i<fd_count && err==NO_ERROR ; i++) {
   1218         fds[i] = dup(this->readFileDescriptor());
   1219         if (fds[i] < 0) err = BAD_VALUE;
   1220     }
   1221 
   1222     if (err == NO_ERROR) {
   1223         err = val.unflatten(buf, len, fds, fd_count);
   1224     }
   1225 
   1226     if (fd_count) {
   1227         delete [] fds;
   1228     }
   1229 
   1230     return err;
   1231 }
   1232 const flat_binder_object* Parcel::readObject(bool nullMetaData) const
   1233 {
   1234     const size_t DPOS = mDataPos;
   1235     if ((DPOS+sizeof(flat_binder_object)) <= mDataSize) {
   1236         const flat_binder_object* obj
   1237                 = reinterpret_cast<const flat_binder_object*>(mData+DPOS);
   1238         mDataPos = DPOS + sizeof(flat_binder_object);
   1239         if (!nullMetaData && (obj->cookie == NULL && obj->binder == NULL)) {
   1240             // When transferring a NULL object, we don't write it into
   1241             // the object list, so we don't want to check for it when
   1242             // reading.
   1243             ALOGV("readObject Setting data pos of %p to %d\n", this, mDataPos);
   1244             return obj;
   1245         }
   1246 
   1247         // Ensure that this object is valid...
   1248         size_t* const OBJS = mObjects;
   1249         const size_t N = mObjectsSize;
   1250         size_t opos = mNextObjectHint;
   1251 
   1252         if (N > 0) {
   1253             ALOGV("Parcel %p looking for obj at %d, hint=%d\n",
   1254                  this, DPOS, opos);
   1255 
   1256             // Start at the current hint position, looking for an object at
   1257             // the current data position.
   1258             if (opos < N) {
   1259                 while (opos < (N-1) && OBJS[opos] < DPOS) {
   1260                     opos++;
   1261                 }
   1262             } else {
   1263                 opos = N-1;
   1264             }
   1265             if (OBJS[opos] == DPOS) {
   1266                 // Found it!
   1267                 ALOGV("Parcel found obj %d at index %d with forward search",
   1268                      this, DPOS, opos);
   1269                 mNextObjectHint = opos+1;
   1270                 ALOGV("readObject Setting data pos of %p to %d\n", this, mDataPos);
   1271                 return obj;
   1272             }
   1273 
   1274             // Look backwards for it...
   1275             while (opos > 0 && OBJS[opos] > DPOS) {
   1276                 opos--;
   1277             }
   1278             if (OBJS[opos] == DPOS) {
   1279                 // Found it!
   1280                 ALOGV("Parcel found obj %d at index %d with backward search",
   1281                      this, DPOS, opos);
   1282                 mNextObjectHint = opos+1;
   1283                 ALOGV("readObject Setting data pos of %p to %d\n", this, mDataPos);
   1284                 return obj;
   1285             }
   1286         }
   1287         ALOGW("Attempt to read object from Parcel %p at offset %d that is not in the object list",
   1288              this, DPOS);
   1289     }
   1290     return NULL;
   1291 }
   1292 
   1293 void Parcel::closeFileDescriptors()
   1294 {
   1295     size_t i = mObjectsSize;
   1296     if (i > 0) {
   1297         //ALOGI("Closing file descriptors for %d objects...", mObjectsSize);
   1298     }
   1299     while (i > 0) {
   1300         i--;
   1301         const flat_binder_object* flat
   1302             = reinterpret_cast<flat_binder_object*>(mData+mObjects[i]);
   1303         if (flat->type == BINDER_TYPE_FD) {
   1304             //ALOGI("Closing fd: %ld\n", flat->handle);
   1305             close(flat->handle);
   1306         }
   1307     }
   1308 }
   1309 
   1310 const uint8_t* Parcel::ipcData() const
   1311 {
   1312     return mData;
   1313 }
   1314 
   1315 size_t Parcel::ipcDataSize() const
   1316 {
   1317     return (mDataSize > mDataPos ? mDataSize : mDataPos);
   1318 }
   1319 
   1320 const size_t* Parcel::ipcObjects() const
   1321 {
   1322     return mObjects;
   1323 }
   1324 
   1325 size_t Parcel::ipcObjectsCount() const
   1326 {
   1327     return mObjectsSize;
   1328 }
   1329 
   1330 void Parcel::ipcSetDataReference(const uint8_t* data, size_t dataSize,
   1331     const size_t* objects, size_t objectsCount, release_func relFunc, void* relCookie)
   1332 {
   1333     size_t minOffset = 0;
   1334     freeDataNoInit();
   1335     mError = NO_ERROR;
   1336     mData = const_cast<uint8_t*>(data);
   1337     mDataSize = mDataCapacity = dataSize;
   1338     //ALOGI("setDataReference Setting data size of %p to %lu (pid=%d)\n", this, mDataSize, getpid());
   1339     mDataPos = 0;
   1340     ALOGV("setDataReference Setting data pos of %p to %d\n", this, mDataPos);
   1341     mObjects = const_cast<size_t*>(objects);
   1342     mObjectsSize = mObjectsCapacity = objectsCount;
   1343     mNextObjectHint = 0;
   1344     mOwner = relFunc;
   1345     mOwnerCookie = relCookie;
   1346     for (size_t i = 0; i < mObjectsSize; i++) {
   1347         size_t offset = mObjects[i];
   1348         if (offset < minOffset) {
   1349             ALOGE("%s: bad object offset %zu < %zu\n",
   1350                   __func__, offset, minOffset);
   1351             mObjectsSize = 0;
   1352             break;
   1353         }
   1354         minOffset = offset + sizeof(flat_binder_object);
   1355     }
   1356     scanForFds();
   1357 }
   1358 
   1359 void Parcel::print(TextOutput& to, uint32_t flags) const
   1360 {
   1361     to << "Parcel(";
   1362 
   1363     if (errorCheck() != NO_ERROR) {
   1364         const status_t err = errorCheck();
   1365         to << "Error: " << (void*)err << " \"" << strerror(-err) << "\"";
   1366     } else if (dataSize() > 0) {
   1367         const uint8_t* DATA = data();
   1368         to << indent << HexDump(DATA, dataSize()) << dedent;
   1369         const size_t* OBJS = objects();
   1370         const size_t N = objectsCount();
   1371         for (size_t i=0; i<N; i++) {
   1372             const flat_binder_object* flat
   1373                 = reinterpret_cast<const flat_binder_object*>(DATA+OBJS[i]);
   1374             to << endl << "Object #" << i << " @ " << (void*)OBJS[i] << ": "
   1375                 << TypeCode(flat->type & 0x7f7f7f00)
   1376                 << " = " << flat->binder;
   1377         }
   1378     } else {
   1379         to << "NULL";
   1380     }
   1381 
   1382     to << ")";
   1383 }
   1384 
   1385 void Parcel::releaseObjects()
   1386 {
   1387     const sp<ProcessState> proc(ProcessState::self());
   1388     size_t i = mObjectsSize;
   1389     uint8_t* const data = mData;
   1390     size_t* const objects = mObjects;
   1391     while (i > 0) {
   1392         i--;
   1393         const flat_binder_object* flat
   1394             = reinterpret_cast<flat_binder_object*>(data+objects[i]);
   1395         release_object(proc, *flat, this);
   1396     }
   1397 }
   1398 
   1399 void Parcel::acquireObjects()
   1400 {
   1401     const sp<ProcessState> proc(ProcessState::self());
   1402     size_t i = mObjectsSize;
   1403     uint8_t* const data = mData;
   1404     size_t* const objects = mObjects;
   1405     while (i > 0) {
   1406         i--;
   1407         const flat_binder_object* flat
   1408             = reinterpret_cast<flat_binder_object*>(data+objects[i]);
   1409         acquire_object(proc, *flat, this);
   1410     }
   1411 }
   1412 
   1413 void Parcel::freeData()
   1414 {
   1415     freeDataNoInit();
   1416     initState();
   1417 }
   1418 
   1419 void Parcel::freeDataNoInit()
   1420 {
   1421     if (mOwner) {
   1422         //ALOGI("Freeing data ref of %p (pid=%d)\n", this, getpid());
   1423         mOwner(this, mData, mDataSize, mObjects, mObjectsSize, mOwnerCookie);
   1424     } else {
   1425         releaseObjects();
   1426         if (mData) free(mData);
   1427         if (mObjects) free(mObjects);
   1428     }
   1429 }
   1430 
   1431 status_t Parcel::growData(size_t len)
   1432 {
   1433     size_t newSize = ((mDataSize+len)*3)/2;
   1434     return (newSize <= mDataSize)
   1435             ? (status_t) NO_MEMORY
   1436             : continueWrite(newSize);
   1437 }
   1438 
   1439 status_t Parcel::restartWrite(size_t desired)
   1440 {
   1441     if (mOwner) {
   1442         freeData();
   1443         return continueWrite(desired);
   1444     }
   1445 
   1446     uint8_t* data = (uint8_t*)realloc(mData, desired);
   1447     if (!data && desired > mDataCapacity) {
   1448         mError = NO_MEMORY;
   1449         return NO_MEMORY;
   1450     }
   1451 
   1452     releaseObjects();
   1453 
   1454     if (data) {
   1455         mData = data;
   1456         mDataCapacity = desired;
   1457     }
   1458 
   1459     mDataSize = mDataPos = 0;
   1460     ALOGV("restartWrite Setting data size of %p to %d\n", this, mDataSize);
   1461     ALOGV("restartWrite Setting data pos of %p to %d\n", this, mDataPos);
   1462 
   1463     free(mObjects);
   1464     mObjects = NULL;
   1465     mObjectsSize = mObjectsCapacity = 0;
   1466     mNextObjectHint = 0;
   1467     mHasFds = false;
   1468     mFdsKnown = true;
   1469     mAllowFds = true;
   1470 
   1471     return NO_ERROR;
   1472 }
   1473 
   1474 status_t Parcel::continueWrite(size_t desired)
   1475 {
   1476     // If shrinking, first adjust for any objects that appear
   1477     // after the new data size.
   1478     size_t objectsSize = mObjectsSize;
   1479     if (desired < mDataSize) {
   1480         if (desired == 0) {
   1481             objectsSize = 0;
   1482         } else {
   1483             while (objectsSize > 0) {
   1484                 if (mObjects[objectsSize-1] < desired)
   1485                     break;
   1486                 objectsSize--;
   1487             }
   1488         }
   1489     }
   1490 
   1491     if (mOwner) {
   1492         // If the size is going to zero, just release the owner's data.
   1493         if (desired == 0) {
   1494             freeData();
   1495             return NO_ERROR;
   1496         }
   1497 
   1498         // If there is a different owner, we need to take
   1499         // posession.
   1500         uint8_t* data = (uint8_t*)malloc(desired);
   1501         if (!data) {
   1502             mError = NO_MEMORY;
   1503             return NO_MEMORY;
   1504         }
   1505         size_t* objects = NULL;
   1506 
   1507         if (objectsSize) {
   1508             objects = (size_t*)malloc(objectsSize*sizeof(size_t));
   1509             if (!objects) {
   1510                 free(data);
   1511 
   1512                 mError = NO_MEMORY;
   1513                 return NO_MEMORY;
   1514             }
   1515 
   1516             // Little hack to only acquire references on objects
   1517             // we will be keeping.
   1518             size_t oldObjectsSize = mObjectsSize;
   1519             mObjectsSize = objectsSize;
   1520             acquireObjects();
   1521             mObjectsSize = oldObjectsSize;
   1522         }
   1523 
   1524         if (mData) {
   1525             memcpy(data, mData, mDataSize < desired ? mDataSize : desired);
   1526         }
   1527         if (objects && mObjects) {
   1528             memcpy(objects, mObjects, objectsSize*sizeof(size_t));
   1529         }
   1530         //ALOGI("Freeing data ref of %p (pid=%d)\n", this, getpid());
   1531         mOwner(this, mData, mDataSize, mObjects, mObjectsSize, mOwnerCookie);
   1532         mOwner = NULL;
   1533 
   1534         mData = data;
   1535         mObjects = objects;
   1536         mDataSize = (mDataSize < desired) ? mDataSize : desired;
   1537         ALOGV("continueWrite Setting data size of %p to %d\n", this, mDataSize);
   1538         mDataCapacity = desired;
   1539         mObjectsSize = mObjectsCapacity = objectsSize;
   1540         mNextObjectHint = 0;
   1541 
   1542     } else if (mData) {
   1543         if (objectsSize < mObjectsSize) {
   1544             // Need to release refs on any objects we are dropping.
   1545             const sp<ProcessState> proc(ProcessState::self());
   1546             for (size_t i=objectsSize; i<mObjectsSize; i++) {
   1547                 const flat_binder_object* flat
   1548                     = reinterpret_cast<flat_binder_object*>(mData+mObjects[i]);
   1549                 if (flat->type == BINDER_TYPE_FD) {
   1550                     // will need to rescan because we may have lopped off the only FDs
   1551                     mFdsKnown = false;
   1552                 }
   1553                 release_object(proc, *flat, this);
   1554             }
   1555             size_t* objects =
   1556                 (size_t*)realloc(mObjects, objectsSize*sizeof(size_t));
   1557             if (objects) {
   1558                 mObjects = objects;
   1559             }
   1560             mObjectsSize = objectsSize;
   1561             mNextObjectHint = 0;
   1562         }
   1563 
   1564         // We own the data, so we can just do a realloc().
   1565         if (desired > mDataCapacity) {
   1566             uint8_t* data = (uint8_t*)realloc(mData, desired);
   1567             if (data) {
   1568                 mData = data;
   1569                 mDataCapacity = desired;
   1570             } else if (desired > mDataCapacity) {
   1571                 mError = NO_MEMORY;
   1572                 return NO_MEMORY;
   1573             }
   1574         } else {
   1575             if (mDataSize > desired) {
   1576                 mDataSize = desired;
   1577                 ALOGV("continueWrite Setting data size of %p to %d\n", this, mDataSize);
   1578             }
   1579             if (mDataPos > desired) {
   1580                 mDataPos = desired;
   1581                 ALOGV("continueWrite Setting data pos of %p to %d\n", this, mDataPos);
   1582             }
   1583         }
   1584 
   1585     } else {
   1586         // This is the first data.  Easy!
   1587         uint8_t* data = (uint8_t*)malloc(desired);
   1588         if (!data) {
   1589             mError = NO_MEMORY;
   1590             return NO_MEMORY;
   1591         }
   1592 
   1593         if(!(mDataCapacity == 0 && mObjects == NULL
   1594              && mObjectsCapacity == 0)) {
   1595             ALOGE("continueWrite: %d/%p/%d/%d", mDataCapacity, mObjects, mObjectsCapacity, desired);
   1596         }
   1597 
   1598         mData = data;
   1599         mDataSize = mDataPos = 0;
   1600         ALOGV("continueWrite Setting data size of %p to %d\n", this, mDataSize);
   1601         ALOGV("continueWrite Setting data pos of %p to %d\n", this, mDataPos);
   1602         mDataCapacity = desired;
   1603     }
   1604 
   1605     return NO_ERROR;
   1606 }
   1607 
   1608 void Parcel::initState()
   1609 {
   1610     mError = NO_ERROR;
   1611     mData = 0;
   1612     mDataSize = 0;
   1613     mDataCapacity = 0;
   1614     mDataPos = 0;
   1615     ALOGV("initState Setting data size of %p to %d\n", this, mDataSize);
   1616     ALOGV("initState Setting data pos of %p to %d\n", this, mDataPos);
   1617     mObjects = NULL;
   1618     mObjectsSize = 0;
   1619     mObjectsCapacity = 0;
   1620     mNextObjectHint = 0;
   1621     mHasFds = false;
   1622     mFdsKnown = true;
   1623     mAllowFds = true;
   1624     mOwner = NULL;
   1625 }
   1626 
   1627 void Parcel::scanForFds() const
   1628 {
   1629     bool hasFds = false;
   1630     for (size_t i=0; i<mObjectsSize; i++) {
   1631         const flat_binder_object* flat
   1632             = reinterpret_cast<const flat_binder_object*>(mData + mObjects[i]);
   1633         if (flat->type == BINDER_TYPE_FD) {
   1634             hasFds = true;
   1635             break;
   1636         }
   1637     }
   1638     mHasFds = hasFds;
   1639     mFdsKnown = true;
   1640 }
   1641 
   1642 // --- Parcel::Blob ---
   1643 
   1644 Parcel::Blob::Blob() :
   1645         mMapped(false), mData(NULL), mSize(0) {
   1646 }
   1647 
   1648 Parcel::Blob::~Blob() {
   1649     release();
   1650 }
   1651 
   1652 void Parcel::Blob::release() {
   1653     if (mMapped && mData) {
   1654         ::munmap(mData, mSize);
   1655     }
   1656     clear();
   1657 }
   1658 
   1659 void Parcel::Blob::init(bool mapped, void* data, size_t size) {
   1660     mMapped = mapped;
   1661     mData = data;
   1662     mSize = size;
   1663 }
   1664 
   1665 void Parcel::Blob::clear() {
   1666     mMapped = false;
   1667     mData = NULL;
   1668     mSize = 0;
   1669 }
   1670 
   1671 }; // namespace android
   1672