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