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