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