Parcel.h revision 75c5de42b759bdcfa7c0e6103fb959c28d686116
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 <vector>
21
22#include <cutils/native_handle.h>
23#include <utils/Errors.h>
24#include <utils/RefBase.h>
25#include <utils/String16.h>
26#include <utils/Vector.h>
27#include <utils/Flattenable.h>
28#include <linux/binder.h>
29
30#include <binder/IInterface.h>
31
32// ---------------------------------------------------------------------------
33namespace android {
34
35template <typename T> class Flattenable;
36template <typename T> class LightFlattenable;
37class IBinder;
38class IPCThreadState;
39class ProcessState;
40class String8;
41class TextOutput;
42
43class Parcel {
44    friend class IPCThreadState;
45public:
46    class ReadableBlob;
47    class WritableBlob;
48
49                        Parcel();
50                        ~Parcel();
51
52    const uint8_t*      data() const;
53    size_t              dataSize() const;
54    size_t              dataAvail() const;
55    size_t              dataPosition() const;
56    size_t              dataCapacity() const;
57
58    status_t            setDataSize(size_t size);
59    void                setDataPosition(size_t pos) const;
60    status_t            setDataCapacity(size_t size);
61
62    status_t            setData(const uint8_t* buffer, size_t len);
63
64    status_t            appendFrom(const Parcel *parcel,
65                                   size_t start, size_t len);
66
67    bool                allowFds() const;
68    bool                pushAllowFds(bool allowFds);
69    void                restoreAllowFds(bool lastValue);
70
71    bool                hasFileDescriptors() const;
72
73    // Writes the RPC header.
74    status_t            writeInterfaceToken(const String16& interface);
75
76    // Parses the RPC header, returning true if the interface name
77    // in the header matches the expected interface from the caller.
78    //
79    // Additionally, enforceInterface does part of the work of
80    // propagating the StrictMode policy mask, populating the current
81    // IPCThreadState, which as an optimization may optionally be
82    // passed in.
83    bool                enforceInterface(const String16& interface,
84                                         IPCThreadState* threadState = NULL) const;
85    bool                checkInterface(IBinder*) const;
86
87    void                freeData();
88
89private:
90    const binder_size_t* objects() const;
91
92public:
93    size_t              objectsCount() const;
94
95    status_t            errorCheck() const;
96    void                setError(status_t err);
97
98    status_t            write(const void* data, size_t len);
99    void*               writeInplace(size_t len);
100    status_t            writeUnpadded(const void* data, size_t len);
101    status_t            writeInt32(int32_t val);
102    status_t            writeUint32(uint32_t val);
103    status_t            writeInt64(int64_t val);
104    status_t            writeUint64(uint64_t val);
105    status_t            writeFloat(float val);
106    status_t            writeDouble(double val);
107    status_t            writeCString(const char* str);
108    status_t            writeString8(const String8& str);
109    status_t            writeString16(const String16& str);
110    status_t            writeString16(const char16_t* str, size_t len);
111    status_t            writeStrongBinder(const sp<IBinder>& val);
112    status_t            writeWeakBinder(const wp<IBinder>& val);
113    status_t            writeInt32Array(size_t len, const int32_t *val);
114    status_t            writeByteArray(size_t len, const uint8_t *val);
115    status_t            writeBool(bool val);
116    status_t            writeChar(char16_t val);
117    status_t            writeByte(int8_t val);
118
119    status_t            writeByteVector(const std::vector<int8_t>& val);
120    status_t            writeInt32Vector(const std::vector<int32_t>& val);
121    status_t            writeInt64Vector(const std::vector<int64_t>& val);
122    status_t            writeFloatVector(const std::vector<float>& val);
123    status_t            writeDoubleVector(const std::vector<double>& val);
124    status_t            writeBoolVector(const std::vector<bool>& val);
125    status_t            writeCharVector(const std::vector<char16_t>& val);
126    status_t            writeString16Vector(const std::vector<String16>& val);
127
128    template<typename T>
129    status_t            write(const Flattenable<T>& val);
130
131    template<typename T>
132    status_t            write(const LightFlattenable<T>& val);
133
134
135    // Place a native_handle into the parcel (the native_handle's file-
136    // descriptors are dup'ed, so it is safe to delete the native_handle
137    // when this function returns).
138    // Doesn't take ownership of the native_handle.
139    status_t            writeNativeHandle(const native_handle* handle);
140
141    // Place a file descriptor into the parcel.  The given fd must remain
142    // valid for the lifetime of the parcel.
143    // The Parcel does not take ownership of the given fd unless you ask it to.
144    status_t            writeFileDescriptor(int fd, bool takeOwnership = false);
145
146    // Place a file descriptor into the parcel.  A dup of the fd is made, which
147    // will be closed once the parcel is destroyed.
148    status_t            writeDupFileDescriptor(int fd);
149
150    // Writes a blob to the parcel.
151    // If the blob is small, then it is stored in-place, otherwise it is
152    // transferred by way of an anonymous shared memory region.  Prefer sending
153    // immutable blobs if possible since they may be subsequently transferred between
154    // processes without further copying whereas mutable blobs always need to be copied.
155    // The caller should call release() on the blob after writing its contents.
156    status_t            writeBlob(size_t len, bool mutableCopy, WritableBlob* outBlob);
157
158    // Write an existing immutable blob file descriptor to the parcel.
159    // This allows the client to send the same blob to multiple processes
160    // as long as it keeps a dup of the blob file descriptor handy for later.
161    status_t            writeDupImmutableBlobFileDescriptor(int fd);
162
163    status_t            writeObject(const flat_binder_object& val, bool nullMetaData);
164
165    // Like Parcel.java's writeNoException().  Just writes a zero int32.
166    // Currently the native implementation doesn't do any of the StrictMode
167    // stack gathering and serialization that the Java implementation does.
168    status_t            writeNoException();
169
170    void                remove(size_t start, size_t amt);
171
172    status_t            read(void* outData, size_t len) const;
173    const void*         readInplace(size_t len) const;
174    int32_t             readInt32() const;
175    status_t            readInt32(int32_t *pArg) const;
176    uint32_t            readUint32() const;
177    status_t            readUint32(uint32_t *pArg) const;
178    int64_t             readInt64() const;
179    status_t            readInt64(int64_t *pArg) const;
180    uint64_t            readUint64() const;
181    status_t            readUint64(uint64_t *pArg) const;
182    float               readFloat() const;
183    status_t            readFloat(float *pArg) const;
184    double              readDouble() const;
185    status_t            readDouble(double *pArg) const;
186    intptr_t            readIntPtr() const;
187    status_t            readIntPtr(intptr_t *pArg) const;
188    bool                readBool() const;
189    status_t            readBool(bool *pArg) const;
190    char16_t            readChar() const;
191    status_t            readChar(char16_t *pArg) const;
192    int8_t              readByte() const;
193    status_t            readByte(int8_t *pArg) const;
194
195    const char*         readCString() const;
196    String8             readString8() const;
197    String16            readString16() const;
198    status_t            readString16(String16* pArg) const;
199    const char16_t*     readString16Inplace(size_t* outLen) const;
200    sp<IBinder>         readStrongBinder() const;
201    status_t            readStrongBinder(sp<IBinder>* val) const;
202    wp<IBinder>         readWeakBinder() const;
203
204    template<typename T>
205    status_t readStrongBinder(sp<T>* val) const;
206
207    status_t            readByteVector(std::vector<int8_t>* val) const;
208    status_t            readInt32Vector(std::vector<int32_t>* val) const;
209    status_t            readInt64Vector(std::vector<int64_t>* val) const;
210    status_t            readFloatVector(std::vector<float>* val) const;
211    status_t            readDoubleVector(std::vector<double>* val) const;
212    status_t            readBoolVector(std::vector<bool>* val) const;
213    status_t            readCharVector(std::vector<char16_t>* val) const;
214    status_t            readString16Vector(std::vector<String16>* val) const;
215
216    template<typename T>
217    status_t            read(Flattenable<T>& val) const;
218
219    template<typename T>
220    status_t            read(LightFlattenable<T>& val) const;
221
222    // Like Parcel.java's readExceptionCode().  Reads the first int32
223    // off of a Parcel's header, returning 0 or the negative error
224    // code on exceptions, but also deals with skipping over rich
225    // response headers.  Callers should use this to read & parse the
226    // response headers rather than doing it by hand.
227    int32_t             readExceptionCode() const;
228
229    // Retrieve native_handle from the parcel. This returns a copy of the
230    // parcel's native_handle (the caller takes ownership). The caller
231    // must free the native_handle with native_handle_close() and
232    // native_handle_delete().
233    native_handle*     readNativeHandle() const;
234
235
236    // Retrieve a file descriptor from the parcel.  This returns the raw fd
237    // in the parcel, which you do not own -- use dup() to get your own copy.
238    int                 readFileDescriptor() const;
239
240    // Reads a blob from the parcel.
241    // The caller should call release() on the blob after reading its contents.
242    status_t            readBlob(size_t len, ReadableBlob* outBlob) const;
243
244    const flat_binder_object* readObject(bool nullMetaData) const;
245
246    // Explicitly close all file descriptors in the parcel.
247    void                closeFileDescriptors();
248
249    // Debugging: get metrics on current allocations.
250    static size_t       getGlobalAllocSize();
251    static size_t       getGlobalAllocCount();
252
253private:
254    typedef void        (*release_func)(Parcel* parcel,
255                                        const uint8_t* data, size_t dataSize,
256                                        const binder_size_t* objects, size_t objectsSize,
257                                        void* cookie);
258
259    uintptr_t           ipcData() const;
260    size_t              ipcDataSize() const;
261    uintptr_t           ipcObjects() const;
262    size_t              ipcObjectsCount() const;
263    void                ipcSetDataReference(const uint8_t* data, size_t dataSize,
264                                            const binder_size_t* objects, size_t objectsCount,
265                                            release_func relFunc, void* relCookie);
266
267public:
268    void                print(TextOutput& to, uint32_t flags = 0) const;
269
270private:
271                        Parcel(const Parcel& o);
272    Parcel&             operator=(const Parcel& o);
273
274    status_t            finishWrite(size_t len);
275    void                releaseObjects();
276    void                acquireObjects();
277    status_t            growData(size_t len);
278    status_t            restartWrite(size_t desired);
279    status_t            continueWrite(size_t desired);
280    status_t            writePointer(uintptr_t val);
281    status_t            readPointer(uintptr_t *pArg) const;
282    uintptr_t           readPointer() const;
283    void                freeDataNoInit();
284    void                initState();
285    void                scanForFds() const;
286
287    template<class T>
288    status_t            readAligned(T *pArg) const;
289
290    template<class T>   T readAligned() const;
291
292    template<class T>
293    status_t            writeAligned(T val);
294
295    status_t            mError;
296    uint8_t*            mData;
297    size_t              mDataSize;
298    size_t              mDataCapacity;
299    mutable size_t      mDataPos;
300    binder_size_t*      mObjects;
301    size_t              mObjectsSize;
302    size_t              mObjectsCapacity;
303    mutable size_t      mNextObjectHint;
304
305    mutable bool        mFdsKnown;
306    mutable bool        mHasFds;
307    bool                mAllowFds;
308
309    release_func        mOwner;
310    void*               mOwnerCookie;
311
312    class Blob {
313    public:
314        Blob();
315        ~Blob();
316
317        void clear();
318        void release();
319        inline size_t size() const { return mSize; }
320        inline int fd() const { return mFd; };
321        inline bool isMutable() const { return mMutable; }
322
323    protected:
324        void init(int fd, void* data, size_t size, bool isMutable);
325
326        int mFd; // owned by parcel so not closed when released
327        void* mData;
328        size_t mSize;
329        bool mMutable;
330    };
331
332    class FlattenableHelperInterface {
333    protected:
334        ~FlattenableHelperInterface() { }
335    public:
336        virtual size_t getFlattenedSize() const = 0;
337        virtual size_t getFdCount() const = 0;
338        virtual status_t flatten(void* buffer, size_t size, int* fds, size_t count) const = 0;
339        virtual status_t unflatten(void const* buffer, size_t size, int const* fds, size_t count) = 0;
340    };
341
342    template<typename T>
343    class FlattenableHelper : public FlattenableHelperInterface {
344        friend class Parcel;
345        const Flattenable<T>& val;
346        explicit FlattenableHelper(const Flattenable<T>& val) : val(val) { }
347
348    public:
349        virtual size_t getFlattenedSize() const {
350            return val.getFlattenedSize();
351        }
352        virtual size_t getFdCount() const {
353            return val.getFdCount();
354        }
355        virtual status_t flatten(void* buffer, size_t size, int* fds, size_t count) const {
356            return val.flatten(buffer, size, fds, count);
357        }
358        virtual status_t unflatten(void const* buffer, size_t size, int const* fds, size_t count) {
359            return const_cast<Flattenable<T>&>(val).unflatten(buffer, size, fds, count);
360        }
361    };
362    status_t write(const FlattenableHelperInterface& val);
363    status_t read(FlattenableHelperInterface& val) const;
364
365public:
366    class ReadableBlob : public Blob {
367        friend class Parcel;
368    public:
369        inline const void* data() const { return mData; }
370        inline void* mutableData() { return isMutable() ? mData : NULL; }
371    };
372
373    class WritableBlob : public Blob {
374        friend class Parcel;
375    public:
376        inline void* data() { return mData; }
377    };
378
379private:
380    size_t mOpenAshmemSize;
381
382public:
383    // TODO: Remove once ABI can be changed.
384    size_t getBlobAshmemSize() const;
385    size_t getOpenAshmemSize() const;
386};
387
388// ---------------------------------------------------------------------------
389
390template<typename T>
391status_t Parcel::write(const Flattenable<T>& val) {
392    const FlattenableHelper<T> helper(val);
393    return write(helper);
394}
395
396template<typename T>
397status_t Parcel::write(const LightFlattenable<T>& val) {
398    size_t size(val.getFlattenedSize());
399    if (!val.isFixedSize()) {
400        status_t err = writeInt32(size);
401        if (err != NO_ERROR) {
402            return err;
403        }
404    }
405    if (size) {
406        void* buffer = writeInplace(size);
407        if (buffer == NULL)
408            return NO_MEMORY;
409        return val.flatten(buffer, size);
410    }
411    return NO_ERROR;
412}
413
414template<typename T>
415status_t Parcel::read(Flattenable<T>& val) const {
416    FlattenableHelper<T> helper(val);
417    return read(helper);
418}
419
420template<typename T>
421status_t Parcel::read(LightFlattenable<T>& val) const {
422    size_t size;
423    if (val.isFixedSize()) {
424        size = val.getFlattenedSize();
425    } else {
426        int32_t s;
427        status_t err = readInt32(&s);
428        if (err != NO_ERROR) {
429            return err;
430        }
431        size = s;
432    }
433    if (size) {
434        void const* buffer = readInplace(size);
435        return buffer == NULL ? NO_MEMORY :
436                val.unflatten(buffer, size);
437    }
438    return NO_ERROR;
439}
440
441template<typename T>
442status_t Parcel::readStrongBinder(sp<T>* val) const {
443    sp<IBinder> tmp;
444    status_t ret = readStrongBinder(&tmp);
445
446    if (ret == OK) {
447        *val = interface_cast<T>(tmp);
448
449        if (val->get() == nullptr) {
450            return UNKNOWN_ERROR;
451        }
452    }
453
454    return ret;
455}
456
457// ---------------------------------------------------------------------------
458
459inline TextOutput& operator<<(TextOutput& to, const Parcel& parcel)
460{
461    parcel.print(to);
462    return to;
463}
464
465// ---------------------------------------------------------------------------
466
467// Generic acquire and release of objects.
468void acquire_object(const sp<ProcessState>& proc,
469                    const flat_binder_object& obj, const void* who);
470void release_object(const sp<ProcessState>& proc,
471                    const flat_binder_object& obj, const void* who);
472
473void flatten_binder(const sp<ProcessState>& proc,
474                    const sp<IBinder>& binder, flat_binder_object* out);
475void flatten_binder(const sp<ProcessState>& proc,
476                    const wp<IBinder>& binder, flat_binder_object* out);
477status_t unflatten_binder(const sp<ProcessState>& proc,
478                          const flat_binder_object& flat, sp<IBinder>* out);
479status_t unflatten_binder(const sp<ProcessState>& proc,
480                          const flat_binder_object& flat, wp<IBinder>* out);
481
482}; // namespace android
483
484// ---------------------------------------------------------------------------
485
486#endif // ANDROID_PARCEL_H
487