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