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 #ifndef ANDROID_PARCEL_H
     18 #define ANDROID_PARCEL_H
     19 
     20 #include <cutils/native_handle.h>
     21 #include <utils/Errors.h>
     22 #include <utils/RefBase.h>
     23 #include <utils/String16.h>
     24 #include <utils/Vector.h>
     25 #include <utils/Flattenable.h>
     26 
     27 // ---------------------------------------------------------------------------
     28 namespace android {
     29 
     30 template <typename T> class Flattenable;
     31 template <typename T> class LightFlattenable;
     32 class IBinder;
     33 class IPCThreadState;
     34 class ProcessState;
     35 class String8;
     36 class TextOutput;
     37 
     38 struct flat_binder_object;  // defined in support_p/binder_module.h
     39 
     40 class Parcel {
     41 public:
     42     class ReadableBlob;
     43     class WritableBlob;
     44 
     45                         Parcel();
     46                         ~Parcel();
     47 
     48     const uint8_t*      data() const;
     49     size_t              dataSize() const;
     50     size_t              dataAvail() const;
     51     size_t              dataPosition() const;
     52     size_t              dataCapacity() const;
     53 
     54     status_t            setDataSize(size_t size);
     55     void                setDataPosition(size_t pos) const;
     56     status_t            setDataCapacity(size_t size);
     57 
     58     status_t            setData(const uint8_t* buffer, size_t len);
     59 
     60     status_t            appendFrom(const Parcel *parcel,
     61                                    size_t start, size_t len);
     62 
     63     bool                pushAllowFds(bool allowFds);
     64     void                restoreAllowFds(bool lastValue);
     65 
     66     bool                hasFileDescriptors() const;
     67 
     68     // Writes the RPC header.
     69     status_t            writeInterfaceToken(const String16& interface);
     70 
     71     // Parses the RPC header, returning true if the interface name
     72     // in the header matches the expected interface from the caller.
     73     //
     74     // Additionally, enforceInterface does part of the work of
     75     // propagating the StrictMode policy mask, populating the current
     76     // IPCThreadState, which as an optimization may optionally be
     77     // passed in.
     78     bool                enforceInterface(const String16& interface,
     79                                          IPCThreadState* threadState = NULL) const;
     80     bool                checkInterface(IBinder*) const;
     81 
     82     void                freeData();
     83 
     84     const size_t*       objects() const;
     85     size_t              objectsCount() const;
     86 
     87     status_t            errorCheck() const;
     88     void                setError(status_t err);
     89 
     90     status_t            write(const void* data, size_t len);
     91     void*               writeInplace(size_t len);
     92     status_t            writeUnpadded(const void* data, size_t len);
     93     status_t            writeInt32(int32_t val);
     94     status_t            writeInt64(int64_t val);
     95     status_t            writeFloat(float val);
     96     status_t            writeDouble(double val);
     97     status_t            writeIntPtr(intptr_t val);
     98     status_t            writeCString(const char* str);
     99     status_t            writeString8(const String8& str);
    100     status_t            writeString16(const String16& str);
    101     status_t            writeString16(const char16_t* str, size_t len);
    102     status_t            writeStrongBinder(const sp<IBinder>& val);
    103     status_t            writeWeakBinder(const wp<IBinder>& val);
    104     status_t            writeInt32Array(size_t len, const int32_t *val);
    105 
    106     template<typename T>
    107     status_t            write(const Flattenable<T>& val);
    108 
    109     template<typename T>
    110     status_t            write(const LightFlattenable<T>& val);
    111 
    112 
    113     // Place a native_handle into the parcel (the native_handle's file-
    114     // descriptors are dup'ed, so it is safe to delete the native_handle
    115     // when this function returns).
    116     // Doesn't take ownership of the native_handle.
    117     status_t            writeNativeHandle(const native_handle* handle);
    118 
    119     // Place a file descriptor into the parcel.  The given fd must remain
    120     // valid for the lifetime of the parcel.
    121     // The Parcel does not take ownership of the given fd unless you ask it to.
    122     status_t            writeFileDescriptor(int fd, bool takeOwnership = false);
    123 
    124     // Place a file descriptor into the parcel.  A dup of the fd is made, which
    125     // will be closed once the parcel is destroyed.
    126     status_t            writeDupFileDescriptor(int fd);
    127 
    128     // Writes a blob to the parcel.
    129     // If the blob is small, then it is stored in-place, otherwise it is
    130     // transferred by way of an anonymous shared memory region.
    131     // The caller should call release() on the blob after writing its contents.
    132     status_t            writeBlob(size_t len, WritableBlob* outBlob);
    133 
    134     status_t            writeObject(const flat_binder_object& val, bool nullMetaData);
    135 
    136     // Like Parcel.java's writeNoException().  Just writes a zero int32.
    137     // Currently the native implementation doesn't do any of the StrictMode
    138     // stack gathering and serialization that the Java implementation does.
    139     status_t            writeNoException();
    140 
    141     void                remove(size_t start, size_t amt);
    142 
    143     status_t            read(void* outData, size_t len) const;
    144     const void*         readInplace(size_t len) const;
    145     int32_t             readInt32() const;
    146     status_t            readInt32(int32_t *pArg) const;
    147     int64_t             readInt64() const;
    148     status_t            readInt64(int64_t *pArg) const;
    149     float               readFloat() const;
    150     status_t            readFloat(float *pArg) const;
    151     double              readDouble() const;
    152     status_t            readDouble(double *pArg) const;
    153     intptr_t            readIntPtr() const;
    154     status_t            readIntPtr(intptr_t *pArg) const;
    155 
    156     const char*         readCString() const;
    157     String8             readString8() const;
    158     String16            readString16() const;
    159     const char16_t*     readString16Inplace(size_t* outLen) const;
    160     sp<IBinder>         readStrongBinder() const;
    161     wp<IBinder>         readWeakBinder() const;
    162 
    163     template<typename T>
    164     status_t            read(Flattenable<T>& val) const;
    165 
    166     template<typename T>
    167     status_t            read(LightFlattenable<T>& val) const;
    168 
    169     // Like Parcel.java's readExceptionCode().  Reads the first int32
    170     // off of a Parcel's header, returning 0 or the negative error
    171     // code on exceptions, but also deals with skipping over rich
    172     // response headers.  Callers should use this to read & parse the
    173     // response headers rather than doing it by hand.
    174     int32_t             readExceptionCode() const;
    175 
    176     // Retrieve native_handle from the parcel. This returns a copy of the
    177     // parcel's native_handle (the caller takes ownership). The caller
    178     // must free the native_handle with native_handle_close() and
    179     // native_handle_delete().
    180     native_handle*     readNativeHandle() const;
    181 
    182 
    183     // Retrieve a file descriptor from the parcel.  This returns the raw fd
    184     // in the parcel, which you do not own -- use dup() to get your own copy.
    185     int                 readFileDescriptor() const;
    186 
    187     // Reads a blob from the parcel.
    188     // The caller should call release() on the blob after reading its contents.
    189     status_t            readBlob(size_t len, ReadableBlob* outBlob) const;
    190 
    191     const flat_binder_object* readObject(bool nullMetaData) const;
    192 
    193     // Explicitly close all file descriptors in the parcel.
    194     void                closeFileDescriptors();
    195 
    196     typedef void        (*release_func)(Parcel* parcel,
    197                                         const uint8_t* data, size_t dataSize,
    198                                         const size_t* objects, size_t objectsSize,
    199                                         void* cookie);
    200 
    201     const uint8_t*      ipcData() const;
    202     size_t              ipcDataSize() const;
    203     const size_t*       ipcObjects() const;
    204     size_t              ipcObjectsCount() const;
    205     void                ipcSetDataReference(const uint8_t* data, size_t dataSize,
    206                                             const size_t* objects, size_t objectsCount,
    207                                             release_func relFunc, void* relCookie);
    208 
    209     void                print(TextOutput& to, uint32_t flags = 0) const;
    210 
    211 private:
    212                         Parcel(const Parcel& o);
    213     Parcel&             operator=(const Parcel& o);
    214 
    215     status_t            finishWrite(size_t len);
    216     void                releaseObjects();
    217     void                acquireObjects();
    218     status_t            growData(size_t len);
    219     status_t            restartWrite(size_t desired);
    220     status_t            continueWrite(size_t desired);
    221     void                freeDataNoInit();
    222     void                initState();
    223     void                scanForFds() const;
    224 
    225     template<class T>
    226     status_t            readAligned(T *pArg) const;
    227 
    228     template<class T>   T readAligned() const;
    229 
    230     template<class T>
    231     status_t            writeAligned(T val);
    232 
    233     status_t            mError;
    234     uint8_t*            mData;
    235     size_t              mDataSize;
    236     size_t              mDataCapacity;
    237     mutable size_t      mDataPos;
    238     size_t*             mObjects;
    239     size_t              mObjectsSize;
    240     size_t              mObjectsCapacity;
    241     mutable size_t      mNextObjectHint;
    242 
    243     mutable bool        mFdsKnown;
    244     mutable bool        mHasFds;
    245     bool                mAllowFds;
    246 
    247     release_func        mOwner;
    248     void*               mOwnerCookie;
    249 
    250     class Blob {
    251     public:
    252         Blob();
    253         ~Blob();
    254 
    255         void release();
    256         inline size_t size() const { return mSize; }
    257 
    258     protected:
    259         void init(bool mapped, void* data, size_t size);
    260         void clear();
    261 
    262         bool mMapped;
    263         void* mData;
    264         size_t mSize;
    265     };
    266 
    267     class FlattenableHelperInterface {
    268     protected:
    269         ~FlattenableHelperInterface() { }
    270     public:
    271         virtual size_t getFlattenedSize() const = 0;
    272         virtual size_t getFdCount() const = 0;
    273         virtual status_t flatten(void* buffer, size_t size, int* fds, size_t count) const = 0;
    274         virtual status_t unflatten(void const* buffer, size_t size, int const* fds, size_t count) = 0;
    275     };
    276 
    277     template<typename T>
    278     class FlattenableHelper : public FlattenableHelperInterface {
    279         friend class Parcel;
    280         const Flattenable<T>& val;
    281         explicit FlattenableHelper(const Flattenable<T>& val) : val(val) { }
    282 
    283     public:
    284         virtual size_t getFlattenedSize() const {
    285             return val.getFlattenedSize();
    286         }
    287         virtual size_t getFdCount() const {
    288             return val.getFdCount();
    289         }
    290         virtual status_t flatten(void* buffer, size_t size, int* fds, size_t count) const {
    291             return val.flatten(buffer, size, fds, count);
    292         }
    293         virtual status_t unflatten(void const* buffer, size_t size, int const* fds, size_t count) {
    294             return const_cast<Flattenable<T>&>(val).unflatten(buffer, size, fds, count);
    295         }
    296     };
    297     status_t write(const FlattenableHelperInterface& val);
    298     status_t read(FlattenableHelperInterface& val) const;
    299 
    300 public:
    301     class ReadableBlob : public Blob {
    302         friend class Parcel;
    303     public:
    304         inline const void* data() const { return mData; }
    305     };
    306 
    307     class WritableBlob : public Blob {
    308         friend class Parcel;
    309     public:
    310         inline void* data() { return mData; }
    311     };
    312 };
    313 
    314 // ---------------------------------------------------------------------------
    315 
    316 template<typename T>
    317 status_t Parcel::write(const Flattenable<T>& val) {
    318     const FlattenableHelper<T> helper(val);
    319     return write(helper);
    320 }
    321 
    322 template<typename T>
    323 status_t Parcel::write(const LightFlattenable<T>& val) {
    324     size_t size(val.getFlattenedSize());
    325     if (!val.isFixedSize()) {
    326         status_t err = writeInt32(size);
    327         if (err != NO_ERROR) {
    328             return err;
    329         }
    330     }
    331     if (size) {
    332         void* buffer = writeInplace(size);
    333         if (buffer == NULL)
    334             return NO_MEMORY;
    335         return val.flatten(buffer, size);
    336     }
    337     return NO_ERROR;
    338 }
    339 
    340 template<typename T>
    341 status_t Parcel::read(Flattenable<T>& val) const {
    342     FlattenableHelper<T> helper(val);
    343     return read(helper);
    344 }
    345 
    346 template<typename T>
    347 status_t Parcel::read(LightFlattenable<T>& val) const {
    348     size_t size;
    349     if (val.isFixedSize()) {
    350         size = val.getFlattenedSize();
    351     } else {
    352         int32_t s;
    353         status_t err = readInt32(&s);
    354         if (err != NO_ERROR) {
    355             return err;
    356         }
    357         size = s;
    358     }
    359     if (size) {
    360         void const* buffer = readInplace(size);
    361         return buffer == NULL ? NO_MEMORY :
    362                 val.unflatten(buffer, size);
    363     }
    364     return NO_ERROR;
    365 }
    366 
    367 // ---------------------------------------------------------------------------
    368 
    369 inline TextOutput& operator<<(TextOutput& to, const Parcel& parcel)
    370 {
    371     parcel.print(to);
    372     return to;
    373 }
    374 
    375 // ---------------------------------------------------------------------------
    376 
    377 // Generic acquire and release of objects.
    378 void acquire_object(const sp<ProcessState>& proc,
    379                     const flat_binder_object& obj, const void* who);
    380 void release_object(const sp<ProcessState>& proc,
    381                     const flat_binder_object& obj, const void* who);
    382 
    383 void flatten_binder(const sp<ProcessState>& proc,
    384                     const sp<IBinder>& binder, flat_binder_object* out);
    385 void flatten_binder(const sp<ProcessState>& proc,
    386                     const wp<IBinder>& binder, flat_binder_object* out);
    387 status_t unflatten_binder(const sp<ProcessState>& proc,
    388                           const flat_binder_object& flat, sp<IBinder>* out);
    389 status_t unflatten_binder(const sp<ProcessState>& proc,
    390                           const flat_binder_object& flat, wp<IBinder>* out);
    391 
    392 }; // namespace android
    393 
    394 // ---------------------------------------------------------------------------
    395 
    396 #endif // ANDROID_PARCEL_H
    397