Parcel.h revision 6c31acd969ffc754e514885fa7f4d0c25403f580
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#include <binder/Parcelable.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            writeParcelableVector(const std::vector<T>& val);
133    status_t            writeParcelable(const Parcelable& parcelable);
134
135    template<typename T>
136    status_t            write(const Flattenable<T>& val);
137
138    template<typename T>
139    status_t            write(const LightFlattenable<T>& val);
140
141
142    // Place a native_handle into the parcel (the native_handle's file-
143    // descriptors are dup'ed, so it is safe to delete the native_handle
144    // when this function returns).
145    // Doesn't take ownership of the native_handle.
146    status_t            writeNativeHandle(const native_handle* handle);
147
148    // Place a file descriptor into the parcel.  The given fd must remain
149    // valid for the lifetime of the parcel.
150    // The Parcel does not take ownership of the given fd unless you ask it to.
151    status_t            writeFileDescriptor(int fd, bool takeOwnership = false);
152
153    // Place a file descriptor into the parcel.  A dup of the fd is made, which
154    // will be closed once the parcel is destroyed.
155    status_t            writeDupFileDescriptor(int fd);
156
157    // Writes a blob to the parcel.
158    // If the blob is small, then it is stored in-place, otherwise it is
159    // transferred by way of an anonymous shared memory region.  Prefer sending
160    // immutable blobs if possible since they may be subsequently transferred between
161    // processes without further copying whereas mutable blobs always need to be copied.
162    // The caller should call release() on the blob after writing its contents.
163    status_t            writeBlob(size_t len, bool mutableCopy, WritableBlob* outBlob);
164
165    // Write an existing immutable blob file descriptor to the parcel.
166    // This allows the client to send the same blob to multiple processes
167    // as long as it keeps a dup of the blob file descriptor handy for later.
168    status_t            writeDupImmutableBlobFileDescriptor(int fd);
169
170    status_t            writeObject(const flat_binder_object& val, bool nullMetaData);
171
172    // Like Parcel.java's writeNoException().  Just writes a zero int32.
173    // Currently the native implementation doesn't do any of the StrictMode
174    // stack gathering and serialization that the Java implementation does.
175    status_t            writeNoException();
176
177    void                remove(size_t start, size_t amt);
178
179    status_t            read(void* outData, size_t len) const;
180    const void*         readInplace(size_t len) const;
181    int32_t             readInt32() const;
182    status_t            readInt32(int32_t *pArg) const;
183    uint32_t            readUint32() const;
184    status_t            readUint32(uint32_t *pArg) const;
185    int64_t             readInt64() const;
186    status_t            readInt64(int64_t *pArg) const;
187    uint64_t            readUint64() const;
188    status_t            readUint64(uint64_t *pArg) const;
189    float               readFloat() const;
190    status_t            readFloat(float *pArg) const;
191    double              readDouble() const;
192    status_t            readDouble(double *pArg) const;
193    intptr_t            readIntPtr() const;
194    status_t            readIntPtr(intptr_t *pArg) const;
195    bool                readBool() const;
196    status_t            readBool(bool *pArg) const;
197    char16_t            readChar() const;
198    status_t            readChar(char16_t *pArg) const;
199    int8_t              readByte() const;
200    status_t            readByte(int8_t *pArg) const;
201
202    const char*         readCString() const;
203    String8             readString8() const;
204    String16            readString16() const;
205    status_t            readString16(String16* pArg) const;
206    const char16_t*     readString16Inplace(size_t* outLen) const;
207    sp<IBinder>         readStrongBinder() const;
208    status_t            readStrongBinder(sp<IBinder>* val) const;
209    wp<IBinder>         readWeakBinder() const;
210
211    template<typename T>
212    status_t            readParcelableVector(std::vector<T>* val) const;
213    status_t            readParcelable(Parcelable* parcelable) const;
214
215    template<typename T>
216    status_t            readStrongBinder(sp<T>* val) const;
217
218    status_t            readStrongBinderVector(std::vector<sp<IBinder>>* val) const;
219
220    status_t            readByteVector(std::vector<int8_t>* val) const;
221    status_t            readInt32Vector(std::vector<int32_t>* val) const;
222    status_t            readInt64Vector(std::vector<int64_t>* val) const;
223    status_t            readFloatVector(std::vector<float>* val) const;
224    status_t            readDoubleVector(std::vector<double>* val) const;
225    status_t            readBoolVector(std::vector<bool>* val) const;
226    status_t            readCharVector(std::vector<char16_t>* val) const;
227    status_t            readString16Vector(std::vector<String16>* val) const;
228
229    template<typename T>
230    status_t            read(Flattenable<T>& val) const;
231
232    template<typename T>
233    status_t            read(LightFlattenable<T>& val) const;
234
235    // Like Parcel.java's readExceptionCode().  Reads the first int32
236    // off of a Parcel's header, returning 0 or the negative error
237    // code on exceptions, but also deals with skipping over rich
238    // response headers.  Callers should use this to read & parse the
239    // response headers rather than doing it by hand.
240    int32_t             readExceptionCode() const;
241
242    // Retrieve native_handle from the parcel. This returns a copy of the
243    // parcel's native_handle (the caller takes ownership). The caller
244    // must free the native_handle with native_handle_close() and
245    // native_handle_delete().
246    native_handle*     readNativeHandle() const;
247
248
249    // Retrieve a file descriptor from the parcel.  This returns the raw fd
250    // in the parcel, which you do not own -- use dup() to get your own copy.
251    int                 readFileDescriptor() const;
252
253    // Reads a blob from the parcel.
254    // The caller should call release() on the blob after reading its contents.
255    status_t            readBlob(size_t len, ReadableBlob* outBlob) const;
256
257    const flat_binder_object* readObject(bool nullMetaData) const;
258
259    // Explicitly close all file descriptors in the parcel.
260    void                closeFileDescriptors();
261
262    // Debugging: get metrics on current allocations.
263    static size_t       getGlobalAllocSize();
264    static size_t       getGlobalAllocCount();
265
266private:
267    typedef void        (*release_func)(Parcel* parcel,
268                                        const uint8_t* data, size_t dataSize,
269                                        const binder_size_t* objects, size_t objectsSize,
270                                        void* cookie);
271
272    uintptr_t           ipcData() const;
273    size_t              ipcDataSize() const;
274    uintptr_t           ipcObjects() const;
275    size_t              ipcObjectsCount() const;
276    void                ipcSetDataReference(const uint8_t* data, size_t dataSize,
277                                            const binder_size_t* objects, size_t objectsCount,
278                                            release_func relFunc, void* relCookie);
279
280public:
281    void                print(TextOutput& to, uint32_t flags = 0) const;
282
283private:
284                        Parcel(const Parcel& o);
285    Parcel&             operator=(const Parcel& o);
286
287    status_t            finishWrite(size_t len);
288    void                releaseObjects();
289    void                acquireObjects();
290    status_t            growData(size_t len);
291    status_t            restartWrite(size_t desired);
292    status_t            continueWrite(size_t desired);
293    status_t            writePointer(uintptr_t val);
294    status_t            readPointer(uintptr_t *pArg) const;
295    uintptr_t           readPointer() const;
296    void                freeDataNoInit();
297    void                initState();
298    void                scanForFds() const;
299
300    template<class T>
301    status_t            readAligned(T *pArg) const;
302
303    template<class T>   T readAligned() const;
304
305    template<class T>
306    status_t            writeAligned(T val);
307
308    template<typename T, typename U>
309    status_t            unsafeReadTypedVector(std::vector<T>* val,
310                                              status_t(Parcel::*read_func)(U*) const) const;
311    template<typename T>
312    status_t            readTypedVector(std::vector<T>* val,
313                                        status_t(Parcel::*read_func)(T*) const) const;
314    template<typename T, typename U>
315    status_t            unsafeWriteTypedVector(const std::vector<T>& val,
316                                               status_t(Parcel::*write_func)(U));
317    template<typename T>
318    status_t            writeTypedVector(const std::vector<T>& val,
319                                         status_t(Parcel::*write_func)(const T&));
320    template<typename T>
321    status_t            writeTypedVector(const std::vector<T>& val,
322                                         status_t(Parcel::*write_func)(T));
323
324    status_t            mError;
325    uint8_t*            mData;
326    size_t              mDataSize;
327    size_t              mDataCapacity;
328    mutable size_t      mDataPos;
329    binder_size_t*      mObjects;
330    size_t              mObjectsSize;
331    size_t              mObjectsCapacity;
332    mutable size_t      mNextObjectHint;
333
334    mutable bool        mFdsKnown;
335    mutable bool        mHasFds;
336    bool                mAllowFds;
337
338    release_func        mOwner;
339    void*               mOwnerCookie;
340
341    class Blob {
342    public:
343        Blob();
344        ~Blob();
345
346        void clear();
347        void release();
348        inline size_t size() const { return mSize; }
349        inline int fd() const { return mFd; };
350        inline bool isMutable() const { return mMutable; }
351
352    protected:
353        void init(int fd, void* data, size_t size, bool isMutable);
354
355        int mFd; // owned by parcel so not closed when released
356        void* mData;
357        size_t mSize;
358        bool mMutable;
359    };
360
361    class FlattenableHelperInterface {
362    protected:
363        ~FlattenableHelperInterface() { }
364    public:
365        virtual size_t getFlattenedSize() const = 0;
366        virtual size_t getFdCount() const = 0;
367        virtual status_t flatten(void* buffer, size_t size, int* fds, size_t count) const = 0;
368        virtual status_t unflatten(void const* buffer, size_t size, int const* fds, size_t count) = 0;
369    };
370
371    template<typename T>
372    class FlattenableHelper : public FlattenableHelperInterface {
373        friend class Parcel;
374        const Flattenable<T>& val;
375        explicit FlattenableHelper(const Flattenable<T>& val) : val(val) { }
376
377    public:
378        virtual size_t getFlattenedSize() const {
379            return val.getFlattenedSize();
380        }
381        virtual size_t getFdCount() const {
382            return val.getFdCount();
383        }
384        virtual status_t flatten(void* buffer, size_t size, int* fds, size_t count) const {
385            return val.flatten(buffer, size, fds, count);
386        }
387        virtual status_t unflatten(void const* buffer, size_t size, int const* fds, size_t count) {
388            return const_cast<Flattenable<T>&>(val).unflatten(buffer, size, fds, count);
389        }
390    };
391    status_t write(const FlattenableHelperInterface& val);
392    status_t read(FlattenableHelperInterface& val) const;
393
394public:
395    class ReadableBlob : public Blob {
396        friend class Parcel;
397    public:
398        inline const void* data() const { return mData; }
399        inline void* mutableData() { return isMutable() ? mData : NULL; }
400    };
401
402    class WritableBlob : public Blob {
403        friend class Parcel;
404    public:
405        inline void* data() { return mData; }
406    };
407
408private:
409    size_t mOpenAshmemSize;
410
411public:
412    // TODO: Remove once ABI can be changed.
413    size_t getBlobAshmemSize() const;
414    size_t getOpenAshmemSize() const;
415};
416
417// ---------------------------------------------------------------------------
418
419template<typename T>
420status_t Parcel::write(const Flattenable<T>& val) {
421    const FlattenableHelper<T> helper(val);
422    return write(helper);
423}
424
425template<typename T>
426status_t Parcel::write(const LightFlattenable<T>& val) {
427    size_t size(val.getFlattenedSize());
428    if (!val.isFixedSize()) {
429        status_t err = writeInt32(size);
430        if (err != NO_ERROR) {
431            return err;
432        }
433    }
434    if (size) {
435        void* buffer = writeInplace(size);
436        if (buffer == NULL)
437            return NO_MEMORY;
438        return val.flatten(buffer, size);
439    }
440    return NO_ERROR;
441}
442
443template<typename T>
444status_t Parcel::read(Flattenable<T>& val) const {
445    FlattenableHelper<T> helper(val);
446    return read(helper);
447}
448
449template<typename T>
450status_t Parcel::read(LightFlattenable<T>& val) const {
451    size_t size;
452    if (val.isFixedSize()) {
453        size = val.getFlattenedSize();
454    } else {
455        int32_t s;
456        status_t err = readInt32(&s);
457        if (err != NO_ERROR) {
458            return err;
459        }
460        size = s;
461    }
462    if (size) {
463        void const* buffer = readInplace(size);
464        return buffer == NULL ? NO_MEMORY :
465                val.unflatten(buffer, size);
466    }
467    return NO_ERROR;
468}
469
470template<typename T>
471status_t Parcel::readStrongBinder(sp<T>* val) const {
472    sp<IBinder> tmp;
473    status_t ret = readStrongBinder(&tmp);
474
475    if (ret == OK) {
476        *val = interface_cast<T>(tmp);
477
478        if (val->get() == nullptr) {
479            return UNKNOWN_ERROR;
480        }
481    }
482
483    return ret;
484}
485
486template<typename T, typename U>
487status_t Parcel::unsafeReadTypedVector(
488        std::vector<T>* val, status_t(Parcel::*read_func)(U*) const) const {
489    val->clear();
490
491    int32_t size;
492    status_t status = this->readInt32(&size);
493
494    if (status != OK) {
495        return status;
496    }
497
498    if (size < 0) {
499        return UNEXPECTED_NULL;
500    }
501
502    val->resize(size);
503
504    for (auto& v: *val) {
505        status = (this->*read_func)(&v);
506
507        if (status != OK) {
508            return status;
509        }
510    }
511
512    return OK;
513}
514
515template<typename T>
516status_t Parcel::readTypedVector(std::vector<T>* val,
517                                 status_t(Parcel::*read_func)(T*) const) const {
518    return unsafeReadTypedVector(val, read_func);
519}
520
521template<typename T, typename U>
522status_t Parcel::unsafeWriteTypedVector(const std::vector<T>& val,
523                                        status_t(Parcel::*write_func)(U)) {
524    if (val.size() > std::numeric_limits<int32_t>::max()) {
525        return BAD_VALUE;
526    }
527
528    status_t status = this->writeInt32(val.size());
529
530    if (status != OK) {
531        return status;
532    }
533
534    for (const auto& item : val) {
535        status = (this->*write_func)(item);
536
537        if (status != OK) {
538            return status;
539        }
540    }
541
542    return OK;
543}
544
545template<typename T>
546status_t Parcel::writeTypedVector(const std::vector<T>& val,
547                          status_t(Parcel::*write_func)(const T&)) {
548    return unsafeWriteTypedVector(val, write_func);
549}
550
551template<typename T>
552status_t Parcel::writeTypedVector(const std::vector<T>& val,
553                          status_t(Parcel::*write_func)(T)) {
554    return unsafeWriteTypedVector(val, write_func);
555}
556
557template<typename T>
558status_t Parcel::readParcelableVector(std::vector<T>* val) const {
559    return unsafeReadTypedVector(val, &Parcel::readParcelable);
560}
561
562template<typename T>
563status_t Parcel::writeParcelableVector(const std::vector<T>& val) {
564    return unsafeWriteTypedVector(val, &Parcel::writeParcelable);
565}
566
567// ---------------------------------------------------------------------------
568
569inline TextOutput& operator<<(TextOutput& to, const Parcel& parcel)
570{
571    parcel.print(to);
572    return to;
573}
574
575// ---------------------------------------------------------------------------
576
577// Generic acquire and release of objects.
578void acquire_object(const sp<ProcessState>& proc,
579                    const flat_binder_object& obj, const void* who);
580void release_object(const sp<ProcessState>& proc,
581                    const flat_binder_object& obj, const void* who);
582
583void flatten_binder(const sp<ProcessState>& proc,
584                    const sp<IBinder>& binder, flat_binder_object* out);
585void flatten_binder(const sp<ProcessState>& proc,
586                    const wp<IBinder>& binder, flat_binder_object* out);
587status_t unflatten_binder(const sp<ProcessState>& proc,
588                          const flat_binder_object& flat, sp<IBinder>* out);
589status_t unflatten_binder(const sp<ProcessState>& proc,
590                          const flat_binder_object& flat, wp<IBinder>* out);
591
592}; // namespace android
593
594// ---------------------------------------------------------------------------
595
596#endif // ANDROID_PARCEL_H
597