xref: /aosp_15_r20/system/libhwbinder/include/hwbinder/Parcel.h (revision 77b80299c8bdfeca3ae6d0ce27ae1ad3db289be3)
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_HARDWARE_PARCEL_H
18 #define ANDROID_HARDWARE_PARCEL_H
19 
20 #include <string>
21 #include <vector>
22 
23 #include <cutils/native_handle.h>
24 #include <utils/Errors.h>
25 #include <utils/RefBase.h>
26 #include <utils/String16.h>
27 
28 #include <hwbinder/IInterface.h>
29 
30 // WARNING: this code is part of libhwbinder, a fork of libbinder. Generally,
31 // this means that it is only relevant to HIDL. Any AIDL- or libbinder-specific
32 // code should not try to use these things.
33 
34 struct binder_buffer_object;
35 struct flat_binder_object;
36 
37 // ---------------------------------------------------------------------------
38 namespace android {
39 namespace hardware {
40 
41 #ifdef BINDER_IPC_32BIT
42 typedef unsigned int binder_size_t;
43 typedef unsigned int binder_uintptr_t;
44 #else
45 typedef unsigned long long binder_size_t;
46 typedef unsigned long long binder_uintptr_t;
47 #endif
48 
49 class IBinder;
50 class IPCThreadState;
51 class ProcessState;
52 class TextOutput;
53 
54 class Parcel {
55     friend class IPCThreadState;
56 public:
57 
58                         Parcel();
59                         ~Parcel();
60 
61     const uint8_t*      data() const;
62     size_t              dataSize() const;
63     size_t              dataAvail() const;
64     size_t              dataPosition() const;
65     size_t              dataCapacity() const;
66 
67     status_t            setDataSize(size_t size);
68     void                setDataPosition(size_t pos) const;
69     status_t            setDataCapacity(size_t size);
70 
71     // Zeros data when reallocating. Other mitigations may be added
72     // in the future.
73     //
74     // WARNING: some read methods may make additional copies of data.
75     // In order to verify this, heap dumps should be used.
76     void                markSensitive() const;
77 
78     // Writes the RPC header.
79     status_t            writeInterfaceToken(const char* interface);
80 
81     // Parses the RPC header, returning true if the interface name
82     // in the header matches the expected interface from the caller.
83     bool                enforceInterface(const char* interface) const;
84 
85     void                freeData();
86 
87 private:
88     const binder_size_t* objects() const;
89 
90 public:
91     size_t              objectsCount() const;
92 
93     status_t            errorCheck() const;
94     void                setError(status_t err);
95 
96     status_t            write(const void* data, size_t len);
97     void*               writeInplace(size_t len);
98     status_t            writeInt8(int8_t val);
99     status_t            writeUint8(uint8_t val);
100     status_t            writeInt16(int16_t val);
101     status_t            writeUint16(uint16_t val);
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            writeString16(const String16& str);
110     status_t            writeString16(const std::unique_ptr<String16>& str);
111     status_t            writeString16(const char16_t* str, size_t len);
112     status_t            writeStrongBinder(const sp<IBinder>& val);
113     status_t            writeBool(bool val);
114 
115     template<typename T>
116     status_t            writeObject(const T& val);
117 
118     status_t            writeBuffer(const void *buffer, size_t length, size_t *handle);
119     status_t            writeEmbeddedBuffer(const void *buffer, size_t length, size_t *handle,
120                             size_t parent_buffer_handle, size_t parent_offset);
121 public:
122     status_t            writeEmbeddedNativeHandle(const native_handle_t *handle,
123                             size_t parent_buffer_handle, size_t parent_offset);
124     status_t            writeNativeHandleNoDup(const native_handle* handle, bool embedded,
125                                                size_t parent_buffer_handle = 0,
126                                                size_t parent_offset = 0);
127     status_t            writeNativeHandleNoDup(const native_handle* handle);
128 
129     status_t            read(void* outData, size_t len) const;
130     const void*         readInplace(size_t len) const;
131     status_t            readInt8(int8_t *pArg) const;
132     status_t            readUint8(uint8_t *pArg) const;
133     status_t            readInt16(int16_t *pArg) const;
134     status_t            readUint16(uint16_t *pArg) const;
135     int32_t             readInt32() const;
136     status_t            readInt32(int32_t *pArg) const;
137     uint32_t            readUint32() const;
138     status_t            readUint32(uint32_t *pArg) const;
139     int64_t             readInt64() const;
140     status_t            readInt64(int64_t *pArg) const;
141     uint64_t            readUint64() const;
142     status_t            readUint64(uint64_t *pArg) const;
143     float               readFloat() const;
144     status_t            readFloat(float *pArg) const;
145     double              readDouble() const;
146     status_t            readDouble(double *pArg) const;
147 
148     bool                readBool() const;
149     status_t            readBool(bool *pArg) const;
150     const char*         readCString() const;
151     String16            readString16() const;
152     status_t            readString16(String16* pArg) const;
153     status_t            readString16(std::unique_ptr<String16>* pArg) const;
154     const char16_t*     readString16Inplace(size_t* outLen) const;
155     sp<IBinder>         readStrongBinder() const;
156     status_t            readStrongBinder(sp<IBinder>* val) const;
157     status_t            readNullableStrongBinder(sp<IBinder>* val) const;
158 
159     template<typename T>
160     const T*            readObject(size_t *objects_offset = nullptr) const;
161 
162     status_t            readBuffer(size_t buffer_size, size_t *buffer_handle,
163                                    const void **buffer_out) const;
164     status_t            readNullableBuffer(size_t buffer_size, size_t *buffer_handle,
165                                            const void **buffer_out) const;
166     status_t            readEmbeddedBuffer(size_t buffer_size, size_t *buffer_handle,
167                                            size_t parent_buffer_handle, size_t parent_offset,
168                                            const void **buffer_out) const;
169     status_t            readNullableEmbeddedBuffer(size_t buffer_size,
170                                                    size_t *buffer_handle,
171                                                    size_t parent_buffer_handle,
172                                                    size_t parent_offset,
173                                                    const void **buffer_out) const;
174 
175     status_t            readEmbeddedNativeHandle(size_t parent_buffer_handle,
176                            size_t parent_offset, const native_handle_t **handle) const;
177     status_t            readNullableEmbeddedNativeHandle(size_t parent_buffer_handle,
178                            size_t parent_offset, const native_handle_t **handle) const;
179     status_t            readNativeHandleNoDup(const native_handle_t **handle) const;
180     status_t            readNullableNativeHandleNoDup(const native_handle_t **handle) const;
181 
182     // Explicitly close all file descriptors in the parcel.
183     void                closeFileDescriptors();
184 
185     // Debugging: get metrics on current allocations.
186     static size_t       getGlobalAllocSize();
187     static size_t       getGlobalAllocCount();
188 
189 private:
190     // Below is a cache that records some information about all actual buffers
191     // in this parcel.
192     struct BufferInfo {
193         size_t index;
194         binder_uintptr_t buffer;
195         binder_uintptr_t bufend; // buffer + length
196     };
197     // value of mObjectSize when mBufCache is last updated.
198     mutable size_t                  mBufCachePos;
199     mutable std::vector<BufferInfo> mBufCache;
200     // clear mBufCachePos and mBufCache.
201     void                clearCache() const;
202     // update mBufCache for all objects between mBufCachePos and mObjectsSize
203     void                updateCache() const;
204 
205     bool                verifyBufferObject(const binder_buffer_object *buffer_obj,
206                                            size_t size, uint32_t flags, size_t parent,
207                                            size_t parentOffset) const;
208 
209     status_t            readBuffer(size_t buffer_size, size_t *buffer_handle,
210                                    uint32_t flags, size_t parent, size_t parentOffset,
211                                    const void **buffer_out) const;
212 
213     status_t            readNullableNativeHandleNoDup(const native_handle_t **handle,
214                                                       bool embedded,
215                                                       size_t parent_buffer_handle = 0,
216                                                       size_t parent_offset = 0) const;
217 public:
218 
219     // The following two methods attempt to find if a chunk of memory ("buffer")
220     // is written / read before (by (read|write)(Embedded)?Buffer methods. )
221     // 1. Call findBuffer if the chunk of memory could be a small part of a larger
222     //    buffer written before (for example, an element of a hidl_vec). The
223     //    method will also ensure that the end address (ptr + length) is also
224     //    within the buffer.
225     // 2. Call quickFindBuffer if the buffer could only be written previously
226     //    by itself (for example, the mBuffer field of a hidl_vec). No lengths
227     //    are checked.
228     status_t            findBuffer(const void *ptr,
229                                    size_t length,
230                                    bool *found,
231                                    size_t *handle,
232                                    size_t *offset // valid if found
233                                   ) const;
234     status_t            quickFindBuffer(const void *ptr,
235                                         size_t *handle // valid if found
236                                        ) const;
237 
238 private:
239     bool                validateBufferChild(size_t child_buffer_handle,
240                                             size_t child_offset) const;
241     bool                validateBufferParent(size_t parent_buffer_handle,
242                                              size_t parent_offset) const;
243 
244 private:
245     typedef void        (*release_func)(Parcel* parcel,
246                                         const uint8_t* data, size_t dataSize,
247                                         const binder_size_t* objects, size_t objectsSize,
248                                         void* cookie);
249 
250     uintptr_t           ipcData() const;
251     size_t              ipcDataSize() const;
252     uintptr_t           ipcObjects() const;
253     size_t              ipcObjectsCount() const;
254     size_t              ipcBufferSize() const;
255     void                ipcSetDataReference(const uint8_t* data, size_t dataSize,
256                                             const binder_size_t* objects, size_t objectsCount,
257                                             release_func relFunc, void* relCookie);
258 
259 public:
260     void                print(TextOutput& to, uint32_t flags = 0) const;
261 
262 private:
263                         Parcel(const Parcel& o);
264     Parcel&             operator=(const Parcel& o);
265 
266     status_t            finishWrite(size_t len);
267     void                releaseObjects();
268     void                acquireObjects();
269     status_t            growData(size_t len);
270     status_t            continueWrite(size_t desired);
271     status_t            writePointer(uintptr_t val);
272     status_t            readPointer(uintptr_t *pArg) const;
273     uintptr_t           readPointer() const;
274     void                freeDataNoInit();
275     void                initState();
276     void                scanForFds() const;
277 
278     template<class T>
279     status_t            readAligned(T *pArg) const;
280 
281     template<class T>   T readAligned() const;
282 
283     template<class T>
284     status_t            writeAligned(T val);
285 
286     status_t            mError;
287     uint8_t*            mData;
288     size_t              mDataSize;
289     size_t              mDataCapacity;
290     mutable size_t      mDataPos;
291     binder_size_t*      mObjects;
292     size_t              mObjectsSize;
293     size_t              mObjectsCapacity;
294     mutable size_t      mNextObjectHint;
295 
296     [[deprecated]] size_t mNumRef;
297 
298     mutable bool        mFdsKnown;
299     mutable bool        mHasFds;
300     bool                mAllowFds;
301 
302     // if this parcelable is involved in a secure transaction, force the
303     // data to be overridden with zero when deallocated
304     mutable bool        mDeallocZero;
305 
306     release_func        mOwner;
307     void*               mOwnerCookie;
308 };
309 // ---------------------------------------------------------------------------
310 
311 inline TextOutput& operator<<(TextOutput& to, const Parcel& parcel)
312 {
313     parcel.print(to);
314     return to;
315 }
316 
317 // ---------------------------------------------------------------------------
318 
319 // Generic acquire and release of objects.
320 void acquire_object(const sp<ProcessState>& proc,
321                     const flat_binder_object& obj, const void* who);
322 void release_object(const sp<ProcessState>& proc,
323                     const flat_binder_object& obj, const void* who);
324 
325 void flatten_binder(const sp<ProcessState>& proc,
326                     const sp<IBinder>& binder, flat_binder_object* out);
327 void flatten_binder(const sp<ProcessState>& proc,
328                     const wp<IBinder>& binder, flat_binder_object* out);
329 status_t unflatten_binder(const sp<ProcessState>& proc,
330                           const flat_binder_object& flat, sp<IBinder>* out);
331 status_t unflatten_binder(const sp<ProcessState>& proc,
332                           const flat_binder_object& flat, wp<IBinder>* out);
333 
334 } // namespace hardware
335 } // namespace android
336 
337 // ---------------------------------------------------------------------------
338 
339 #endif // ANDROID_HARDWARE_PARCEL_H
340