• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #define LOG_TAG "hw-Parcel"
18 //#define LOG_NDEBUG 0
19 
20 #include <errno.h>
21 #include <fcntl.h>
22 #include <inttypes.h>
23 #include <pthread.h>
24 #include <stdint.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <sys/mman.h>
28 #include <sys/stat.h>
29 #include <sys/types.h>
30 #include <sys/resource.h>
31 #include <unistd.h>
32 
33 #include <hwbinder/Binder.h>
34 #include <hwbinder/BpHwBinder.h>
35 #include <hwbinder/IPCThreadState.h>
36 #include <hwbinder/Parcel.h>
37 #include <hwbinder/ProcessState.h>
38 
39 #include <cutils/ashmem.h>
40 #include <utils/Log.h>
41 #include <utils/misc.h>
42 #include <utils/String8.h>
43 #include <utils/String16.h>
44 
45 #include "binder_kernel.h"
46 #include <hwbinder/Static.h>
47 #include "TextOutput.h"
48 #include "Utils.h"
49 
50 #include <atomic>
51 
52 #define LOG_REFS(...)
53 //#define LOG_REFS(...) ALOG(LOG_DEBUG, LOG_TAG, __VA_ARGS__)
54 #define LOG_ALLOC(...)
55 //#define LOG_ALLOC(...) ALOG(LOG_DEBUG, LOG_TAG, __VA_ARGS__)
56 #define LOG_BUFFER(...)
57 // #define LOG_BUFFER(...) ALOG(LOG_DEBUG, LOG_TAG, __VA_ARGS__)
58 
59 // ---------------------------------------------------------------------------
60 
61 // This macro should never be used at runtime, as a too large value
62 // of s could cause an integer overflow. Instead, you should always
63 // use the wrapper function pad_size()
64 #define PAD_SIZE_UNSAFE(s) (((s)+3)&~3)
65 
pad_size(size_t s)66 static size_t pad_size(size_t s) {
67     if (s > (std::numeric_limits<size_t>::max() - 3)) {
68         LOG_ALWAYS_FATAL("pad size too big %zu", s);
69     }
70     return PAD_SIZE_UNSAFE(s);
71 }
72 
73 // Note: must be kept in sync with android/os/StrictMode.java's PENALTY_GATHER
74 #define STRICT_MODE_PENALTY_GATHER (0x40 << 16)
75 
76 namespace android {
77 namespace hardware {
78 
79 static std::atomic<size_t> gParcelGlobalAllocCount;
80 static std::atomic<size_t> gParcelGlobalAllocSize;
81 
82 static size_t gMaxFds = 0;
83 
acquire_binder_object(const sp<ProcessState> & proc,const flat_binder_object & obj,const void * who)84 void acquire_binder_object(const sp<ProcessState>& proc,
85     const flat_binder_object& obj, const void* who)
86 {
87     switch (obj.hdr.type) {
88         case BINDER_TYPE_BINDER:
89             if (obj.binder) {
90                 LOG_REFS("Parcel %p acquiring reference on local %p", who, obj.cookie);
91                 reinterpret_cast<IBinder*>(obj.cookie)->incStrong(who);
92             }
93             return;
94         case BINDER_TYPE_WEAK_BINDER:
95             if (obj.binder)
96                 reinterpret_cast<RefBase::weakref_type*>(obj.binder)->incWeak(who);
97             return;
98         case BINDER_TYPE_HANDLE: {
99             const sp<IBinder> b = proc->getStrongProxyForHandle(obj.handle);
100             if (b != nullptr) {
101                 LOG_REFS("Parcel %p acquiring reference on remote %p", who, b.get());
102                 b->incStrong(who);
103             }
104             return;
105         }
106         case BINDER_TYPE_WEAK_HANDLE: {
107             const wp<IBinder> b = proc->getWeakProxyForHandle(obj.handle);
108             if (b != nullptr) b.get_refs()->incWeak(who);
109             return;
110         }
111     }
112 
113     ALOGD("Invalid object type 0x%08x", obj.hdr.type);
114 }
115 
acquire_object(const sp<ProcessState> & proc,const binder_object_header & obj,const void * who)116 void acquire_object(const sp<ProcessState>& proc, const binder_object_header& obj,
117         const void *who) {
118     switch (obj.type) {
119         case BINDER_TYPE_BINDER:
120         case BINDER_TYPE_WEAK_BINDER:
121         case BINDER_TYPE_HANDLE:
122         case BINDER_TYPE_WEAK_HANDLE: {
123             const flat_binder_object& fbo = reinterpret_cast<const flat_binder_object&>(obj);
124             acquire_binder_object(proc, fbo, who);
125             break;
126         }
127     }
128 }
129 
release_object(const sp<ProcessState> & proc,const flat_binder_object & obj,const void * who)130 void release_object(const sp<ProcessState>& proc,
131     const flat_binder_object& obj, const void* who)
132 {
133     switch (obj.hdr.type) {
134         case BINDER_TYPE_BINDER:
135             if (obj.binder) {
136                 LOG_REFS("Parcel %p releasing reference on local %p", who, obj.cookie);
137                 reinterpret_cast<IBinder*>(obj.cookie)->decStrong(who);
138             }
139             return;
140         case BINDER_TYPE_WEAK_BINDER:
141             if (obj.binder)
142                 reinterpret_cast<RefBase::weakref_type*>(obj.binder)->decWeak(who);
143             return;
144         case BINDER_TYPE_HANDLE: {
145             const sp<IBinder> b = proc->getStrongProxyForHandle(obj.handle);
146             if (b != nullptr) {
147                 LOG_REFS("Parcel %p releasing reference on remote %p", who, b.get());
148                 b->decStrong(who);
149             }
150             return;
151         }
152         case BINDER_TYPE_WEAK_HANDLE: {
153             const wp<IBinder> b = proc->getWeakProxyForHandle(obj.handle);
154             if (b != nullptr) b.get_refs()->decWeak(who);
155             return;
156         }
157         case BINDER_TYPE_FD: {
158             if (obj.cookie != 0) { // owned
159                 close(obj.handle);
160             }
161             return;
162         }
163         case BINDER_TYPE_PTR: {
164             // The relevant buffer is part of the transaction buffer and will be freed that way
165             return;
166         }
167         case BINDER_TYPE_FDA: {
168             // The enclosed file descriptors are closed in the kernel
169             return;
170         }
171     }
172 
173     ALOGE("Invalid object type 0x%08x", obj.hdr.type);
174 }
175 
finish_flatten_binder(const sp<IBinder> &,const flat_binder_object & flat,Parcel * out)176 inline static status_t finish_flatten_binder(
177     const sp<IBinder>& /*binder*/, const flat_binder_object& flat, Parcel* out)
178 {
179     return out->writeObject(flat);
180 }
181 
flatten_binder(const sp<ProcessState> &,const sp<IBinder> & binder,Parcel * out)182 status_t flatten_binder(const sp<ProcessState>& /*proc*/,
183     const sp<IBinder>& binder, Parcel* out)
184 {
185     flat_binder_object obj = {};
186 
187     if (binder != nullptr) {
188         BHwBinder *local = binder->localBinder();
189         if (!local) {
190             BpHwBinder *proxy = binder->remoteBinder();
191             if (proxy == nullptr) {
192                 ALOGE("null proxy");
193             }
194             const int32_t handle = proxy ? proxy->handle() : 0;
195             obj.hdr.type = BINDER_TYPE_HANDLE;
196             obj.flags = FLAT_BINDER_FLAG_ACCEPTS_FDS;
197             obj.binder = 0; /* Don't pass uninitialized stack data to a remote process */
198             obj.handle = handle;
199             obj.cookie = 0;
200         } else {
201             // Get policy and convert it
202             int policy = local->getMinSchedulingPolicy();
203             int priority = local->getMinSchedulingPriority();
204 
205             obj.flags = priority & FLAT_BINDER_FLAG_PRIORITY_MASK;
206             obj.flags |= FLAT_BINDER_FLAG_ACCEPTS_FDS | FLAT_BINDER_FLAG_INHERIT_RT;
207             obj.flags |= (policy & 3) << FLAT_BINDER_FLAG_SCHED_POLICY_SHIFT;
208             if (local->isRequestingSid()) {
209                 obj.flags |= FLAT_BINDER_FLAG_TXN_SECURITY_CTX;
210             }
211             obj.hdr.type = BINDER_TYPE_BINDER;
212             obj.binder = reinterpret_cast<uintptr_t>(local->getWeakRefs());
213             obj.cookie = reinterpret_cast<uintptr_t>(local);
214         }
215     } else {
216         obj.hdr.type = BINDER_TYPE_BINDER;
217         obj.binder = 0;
218         obj.cookie = 0;
219     }
220 
221     return finish_flatten_binder(binder, obj, out);
222 }
223 
finish_unflatten_binder(BpHwBinder *,const flat_binder_object &,const Parcel &)224 inline static status_t finish_unflatten_binder(
225     BpHwBinder* /*proxy*/, const flat_binder_object& /*flat*/,
226     const Parcel& /*in*/)
227 {
228     return NO_ERROR;
229 }
230 
unflatten_binder(const sp<ProcessState> & proc,const Parcel & in,sp<IBinder> * out)231 status_t unflatten_binder(const sp<ProcessState>& proc,
232     const Parcel& in, sp<IBinder>* out)
233 {
234     const flat_binder_object* flat = in.readObject<flat_binder_object>();
235 
236     if (flat) {
237         switch (flat->hdr.type) {
238             case BINDER_TYPE_BINDER:
239                 *out = reinterpret_cast<IBinder*>(flat->cookie);
240                 return finish_unflatten_binder(nullptr, *flat, in);
241             case BINDER_TYPE_HANDLE:
242                 *out = proc->getStrongProxyForHandle(flat->handle);
243                 return finish_unflatten_binder(
244                     static_cast<BpHwBinder*>(out->get()), *flat, in);
245         }
246     }
247     return BAD_TYPE;
248 }
249 
250 // ---------------------------------------------------------------------------
251 
Parcel()252 Parcel::Parcel()
253 {
254     LOG_ALLOC("Parcel %p: constructing", this);
255     initState();
256 }
257 
~Parcel()258 Parcel::~Parcel()
259 {
260     freeDataNoInit();
261     LOG_ALLOC("Parcel %p: destroyed", this);
262 }
263 
getGlobalAllocSize()264 size_t Parcel::getGlobalAllocSize() {
265     return gParcelGlobalAllocSize.load();
266 }
267 
getGlobalAllocCount()268 size_t Parcel::getGlobalAllocCount() {
269     return gParcelGlobalAllocCount.load();
270 }
271 
data() const272 const uint8_t* Parcel::data() const
273 {
274     return mData;
275 }
276 
dataSize() const277 size_t Parcel::dataSize() const
278 {
279     return (mDataSize > mDataPos ? mDataSize : mDataPos);
280 }
281 
dataAvail() const282 size_t Parcel::dataAvail() const
283 {
284     size_t result = dataSize() - dataPosition();
285     if (result > INT32_MAX) {
286         LOG_ALWAYS_FATAL("result too big: %zu", result);
287     }
288     return result;
289 }
290 
dataPosition() const291 size_t Parcel::dataPosition() const
292 {
293     return mDataPos;
294 }
295 
dataCapacity() const296 size_t Parcel::dataCapacity() const
297 {
298     return mDataCapacity;
299 }
300 
setDataSize(size_t size)301 status_t Parcel::setDataSize(size_t size)
302 {
303     if (size > INT32_MAX) {
304         // don't accept size_t values which may have come from an
305         // inadvertent conversion from a negative int.
306         return BAD_VALUE;
307     }
308 
309     status_t err;
310     err = continueWrite(size);
311     if (err == NO_ERROR) {
312         mDataSize = size;
313         ALOGV("setDataSize Setting data size of %p to %zu", this, mDataSize);
314     }
315     return err;
316 }
317 
setDataPosition(size_t pos) const318 void Parcel::setDataPosition(size_t pos) const
319 {
320     if (pos > INT32_MAX) {
321         // don't accept size_t values which may have come from an
322         // inadvertent conversion from a negative int.
323         LOG_ALWAYS_FATAL("pos too big: %zu", pos);
324     }
325 
326     mDataPos = pos;
327     mNextObjectHint = 0;
328 }
329 
setDataCapacity(size_t size)330 status_t Parcel::setDataCapacity(size_t size)
331 {
332     if (size > INT32_MAX) {
333         // don't accept size_t values which may have come from an
334         // inadvertent conversion from a negative int.
335         return BAD_VALUE;
336     }
337 
338     if (size > mDataCapacity) return continueWrite(size);
339     return NO_ERROR;
340 }
341 
setData(const uint8_t * buffer,size_t len)342 status_t Parcel::setData(const uint8_t* buffer, size_t len)
343 {
344     if (len > INT32_MAX) {
345         // don't accept size_t values which may have come from an
346         // inadvertent conversion from a negative int.
347         return BAD_VALUE;
348     }
349 
350     status_t err = restartWrite(len);
351     if (err == NO_ERROR) {
352         memcpy(const_cast<uint8_t*>(data()), buffer, len);
353         mDataSize = len;
354         mFdsKnown = false;
355     }
356     return err;
357 }
358 
markSensitive() const359 void Parcel::markSensitive() const
360 {
361     mDeallocZero = true;
362 }
363 
364 // Write RPC headers.  (previously just the interface token)
writeInterfaceToken(const char * interface)365 status_t Parcel::writeInterfaceToken(const char* interface)
366 {
367     // currently the interface identification token is just its name as a string
368     return writeCString(interface);
369 }
370 
enforceInterface(const char * interface) const371 bool Parcel::enforceInterface(const char* interface) const
372 {
373     const char* str = readCString();
374     if (str != nullptr && strcmp(str, interface) == 0) {
375         return true;
376     } else {
377         ALOGW("**** enforceInterface() expected '%s' but read '%s'",
378                 interface, (str ? str : "<empty string>"));
379         return false;
380     }
381 }
382 
objects() const383 const binder_size_t* Parcel::objects() const
384 {
385     return mObjects;
386 }
387 
objectsCount() const388 size_t Parcel::objectsCount() const
389 {
390     return mObjectsSize;
391 }
392 
errorCheck() const393 status_t Parcel::errorCheck() const
394 {
395     return mError;
396 }
397 
setError(status_t err)398 void Parcel::setError(status_t err)
399 {
400     mError = err;
401 }
402 
finishWrite(size_t len)403 status_t Parcel::finishWrite(size_t len)
404 {
405     if (len > INT32_MAX) {
406         // don't accept size_t values which may have come from an
407         // inadvertent conversion from a negative int.
408         return BAD_VALUE;
409     }
410 
411     //printf("Finish write of %d\n", len);
412     mDataPos += len;
413     ALOGV("finishWrite Setting data pos of %p to %zu", this, mDataPos);
414     if (mDataPos > mDataSize) {
415         mDataSize = mDataPos;
416         ALOGV("finishWrite Setting data size of %p to %zu", this, mDataSize);
417     }
418     //printf("New pos=%d, size=%d\n", mDataPos, mDataSize);
419     return NO_ERROR;
420 }
421 
writeUnpadded(const void * data,size_t len)422 status_t Parcel::writeUnpadded(const void* data, size_t len)
423 {
424     if (len > INT32_MAX) {
425         // don't accept size_t values which may have come from an
426         // inadvertent conversion from a negative int.
427         return BAD_VALUE;
428     }
429 
430     size_t end = mDataPos + len;
431     if (end < mDataPos) {
432         // integer overflow
433         return BAD_VALUE;
434     }
435 
436     if (end <= mDataCapacity) {
437 restart_write:
438         memcpy(mData+mDataPos, data, len);
439         return finishWrite(len);
440     }
441 
442     status_t err = growData(len);
443     if (err == NO_ERROR) goto restart_write;
444     return err;
445 }
446 
write(const void * data,size_t len)447 status_t Parcel::write(const void* data, size_t len)
448 {
449     if (len > INT32_MAX) {
450         // don't accept size_t values which may have come from an
451         // inadvertent conversion from a negative int.
452         return BAD_VALUE;
453     }
454 
455     void* const d = writeInplace(len);
456     if (d) {
457         memcpy(d, data, len);
458         return NO_ERROR;
459     }
460     return mError;
461 }
462 
writeInplace(size_t len)463 void* Parcel::writeInplace(size_t len)
464 {
465     if (len > INT32_MAX) {
466         // don't accept size_t values which may have come from an
467         // inadvertent conversion from a negative int.
468         return nullptr;
469     }
470 
471     const size_t padded = pad_size(len);
472 
473     // validate for integer overflow
474     if (mDataPos+padded < mDataPos) {
475         return nullptr;
476     }
477 
478     if ((mDataPos+padded) <= mDataCapacity) {
479 restart_write:
480         //printf("Writing %ld bytes, padded to %ld\n", len, padded);
481         uint8_t* const data = mData+mDataPos;
482 
483         // Need to pad at end?
484         if (padded != len) {
485 #if BYTE_ORDER == BIG_ENDIAN
486             static const uint32_t mask[4] = {
487                 0x00000000, 0xffffff00, 0xffff0000, 0xff000000
488             };
489 #endif
490 #if BYTE_ORDER == LITTLE_ENDIAN
491             static const uint32_t mask[4] = {
492                 0x00000000, 0x00ffffff, 0x0000ffff, 0x000000ff
493             };
494 #endif
495             //printf("Applying pad mask: %p to %p\n", (void*)mask[padded-len],
496             //    *reinterpret_cast<void**>(data+padded-4));
497             *reinterpret_cast<uint32_t*>(data+padded-4) &= mask[padded-len];
498         }
499 
500         finishWrite(padded);
501         return data;
502     }
503 
504     status_t err = growData(padded);
505     if (err == NO_ERROR) goto restart_write;
506     return nullptr;
507 }
508 
writeInt8(int8_t val)509 status_t Parcel::writeInt8(int8_t val)
510 {
511     return write(&val, sizeof(val));
512 }
513 
writeUint8(uint8_t val)514 status_t Parcel::writeUint8(uint8_t val)
515 {
516     return write(&val, sizeof(val));
517 }
518 
writeInt16(int16_t val)519 status_t Parcel::writeInt16(int16_t val)
520 {
521     return write(&val, sizeof(val));
522 }
523 
writeUint16(uint16_t val)524 status_t Parcel::writeUint16(uint16_t val)
525 {
526     return write(&val, sizeof(val));
527 }
528 
writeInt32(int32_t val)529 status_t Parcel::writeInt32(int32_t val)
530 {
531     return writeAligned(val);
532 }
533 
writeUint32(uint32_t val)534 status_t Parcel::writeUint32(uint32_t val)
535 {
536     return writeAligned(val);
537 }
538 
writeBool(bool val)539 status_t Parcel::writeBool(bool val)
540 {
541     return writeInt8(int8_t(val));
542 }
writeInt64(int64_t val)543 status_t Parcel::writeInt64(int64_t val)
544 {
545     return writeAligned(val);
546 }
547 
writeUint64(uint64_t val)548 status_t Parcel::writeUint64(uint64_t val)
549 {
550     return writeAligned(val);
551 }
552 
writePointer(uintptr_t val)553 status_t Parcel::writePointer(uintptr_t val)
554 {
555     return writeAligned<binder_uintptr_t>(val);
556 }
557 
writeFloat(float val)558 status_t Parcel::writeFloat(float val)
559 {
560     return writeAligned(val);
561 }
562 
563 #if defined(__mips__) && defined(__mips_hard_float)
564 
writeDouble(double val)565 status_t Parcel::writeDouble(double val)
566 {
567     union {
568         double d;
569         unsigned long long ll;
570     } u;
571     u.d = val;
572     return writeAligned(u.ll);
573 }
574 
575 #else
576 
writeDouble(double val)577 status_t Parcel::writeDouble(double val)
578 {
579     return writeAligned(val);
580 }
581 
582 #endif
583 
writeCString(const char * str)584 status_t Parcel::writeCString(const char* str)
585 {
586     return write(str, strlen(str)+1);
587 }
writeString16(const std::unique_ptr<String16> & str)588 status_t Parcel::writeString16(const std::unique_ptr<String16>& str)
589 {
590     if (!str) {
591         return writeInt32(-1);
592     }
593 
594     return writeString16(*str);
595 }
596 
writeString16(const String16 & str)597 status_t Parcel::writeString16(const String16& str)
598 {
599     return writeString16(str.string(), str.size());
600 }
601 
writeString16(const char16_t * str,size_t len)602 status_t Parcel::writeString16(const char16_t* str, size_t len)
603 {
604     if (str == nullptr) return writeInt32(-1);
605 
606     status_t err = writeInt32(len);
607     if (err == NO_ERROR) {
608         len *= sizeof(char16_t);
609         uint8_t* data = (uint8_t*)writeInplace(len+sizeof(char16_t));
610         if (data) {
611             memcpy(data, str, len);
612             *reinterpret_cast<char16_t*>(data+len) = 0;
613             return NO_ERROR;
614         }
615         err = mError;
616     }
617     return err;
618 }
writeStrongBinder(const sp<IBinder> & val)619 status_t Parcel::writeStrongBinder(const sp<IBinder>& val)
620 {
621     return flatten_binder(ProcessState::self(), val, this);
622 }
623 
624 template <typename T>
writeObject(const T & val)625 status_t Parcel::writeObject(const T& val)
626 {
627     const bool enoughData = (mDataPos+sizeof(val)) <= mDataCapacity;
628     const bool enoughObjects = mObjectsSize < mObjectsCapacity;
629     if (enoughData && enoughObjects) {
630 restart_write:
631         *reinterpret_cast<T*>(mData+mDataPos) = val;
632 
633         const binder_object_header* hdr = reinterpret_cast<binder_object_header*>(mData+mDataPos);
634         switch (hdr->type) {
635             case BINDER_TYPE_BINDER:
636             case BINDER_TYPE_WEAK_BINDER:
637             case BINDER_TYPE_HANDLE:
638             case BINDER_TYPE_WEAK_HANDLE: {
639                 const flat_binder_object *fbo = reinterpret_cast<const flat_binder_object*>(hdr);
640                 if (fbo->binder != 0) {
641                     mObjects[mObjectsSize++] = mDataPos;
642                     acquire_binder_object(ProcessState::self(), *fbo, this);
643                 }
644                 break;
645             }
646             case BINDER_TYPE_FD: {
647                 // remember if it's a file descriptor
648                 if (!mAllowFds) {
649                     // fail before modifying our object index
650                     return FDS_NOT_ALLOWED;
651                 }
652                 mHasFds = mFdsKnown = true;
653                 mObjects[mObjectsSize++] = mDataPos;
654                 break;
655             }
656             case BINDER_TYPE_FDA:
657                 mObjects[mObjectsSize++] = mDataPos;
658                 break;
659             case BINDER_TYPE_PTR: {
660                 const binder_buffer_object *buffer_obj = reinterpret_cast<
661                     const binder_buffer_object*>(hdr);
662                 if ((void *)buffer_obj->buffer != nullptr) {
663                     mObjects[mObjectsSize++] = mDataPos;
664                 }
665                 break;
666             }
667             default: {
668                 ALOGE("writeObject: unknown type %d", hdr->type);
669                 break;
670             }
671         }
672         return finishWrite(sizeof(val));
673     }
674 
675     if (!enoughData) {
676         const status_t err = growData(sizeof(val));
677         if (err != NO_ERROR) return err;
678     }
679     if (!enoughObjects) {
680         if (mObjectsSize > SIZE_MAX - 2) return NO_MEMORY; // overflow
681         if (mObjectsSize + 2 > SIZE_MAX / 3) return NO_MEMORY; // overflow
682         size_t newSize = ((mObjectsSize+2)*3)/2;
683         if (newSize > SIZE_MAX / sizeof(binder_size_t)) return NO_MEMORY; // overflow
684         binder_size_t* objects = (binder_size_t*)realloc(mObjects, newSize*sizeof(binder_size_t));
685         if (objects == nullptr) return NO_MEMORY;
686         mObjects = objects;
687         mObjectsCapacity = newSize;
688     }
689 
690     goto restart_write;
691 }
692 
693 template status_t Parcel::writeObject<flat_binder_object>(const flat_binder_object& val);
694 template status_t Parcel::writeObject<binder_fd_object>(const binder_fd_object& val);
695 template status_t Parcel::writeObject<binder_buffer_object>(const binder_buffer_object& val);
696 template status_t Parcel::writeObject<binder_fd_array_object>(const binder_fd_array_object& val);
697 
validateBufferChild(size_t child_buffer_handle,size_t child_offset) const698 bool Parcel::validateBufferChild(size_t child_buffer_handle,
699                                  size_t child_offset) const {
700     if (child_buffer_handle >= mObjectsSize)
701         return false;
702     binder_buffer_object *child = reinterpret_cast<binder_buffer_object*>
703             (mData + mObjects[child_buffer_handle]);
704     if (child->hdr.type != BINDER_TYPE_PTR || child_offset > child->length) {
705         // Parent object not a buffer, or not large enough
706         LOG_BUFFER("writeEmbeddedReference found weird child. "
707                    "child_offset = %zu, child->length = %zu",
708                    child_offset, (size_t)child->length);
709         return false;
710     }
711     return true;
712 }
713 
validateBufferParent(size_t parent_buffer_handle,size_t parent_offset) const714 bool Parcel::validateBufferParent(size_t parent_buffer_handle,
715                                   size_t parent_offset) const {
716     if (parent_buffer_handle >= mObjectsSize)
717         return false;
718     binder_buffer_object *parent = reinterpret_cast<binder_buffer_object*>
719             (mData + mObjects[parent_buffer_handle]);
720     if (parent->hdr.type != BINDER_TYPE_PTR ||
721             sizeof(binder_uintptr_t) > parent->length ||
722             parent_offset > parent->length - sizeof(binder_uintptr_t)) {
723         // Parent object not a buffer, or not large enough
724         return false;
725     }
726     return true;
727 }
writeEmbeddedBuffer(const void * buffer,size_t length,size_t * handle,size_t parent_buffer_handle,size_t parent_offset)728 status_t Parcel::writeEmbeddedBuffer(
729         const void *buffer, size_t length, size_t *handle,
730         size_t parent_buffer_handle, size_t parent_offset) {
731     LOG_BUFFER("writeEmbeddedBuffer(%p, %zu, parent = (%zu, %zu)) -> %zu",
732         buffer, length, parent_buffer_handle,
733          parent_offset, mObjectsSize);
734     if(!validateBufferParent(parent_buffer_handle, parent_offset))
735         return BAD_VALUE;
736     binder_buffer_object obj = {
737         .hdr = { .type = BINDER_TYPE_PTR },
738         .flags = BINDER_BUFFER_FLAG_HAS_PARENT,
739         .buffer = reinterpret_cast<binder_uintptr_t>(buffer),
740         .length = length,
741         .parent = parent_buffer_handle,
742         .parent_offset = parent_offset,
743     };
744     if (handle != nullptr) {
745         // We use an index into mObjects as a handle
746         *handle = mObjectsSize;
747     }
748     return writeObject(obj);
749 }
750 
writeBuffer(const void * buffer,size_t length,size_t * handle)751 status_t Parcel::writeBuffer(const void *buffer, size_t length, size_t *handle)
752 {
753     LOG_BUFFER("writeBuffer(%p, %zu) -> %zu",
754         buffer, length, mObjectsSize);
755     binder_buffer_object obj {
756         .hdr = { .type = BINDER_TYPE_PTR },
757         .flags = 0,
758         .buffer = reinterpret_cast<binder_uintptr_t>(buffer),
759         .length = length,
760     };
761     if (handle != nullptr) {
762         // We use an index into mObjects as a handle
763         *handle = mObjectsSize;
764     }
765     return writeObject(obj);
766 }
767 
clearCache() const768 void Parcel::clearCache() const {
769     LOG_BUFFER("clearing cache.");
770     mBufCachePos = 0;
771     mBufCache.clear();
772 }
773 
updateCache() const774 void Parcel::updateCache() const {
775     if(mBufCachePos == mObjectsSize)
776         return;
777     LOG_BUFFER("updating cache from %zu to %zu", mBufCachePos, mObjectsSize);
778     for(size_t i = mBufCachePos; i < mObjectsSize; i++) {
779         binder_size_t dataPos = mObjects[i];
780         binder_buffer_object *obj =
781             reinterpret_cast<binder_buffer_object*>(mData+dataPos);
782         if(obj->hdr.type != BINDER_TYPE_PTR)
783             continue;
784         BufferInfo ifo;
785         ifo.index = i;
786         ifo.buffer = obj->buffer;
787         ifo.bufend = obj->buffer + obj->length;
788         mBufCache.push_back(ifo);
789     }
790     mBufCachePos = mObjectsSize;
791 }
792 
793 /* O(n) (n=#buffers) to find a buffer that contains the given addr */
findBuffer(const void * ptr,size_t length,bool * found,size_t * handle,size_t * offset) const794 status_t Parcel::findBuffer(const void *ptr, size_t length, bool *found,
795                         size_t *handle, size_t *offset) const {
796     if(found == nullptr)
797         return UNKNOWN_ERROR;
798     updateCache();
799     binder_uintptr_t ptrVal = reinterpret_cast<binder_uintptr_t>(ptr);
800     // true if the pointer is in some buffer, but the length is too big
801     // so that ptr + length doesn't fit into the buffer.
802     bool suspectRejectBadPointer = false;
803     LOG_BUFFER("findBuffer examining %zu objects.", mObjectsSize);
804     for(auto entry = mBufCache.rbegin(); entry != mBufCache.rend(); ++entry ) {
805         if(entry->buffer <= ptrVal && ptrVal < entry->bufend) {
806             // might have found it.
807             if(ptrVal + length <= entry->bufend) {
808                 *found = true;
809                 if(handle != nullptr) *handle = entry->index;
810                 if(offset != nullptr) *offset = ptrVal - entry->buffer;
811                 LOG_BUFFER("    findBuffer has a match at %zu!", entry->index);
812                 return OK;
813             } else {
814                 suspectRejectBadPointer = true;
815             }
816         }
817     }
818     LOG_BUFFER("findBuffer did not find for ptr = %p.", ptr);
819     *found = false;
820     return suspectRejectBadPointer ? BAD_VALUE : OK;
821 }
822 
823 /* findBuffer with the assumption that ptr = .buffer (so it points to top
824  * of the buffer, aka offset 0).
825  *  */
quickFindBuffer(const void * ptr,size_t * handle) const826 status_t Parcel::quickFindBuffer(const void *ptr, size_t *handle) const {
827     updateCache();
828     binder_uintptr_t ptrVal = reinterpret_cast<binder_uintptr_t>(ptr);
829     LOG_BUFFER("quickFindBuffer examining %zu objects.", mObjectsSize);
830     for(auto entry = mBufCache.rbegin(); entry != mBufCache.rend(); ++entry ) {
831         if(entry->buffer == ptrVal) {
832             if(handle != nullptr) *handle = entry->index;
833             return OK;
834         }
835     }
836     LOG_BUFFER("quickFindBuffer did not find for ptr = %p.", ptr);
837     return NO_INIT;
838 }
839 
writeNativeHandleNoDup(const native_handle_t * handle,bool embedded,size_t parent_buffer_handle,size_t parent_offset)840 status_t Parcel::writeNativeHandleNoDup(const native_handle_t *handle,
841                                         bool embedded,
842                                         size_t parent_buffer_handle,
843                                         size_t parent_offset)
844 {
845     size_t buffer_handle;
846     status_t status = OK;
847 
848     if (handle == nullptr) {
849         status = writeUint64(0);
850         return status;
851     }
852 
853     size_t native_handle_size = sizeof(native_handle_t)
854                 + handle->numFds * sizeof(int) + handle->numInts * sizeof(int);
855     writeUint64(native_handle_size);
856 
857     if (embedded) {
858         status = writeEmbeddedBuffer((void*) handle,
859                 native_handle_size, &buffer_handle,
860                 parent_buffer_handle, parent_offset);
861     } else {
862         status = writeBuffer((void*) handle, native_handle_size, &buffer_handle);
863     }
864 
865     if (status != OK) {
866         return status;
867     }
868 
869     struct binder_fd_array_object fd_array {
870         .hdr = { .type = BINDER_TYPE_FDA },
871         .num_fds = static_cast<binder_size_t>(handle->numFds),
872         .parent = buffer_handle,
873         .parent_offset = offsetof(native_handle_t, data),
874     };
875 
876     return writeObject(fd_array);
877 }
878 
writeNativeHandleNoDup(const native_handle_t * handle)879 status_t Parcel::writeNativeHandleNoDup(const native_handle_t *handle)
880 {
881     return writeNativeHandleNoDup(handle, false /* embedded */);
882 }
883 
writeEmbeddedNativeHandle(const native_handle_t * handle,size_t parent_buffer_handle,size_t parent_offset)884 status_t Parcel::writeEmbeddedNativeHandle(const native_handle_t *handle,
885                                            size_t parent_buffer_handle,
886                                            size_t parent_offset)
887 {
888     return writeNativeHandleNoDup(handle, true /* embedded */,
889                                   parent_buffer_handle, parent_offset);
890 }
891 
read(void * outData,size_t len) const892 status_t Parcel::read(void* outData, size_t len) const
893 {
894     if (len > INT32_MAX) {
895         // don't accept size_t values which may have come from an
896         // inadvertent conversion from a negative int.
897         return BAD_VALUE;
898     }
899 
900     if ((mDataPos+pad_size(len)) >= mDataPos && (mDataPos+pad_size(len)) <= mDataSize
901             && len <= pad_size(len)) {
902         memcpy(outData, mData+mDataPos, len);
903         mDataPos += pad_size(len);
904         ALOGV("read Setting data pos of %p to %zu", this, mDataPos);
905         return NO_ERROR;
906     }
907     return NOT_ENOUGH_DATA;
908 }
909 
readInplace(size_t len) const910 const void* Parcel::readInplace(size_t len) const
911 {
912     if (len > INT32_MAX) {
913         // don't accept size_t values which may have come from an
914         // inadvertent conversion from a negative int.
915         return nullptr;
916     }
917 
918     if ((mDataPos+pad_size(len)) >= mDataPos && (mDataPos+pad_size(len)) <= mDataSize
919             && len <= pad_size(len)) {
920         const void* data = mData+mDataPos;
921         mDataPos += pad_size(len);
922         ALOGV("readInplace Setting data pos of %p to %zu", this, mDataPos);
923         return data;
924     }
925     return nullptr;
926 }
927 
928 template<class T>
readAligned(T * pArg) const929 status_t Parcel::readAligned(T *pArg) const {
930     static_assert(PAD_SIZE_UNSAFE(sizeof(T)) == sizeof(T));
931 
932     if ((mDataPos+sizeof(T)) <= mDataSize) {
933         const void* data = mData+mDataPos;
934         mDataPos += sizeof(T);
935         *pArg =  *reinterpret_cast<const T*>(data);
936         return NO_ERROR;
937     } else {
938         return NOT_ENOUGH_DATA;
939     }
940 }
941 
942 template<class T>
readAligned() const943 T Parcel::readAligned() const {
944     T result;
945     if (readAligned(&result) != NO_ERROR) {
946         result = 0;
947     }
948 
949     return result;
950 }
951 
952 template<class T>
writeAligned(T val)953 status_t Parcel::writeAligned(T val) {
954     static_assert(PAD_SIZE_UNSAFE(sizeof(T)) == sizeof(T));
955 
956     if ((mDataPos+sizeof(val)) <= mDataCapacity) {
957 restart_write:
958         *reinterpret_cast<T*>(mData+mDataPos) = val;
959         return finishWrite(sizeof(val));
960     }
961 
962     status_t err = growData(sizeof(val));
963     if (err == NO_ERROR) goto restart_write;
964     return err;
965 }
966 
readInt8(int8_t * pArg) const967 status_t Parcel::readInt8(int8_t *pArg) const
968 {
969     return read(pArg, sizeof(*pArg));
970 }
971 
readUint8(uint8_t * pArg) const972 status_t Parcel::readUint8(uint8_t *pArg) const
973 {
974     return read(pArg, sizeof(*pArg));
975 }
976 
readInt16(int16_t * pArg) const977 status_t Parcel::readInt16(int16_t *pArg) const
978 {
979     return read(pArg, sizeof(*pArg));
980 }
981 
readUint16(uint16_t * pArg) const982 status_t Parcel::readUint16(uint16_t *pArg) const
983 {
984     return read(pArg, sizeof(*pArg));
985 }
986 
readInt32(int32_t * pArg) const987 status_t Parcel::readInt32(int32_t *pArg) const
988 {
989     return readAligned(pArg);
990 }
991 
readInt32() const992 int32_t Parcel::readInt32() const
993 {
994     return readAligned<int32_t>();
995 }
996 
readUint32(uint32_t * pArg) const997 status_t Parcel::readUint32(uint32_t *pArg) const
998 {
999     return readAligned(pArg);
1000 }
1001 
readUint32() const1002 uint32_t Parcel::readUint32() const
1003 {
1004     return readAligned<uint32_t>();
1005 }
1006 
readInt64(int64_t * pArg) const1007 status_t Parcel::readInt64(int64_t *pArg) const
1008 {
1009     return readAligned(pArg);
1010 }
1011 
readInt64() const1012 int64_t Parcel::readInt64() const
1013 {
1014     return readAligned<int64_t>();
1015 }
1016 
readUint64(uint64_t * pArg) const1017 status_t Parcel::readUint64(uint64_t *pArg) const
1018 {
1019     return readAligned(pArg);
1020 }
1021 
readUint64() const1022 uint64_t Parcel::readUint64() const
1023 {
1024     return readAligned<uint64_t>();
1025 }
1026 
readPointer(uintptr_t * pArg) const1027 status_t Parcel::readPointer(uintptr_t *pArg) const
1028 {
1029     status_t ret;
1030     binder_uintptr_t ptr;
1031     ret = readAligned(&ptr);
1032     if (!ret)
1033         *pArg = ptr;
1034     return ret;
1035 }
1036 
readPointer() const1037 uintptr_t Parcel::readPointer() const
1038 {
1039     return readAligned<binder_uintptr_t>();
1040 }
1041 
1042 
readFloat(float * pArg) const1043 status_t Parcel::readFloat(float *pArg) const
1044 {
1045     return readAligned(pArg);
1046 }
1047 
1048 
readFloat() const1049 float Parcel::readFloat() const
1050 {
1051     return readAligned<float>();
1052 }
1053 
1054 #if defined(__mips__) && defined(__mips_hard_float)
1055 
readDouble(double * pArg) const1056 status_t Parcel::readDouble(double *pArg) const
1057 {
1058     union {
1059       double d;
1060       unsigned long long ll;
1061     } u;
1062     u.d = 0;
1063     status_t status;
1064     status = readAligned(&u.ll);
1065     *pArg = u.d;
1066     return status;
1067 }
1068 
readDouble() const1069 double Parcel::readDouble() const
1070 {
1071     union {
1072       double d;
1073       unsigned long long ll;
1074     } u;
1075     u.ll = readAligned<unsigned long long>();
1076     return u.d;
1077 }
1078 
1079 #else
1080 
readDouble(double * pArg) const1081 status_t Parcel::readDouble(double *pArg) const
1082 {
1083     return readAligned(pArg);
1084 }
1085 
readDouble() const1086 double Parcel::readDouble() const
1087 {
1088     return readAligned<double>();
1089 }
1090 
1091 #endif
1092 
readBool(bool * pArg) const1093 status_t Parcel::readBool(bool *pArg) const
1094 {
1095     int8_t tmp;
1096     status_t ret = readInt8(&tmp);
1097     *pArg = (tmp != 0);
1098     return ret;
1099 }
1100 
readBool() const1101 bool Parcel::readBool() const
1102 {
1103     int8_t tmp;
1104     status_t err = readInt8(&tmp);
1105 
1106     if (err != OK) {
1107         return 0;
1108     }
1109 
1110     return tmp != 0;
1111 }
1112 
readCString() const1113 const char* Parcel::readCString() const
1114 {
1115     if (mDataPos < mDataSize) {
1116         const size_t avail = mDataSize-mDataPos;
1117         const char* str = reinterpret_cast<const char*>(mData+mDataPos);
1118         // is the string's trailing NUL within the parcel's valid bounds?
1119         const char* eos = reinterpret_cast<const char*>(memchr(str, 0, avail));
1120         if (eos) {
1121             const size_t len = eos - str;
1122             mDataPos += pad_size(len+1);
1123             ALOGV("readCString Setting data pos of %p to %zu", this, mDataPos);
1124             return str;
1125         }
1126     }
1127     return nullptr;
1128 }
readString16() const1129 String16 Parcel::readString16() const
1130 {
1131     size_t len;
1132     const char16_t* str = readString16Inplace(&len);
1133     if (str) return String16(str, len);
1134     ALOGE("Reading a NULL string not supported here.");
1135     return String16();
1136 }
1137 
readString16(std::unique_ptr<String16> * pArg) const1138 status_t Parcel::readString16(std::unique_ptr<String16>* pArg) const
1139 {
1140     const int32_t start = dataPosition();
1141     int32_t size;
1142     status_t status = readInt32(&size);
1143     pArg->reset();
1144 
1145     if (status != OK || size < 0) {
1146         return status;
1147     }
1148 
1149     setDataPosition(start);
1150     pArg->reset(new (std::nothrow) String16());
1151 
1152     status = readString16(pArg->get());
1153 
1154     if (status != OK) {
1155         pArg->reset();
1156     }
1157 
1158     return status;
1159 }
1160 
readString16(String16 * pArg) const1161 status_t Parcel::readString16(String16* pArg) const
1162 {
1163     size_t len;
1164     const char16_t* str = readString16Inplace(&len);
1165     if (str) {
1166         pArg->setTo(str, len);
1167         return 0;
1168     } else {
1169         *pArg = String16();
1170         return UNEXPECTED_NULL;
1171     }
1172 }
1173 
readString16Inplace(size_t * outLen) const1174 const char16_t* Parcel::readString16Inplace(size_t* outLen) const
1175 {
1176     int32_t size = readInt32();
1177     // watch for potential int overflow from size+1
1178     if (size >= 0 && size < INT32_MAX) {
1179         *outLen = size;
1180         const char16_t* str = (const char16_t*)readInplace((size+1)*sizeof(char16_t));
1181         if (str != nullptr) {
1182             return str;
1183         }
1184     }
1185     *outLen = 0;
1186     return nullptr;
1187 }
readStrongBinder(sp<IBinder> * val) const1188 status_t Parcel::readStrongBinder(sp<IBinder>* val) const
1189 {
1190     status_t status = readNullableStrongBinder(val);
1191     if (status == OK && !val->get()) {
1192         status = UNEXPECTED_NULL;
1193     }
1194     return status;
1195 }
1196 
readNullableStrongBinder(sp<IBinder> * val) const1197 status_t Parcel::readNullableStrongBinder(sp<IBinder>* val) const
1198 {
1199     return unflatten_binder(ProcessState::self(), *this, val);
1200 }
1201 
readStrongBinder() const1202 sp<IBinder> Parcel::readStrongBinder() const
1203 {
1204     sp<IBinder> val;
1205     // Note that a lot of code in Android reads binders by hand with this
1206     // method, and that code has historically been ok with getting nullptr
1207     // back (while ignoring error codes).
1208     readNullableStrongBinder(&val);
1209     return val;
1210 }
1211 
1212 template<typename T>
readObject(size_t * objects_offset) const1213 const T* Parcel::readObject(size_t *objects_offset) const
1214 {
1215     const size_t DPOS = mDataPos;
1216     if (objects_offset != nullptr) {
1217         *objects_offset = 0;
1218     }
1219 
1220     if ((DPOS+sizeof(T)) <= mDataSize) {
1221         const T* obj = reinterpret_cast<const T*>(mData+DPOS);
1222         mDataPos = DPOS + sizeof(T);
1223         const binder_object_header *hdr = reinterpret_cast<const binder_object_header*>(obj);
1224         switch (hdr->type) {
1225             case BINDER_TYPE_BINDER:
1226             case BINDER_TYPE_WEAK_BINDER:
1227             case BINDER_TYPE_HANDLE:
1228             case BINDER_TYPE_WEAK_HANDLE: {
1229                 const flat_binder_object *flat_obj =
1230                     reinterpret_cast<const flat_binder_object*>(hdr);
1231                 if (flat_obj->cookie == 0 && flat_obj->binder == 0) {
1232                     // When transferring a NULL binder object, we don't write it into
1233                     // the object list, so we don't want to check for it when
1234                     // reading.
1235                     ALOGV("readObject Setting data pos of %p to %zu", this, mDataPos);
1236                     return obj;
1237                 }
1238                 break;
1239             }
1240             case BINDER_TYPE_FD:
1241             case BINDER_TYPE_FDA:
1242                 // fd (-arrays) must always appear in the meta-data list (eg touched by the kernel)
1243                 break;
1244             case BINDER_TYPE_PTR: {
1245                 const binder_buffer_object *buffer_obj =
1246                     reinterpret_cast<const binder_buffer_object*>(hdr);
1247                 if ((void *)buffer_obj->buffer == nullptr) {
1248                     // null pointers can be returned directly - they're not written in the
1249                     // object list. All non-null buffers must appear in the objects list.
1250                     return obj;
1251                 }
1252                 break;
1253             }
1254         }
1255         // Ensure that this object is valid...
1256         binder_size_t* const OBJS = mObjects;
1257         const size_t N = mObjectsSize;
1258         size_t opos = mNextObjectHint;
1259 
1260         if (N > 0) {
1261             ALOGV("Parcel %p looking for obj at %zu, hint=%zu",
1262                  this, DPOS, opos);
1263 
1264             // Start at the current hint position, looking for an object at
1265             // the current data position.
1266             if (opos < N) {
1267                 while (opos < (N-1) && OBJS[opos] < DPOS) {
1268                     opos++;
1269                 }
1270             } else {
1271                 opos = N-1;
1272             }
1273             if (OBJS[opos] == DPOS) {
1274                 // Found it!
1275                 ALOGV("Parcel %p found obj %zu at index %zu with forward search",
1276                      this, DPOS, opos);
1277                 mNextObjectHint = opos+1;
1278                 ALOGV("readObject Setting data pos of %p to %zu", this, mDataPos);
1279                 if (objects_offset != nullptr) {
1280                     *objects_offset = opos;
1281                 }
1282                 return obj;
1283             }
1284 
1285             // Look backwards for it...
1286             while (opos > 0 && OBJS[opos] > DPOS) {
1287                 opos--;
1288             }
1289             if (OBJS[opos] == DPOS) {
1290                 // Found it!
1291                 ALOGV("Parcel %p found obj %zu at index %zu with backward search",
1292                      this, DPOS, opos);
1293                 mNextObjectHint = opos+1;
1294                 ALOGV("readObject Setting data pos of %p to %zu", this, mDataPos);
1295                 if (objects_offset != nullptr) {
1296                     *objects_offset = opos;
1297                 }
1298                 return obj;
1299             }
1300         }
1301         ALOGW("Attempt to read object from Parcel %p at offset %zu that is not in the object list",
1302              this, DPOS);
1303     }
1304     return nullptr;
1305 }
1306 
1307 template const flat_binder_object* Parcel::readObject<flat_binder_object>(size_t *objects_offset) const;
1308 
1309 template const binder_fd_object* Parcel::readObject<binder_fd_object>(size_t *objects_offset) const;
1310 
1311 template const binder_buffer_object* Parcel::readObject<binder_buffer_object>(size_t *objects_offset) const;
1312 
1313 template const binder_fd_array_object* Parcel::readObject<binder_fd_array_object>(size_t *objects_offset) const;
1314 
verifyBufferObject(const binder_buffer_object * buffer_obj,size_t size,uint32_t flags,size_t parent,size_t parentOffset) const1315 bool Parcel::verifyBufferObject(const binder_buffer_object *buffer_obj,
1316                                 size_t size, uint32_t flags, size_t parent,
1317                                 size_t parentOffset) const {
1318     if (buffer_obj->length != size) {
1319         ALOGE("Buffer length %" PRIu64 " does not match expected size %zu.",
1320               static_cast<uint64_t>(buffer_obj->length), size);
1321         return false;
1322     }
1323 
1324     if (buffer_obj->flags != flags) {
1325         ALOGE("Buffer flags 0x%02X do not match expected flags 0x%02X.", buffer_obj->flags, flags);
1326         return false;
1327     }
1328 
1329     if (flags & BINDER_BUFFER_FLAG_HAS_PARENT) {
1330         if (buffer_obj->parent != parent) {
1331             ALOGE("Buffer parent %" PRIu64 " does not match expected parent %zu.",
1332                   static_cast<uint64_t>(buffer_obj->parent), parent);
1333             return false;
1334         }
1335         if (buffer_obj->parent_offset != parentOffset) {
1336               ALOGE("Buffer parent offset %" PRIu64 " does not match expected offset %zu.",
1337                   static_cast<uint64_t>(buffer_obj->parent_offset), parentOffset);
1338             return false;
1339         }
1340 
1341         binder_buffer_object *parentBuffer =
1342             reinterpret_cast<binder_buffer_object*>(mData + mObjects[parent]);
1343         void* bufferInParent = *reinterpret_cast<void**>(
1344             reinterpret_cast<uint8_t*>(parentBuffer->buffer) + parentOffset);
1345         void* childBuffer = reinterpret_cast<void*>(buffer_obj->buffer);
1346 
1347         if (bufferInParent != childBuffer) {
1348               ALOGE("Buffer in parent %p differs from embedded buffer %p",
1349                     bufferInParent, childBuffer);
1350               android_errorWriteLog(0x534e4554, "179289794");
1351               return false;
1352         }
1353     }
1354 
1355     return true;
1356 }
1357 
readBuffer(size_t buffer_size,size_t * buffer_handle,uint32_t flags,size_t parent,size_t parentOffset,const void ** buffer_out) const1358 status_t Parcel::readBuffer(size_t buffer_size, size_t *buffer_handle,
1359                             uint32_t flags, size_t parent, size_t parentOffset,
1360                             const void **buffer_out) const {
1361 
1362     const binder_buffer_object* buffer_obj = readObject<binder_buffer_object>(buffer_handle);
1363 
1364     if (buffer_obj == nullptr || buffer_obj->hdr.type != BINDER_TYPE_PTR) {
1365         return BAD_VALUE;
1366     }
1367 
1368     if (!verifyBufferObject(buffer_obj, buffer_size, flags, parent, parentOffset)) {
1369         return BAD_VALUE;
1370     }
1371 
1372     // in read side, always use .buffer and .length.
1373     *buffer_out = reinterpret_cast<void*>(buffer_obj->buffer);
1374 
1375     return OK;
1376 }
1377 
readNullableBuffer(size_t buffer_size,size_t * buffer_handle,const void ** buffer_out) const1378 status_t Parcel::readNullableBuffer(size_t buffer_size, size_t *buffer_handle,
1379                                     const void **buffer_out) const
1380 {
1381     return readBuffer(buffer_size, buffer_handle,
1382                       0 /* flags */, 0 /* parent */, 0 /* parentOffset */,
1383                       buffer_out);
1384 }
1385 
readBuffer(size_t buffer_size,size_t * buffer_handle,const void ** buffer_out) const1386 status_t Parcel::readBuffer(size_t buffer_size, size_t *buffer_handle,
1387                             const void **buffer_out) const
1388 {
1389     status_t status = readNullableBuffer(buffer_size, buffer_handle, buffer_out);
1390     if (status == OK && *buffer_out == nullptr) {
1391         return UNEXPECTED_NULL;
1392     }
1393     return status;
1394 }
1395 
1396 
readEmbeddedBuffer(size_t buffer_size,size_t * buffer_handle,size_t parent_buffer_handle,size_t parent_offset,const void ** buffer_out) const1397 status_t Parcel::readEmbeddedBuffer(size_t buffer_size,
1398                                     size_t *buffer_handle,
1399                                     size_t parent_buffer_handle,
1400                                     size_t parent_offset,
1401                                     const void **buffer_out) const
1402 {
1403     status_t status = readNullableEmbeddedBuffer(buffer_size, buffer_handle,
1404                                                  parent_buffer_handle,
1405                                                  parent_offset, buffer_out);
1406     if (status == OK && *buffer_out == nullptr) {
1407         return UNEXPECTED_NULL;
1408     }
1409     return status;
1410 }
1411 
readNullableEmbeddedBuffer(size_t buffer_size,size_t * buffer_handle,size_t parent_buffer_handle,size_t parent_offset,const void ** buffer_out) const1412 status_t Parcel::readNullableEmbeddedBuffer(size_t buffer_size,
1413                                             size_t *buffer_handle,
1414                                             size_t parent_buffer_handle,
1415                                             size_t parent_offset,
1416                                             const void **buffer_out) const
1417 {
1418     return readBuffer(buffer_size, buffer_handle, BINDER_BUFFER_FLAG_HAS_PARENT,
1419                       parent_buffer_handle, parent_offset, buffer_out);
1420 }
1421 
readEmbeddedNativeHandle(size_t parent_buffer_handle,size_t parent_offset,const native_handle_t ** handle) const1422 status_t Parcel::readEmbeddedNativeHandle(size_t parent_buffer_handle,
1423                                           size_t parent_offset,
1424                                           const native_handle_t **handle) const
1425 {
1426     status_t status = readNullableEmbeddedNativeHandle(parent_buffer_handle, parent_offset, handle);
1427     if (status == OK && *handle == nullptr) {
1428         return UNEXPECTED_NULL;
1429     }
1430     return status;
1431 }
1432 
readNullableNativeHandleNoDup(const native_handle_t ** handle,bool embedded,size_t parent_buffer_handle,size_t parent_offset) const1433 status_t Parcel::readNullableNativeHandleNoDup(const native_handle_t **handle,
1434                                                bool embedded,
1435                                                size_t parent_buffer_handle,
1436                                                size_t parent_offset) const
1437 {
1438     uint64_t nativeHandleSize;
1439     status_t status = readUint64(&nativeHandleSize);
1440     if (status != OK) {
1441         return BAD_VALUE;
1442     }
1443 
1444     if (nativeHandleSize == 0) {
1445         // If !embedded, then parent_* vars are 0 and don't actually correspond
1446         // to anything. In that case, we're actually reading this data into
1447         // writable memory, and the handle returned from here will actually be
1448         // used (rather than be ignored).
1449         if (embedded) {
1450             binder_buffer_object *parentBuffer =
1451                 reinterpret_cast<binder_buffer_object*>(mData + mObjects[parent_buffer_handle]);
1452 
1453             void* bufferInParent = *reinterpret_cast<void**>(
1454                 reinterpret_cast<uint8_t*>(parentBuffer->buffer) + parent_offset);
1455 
1456             if (bufferInParent != nullptr) {
1457                   ALOGE("Buffer in (handle) parent %p is not nullptr.", bufferInParent);
1458                   android_errorWriteLog(0x534e4554, "179289794");
1459                   return BAD_VALUE;
1460             }
1461         }
1462 
1463         *handle = nullptr;
1464         return status;
1465     }
1466 
1467     if (nativeHandleSize < sizeof(native_handle_t)) {
1468         ALOGE("Received a native_handle_t size that was too small.");
1469         return BAD_VALUE;
1470     }
1471 
1472     size_t fdaParent;
1473     if (embedded) {
1474         status = readNullableEmbeddedBuffer(nativeHandleSize, &fdaParent,
1475                                             parent_buffer_handle, parent_offset,
1476                                             reinterpret_cast<const void**>(handle));
1477     } else {
1478         status = readNullableBuffer(nativeHandleSize, &fdaParent,
1479                                     reinterpret_cast<const void**>(handle));
1480     }
1481 
1482     if (status != OK) {
1483         return status;
1484     }
1485 
1486     if (*handle == nullptr) {
1487         // null handle already read above
1488         ALOGE("Expecting non-null handle buffer");
1489         return BAD_VALUE;
1490     }
1491 
1492     int numFds = (*handle)->numFds;
1493     int numInts = (*handle)->numInts;
1494 
1495     if (numFds < 0 || numFds > NATIVE_HANDLE_MAX_FDS) {
1496         ALOGE("Received native_handle with invalid number of fds.");
1497         return BAD_VALUE;
1498     }
1499 
1500     if (numInts < 0 || numInts > NATIVE_HANDLE_MAX_INTS) {
1501         ALOGE("Received native_handle with invalid number of ints.");
1502         return BAD_VALUE;
1503     }
1504 
1505     if (nativeHandleSize != (sizeof(native_handle_t) + ((numFds + numInts) * sizeof(int)))) {
1506         ALOGE("Size of native_handle doesn't match.");
1507         return BAD_VALUE;
1508     }
1509 
1510     const binder_fd_array_object* fd_array_obj = readObject<binder_fd_array_object>();
1511 
1512     if (fd_array_obj == nullptr || fd_array_obj->hdr.type != BINDER_TYPE_FDA) {
1513         ALOGE("Can't find file-descriptor array object.");
1514         return BAD_VALUE;
1515     }
1516 
1517     if (static_cast<int>(fd_array_obj->num_fds) != numFds) {
1518         ALOGE("Number of native handles does not match.");
1519         return BAD_VALUE;
1520     }
1521 
1522     if (fd_array_obj->parent != fdaParent) {
1523         ALOGE("Parent handle of file-descriptor array not correct.");
1524         return BAD_VALUE;
1525     }
1526 
1527     if (fd_array_obj->parent_offset != offsetof(native_handle_t, data)) {
1528         ALOGE("FD array object not properly offset in parent.");
1529         return BAD_VALUE;
1530     }
1531 
1532     return OK;
1533 }
1534 
readNullableEmbeddedNativeHandle(size_t parent_buffer_handle,size_t parent_offset,const native_handle_t ** handle) const1535 status_t Parcel::readNullableEmbeddedNativeHandle(size_t parent_buffer_handle,
1536                                                   size_t parent_offset,
1537                                                   const native_handle_t **handle) const
1538 {
1539     return readNullableNativeHandleNoDup(handle, true /* embedded */, parent_buffer_handle,
1540                                          parent_offset);
1541 }
1542 
readNativeHandleNoDup(const native_handle_t ** handle) const1543 status_t Parcel::readNativeHandleNoDup(const native_handle_t **handle) const
1544 {
1545     status_t status = readNullableNativeHandleNoDup(handle);
1546     if (status == OK && *handle == nullptr) {
1547         return UNEXPECTED_NULL;
1548     }
1549     return status;
1550 }
1551 
readNullableNativeHandleNoDup(const native_handle_t ** handle) const1552 status_t Parcel::readNullableNativeHandleNoDup(const native_handle_t **handle) const
1553 {
1554     return readNullableNativeHandleNoDup(handle, false /* embedded */);
1555 }
1556 
closeFileDescriptors()1557 void Parcel::closeFileDescriptors()
1558 {
1559     size_t i = mObjectsSize;
1560     if (i > 0) {
1561         //ALOGI("Closing file descriptors for %zu objects...", i);
1562     }
1563     while (i > 0) {
1564         i--;
1565         const flat_binder_object* flat
1566             = reinterpret_cast<flat_binder_object*>(mData+mObjects[i]);
1567         if (flat->hdr.type == BINDER_TYPE_FD) {
1568             //ALOGI("Closing fd: %ld", flat->handle);
1569             close(flat->handle);
1570         }
1571     }
1572 }
1573 
ipcData() const1574 uintptr_t Parcel::ipcData() const
1575 {
1576     return reinterpret_cast<uintptr_t>(mData);
1577 }
1578 
ipcDataSize() const1579 size_t Parcel::ipcDataSize() const
1580 {
1581     return mDataSize > mDataPos ? mDataSize : mDataPos;
1582 }
1583 
ipcObjects() const1584 uintptr_t Parcel::ipcObjects() const
1585 {
1586     return reinterpret_cast<uintptr_t>(mObjects);
1587 }
1588 
ipcObjectsCount() const1589 size_t Parcel::ipcObjectsCount() const
1590 {
1591     return mObjectsSize;
1592 }
1593 
1594 #define BUFFER_ALIGNMENT_BYTES 8
ipcBufferSize() const1595 size_t Parcel::ipcBufferSize() const
1596 {
1597     size_t totalBuffersSize = 0;
1598     // Add size for BINDER_TYPE_PTR
1599     size_t i = mObjectsSize;
1600     while (i > 0) {
1601         i--;
1602         const binder_buffer_object* buffer
1603             = reinterpret_cast<binder_buffer_object*>(mData+mObjects[i]);
1604         if (buffer->hdr.type == BINDER_TYPE_PTR) {
1605             /* The binder kernel driver requires each buffer to be 8-byte
1606              * aligned */
1607             size_t alignedSize = (buffer->length + (BUFFER_ALIGNMENT_BYTES - 1))
1608                     & ~(BUFFER_ALIGNMENT_BYTES - 1);
1609             if (alignedSize > SIZE_MAX - totalBuffersSize) {
1610                 ALOGE("ipcBuffersSize(): invalid buffer sizes.");
1611                 return 0;
1612             }
1613             totalBuffersSize += alignedSize;
1614         }
1615     }
1616     return totalBuffersSize;
1617 }
1618 
ipcSetDataReference(const uint8_t * data,size_t dataSize,const binder_size_t * objects,size_t objectsCount,release_func relFunc,void * relCookie)1619 void Parcel::ipcSetDataReference(const uint8_t* data, size_t dataSize,
1620     const binder_size_t* objects, size_t objectsCount, release_func relFunc, void* relCookie)
1621 {
1622     binder_size_t minOffset = 0;
1623     freeDataNoInit();
1624     mError = NO_ERROR;
1625     mData = const_cast<uint8_t*>(data);
1626     mDataSize = mDataCapacity = dataSize;
1627     //ALOGI("setDataReference Setting data size of %p to %lu (pid=%d)", this, mDataSize, getpid());
1628     mDataPos = 0;
1629     ALOGV("setDataReference Setting data pos of %p to %zu", this, mDataPos);
1630     mObjects = const_cast<binder_size_t*>(objects);
1631     mObjectsSize = mObjectsCapacity = objectsCount;
1632     mNextObjectHint = 0;
1633     clearCache();
1634     mOwner = relFunc;
1635     mOwnerCookie = relCookie;
1636     for (size_t i = 0; i < mObjectsSize; i++) {
1637         binder_size_t offset = mObjects[i];
1638         if (offset < minOffset) {
1639             ALOGE("%s: bad object offset %" PRIu64 " < %" PRIu64 "\n",
1640                   __func__, (uint64_t)offset, (uint64_t)minOffset);
1641             mObjectsSize = 0;
1642             break;
1643         }
1644         minOffset = offset + sizeof(flat_binder_object);
1645     }
1646     scanForFds();
1647 }
1648 
print(TextOutput & to,uint32_t) const1649 void Parcel::print(TextOutput& to, uint32_t /*flags*/) const
1650 {
1651     to << "Parcel(";
1652 
1653     if (errorCheck() != NO_ERROR) {
1654         const status_t err = errorCheck();
1655         to << "Error: " << (void*)(intptr_t)err << " \"" << strerror(-err) << "\"";
1656     } else if (dataSize() > 0) {
1657         const uint8_t* DATA = data();
1658         to << indent << HexDump(DATA, dataSize()) << dedent;
1659         const binder_size_t* OBJS = objects();
1660         const size_t N = objectsCount();
1661         for (size_t i=0; i<N; i++) {
1662             const flat_binder_object* flat
1663                 = reinterpret_cast<const flat_binder_object*>(DATA+OBJS[i]);
1664             if (flat->hdr.type == BINDER_TYPE_PTR) {
1665                 const binder_buffer_object* buffer
1666                     = reinterpret_cast<const binder_buffer_object*>(DATA+OBJS[i]);
1667                 HexDump bufferDump((const uint8_t*)buffer->buffer, (size_t)buffer->length);
1668                 bufferDump.setSingleLineCutoff(0);
1669                 to << endl << "Object #" << i << " @ " << (void*)OBJS[i] << " (buffer size " << buffer->length << "):";
1670                 to << indent << bufferDump << dedent;
1671             } else {
1672                 to << endl << "Object #" << i << " @ " << (void*)OBJS[i] << ": "
1673                     << TypeCode(flat->hdr.type & 0x7f7f7f00)
1674                     << " = " << flat->binder;
1675             }
1676         }
1677     } else {
1678         to << "NULL";
1679     }
1680 
1681     to << ")";
1682 }
1683 
releaseObjects()1684 void Parcel::releaseObjects()
1685 {
1686     const sp<ProcessState> proc(ProcessState::self());
1687     size_t i = mObjectsSize;
1688     uint8_t* const data = mData;
1689     binder_size_t* const objects = mObjects;
1690     while (i > 0) {
1691         i--;
1692         const flat_binder_object* flat
1693             = reinterpret_cast<flat_binder_object*>(data+objects[i]);
1694         release_object(proc, *flat, this);
1695     }
1696 }
1697 
acquireObjects()1698 void Parcel::acquireObjects()
1699 {
1700     const sp<ProcessState> proc(ProcessState::self());
1701     size_t i = mObjectsSize;
1702     uint8_t* const data = mData;
1703     binder_size_t* const objects = mObjects;
1704     while (i > 0) {
1705         i--;
1706         const binder_object_header* flat
1707             = reinterpret_cast<binder_object_header*>(data+objects[i]);
1708         acquire_object(proc, *flat, this);
1709     }
1710 }
1711 
freeData()1712 void Parcel::freeData()
1713 {
1714     freeDataNoInit();
1715     initState();
1716 }
1717 
freeDataNoInit()1718 void Parcel::freeDataNoInit()
1719 {
1720     if (mOwner) {
1721         LOG_ALLOC("Parcel %p: freeing other owner data", this);
1722         //ALOGI("Freeing data ref of %p (pid=%d)", this, getpid());
1723         mOwner(this, mData, mDataSize, mObjects, mObjectsSize, mOwnerCookie);
1724     } else {
1725         LOG_ALLOC("Parcel %p: freeing allocated data", this);
1726         releaseObjects();
1727         if (mData) {
1728             LOG_ALLOC("Parcel %p: freeing with %zu capacity", this, mDataCapacity);
1729             gParcelGlobalAllocSize -= mDataCapacity;
1730             gParcelGlobalAllocCount--;
1731             if (mDeallocZero) {
1732                 zeroMemory(mData, mDataSize);
1733             }
1734             free(mData);
1735         }
1736         if (mObjects) free(mObjects);
1737     }
1738 }
1739 
growData(size_t len)1740 status_t Parcel::growData(size_t len)
1741 {
1742     if (len > INT32_MAX) {
1743         // don't accept size_t values which may have come from an
1744         // inadvertent conversion from a negative int.
1745         return BAD_VALUE;
1746     }
1747     if (len > SIZE_MAX - mDataSize) return NO_MEMORY; // overflow
1748     if (mDataSize + len > SIZE_MAX / 3) return NO_MEMORY; // overflow
1749     size_t newSize = ((mDataSize+len)*3)/2;
1750     return continueWrite(newSize);
1751 }
1752 
reallocZeroFree(uint8_t * data,size_t oldCapacity,size_t newCapacity,bool zero)1753 static uint8_t* reallocZeroFree(uint8_t* data, size_t oldCapacity, size_t newCapacity, bool zero) {
1754     if (!zero) {
1755         return (uint8_t*)realloc(data, newCapacity);
1756     }
1757     uint8_t* newData = (uint8_t*)malloc(newCapacity);
1758     if (!newData) {
1759         return nullptr;
1760     }
1761 
1762     memcpy(newData, data, std::min(oldCapacity, newCapacity));
1763     zeroMemory(data, oldCapacity);
1764     free(data);
1765     return newData;
1766 }
1767 
restartWrite(size_t desired)1768 status_t Parcel::restartWrite(size_t desired)
1769 {
1770     if (desired > INT32_MAX) {
1771         // don't accept size_t values which may have come from an
1772         // inadvertent conversion from a negative int.
1773         return BAD_VALUE;
1774     }
1775 
1776     if (mOwner) {
1777         freeData();
1778         return continueWrite(desired);
1779     }
1780 
1781     uint8_t* data = reallocZeroFree(mData, mDataCapacity, desired, mDeallocZero);
1782     if (!data && desired > mDataCapacity) {
1783         mError = NO_MEMORY;
1784         return NO_MEMORY;
1785     }
1786 
1787     releaseObjects();
1788 
1789     if (data || desired == 0) {
1790         LOG_ALLOC("Parcel %p: restart from %zu to %zu capacity", this, mDataCapacity, desired);
1791         if (mDataCapacity > desired) {
1792             gParcelGlobalAllocSize -= (mDataCapacity - desired);
1793         } else {
1794             gParcelGlobalAllocSize += (desired - mDataCapacity);
1795         }
1796 
1797         if (!mData) {
1798             gParcelGlobalAllocCount++;
1799         }
1800         mData = data;
1801         mDataCapacity = desired;
1802     }
1803 
1804     mDataSize = mDataPos = 0;
1805     ALOGV("restartWrite Setting data size of %p to %zu", this, mDataSize);
1806     ALOGV("restartWrite Setting data pos of %p to %zu", this, mDataPos);
1807 
1808     free(mObjects);
1809     mObjects = nullptr;
1810     mObjectsSize = mObjectsCapacity = 0;
1811     mNextObjectHint = 0;
1812     mHasFds = false;
1813     clearCache();
1814     mFdsKnown = true;
1815     mAllowFds = true;
1816 
1817     return NO_ERROR;
1818 }
1819 
continueWrite(size_t desired)1820 status_t Parcel::continueWrite(size_t desired)
1821 {
1822     if (desired > INT32_MAX) {
1823         // don't accept size_t values which may have come from an
1824         // inadvertent conversion from a negative int.
1825         return BAD_VALUE;
1826     }
1827 
1828     // If shrinking, first adjust for any objects that appear
1829     // after the new data size.
1830     size_t objectsSize = mObjectsSize;
1831     if (desired < mDataSize) {
1832         if (desired == 0) {
1833             objectsSize = 0;
1834         } else {
1835             while (objectsSize > 0) {
1836                 if (mObjects[objectsSize-1] < desired)
1837                     break;
1838                 objectsSize--;
1839             }
1840         }
1841     }
1842 
1843     if (mOwner) {
1844         // If the size is going to zero, just release the owner's data.
1845         if (desired == 0) {
1846             freeData();
1847             return NO_ERROR;
1848         }
1849 
1850         // If there is a different owner, we need to take
1851         // posession.
1852         uint8_t* data = (uint8_t*)malloc(desired);
1853         if (!data) {
1854             mError = NO_MEMORY;
1855             return NO_MEMORY;
1856         }
1857         binder_size_t* objects = nullptr;
1858 
1859         if (objectsSize) {
1860             objects = (binder_size_t*)calloc(objectsSize, sizeof(binder_size_t));
1861             if (!objects) {
1862                 free(data);
1863 
1864                 mError = NO_MEMORY;
1865                 return NO_MEMORY;
1866             }
1867 
1868             // Little hack to only acquire references on objects
1869             // we will be keeping.
1870             size_t oldObjectsSize = mObjectsSize;
1871             mObjectsSize = objectsSize;
1872             acquireObjects();
1873             mObjectsSize = oldObjectsSize;
1874         }
1875 
1876         if (mData) {
1877             memcpy(data, mData, mDataSize < desired ? mDataSize : desired);
1878         }
1879         if (objects && mObjects) {
1880             memcpy(objects, mObjects, objectsSize*sizeof(binder_size_t));
1881         }
1882         //ALOGI("Freeing data ref of %p (pid=%d)", this, getpid());
1883         mOwner(this, mData, mDataSize, mObjects, mObjectsSize, mOwnerCookie);
1884         mOwner = nullptr;
1885 
1886         LOG_ALLOC("Parcel %p: taking ownership of %zu capacity", this, desired);
1887         gParcelGlobalAllocSize += desired;
1888         gParcelGlobalAllocCount++;
1889 
1890         mData = data;
1891         mObjects = objects;
1892         mDataSize = (mDataSize < desired) ? mDataSize : desired;
1893         ALOGV("continueWrite Setting data size of %p to %zu", this, mDataSize);
1894         mDataCapacity = desired;
1895         mObjectsSize = mObjectsCapacity = objectsSize;
1896         mNextObjectHint = 0;
1897 
1898         clearCache();
1899     } else if (mData) {
1900         if (objectsSize < mObjectsSize) {
1901             // Need to release refs on any objects we are dropping.
1902             const sp<ProcessState> proc(ProcessState::self());
1903             for (size_t i=objectsSize; i<mObjectsSize; i++) {
1904                 const flat_binder_object* flat
1905                     = reinterpret_cast<flat_binder_object*>(mData+mObjects[i]);
1906                 if (flat->hdr.type == BINDER_TYPE_FD) {
1907                     // will need to rescan because we may have lopped off the only FDs
1908                     mFdsKnown = false;
1909                 }
1910                 release_object(proc, *flat, this);
1911             }
1912 
1913             if (objectsSize == 0) {
1914                 free(mObjects);
1915                 mObjects = nullptr;
1916             } else {
1917                 binder_size_t* objects =
1918                     (binder_size_t*)realloc(mObjects, objectsSize*sizeof(binder_size_t));
1919                 if (objects) {
1920                     mObjects = objects;
1921                 }
1922             }
1923             mObjectsSize = objectsSize;
1924             mNextObjectHint = 0;
1925 
1926             clearCache();
1927         }
1928 
1929         // We own the data, so we can just do a realloc().
1930         if (desired > mDataCapacity) {
1931             uint8_t* data = reallocZeroFree(mData, mDataCapacity, desired, mDeallocZero);
1932             if (data) {
1933                 LOG_ALLOC("Parcel %p: continue from %zu to %zu capacity", this, mDataCapacity,
1934                         desired);
1935                 gParcelGlobalAllocSize += desired;
1936                 gParcelGlobalAllocSize -= mDataCapacity;
1937                 mData = data;
1938                 mDataCapacity = desired;
1939             } else {
1940                 mError = NO_MEMORY;
1941                 return NO_MEMORY;
1942             }
1943         } else {
1944             if (mDataSize > desired) {
1945                 mDataSize = desired;
1946                 ALOGV("continueWrite Setting data size of %p to %zu", this, mDataSize);
1947             }
1948             if (mDataPos > desired) {
1949                 mDataPos = desired;
1950                 ALOGV("continueWrite Setting data pos of %p to %zu", this, mDataPos);
1951             }
1952         }
1953 
1954     } else {
1955         // This is the first data.  Easy!
1956         uint8_t* data = (uint8_t*)malloc(desired);
1957         if (!data) {
1958             mError = NO_MEMORY;
1959             return NO_MEMORY;
1960         }
1961 
1962         if(!(mDataCapacity == 0 && mObjects == nullptr
1963              && mObjectsCapacity == 0)) {
1964             ALOGE("continueWrite: %zu/%p/%zu/%zu", mDataCapacity, mObjects, mObjectsCapacity, desired);
1965         }
1966 
1967         LOG_ALLOC("Parcel %p: allocating with %zu capacity", this, desired);
1968         gParcelGlobalAllocSize += desired;
1969         gParcelGlobalAllocCount++;
1970 
1971         mData = data;
1972         mDataSize = mDataPos = 0;
1973         ALOGV("continueWrite Setting data size of %p to %zu", this, mDataSize);
1974         ALOGV("continueWrite Setting data pos of %p to %zu", this, mDataPos);
1975         mDataCapacity = desired;
1976     }
1977 
1978     return NO_ERROR;
1979 }
1980 
initState()1981 void Parcel::initState()
1982 {
1983     LOG_ALLOC("Parcel %p: initState", this);
1984     mError = NO_ERROR;
1985     mData = nullptr;
1986     mDataSize = 0;
1987     mDataCapacity = 0;
1988     mDataPos = 0;
1989     ALOGV("initState Setting data size of %p to %zu", this, mDataSize);
1990     ALOGV("initState Setting data pos of %p to %zu", this, mDataPos);
1991     mObjects = nullptr;
1992     mObjectsSize = 0;
1993     mObjectsCapacity = 0;
1994     mNextObjectHint = 0;
1995     mHasFds = false;
1996     mFdsKnown = true;
1997     mAllowFds = true;
1998     mDeallocZero = false;
1999     mOwner = nullptr;
2000     clearCache();
2001 
2002     // racing multiple init leads only to multiple identical write
2003     if (gMaxFds == 0) {
2004         struct rlimit result;
2005         if (!getrlimit(RLIMIT_NOFILE, &result)) {
2006             gMaxFds = (size_t)result.rlim_cur;
2007             //ALOGI("parcel fd limit set to %zu", gMaxFds);
2008         } else {
2009             ALOGW("Unable to getrlimit: %s", strerror(errno));
2010             gMaxFds = 1024;
2011         }
2012     }
2013 }
2014 
scanForFds() const2015 void Parcel::scanForFds() const
2016 {
2017     bool hasFds = false;
2018     for (size_t i=0; i<mObjectsSize; i++) {
2019         const flat_binder_object* flat
2020             = reinterpret_cast<const flat_binder_object*>(mData + mObjects[i]);
2021         if (flat->hdr.type == BINDER_TYPE_FD) {
2022             hasFds = true;
2023             break;
2024         }
2025     }
2026     mHasFds = hasFds;
2027     mFdsKnown = true;
2028 }
2029 
2030 } // namespace hardware
2031 } // namespace android
2032