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