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