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