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