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