• 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 #include <hwbinder/TextOutput.h>
39 #include <hwbinder/binder_kernel.h>
40 
41 #include <cutils/ashmem.h>
42 #include <utils/Debug.h>
43 #include <utils/Log.h>
44 #include <utils/misc.h>
45 #include <utils/String8.h>
46 #include <utils/String16.h>
47 
48 #include <private/binder/binder_module.h>
49 #include <hwbinder/Static.h>
50 
51 #ifndef INT32_MAX
52 #define INT32_MAX ((int32_t)(2147483647))
53 #endif
54 
55 #define LOG_REFS(...)
56 //#define LOG_REFS(...) ALOG(LOG_DEBUG, LOG_TAG, __VA_ARGS__)
57 #define LOG_ALLOC(...)
58 //#define LOG_ALLOC(...) ALOG(LOG_DEBUG, LOG_TAG, __VA_ARGS__)
59 #define LOG_BUFFER(...)
60 // #define LOG_BUFFER(...) ALOG(LOG_DEBUG, LOG_TAG, __VA_ARGS__)
61 
62 // ---------------------------------------------------------------------------
63 
64 // This macro should never be used at runtime, as a too large value
65 // of s could cause an integer overflow. Instead, you should always
66 // use the wrapper function pad_size()
67 #define PAD_SIZE_UNSAFE(s) (((s)+3)&~3)
68 
pad_size(size_t s)69 static size_t pad_size(size_t s) {
70     if (s > (SIZE_T_MAX - 3)) {
71         abort();
72     }
73     return PAD_SIZE_UNSAFE(s);
74 }
75 
76 // Note: must be kept in sync with android/os/StrictMode.java's PENALTY_GATHER
77 #define STRICT_MODE_PENALTY_GATHER (0x40 << 16)
78 
79 namespace android {
80 namespace hardware {
81 
82 static pthread_mutex_t gParcelGlobalAllocSizeLock = PTHREAD_MUTEX_INITIALIZER;
83 static size_t gParcelGlobalAllocSize = 0;
84 static size_t gParcelGlobalAllocCount = 0;
85 
86 static size_t gMaxFds = 0;
87 
88 static const size_t PARCEL_REF_CAP = 1024;
89 
acquire_binder_object(const sp<ProcessState> & proc,const flat_binder_object & obj,const void * who)90 void acquire_binder_object(const sp<ProcessState>& proc,
91     const flat_binder_object& obj, const void* who)
92 {
93     switch (obj.hdr.type) {
94         case BINDER_TYPE_BINDER:
95             if (obj.binder) {
96                 LOG_REFS("Parcel %p acquiring reference on local %p", who, obj.cookie);
97                 reinterpret_cast<IBinder*>(obj.cookie)->incStrong(who);
98             }
99             return;
100         case BINDER_TYPE_WEAK_BINDER:
101             if (obj.binder)
102                 reinterpret_cast<RefBase::weakref_type*>(obj.binder)->incWeak(who);
103             return;
104         case BINDER_TYPE_HANDLE: {
105             const sp<IBinder> b = proc->getStrongProxyForHandle(obj.handle);
106             if (b != nullptr) {
107                 LOG_REFS("Parcel %p acquiring reference on remote %p", who, b.get());
108                 b->incStrong(who);
109             }
110             return;
111         }
112         case BINDER_TYPE_WEAK_HANDLE: {
113             const wp<IBinder> b = proc->getWeakProxyForHandle(obj.handle);
114             if (b != nullptr) b.get_refs()->incWeak(who);
115             return;
116         }
117     }
118 
119     ALOGD("Invalid object type 0x%08x", obj.hdr.type);
120 }
121 
acquire_object(const sp<ProcessState> & proc,const binder_object_header & obj,const void * who)122 void acquire_object(const sp<ProcessState>& proc, const binder_object_header& obj,
123         const void *who) {
124     switch (obj.type) {
125         case BINDER_TYPE_BINDER:
126         case BINDER_TYPE_WEAK_BINDER:
127         case BINDER_TYPE_HANDLE:
128         case BINDER_TYPE_WEAK_HANDLE: {
129             const flat_binder_object& fbo = reinterpret_cast<const flat_binder_object&>(obj);
130             acquire_binder_object(proc, fbo, who);
131             break;
132         }
133     }
134 }
135 
release_object(const sp<ProcessState> & proc,const flat_binder_object & obj,const void * who)136 void release_object(const sp<ProcessState>& proc,
137     const flat_binder_object& obj, const void* who)
138 {
139     switch (obj.hdr.type) {
140         case BINDER_TYPE_BINDER:
141             if (obj.binder) {
142                 LOG_REFS("Parcel %p releasing reference on local %p", who, obj.cookie);
143                 reinterpret_cast<IBinder*>(obj.cookie)->decStrong(who);
144             }
145             return;
146         case BINDER_TYPE_WEAK_BINDER:
147             if (obj.binder)
148                 reinterpret_cast<RefBase::weakref_type*>(obj.binder)->decWeak(who);
149             return;
150         case BINDER_TYPE_HANDLE: {
151             const sp<IBinder> b = proc->getStrongProxyForHandle(obj.handle);
152             if (b != nullptr) {
153                 LOG_REFS("Parcel %p releasing reference on remote %p", who, b.get());
154                 b->decStrong(who);
155             }
156             return;
157         }
158         case BINDER_TYPE_WEAK_HANDLE: {
159             const wp<IBinder> b = proc->getWeakProxyForHandle(obj.handle);
160             if (b != nullptr) b.get_refs()->decWeak(who);
161             return;
162         }
163         case BINDER_TYPE_FD: {
164             if (obj.cookie != 0) { // owned
165                 close(obj.handle);
166             }
167             return;
168         }
169         case BINDER_TYPE_PTR: {
170             // The relevant buffer is part of the transaction buffer and will be freed that way
171             return;
172         }
173         case BINDER_TYPE_FDA: {
174             // The enclosed file descriptors are closed in the kernel
175             return;
176         }
177     }
178 
179     ALOGE("Invalid object type 0x%08x", obj.hdr.type);
180 }
181 
finish_flatten_binder(const sp<IBinder> &,const flat_binder_object & flat,Parcel * out)182 inline static status_t finish_flatten_binder(
183     const sp<IBinder>& /*binder*/, const flat_binder_object& flat, Parcel* out)
184 {
185     return out->writeObject(flat);
186 }
187 
flatten_binder(const sp<ProcessState> &,const sp<IBinder> & binder,Parcel * out)188 status_t flatten_binder(const sp<ProcessState>& /*proc*/,
189     const sp<IBinder>& binder, Parcel* out)
190 {
191     flat_binder_object obj = {};
192 
193     if (binder != nullptr) {
194         BHwBinder *local = binder->localBinder();
195         if (!local) {
196             BpHwBinder *proxy = binder->remoteBinder();
197             if (proxy == nullptr) {
198                 ALOGE("null proxy");
199             }
200             const int32_t handle = proxy ? proxy->handle() : 0;
201             obj.hdr.type = BINDER_TYPE_HANDLE;
202             obj.flags = FLAT_BINDER_FLAG_ACCEPTS_FDS;
203             obj.binder = 0; /* Don't pass uninitialized stack data to a remote process */
204             obj.handle = handle;
205             obj.cookie = 0;
206         } else {
207             // Get policy and convert it
208             int policy = local->getMinSchedulingPolicy();
209             int priority = local->getMinSchedulingPriority();
210 
211             obj.flags = priority & FLAT_BINDER_FLAG_PRIORITY_MASK;
212             obj.flags |= FLAT_BINDER_FLAG_ACCEPTS_FDS | FLAT_BINDER_FLAG_INHERIT_RT;
213             obj.flags |= (policy & 3) << FLAT_BINDER_FLAG_SCHEDPOLICY_SHIFT;
214             if (local->isRequestingSid()) {
215                 obj.flags |= FLAT_BINDER_FLAG_TXN_SECURITY_CTX;
216             }
217             obj.hdr.type = BINDER_TYPE_BINDER;
218             obj.binder = reinterpret_cast<uintptr_t>(local->getWeakRefs());
219             obj.cookie = reinterpret_cast<uintptr_t>(local);
220         }
221     } else {
222         obj.hdr.type = BINDER_TYPE_BINDER;
223         obj.binder = 0;
224         obj.cookie = 0;
225     }
226 
227     return finish_flatten_binder(binder, obj, out);
228 }
229 
flatten_binder(const sp<ProcessState> &,const wp<IBinder> & binder,Parcel * out)230 status_t flatten_binder(const sp<ProcessState>& /*proc*/,
231     const wp<IBinder>& binder, Parcel* out)
232 {
233     flat_binder_object obj = {};
234 
235     obj.flags = 0x7f | FLAT_BINDER_FLAG_ACCEPTS_FDS;
236     if (binder != nullptr) {
237         sp<IBinder> real = binder.promote();
238         if (real != nullptr) {
239             IBinder *local = real->localBinder();
240             if (!local) {
241                 BpHwBinder *proxy = real->remoteBinder();
242                 if (proxy == nullptr) {
243                     ALOGE("null proxy");
244                 }
245                 const int32_t handle = proxy ? proxy->handle() : 0;
246                 obj.hdr.type = BINDER_TYPE_WEAK_HANDLE;
247                 obj.binder = 0; /* Don't pass uninitialized stack data to a remote process */
248                 obj.handle = handle;
249                 obj.cookie = 0;
250             } else {
251                 obj.hdr.type = BINDER_TYPE_WEAK_BINDER;
252                 obj.binder = reinterpret_cast<uintptr_t>(binder.get_refs());
253                 obj.cookie = reinterpret_cast<uintptr_t>(binder.unsafe_get());
254             }
255             return finish_flatten_binder(real, obj, out);
256         }
257 
258         // XXX How to deal?  In order to flatten the given binder,
259         // we need to probe it for information, which requires a primary
260         // reference...  but we don't have one.
261         //
262         // The OpenBinder implementation uses a dynamic_cast<> here,
263         // but we can't do that with the different reference counting
264         // implementation we are using.
265         ALOGE("Unable to unflatten Binder weak reference!");
266         obj.hdr.type = BINDER_TYPE_BINDER;
267         obj.binder = 0;
268         obj.cookie = 0;
269         return finish_flatten_binder(nullptr, obj, out);
270 
271     } else {
272         obj.hdr.type = BINDER_TYPE_BINDER;
273         obj.binder = 0;
274         obj.cookie = 0;
275         return finish_flatten_binder(nullptr, obj, out);
276     }
277 }
278 
finish_unflatten_binder(BpHwBinder *,const flat_binder_object &,const Parcel &)279 inline static status_t finish_unflatten_binder(
280     BpHwBinder* /*proxy*/, const flat_binder_object& /*flat*/,
281     const Parcel& /*in*/)
282 {
283     return NO_ERROR;
284 }
285 
unflatten_binder(const sp<ProcessState> & proc,const Parcel & in,sp<IBinder> * out)286 status_t unflatten_binder(const sp<ProcessState>& proc,
287     const Parcel& in, sp<IBinder>* out)
288 {
289     const flat_binder_object* flat = in.readObject<flat_binder_object>();
290 
291     if (flat) {
292         switch (flat->hdr.type) {
293             case BINDER_TYPE_BINDER:
294                 *out = reinterpret_cast<IBinder*>(flat->cookie);
295                 return finish_unflatten_binder(nullptr, *flat, in);
296             case BINDER_TYPE_HANDLE:
297                 *out = proc->getStrongProxyForHandle(flat->handle);
298                 return finish_unflatten_binder(
299                     static_cast<BpHwBinder*>(out->get()), *flat, in);
300         }
301     }
302     return BAD_TYPE;
303 }
304 
unflatten_binder(const sp<ProcessState> & proc,const Parcel & in,wp<IBinder> * out)305 status_t unflatten_binder(const sp<ProcessState>& proc,
306     const Parcel& in, wp<IBinder>* out)
307 {
308     const flat_binder_object* flat = in.readObject<flat_binder_object>();
309 
310     if (flat) {
311         switch (flat->hdr.type) {
312             case BINDER_TYPE_BINDER:
313                 *out = reinterpret_cast<IBinder*>(flat->cookie);
314                 return finish_unflatten_binder(nullptr, *flat, in);
315             case BINDER_TYPE_WEAK_BINDER:
316                 if (flat->binder != 0) {
317                     out->set_object_and_refs(
318                         reinterpret_cast<IBinder*>(flat->cookie),
319                         reinterpret_cast<RefBase::weakref_type*>(flat->binder));
320                 } else {
321                     *out = nullptr;
322                 }
323                 return finish_unflatten_binder(nullptr, *flat, in);
324             case BINDER_TYPE_HANDLE:
325             case BINDER_TYPE_WEAK_HANDLE:
326                 *out = proc->getWeakProxyForHandle(flat->handle);
327                 return finish_unflatten_binder(
328                     static_cast<BpHwBinder*>(out->unsafe_get()), *flat, in);
329         }
330     }
331     return BAD_TYPE;
332 }
333 
334 /*
335  * Return true iff:
336  * 1. obj is indeed a binder_buffer_object (type is BINDER_TYPE_PTR), and
337  * 2. obj does NOT have the flag BINDER_BUFFER_FLAG_REF (it is not a reference, but
338  *    an actual buffer.)
339  */
isBuffer(const binder_buffer_object & obj)340 static inline bool isBuffer(const binder_buffer_object& obj) {
341     return obj.hdr.type == BINDER_TYPE_PTR
342         && (obj.flags & BINDER_BUFFER_FLAG_REF) == 0;
343 }
344 
345 // ---------------------------------------------------------------------------
346 
Parcel()347 Parcel::Parcel()
348 {
349     LOG_ALLOC("Parcel %p: constructing", this);
350     initState();
351 }
352 
~Parcel()353 Parcel::~Parcel()
354 {
355     freeDataNoInit();
356     LOG_ALLOC("Parcel %p: destroyed", this);
357 }
358 
getGlobalAllocSize()359 size_t Parcel::getGlobalAllocSize() {
360     pthread_mutex_lock(&gParcelGlobalAllocSizeLock);
361     size_t size = gParcelGlobalAllocSize;
362     pthread_mutex_unlock(&gParcelGlobalAllocSizeLock);
363     return size;
364 }
365 
getGlobalAllocCount()366 size_t Parcel::getGlobalAllocCount() {
367     pthread_mutex_lock(&gParcelGlobalAllocSizeLock);
368     size_t count = gParcelGlobalAllocCount;
369     pthread_mutex_unlock(&gParcelGlobalAllocSizeLock);
370     return count;
371 }
372 
data() const373 const uint8_t* Parcel::data() const
374 {
375     return mData;
376 }
377 
dataSize() const378 size_t Parcel::dataSize() const
379 {
380     return (mDataSize > mDataPos ? mDataSize : mDataPos);
381 }
382 
dataAvail() const383 size_t Parcel::dataAvail() const
384 {
385     size_t result = dataSize() - dataPosition();
386     if (result > INT32_MAX) {
387         abort();
388     }
389     return result;
390 }
391 
dataPosition() const392 size_t Parcel::dataPosition() const
393 {
394     return mDataPos;
395 }
396 
dataCapacity() const397 size_t Parcel::dataCapacity() const
398 {
399     return mDataCapacity;
400 }
401 
setDataSize(size_t size)402 status_t Parcel::setDataSize(size_t size)
403 {
404     if (size > INT32_MAX) {
405         // don't accept size_t values which may have come from an
406         // inadvertent conversion from a negative int.
407         return BAD_VALUE;
408     }
409 
410     status_t err;
411     err = continueWrite(size);
412     if (err == NO_ERROR) {
413         mDataSize = size;
414         ALOGV("setDataSize Setting data size of %p to %zu", this, mDataSize);
415     }
416     return err;
417 }
418 
setDataPosition(size_t pos) const419 void Parcel::setDataPosition(size_t pos) const
420 {
421     if (pos > INT32_MAX) {
422         // don't accept size_t values which may have come from an
423         // inadvertent conversion from a negative int.
424         abort();
425     }
426 
427     mDataPos = pos;
428     mNextObjectHint = 0;
429 }
430 
setDataCapacity(size_t size)431 status_t Parcel::setDataCapacity(size_t size)
432 {
433     if (size > INT32_MAX) {
434         // don't accept size_t values which may have come from an
435         // inadvertent conversion from a negative int.
436         return BAD_VALUE;
437     }
438 
439     if (size > mDataCapacity) return continueWrite(size);
440     return NO_ERROR;
441 }
442 
setData(const uint8_t * buffer,size_t len)443 status_t Parcel::setData(const uint8_t* buffer, size_t len)
444 {
445     if (len > INT32_MAX) {
446         // don't accept size_t values which may have come from an
447         // inadvertent conversion from a negative int.
448         return BAD_VALUE;
449     }
450 
451     status_t err = restartWrite(len);
452     if (err == NO_ERROR) {
453         memcpy(const_cast<uint8_t*>(data()), buffer, len);
454         mDataSize = len;
455         mFdsKnown = false;
456     }
457     return err;
458 }
459 
460 // Write RPC headers.  (previously just the interface token)
writeInterfaceToken(const char * interface)461 status_t Parcel::writeInterfaceToken(const char* interface)
462 {
463     // currently the interface identification token is just its name as a string
464     return writeCString(interface);
465 }
466 
enforceInterface(const char * interface) const467 bool Parcel::enforceInterface(const char* interface) const
468 {
469     const char* str = readCString();
470     if (str != nullptr && strcmp(str, interface) == 0) {
471         return true;
472     } else {
473         ALOGW("**** enforceInterface() expected '%s' but read '%s'",
474                 interface, (str ? str : "<empty string>"));
475         return false;
476     }
477 }
478 
objects() const479 const binder_size_t* Parcel::objects() const
480 {
481     return mObjects;
482 }
483 
objectsCount() const484 size_t Parcel::objectsCount() const
485 {
486     return mObjectsSize;
487 }
488 
errorCheck() const489 status_t Parcel::errorCheck() const
490 {
491     return mError;
492 }
493 
setError(status_t err)494 void Parcel::setError(status_t err)
495 {
496     mError = err;
497 }
498 
finishWrite(size_t len)499 status_t Parcel::finishWrite(size_t len)
500 {
501     if (len > INT32_MAX) {
502         // don't accept size_t values which may have come from an
503         // inadvertent conversion from a negative int.
504         return BAD_VALUE;
505     }
506 
507     //printf("Finish write of %d\n", len);
508     mDataPos += len;
509     ALOGV("finishWrite Setting data pos of %p to %zu", this, mDataPos);
510     if (mDataPos > mDataSize) {
511         mDataSize = mDataPos;
512         ALOGV("finishWrite Setting data size of %p to %zu", this, mDataSize);
513     }
514     //printf("New pos=%d, size=%d\n", mDataPos, mDataSize);
515     return NO_ERROR;
516 }
517 
writeUnpadded(const void * data,size_t len)518 status_t Parcel::writeUnpadded(const void* data, size_t len)
519 {
520     if (len > INT32_MAX) {
521         // don't accept size_t values which may have come from an
522         // inadvertent conversion from a negative int.
523         return BAD_VALUE;
524     }
525 
526     size_t end = mDataPos + len;
527     if (end < mDataPos) {
528         // integer overflow
529         return BAD_VALUE;
530     }
531 
532     if (end <= mDataCapacity) {
533 restart_write:
534         memcpy(mData+mDataPos, data, len);
535         return finishWrite(len);
536     }
537 
538     status_t err = growData(len);
539     if (err == NO_ERROR) goto restart_write;
540     return err;
541 }
542 
write(const void * data,size_t len)543 status_t Parcel::write(const void* data, size_t len)
544 {
545     if (len > INT32_MAX) {
546         // don't accept size_t values which may have come from an
547         // inadvertent conversion from a negative int.
548         return BAD_VALUE;
549     }
550 
551     void* const d = writeInplace(len);
552     if (d) {
553         memcpy(d, data, len);
554         return NO_ERROR;
555     }
556     return mError;
557 }
558 
writeInplace(size_t len)559 void* Parcel::writeInplace(size_t len)
560 {
561     if (len > INT32_MAX) {
562         // don't accept size_t values which may have come from an
563         // inadvertent conversion from a negative int.
564         return nullptr;
565     }
566 
567     const size_t padded = pad_size(len);
568 
569     // sanity check for integer overflow
570     if (mDataPos+padded < mDataPos) {
571         return nullptr;
572     }
573 
574     if ((mDataPos+padded) <= mDataCapacity) {
575 restart_write:
576         //printf("Writing %ld bytes, padded to %ld\n", len, padded);
577         uint8_t* const data = mData+mDataPos;
578 
579         // Need to pad at end?
580         if (padded != len) {
581 #if BYTE_ORDER == BIG_ENDIAN
582             static const uint32_t mask[4] = {
583                 0x00000000, 0xffffff00, 0xffff0000, 0xff000000
584             };
585 #endif
586 #if BYTE_ORDER == LITTLE_ENDIAN
587             static const uint32_t mask[4] = {
588                 0x00000000, 0x00ffffff, 0x0000ffff, 0x000000ff
589             };
590 #endif
591             //printf("Applying pad mask: %p to %p\n", (void*)mask[padded-len],
592             //    *reinterpret_cast<void**>(data+padded-4));
593             *reinterpret_cast<uint32_t*>(data+padded-4) &= mask[padded-len];
594         }
595 
596         finishWrite(padded);
597         return data;
598     }
599 
600     status_t err = growData(padded);
601     if (err == NO_ERROR) goto restart_write;
602     return nullptr;
603 }
604 
writeInt8(int8_t val)605 status_t Parcel::writeInt8(int8_t val)
606 {
607     return write(&val, sizeof(val));
608 }
609 
writeUint8(uint8_t val)610 status_t Parcel::writeUint8(uint8_t val)
611 {
612     return write(&val, sizeof(val));
613 }
614 
writeInt16(int16_t val)615 status_t Parcel::writeInt16(int16_t val)
616 {
617     return write(&val, sizeof(val));
618 }
619 
writeUint16(uint16_t val)620 status_t Parcel::writeUint16(uint16_t val)
621 {
622     return write(&val, sizeof(val));
623 }
624 
writeInt32(int32_t val)625 status_t Parcel::writeInt32(int32_t val)
626 {
627     return writeAligned(val);
628 }
629 
writeUint32(uint32_t val)630 status_t Parcel::writeUint32(uint32_t val)
631 {
632     return writeAligned(val);
633 }
634 
writeBool(bool val)635 status_t Parcel::writeBool(bool val)
636 {
637     return writeInt8(int8_t(val));
638 }
writeInt64(int64_t val)639 status_t Parcel::writeInt64(int64_t val)
640 {
641     return writeAligned(val);
642 }
643 
writeUint64(uint64_t val)644 status_t Parcel::writeUint64(uint64_t val)
645 {
646     return writeAligned(val);
647 }
648 
writePointer(uintptr_t val)649 status_t Parcel::writePointer(uintptr_t val)
650 {
651     return writeAligned<binder_uintptr_t>(val);
652 }
653 
writeFloat(float val)654 status_t Parcel::writeFloat(float val)
655 {
656     return writeAligned(val);
657 }
658 
659 #if defined(__mips__) && defined(__mips_hard_float)
660 
writeDouble(double val)661 status_t Parcel::writeDouble(double val)
662 {
663     union {
664         double d;
665         unsigned long long ll;
666     } u;
667     u.d = val;
668     return writeAligned(u.ll);
669 }
670 
671 #else
672 
writeDouble(double val)673 status_t Parcel::writeDouble(double val)
674 {
675     return writeAligned(val);
676 }
677 
678 #endif
679 
writeCString(const char * str)680 status_t Parcel::writeCString(const char* str)
681 {
682     return write(str, strlen(str)+1);
683 }
writeString16(const std::unique_ptr<String16> & str)684 status_t Parcel::writeString16(const std::unique_ptr<String16>& str)
685 {
686     if (!str) {
687         return writeInt32(-1);
688     }
689 
690     return writeString16(*str);
691 }
692 
writeString16(const String16 & str)693 status_t Parcel::writeString16(const String16& str)
694 {
695     return writeString16(str.string(), str.size());
696 }
697 
writeString16(const char16_t * str,size_t len)698 status_t Parcel::writeString16(const char16_t* str, size_t len)
699 {
700     if (str == nullptr) return writeInt32(-1);
701 
702     status_t err = writeInt32(len);
703     if (err == NO_ERROR) {
704         len *= sizeof(char16_t);
705         uint8_t* data = (uint8_t*)writeInplace(len+sizeof(char16_t));
706         if (data) {
707             memcpy(data, str, len);
708             *reinterpret_cast<char16_t*>(data+len) = 0;
709             return NO_ERROR;
710         }
711         err = mError;
712     }
713     return err;
714 }
writeStrongBinder(const sp<IBinder> & val)715 status_t Parcel::writeStrongBinder(const sp<IBinder>& val)
716 {
717     return flatten_binder(ProcessState::self(), val, this);
718 }
719 
writeWeakBinder(const wp<IBinder> & val)720 status_t Parcel::writeWeakBinder(const wp<IBinder>& val)
721 {
722     return flatten_binder(ProcessState::self(), val, this);
723 }
724 
725 template <typename T>
writeObject(const T & val)726 status_t Parcel::writeObject(const T& val)
727 {
728     const bool enoughData = (mDataPos+sizeof(val)) <= mDataCapacity;
729     const bool enoughObjects = mObjectsSize < mObjectsCapacity;
730     if (enoughData && enoughObjects) {
731 restart_write:
732         *reinterpret_cast<T*>(mData+mDataPos) = val;
733 
734         const binder_object_header* hdr = reinterpret_cast<binder_object_header*>(mData+mDataPos);
735         switch (hdr->type) {
736             case BINDER_TYPE_BINDER:
737             case BINDER_TYPE_WEAK_BINDER:
738             case BINDER_TYPE_HANDLE:
739             case BINDER_TYPE_WEAK_HANDLE: {
740                 const flat_binder_object *fbo = reinterpret_cast<const flat_binder_object*>(hdr);
741                 if (fbo->binder != 0) {
742                     mObjects[mObjectsSize++] = mDataPos;
743                     acquire_binder_object(ProcessState::self(), *fbo, this);
744                 }
745                 break;
746             }
747             case BINDER_TYPE_FD: {
748                 // remember if it's a file descriptor
749                 if (!mAllowFds) {
750                     // fail before modifying our object index
751                     return FDS_NOT_ALLOWED;
752                 }
753                 mHasFds = mFdsKnown = true;
754                 mObjects[mObjectsSize++] = mDataPos;
755                 break;
756             }
757             case BINDER_TYPE_FDA:
758                 mObjects[mObjectsSize++] = mDataPos;
759                 break;
760             case BINDER_TYPE_PTR: {
761                 const binder_buffer_object *buffer_obj = reinterpret_cast<
762                     const binder_buffer_object*>(hdr);
763                 if ((void *)buffer_obj->buffer != nullptr) {
764                     mObjects[mObjectsSize++] = mDataPos;
765                 }
766                 break;
767             }
768             default: {
769                 ALOGE("writeObject: unknown type %d", hdr->type);
770                 break;
771             }
772         }
773         return finishWrite(sizeof(val));
774     }
775 
776     if (!enoughData) {
777         const status_t err = growData(sizeof(val));
778         if (err != NO_ERROR) return err;
779     }
780     if (!enoughObjects) {
781         size_t newSize = ((mObjectsSize+2)*3)/2;
782         if (newSize * sizeof(binder_size_t) < mObjectsSize) return NO_MEMORY;   // overflow
783         binder_size_t* objects = (binder_size_t*)realloc(mObjects, newSize*sizeof(binder_size_t));
784         if (objects == nullptr) return NO_MEMORY;
785         mObjects = objects;
786         mObjectsCapacity = newSize;
787     }
788 
789     goto restart_write;
790 }
791 
792 template status_t Parcel::writeObject<flat_binder_object>(const flat_binder_object& val);
793 template status_t Parcel::writeObject<binder_fd_object>(const binder_fd_object& val);
794 template status_t Parcel::writeObject<binder_buffer_object>(const binder_buffer_object& val);
795 template status_t Parcel::writeObject<binder_fd_array_object>(const binder_fd_array_object& val);
796 
797 
798 // TODO merge duplicated code in writeEmbeddedBuffer, writeEmbeddedReference, and writeEmbeddedNullReference
799 // TODO merge duplicated code in writeBuffer, writeReference, and writeNullReference
800 
validateBufferChild(size_t child_buffer_handle,size_t child_offset) const801 bool Parcel::validateBufferChild(size_t child_buffer_handle,
802                                  size_t child_offset) const {
803     if (child_buffer_handle >= mObjectsSize)
804         return false;
805     binder_buffer_object *child = reinterpret_cast<binder_buffer_object*>
806             (mData + mObjects[child_buffer_handle]);
807     if (!isBuffer(*child) || child_offset > child->length) {
808         // Parent object not a buffer, or not large enough
809         LOG_BUFFER("writeEmbeddedReference found wierd child. "
810                    "child_offset = %zu, child->length = %zu",
811                    child_offset, (size_t)child->length);
812         return false;
813     }
814     return true;
815 }
816 
validateBufferParent(size_t parent_buffer_handle,size_t parent_offset) const817 bool Parcel::validateBufferParent(size_t parent_buffer_handle,
818                                   size_t parent_offset) const {
819     if (parent_buffer_handle >= mObjectsSize)
820         return false;
821     binder_buffer_object *parent = reinterpret_cast<binder_buffer_object*>
822             (mData + mObjects[parent_buffer_handle]);
823     if (!isBuffer(*parent) ||
824             sizeof(binder_uintptr_t) > parent->length ||
825             parent_offset > parent->length - sizeof(binder_uintptr_t)) {
826         // Parent object not a buffer, or not large enough
827         return false;
828     }
829     return true;
830 }
writeEmbeddedBuffer(const void * buffer,size_t length,size_t * handle,size_t parent_buffer_handle,size_t parent_offset)831 status_t Parcel::writeEmbeddedBuffer(
832         const void *buffer, size_t length, size_t *handle,
833         size_t parent_buffer_handle, size_t parent_offset) {
834     LOG_BUFFER("writeEmbeddedBuffer(%p, %zu, parent = (%zu, %zu)) -> %zu",
835         buffer, length, parent_buffer_handle,
836          parent_offset, mObjectsSize);
837     if(!validateBufferParent(parent_buffer_handle, parent_offset))
838         return BAD_VALUE;
839     binder_buffer_object obj = {
840         .hdr = { .type = BINDER_TYPE_PTR },
841         .buffer = reinterpret_cast<binder_uintptr_t>(buffer),
842         .length = length,
843         .flags = BINDER_BUFFER_FLAG_HAS_PARENT,
844         .parent = parent_buffer_handle,
845         .parent_offset = parent_offset,
846     };
847     if (handle != nullptr) {
848         // We use an index into mObjects as a handle
849         *handle = mObjectsSize;
850     }
851     return writeObject(obj);
852 }
853 
writeBuffer(const void * buffer,size_t length,size_t * handle)854 status_t Parcel::writeBuffer(const void *buffer, size_t length, size_t *handle)
855 {
856     LOG_BUFFER("writeBuffer(%p, %zu) -> %zu",
857         buffer, length, mObjectsSize);
858     binder_buffer_object obj {
859         .hdr = { .type = BINDER_TYPE_PTR },
860         .buffer = reinterpret_cast<binder_uintptr_t>(buffer),
861         .length = length,
862         .flags = 0,
863     };
864     if (handle != nullptr) {
865         // We use an index into mObjects as a handle
866         *handle = mObjectsSize;
867     }
868     return writeObject(obj);
869 }
870 
incrementNumReferences()871 status_t Parcel::incrementNumReferences() {
872     ++mNumRef;
873     LOG_BUFFER("incrementNumReferences: %zu", mNumRef);
874     return mNumRef <= PARCEL_REF_CAP ? OK : NO_MEMORY;
875 }
876 
writeReference(size_t * handle,size_t child_buffer_handle,size_t child_offset)877 status_t Parcel::writeReference(size_t *handle,
878         size_t child_buffer_handle, size_t child_offset) {
879     LOG_BUFFER("writeReference(child = (%zu, %zu)) -> %zu",
880         child_buffer_handle, child_offset,
881         mObjectsSize);
882     status_t status = incrementNumReferences();
883     if (status != OK)
884         return status;
885     if (!validateBufferChild(child_buffer_handle, child_offset))
886         return BAD_VALUE;
887     binder_buffer_object obj {
888         .hdr = { .type = BINDER_TYPE_PTR },
889         .flags = BINDER_BUFFER_FLAG_REF,
890         // The current binder.h does not have child and child_offset names yet.
891         // Use the buffer and length parameters.
892         .buffer = child_buffer_handle,
893         .length = child_offset,
894     };
895     if (handle != nullptr)
896         // We use an index into mObjects as a handle
897         *handle = mObjectsSize;
898     return writeObject(obj);
899 }
900 
901 /* Write an object that describes a pointer from parent to child.
902  * Output the handle of that object in the size_t *handle variable. */
writeEmbeddedReference(size_t * handle,size_t child_buffer_handle,size_t child_offset,size_t parent_buffer_handle,size_t parent_offset)903 status_t Parcel::writeEmbeddedReference(size_t *handle,
904     size_t child_buffer_handle, size_t child_offset,
905     size_t parent_buffer_handle, size_t parent_offset) {
906     LOG_BUFFER("writeEmbeddedReference(child = (%zu, %zu), parent = (%zu, %zu)) -> %zu",
907         child_buffer_handle, child_offset,
908         parent_buffer_handle, parent_offset,
909         mObjectsSize);
910     status_t status = incrementNumReferences();
911     if (status != OK)
912         return status;
913     // The current binder.h does not have child and child_offset names yet.
914     // Use the buffer and length parameters.
915     if (!validateBufferChild(child_buffer_handle, child_offset))
916         return BAD_VALUE;
917     if(!validateBufferParent(parent_buffer_handle, parent_offset))
918         return BAD_VALUE;
919     binder_buffer_object obj {
920         .hdr = { .type = BINDER_TYPE_PTR },
921         .flags = BINDER_BUFFER_FLAG_REF | BINDER_BUFFER_FLAG_HAS_PARENT,
922         .buffer = child_buffer_handle,
923         .length = child_offset,
924         .parent = parent_buffer_handle,
925         .parent_offset = parent_offset,
926     };
927     if (handle != nullptr) {
928         // We use an index into mObjects as a handle
929         *handle = mObjectsSize;
930     }
931     return writeObject(obj);
932 }
933 
writeNullReference(size_t * handle)934 status_t Parcel::writeNullReference(size_t * handle) {
935     LOG_BUFFER("writeNullReference -> %zu", mObjectsSize);
936     status_t status = incrementNumReferences();
937     if (status != OK)
938         return status;
939 
940     binder_buffer_object obj {
941         .hdr = { .type = BINDER_TYPE_PTR },
942         .flags = BINDER_BUFFER_FLAG_REF,
943     };
944 
945     if (handle != nullptr)
946         // We use an index into mObjects as a handle
947         *handle = mObjectsSize;
948     return writeObject(obj);
949 }
950 
writeEmbeddedNullReference(size_t * handle,size_t parent_buffer_handle,size_t parent_offset)951 status_t Parcel::writeEmbeddedNullReference(size_t * handle,
952         size_t parent_buffer_handle, size_t parent_offset) {
953     LOG_BUFFER("writeEmbeddedNullReference(parent = (%zu, %zu)) -> %zu",
954         parent_buffer_handle,
955         parent_offset,
956         mObjectsSize);
957     status_t status = incrementNumReferences();
958     if (status != OK)
959         return status;
960     if(!validateBufferParent(parent_buffer_handle, parent_offset))
961         return BAD_VALUE;
962     binder_buffer_object obj {
963         .hdr = { .type = BINDER_TYPE_PTR, },
964         .flags = BINDER_BUFFER_FLAG_REF | BINDER_BUFFER_FLAG_HAS_PARENT,
965         .parent = parent_buffer_handle,
966         .parent_offset = parent_offset,
967     };
968     if (handle != nullptr) {
969         // We use an index into mObjects as a handle
970         *handle = mObjectsSize;
971     }
972     return writeObject(obj);
973 }
974 
clearCache() const975 void Parcel::clearCache() const {
976     LOG_BUFFER("clearing cache.");
977     mBufCachePos = 0;
978     mBufCache.clear();
979 }
980 
updateCache() const981 void Parcel::updateCache() const {
982     if(mBufCachePos == mObjectsSize)
983         return;
984     LOG_BUFFER("updating cache from %zu to %zu", mBufCachePos, mObjectsSize);
985     for(size_t i = mBufCachePos; i < mObjectsSize; i++) {
986         binder_size_t dataPos = mObjects[i];
987         binder_buffer_object *obj =
988             reinterpret_cast<binder_buffer_object*>(mData+dataPos);
989         if(!isBuffer(*obj))
990             continue;
991         BufferInfo ifo;
992         ifo.index = i;
993         ifo.buffer = obj->buffer;
994         ifo.bufend = obj->buffer + obj->length;
995         mBufCache.push_back(ifo);
996     }
997     mBufCachePos = mObjectsSize;
998 }
999 
1000 /* 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) const1001 status_t Parcel::findBuffer(const void *ptr, size_t length, bool *found,
1002                         size_t *handle, size_t *offset) const {
1003     if(found == nullptr)
1004         return UNKNOWN_ERROR;
1005     updateCache();
1006     binder_uintptr_t ptrVal = reinterpret_cast<binder_uintptr_t>(ptr);
1007     // true if the pointer is in some buffer, but the length is too big
1008     // so that ptr + length doesn't fit into the buffer.
1009     bool suspectRejectBadPointer = false;
1010     LOG_BUFFER("findBuffer examining %zu objects.", mObjectsSize);
1011     for(auto entry = mBufCache.rbegin(); entry != mBufCache.rend(); ++entry ) {
1012         if(entry->buffer <= ptrVal && ptrVal < entry->bufend) {
1013             // might have found it.
1014             if(ptrVal + length <= entry->bufend) {
1015                 *found = true;
1016                 if(handle != nullptr) *handle = entry->index;
1017                 if(offset != nullptr) *offset = ptrVal - entry->buffer;
1018                 LOG_BUFFER("    findBuffer has a match at %zu!", entry->index);
1019                 return OK;
1020             } else {
1021                 suspectRejectBadPointer = true;
1022             }
1023         }
1024     }
1025     LOG_BUFFER("findBuffer did not find for ptr = %p.", ptr);
1026     *found = false;
1027     return suspectRejectBadPointer ? BAD_VALUE : OK;
1028 }
1029 
1030 /* findBuffer with the assumption that ptr = .buffer (so it points to top
1031  * of the buffer, aka offset 0).
1032  *  */
quickFindBuffer(const void * ptr,size_t * handle) const1033 status_t Parcel::quickFindBuffer(const void *ptr, size_t *handle) const {
1034     updateCache();
1035     binder_uintptr_t ptrVal = reinterpret_cast<binder_uintptr_t>(ptr);
1036     LOG_BUFFER("quickFindBuffer examining %zu objects.", mObjectsSize);
1037     for(auto entry = mBufCache.rbegin(); entry != mBufCache.rend(); ++entry ) {
1038         if(entry->buffer == ptrVal) {
1039             if(handle != nullptr) *handle = entry->index;
1040             return OK;
1041         }
1042     }
1043     LOG_BUFFER("quickFindBuffer did not find for ptr = %p.", ptr);
1044     return NO_INIT;
1045 }
1046 
writeNativeHandleNoDup(const native_handle_t * handle,bool embedded,size_t parent_buffer_handle,size_t parent_offset)1047 status_t Parcel::writeNativeHandleNoDup(const native_handle_t *handle,
1048                                         bool embedded,
1049                                         size_t parent_buffer_handle,
1050                                         size_t parent_offset)
1051 {
1052     size_t buffer_handle;
1053     status_t status = OK;
1054 
1055     if (handle == nullptr) {
1056         status = writeUint64(0);
1057         return status;
1058     }
1059 
1060     size_t native_handle_size = sizeof(native_handle_t)
1061                 + handle->numFds * sizeof(int) + handle->numInts * sizeof(int);
1062     writeUint64(native_handle_size);
1063 
1064     if (embedded) {
1065         status = writeEmbeddedBuffer((void*) handle,
1066                 native_handle_size, &buffer_handle,
1067                 parent_buffer_handle, parent_offset);
1068     } else {
1069         status = writeBuffer((void*) handle, native_handle_size, &buffer_handle);
1070     }
1071 
1072     if (status != OK) {
1073         return status;
1074     }
1075 
1076     struct binder_fd_array_object fd_array {
1077         .hdr = { .type = BINDER_TYPE_FDA },
1078         .num_fds = static_cast<binder_size_t>(handle->numFds),
1079         .parent = buffer_handle,
1080         .parent_offset = offsetof(native_handle_t, data),
1081     };
1082 
1083     return writeObject(fd_array);
1084 }
1085 
writeNativeHandleNoDup(const native_handle_t * handle)1086 status_t Parcel::writeNativeHandleNoDup(const native_handle_t *handle)
1087 {
1088     return writeNativeHandleNoDup(handle, false /* embedded */);
1089 }
1090 
writeEmbeddedNativeHandle(const native_handle_t * handle,size_t parent_buffer_handle,size_t parent_offset)1091 status_t Parcel::writeEmbeddedNativeHandle(const native_handle_t *handle,
1092                                            size_t parent_buffer_handle,
1093                                            size_t parent_offset)
1094 {
1095     return writeNativeHandleNoDup(handle, true /* embedded */,
1096                                   parent_buffer_handle, parent_offset);
1097 }
1098 
remove(size_t,size_t)1099 void Parcel::remove(size_t /*start*/, size_t /*amt*/)
1100 {
1101     LOG_ALWAYS_FATAL("Parcel::remove() not yet implemented!");
1102 }
1103 
read(void * outData,size_t len) const1104 status_t Parcel::read(void* outData, size_t len) const
1105 {
1106     if (len > INT32_MAX) {
1107         // don't accept size_t values which may have come from an
1108         // inadvertent conversion from a negative int.
1109         return BAD_VALUE;
1110     }
1111 
1112     if ((mDataPos+pad_size(len)) >= mDataPos && (mDataPos+pad_size(len)) <= mDataSize
1113             && len <= pad_size(len)) {
1114         memcpy(outData, mData+mDataPos, len);
1115         mDataPos += pad_size(len);
1116         ALOGV("read Setting data pos of %p to %zu", this, mDataPos);
1117         return NO_ERROR;
1118     }
1119     return NOT_ENOUGH_DATA;
1120 }
1121 
readInplace(size_t len) const1122 const void* Parcel::readInplace(size_t len) const
1123 {
1124     if (len > INT32_MAX) {
1125         // don't accept size_t values which may have come from an
1126         // inadvertent conversion from a negative int.
1127         return nullptr;
1128     }
1129 
1130     if ((mDataPos+pad_size(len)) >= mDataPos && (mDataPos+pad_size(len)) <= mDataSize
1131             && len <= pad_size(len)) {
1132         const void* data = mData+mDataPos;
1133         mDataPos += pad_size(len);
1134         ALOGV("readInplace Setting data pos of %p to %zu", this, mDataPos);
1135         return data;
1136     }
1137     return nullptr;
1138 }
1139 
1140 template<class T>
readAligned(T * pArg) const1141 status_t Parcel::readAligned(T *pArg) const {
1142     COMPILE_TIME_ASSERT_FUNCTION_SCOPE(PAD_SIZE_UNSAFE(sizeof(T)) == sizeof(T));
1143 
1144     if ((mDataPos+sizeof(T)) <= mDataSize) {
1145         const void* data = mData+mDataPos;
1146         mDataPos += sizeof(T);
1147         *pArg =  *reinterpret_cast<const T*>(data);
1148         return NO_ERROR;
1149     } else {
1150         return NOT_ENOUGH_DATA;
1151     }
1152 }
1153 
1154 template<class T>
readAligned() const1155 T Parcel::readAligned() const {
1156     T result;
1157     if (readAligned(&result) != NO_ERROR) {
1158         result = 0;
1159     }
1160 
1161     return result;
1162 }
1163 
1164 template<class T>
writeAligned(T val)1165 status_t Parcel::writeAligned(T val) {
1166     COMPILE_TIME_ASSERT_FUNCTION_SCOPE(PAD_SIZE_UNSAFE(sizeof(T)) == sizeof(T));
1167 
1168     if ((mDataPos+sizeof(val)) <= mDataCapacity) {
1169 restart_write:
1170         *reinterpret_cast<T*>(mData+mDataPos) = val;
1171         return finishWrite(sizeof(val));
1172     }
1173 
1174     status_t err = growData(sizeof(val));
1175     if (err == NO_ERROR) goto restart_write;
1176     return err;
1177 }
1178 
readInt8(int8_t * pArg) const1179 status_t Parcel::readInt8(int8_t *pArg) const
1180 {
1181     return read(pArg, sizeof(*pArg));
1182 }
1183 
readUint8(uint8_t * pArg) const1184 status_t Parcel::readUint8(uint8_t *pArg) const
1185 {
1186     return read(pArg, sizeof(*pArg));
1187 }
1188 
readInt16(int16_t * pArg) const1189 status_t Parcel::readInt16(int16_t *pArg) const
1190 {
1191     return read(pArg, sizeof(*pArg));
1192 }
1193 
readUint16(uint16_t * pArg) const1194 status_t Parcel::readUint16(uint16_t *pArg) const
1195 {
1196     return read(pArg, sizeof(*pArg));
1197 }
1198 
readInt32(int32_t * pArg) const1199 status_t Parcel::readInt32(int32_t *pArg) const
1200 {
1201     return readAligned(pArg);
1202 }
1203 
readInt32() const1204 int32_t Parcel::readInt32() const
1205 {
1206     return readAligned<int32_t>();
1207 }
1208 
readUint32(uint32_t * pArg) const1209 status_t Parcel::readUint32(uint32_t *pArg) const
1210 {
1211     return readAligned(pArg);
1212 }
1213 
readUint32() const1214 uint32_t Parcel::readUint32() const
1215 {
1216     return readAligned<uint32_t>();
1217 }
1218 
readInt64(int64_t * pArg) const1219 status_t Parcel::readInt64(int64_t *pArg) const
1220 {
1221     return readAligned(pArg);
1222 }
1223 
readInt64() const1224 int64_t Parcel::readInt64() const
1225 {
1226     return readAligned<int64_t>();
1227 }
1228 
readUint64(uint64_t * pArg) const1229 status_t Parcel::readUint64(uint64_t *pArg) const
1230 {
1231     return readAligned(pArg);
1232 }
1233 
readUint64() const1234 uint64_t Parcel::readUint64() const
1235 {
1236     return readAligned<uint64_t>();
1237 }
1238 
readPointer(uintptr_t * pArg) const1239 status_t Parcel::readPointer(uintptr_t *pArg) const
1240 {
1241     status_t ret;
1242     binder_uintptr_t ptr;
1243     ret = readAligned(&ptr);
1244     if (!ret)
1245         *pArg = ptr;
1246     return ret;
1247 }
1248 
readPointer() const1249 uintptr_t Parcel::readPointer() const
1250 {
1251     return readAligned<binder_uintptr_t>();
1252 }
1253 
1254 
readFloat(float * pArg) const1255 status_t Parcel::readFloat(float *pArg) const
1256 {
1257     return readAligned(pArg);
1258 }
1259 
1260 
readFloat() const1261 float Parcel::readFloat() const
1262 {
1263     return readAligned<float>();
1264 }
1265 
1266 #if defined(__mips__) && defined(__mips_hard_float)
1267 
readDouble(double * pArg) const1268 status_t Parcel::readDouble(double *pArg) const
1269 {
1270     union {
1271       double d;
1272       unsigned long long ll;
1273     } u;
1274     u.d = 0;
1275     status_t status;
1276     status = readAligned(&u.ll);
1277     *pArg = u.d;
1278     return status;
1279 }
1280 
readDouble() const1281 double Parcel::readDouble() const
1282 {
1283     union {
1284       double d;
1285       unsigned long long ll;
1286     } u;
1287     u.ll = readAligned<unsigned long long>();
1288     return u.d;
1289 }
1290 
1291 #else
1292 
readDouble(double * pArg) const1293 status_t Parcel::readDouble(double *pArg) const
1294 {
1295     return readAligned(pArg);
1296 }
1297 
readDouble() const1298 double Parcel::readDouble() const
1299 {
1300     return readAligned<double>();
1301 }
1302 
1303 #endif
1304 
readBool(bool * pArg) const1305 status_t Parcel::readBool(bool *pArg) const
1306 {
1307     int8_t tmp;
1308     status_t ret = readInt8(&tmp);
1309     *pArg = (tmp != 0);
1310     return ret;
1311 }
1312 
readBool() const1313 bool Parcel::readBool() const
1314 {
1315     int8_t tmp;
1316     status_t err = readInt8(&tmp);
1317 
1318     if (err != OK) {
1319         return 0;
1320     }
1321 
1322     return tmp != 0;
1323 }
1324 
readCString() const1325 const char* Parcel::readCString() const
1326 {
1327     if (mDataPos < mDataSize) {
1328         const size_t avail = mDataSize-mDataPos;
1329         const char* str = reinterpret_cast<const char*>(mData+mDataPos);
1330         // is the string's trailing NUL within the parcel's valid bounds?
1331         const char* eos = reinterpret_cast<const char*>(memchr(str, 0, avail));
1332         if (eos) {
1333             const size_t len = eos - str;
1334             mDataPos += pad_size(len+1);
1335             ALOGV("readCString Setting data pos of %p to %zu", this, mDataPos);
1336             return str;
1337         }
1338     }
1339     return nullptr;
1340 }
readString16() const1341 String16 Parcel::readString16() const
1342 {
1343     size_t len;
1344     const char16_t* str = readString16Inplace(&len);
1345     if (str) return String16(str, len);
1346     ALOGE("Reading a NULL string not supported here.");
1347     return String16();
1348 }
1349 
readString16(std::unique_ptr<String16> * pArg) const1350 status_t Parcel::readString16(std::unique_ptr<String16>* pArg) const
1351 {
1352     const int32_t start = dataPosition();
1353     int32_t size;
1354     status_t status = readInt32(&size);
1355     pArg->reset();
1356 
1357     if (status != OK || size < 0) {
1358         return status;
1359     }
1360 
1361     setDataPosition(start);
1362     pArg->reset(new (std::nothrow) String16());
1363 
1364     status = readString16(pArg->get());
1365 
1366     if (status != OK) {
1367         pArg->reset();
1368     }
1369 
1370     return status;
1371 }
1372 
readString16(String16 * pArg) const1373 status_t Parcel::readString16(String16* pArg) const
1374 {
1375     size_t len;
1376     const char16_t* str = readString16Inplace(&len);
1377     if (str) {
1378         pArg->setTo(str, len);
1379         return 0;
1380     } else {
1381         *pArg = String16();
1382         return UNEXPECTED_NULL;
1383     }
1384 }
1385 
readString16Inplace(size_t * outLen) const1386 const char16_t* Parcel::readString16Inplace(size_t* outLen) const
1387 {
1388     int32_t size = readInt32();
1389     // watch for potential int overflow from size+1
1390     if (size >= 0 && size < INT32_MAX) {
1391         *outLen = size;
1392         const char16_t* str = (const char16_t*)readInplace((size+1)*sizeof(char16_t));
1393         if (str != nullptr) {
1394             return str;
1395         }
1396     }
1397     *outLen = 0;
1398     return nullptr;
1399 }
readStrongBinder(sp<IBinder> * val) const1400 status_t Parcel::readStrongBinder(sp<IBinder>* val) const
1401 {
1402     status_t status = readNullableStrongBinder(val);
1403     if (status == OK && !val->get()) {
1404         status = UNEXPECTED_NULL;
1405     }
1406     return status;
1407 }
1408 
readNullableStrongBinder(sp<IBinder> * val) const1409 status_t Parcel::readNullableStrongBinder(sp<IBinder>* val) const
1410 {
1411     return unflatten_binder(ProcessState::self(), *this, val);
1412 }
1413 
readStrongBinder() const1414 sp<IBinder> Parcel::readStrongBinder() const
1415 {
1416     sp<IBinder> val;
1417     // Note that a lot of code in Android reads binders by hand with this
1418     // method, and that code has historically been ok with getting nullptr
1419     // back (while ignoring error codes).
1420     readNullableStrongBinder(&val);
1421     return val;
1422 }
1423 
readWeakBinder() const1424 wp<IBinder> Parcel::readWeakBinder() const
1425 {
1426     wp<IBinder> val;
1427     unflatten_binder(ProcessState::self(), *this, &val);
1428     return val;
1429 }
1430 
1431 template<typename T>
readObject(size_t * objects_offset) const1432 const T* Parcel::readObject(size_t *objects_offset) const
1433 {
1434     const size_t DPOS = mDataPos;
1435     if (objects_offset != nullptr) {
1436         *objects_offset = 0;
1437     }
1438 
1439     if ((DPOS+sizeof(T)) <= mDataSize) {
1440         const T* obj = reinterpret_cast<const T*>(mData+DPOS);
1441         mDataPos = DPOS + sizeof(T);
1442         const binder_object_header *hdr = reinterpret_cast<const binder_object_header*>(obj);
1443         switch (hdr->type) {
1444             case BINDER_TYPE_BINDER:
1445             case BINDER_TYPE_WEAK_BINDER:
1446             case BINDER_TYPE_HANDLE:
1447             case BINDER_TYPE_WEAK_HANDLE: {
1448                 const flat_binder_object *flat_obj =
1449                     reinterpret_cast<const flat_binder_object*>(hdr);
1450                 if (flat_obj->cookie == 0 && flat_obj->binder == 0) {
1451                     // When transferring a NULL binder object, we don't write it into
1452                     // the object list, so we don't want to check for it when
1453                     // reading.
1454                     ALOGV("readObject Setting data pos of %p to %zu", this, mDataPos);
1455                     return obj;
1456                 }
1457                 break;
1458             }
1459             case BINDER_TYPE_FD:
1460             case BINDER_TYPE_FDA:
1461                 // fd (-arrays) must always appear in the meta-data list (eg touched by the kernel)
1462                 break;
1463             case BINDER_TYPE_PTR: {
1464                 const binder_buffer_object *buffer_obj =
1465                     reinterpret_cast<const binder_buffer_object*>(hdr);
1466                 if ((void *)buffer_obj->buffer == nullptr) {
1467                     // null pointers can be returned directly - they're not written in the
1468                     // object list. All non-null buffers must appear in the objects list.
1469                     return obj;
1470                 }
1471                 break;
1472             }
1473         }
1474         // Ensure that this object is valid...
1475         binder_size_t* const OBJS = mObjects;
1476         const size_t N = mObjectsSize;
1477         size_t opos = mNextObjectHint;
1478 
1479         if (N > 0) {
1480             ALOGV("Parcel %p looking for obj at %zu, hint=%zu",
1481                  this, DPOS, opos);
1482 
1483             // Start at the current hint position, looking for an object at
1484             // the current data position.
1485             if (opos < N) {
1486                 while (opos < (N-1) && OBJS[opos] < DPOS) {
1487                     opos++;
1488                 }
1489             } else {
1490                 opos = N-1;
1491             }
1492             if (OBJS[opos] == DPOS) {
1493                 // Found it!
1494                 ALOGV("Parcel %p found obj %zu at index %zu with forward search",
1495                      this, DPOS, opos);
1496                 mNextObjectHint = opos+1;
1497                 ALOGV("readObject Setting data pos of %p to %zu", this, mDataPos);
1498                 if (objects_offset != nullptr) {
1499                     *objects_offset = opos;
1500                 }
1501                 return obj;
1502             }
1503 
1504             // Look backwards for it...
1505             while (opos > 0 && OBJS[opos] > DPOS) {
1506                 opos--;
1507             }
1508             if (OBJS[opos] == DPOS) {
1509                 // Found it!
1510                 ALOGV("Parcel %p found obj %zu at index %zu with backward search",
1511                      this, DPOS, opos);
1512                 mNextObjectHint = opos+1;
1513                 ALOGV("readObject Setting data pos of %p to %zu", this, mDataPos);
1514                 if (objects_offset != nullptr) {
1515                     *objects_offset = opos;
1516                 }
1517                 return obj;
1518             }
1519         }
1520         ALOGW("Attempt to read object from Parcel %p at offset %zu that is not in the object list",
1521              this, DPOS);
1522     }
1523     return nullptr;
1524 }
1525 
1526 template const flat_binder_object* Parcel::readObject<flat_binder_object>(size_t *objects_offset) const;
1527 
1528 template const binder_fd_object* Parcel::readObject<binder_fd_object>(size_t *objects_offset) const;
1529 
1530 template const binder_buffer_object* Parcel::readObject<binder_buffer_object>(size_t *objects_offset) const;
1531 
1532 template const binder_fd_array_object* Parcel::readObject<binder_fd_array_object>(size_t *objects_offset) const;
1533 
verifyBufferObject(const binder_buffer_object * buffer_obj,size_t size,uint32_t flags,size_t parent,size_t parentOffset) const1534 bool Parcel::verifyBufferObject(const binder_buffer_object *buffer_obj,
1535                                 size_t size, uint32_t flags, size_t parent,
1536                                 size_t parentOffset) const {
1537     if (buffer_obj->length != size) {
1538         ALOGE("Buffer length %" PRIu64 " does not match expected size %zu.",
1539               static_cast<uint64_t>(buffer_obj->length), size);
1540         return false;
1541     }
1542 
1543     if (buffer_obj->flags != flags) {
1544         ALOGE("Buffer flags 0x%02X do not match expected flags 0x%02X.", buffer_obj->flags, flags);
1545         return false;
1546     }
1547 
1548     if (flags & BINDER_BUFFER_FLAG_HAS_PARENT) {
1549         if (buffer_obj->parent != parent) {
1550             ALOGE("Buffer parent %" PRIu64 " does not match expected parent %zu.",
1551                   static_cast<uint64_t>(buffer_obj->parent), parent);
1552             return false;
1553         }
1554         if (buffer_obj->parent_offset != parentOffset) {
1555               ALOGE("Buffer parent offset %" PRIu64 " does not match expected offset %zu.",
1556                   static_cast<uint64_t>(buffer_obj->parent_offset), parentOffset);
1557             return false;
1558         }
1559     }
1560 
1561     return true;
1562 }
1563 
readBuffer(size_t buffer_size,size_t * buffer_handle,uint32_t flags,size_t parent,size_t parentOffset,const void ** buffer_out) const1564 status_t Parcel::readBuffer(size_t buffer_size, size_t *buffer_handle,
1565                             uint32_t flags, size_t parent, size_t parentOffset,
1566                             const void **buffer_out) const {
1567 
1568     const binder_buffer_object* buffer_obj = readObject<binder_buffer_object>(buffer_handle);
1569 
1570     if (buffer_obj == nullptr || !isBuffer(*buffer_obj)) {
1571         return BAD_VALUE;
1572     }
1573 
1574     if (!verifyBufferObject(buffer_obj, buffer_size, flags, parent, parentOffset)) {
1575         return BAD_VALUE;
1576     }
1577 
1578     // in read side, always use .buffer and .length.
1579     *buffer_out = reinterpret_cast<void*>(buffer_obj->buffer);
1580 
1581     return OK;
1582 }
1583 
readNullableBuffer(size_t buffer_size,size_t * buffer_handle,const void ** buffer_out) const1584 status_t Parcel::readNullableBuffer(size_t buffer_size, size_t *buffer_handle,
1585                                     const void **buffer_out) const
1586 {
1587     return readBuffer(buffer_size, buffer_handle,
1588                       0 /* flags */, 0 /* parent */, 0 /* parentOffset */,
1589                       buffer_out);
1590 }
1591 
readBuffer(size_t buffer_size,size_t * buffer_handle,const void ** buffer_out) const1592 status_t Parcel::readBuffer(size_t buffer_size, size_t *buffer_handle,
1593                             const void **buffer_out) const
1594 {
1595     status_t status = readNullableBuffer(buffer_size, buffer_handle, buffer_out);
1596     if (status == OK && *buffer_out == nullptr) {
1597         return UNEXPECTED_NULL;
1598     }
1599     return status;
1600 }
1601 
1602 
readEmbeddedBuffer(size_t buffer_size,size_t * buffer_handle,size_t parent_buffer_handle,size_t parent_offset,const void ** buffer_out) const1603 status_t Parcel::readEmbeddedBuffer(size_t buffer_size,
1604                                     size_t *buffer_handle,
1605                                     size_t parent_buffer_handle,
1606                                     size_t parent_offset,
1607                                     const void **buffer_out) const
1608 {
1609     status_t status = readNullableEmbeddedBuffer(buffer_size, buffer_handle,
1610                                                  parent_buffer_handle,
1611                                                  parent_offset, buffer_out);
1612     if (status == OK && *buffer_out == nullptr) {
1613         return UNEXPECTED_NULL;
1614     }
1615     return status;
1616 }
1617 
readNullableEmbeddedBuffer(size_t buffer_size,size_t * buffer_handle,size_t parent_buffer_handle,size_t parent_offset,const void ** buffer_out) const1618 status_t Parcel::readNullableEmbeddedBuffer(size_t buffer_size,
1619                                             size_t *buffer_handle,
1620                                             size_t parent_buffer_handle,
1621                                             size_t parent_offset,
1622                                             const void **buffer_out) const
1623 {
1624     return readBuffer(buffer_size, buffer_handle, BINDER_BUFFER_FLAG_HAS_PARENT,
1625                       parent_buffer_handle, parent_offset, buffer_out);
1626 }
1627 
1628 // isRef if corresponds to a writeReference call, else corresponds to a writeBuffer call.
1629 // see ::android::hardware::writeReferenceToParcel for details.
readReference(void const ** bufptr,size_t * buffer_handle,bool * isRef) const1630 status_t Parcel::readReference(void const* *bufptr,
1631                                size_t *buffer_handle, bool *isRef) const
1632 {
1633     LOG_BUFFER("readReference");
1634     const binder_buffer_object* buffer_obj = readObject<binder_buffer_object>();
1635     LOG_BUFFER("    readReference: buf = %p, len = %zu, flags = %x",
1636         (void*)buffer_obj->buffer, (size_t)buffer_obj->length,
1637         (int)buffer_obj->flags);
1638     // TODO need verification here
1639     if (buffer_obj && buffer_obj->hdr.type == BINDER_TYPE_PTR) {
1640         if (buffer_handle != nullptr) {
1641             *buffer_handle = 0; // TODO fix this, as readBuffer would do
1642         }
1643         if(isRef != nullptr) {
1644             *isRef = (buffer_obj->flags & BINDER_BUFFER_FLAG_REF) != 0;
1645             LOG_BUFFER("    readReference: isRef = %d", *isRef);
1646         }
1647         // in read side, always use .buffer and .length.
1648         if(bufptr != nullptr) {
1649             *bufptr = (void*)buffer_obj->buffer;
1650         }
1651         return OK;
1652     }
1653 
1654     return BAD_VALUE;
1655 }
1656 
1657 // isRef if corresponds to a writeEmbeddedReference call, else corresponds to a writeEmbeddedBuffer call.
1658 // see ::android::hardware::writeEmbeddedReferenceToParcel for details.
readEmbeddedReference(void const ** bufptr,size_t * buffer_handle,size_t,size_t,bool * isRef) const1659 status_t Parcel::readEmbeddedReference(void const* *bufptr,
1660                                        size_t *buffer_handle,
1661                                        size_t /* parent_buffer_handle */,
1662                                        size_t /* parent_offset */,
1663                                        bool *isRef) const
1664 {
1665     // TODO verify parent and offset
1666     LOG_BUFFER("readEmbeddedReference");
1667     return (readReference(bufptr, buffer_handle, isRef));
1668 }
1669 
readEmbeddedNativeHandle(size_t parent_buffer_handle,size_t parent_offset,const native_handle_t ** handle) const1670 status_t Parcel::readEmbeddedNativeHandle(size_t parent_buffer_handle,
1671                                           size_t parent_offset,
1672                                           const native_handle_t **handle) const
1673 {
1674     status_t status = readNullableEmbeddedNativeHandle(parent_buffer_handle, parent_offset, handle);
1675     if (status == OK && *handle == nullptr) {
1676         return UNEXPECTED_NULL;
1677     }
1678     return status;
1679 }
1680 
readNullableNativeHandleNoDup(const native_handle_t ** handle,bool embedded,size_t parent_buffer_handle,size_t parent_offset) const1681 status_t Parcel::readNullableNativeHandleNoDup(const native_handle_t **handle,
1682                                                bool embedded,
1683                                                size_t parent_buffer_handle,
1684                                                size_t parent_offset) const
1685 {
1686     status_t status;
1687     uint64_t nativeHandleSize;
1688     size_t fdaParent;
1689 
1690     status = readUint64(&nativeHandleSize);
1691     if (status != OK || nativeHandleSize == 0) {
1692         *handle = nullptr;
1693         return status;
1694     }
1695 
1696     if (nativeHandleSize < sizeof(native_handle_t)) {
1697         ALOGE("Received a native_handle_t size that was too small.");
1698         return BAD_VALUE;
1699     }
1700 
1701     if (embedded) {
1702         status = readNullableEmbeddedBuffer(nativeHandleSize, &fdaParent,
1703                                             parent_buffer_handle, parent_offset,
1704                                             reinterpret_cast<const void**>(handle));
1705     } else {
1706         status = readNullableBuffer(nativeHandleSize, &fdaParent,
1707                                     reinterpret_cast<const void**>(handle));
1708     }
1709 
1710     if (status != OK) {
1711         return status;
1712     }
1713 
1714     int numFds = (*handle)->numFds;
1715     int numInts = (*handle)->numInts;
1716 
1717     if (numFds < 0 || numFds > NATIVE_HANDLE_MAX_FDS) {
1718         ALOGE("Received native_handle with invalid number of fds.");
1719         return BAD_VALUE;
1720     }
1721 
1722     if (numInts < 0 || numInts > NATIVE_HANDLE_MAX_INTS) {
1723         ALOGE("Received native_handle with invalid number of ints.");
1724         return BAD_VALUE;
1725     }
1726 
1727     if (nativeHandleSize != (sizeof(native_handle_t) + ((numFds + numInts) * sizeof(int)))) {
1728         ALOGE("Size of native_handle doesn't match.");
1729         return BAD_VALUE;
1730     }
1731 
1732     const binder_fd_array_object* fd_array_obj = readObject<binder_fd_array_object>();
1733 
1734     if (fd_array_obj == nullptr || fd_array_obj->hdr.type != BINDER_TYPE_FDA) {
1735         ALOGE("Can't find file-descriptor array object.");
1736         return BAD_VALUE;
1737     }
1738 
1739     if (static_cast<int>(fd_array_obj->num_fds) != numFds) {
1740         ALOGE("Number of native handles does not match.");
1741         return BAD_VALUE;
1742     }
1743 
1744     if (fd_array_obj->parent != fdaParent) {
1745         ALOGE("Parent handle of file-descriptor array not correct.");
1746         return BAD_VALUE;
1747     }
1748 
1749     if (fd_array_obj->parent_offset != offsetof(native_handle_t, data)) {
1750         ALOGE("FD array object not properly offset in parent.");
1751         return BAD_VALUE;
1752     }
1753 
1754     return OK;
1755 }
1756 
readNullableEmbeddedNativeHandle(size_t parent_buffer_handle,size_t parent_offset,const native_handle_t ** handle) const1757 status_t Parcel::readNullableEmbeddedNativeHandle(size_t parent_buffer_handle,
1758                                                   size_t parent_offset,
1759                                                   const native_handle_t **handle) const
1760 {
1761     return readNullableNativeHandleNoDup(handle, true /* embedded */, parent_buffer_handle,
1762                                          parent_offset);
1763 }
1764 
readNativeHandleNoDup(const native_handle_t ** handle) const1765 status_t Parcel::readNativeHandleNoDup(const native_handle_t **handle) const
1766 {
1767     status_t status = readNullableNativeHandleNoDup(handle);
1768     if (status == OK && *handle == nullptr) {
1769         return UNEXPECTED_NULL;
1770     }
1771     return status;
1772 }
1773 
readNullableNativeHandleNoDup(const native_handle_t ** handle) const1774 status_t Parcel::readNullableNativeHandleNoDup(const native_handle_t **handle) const
1775 {
1776     return readNullableNativeHandleNoDup(handle, false /* embedded */);
1777 }
1778 
closeFileDescriptors()1779 void Parcel::closeFileDescriptors()
1780 {
1781     size_t i = mObjectsSize;
1782     if (i > 0) {
1783         //ALOGI("Closing file descriptors for %zu objects...", i);
1784     }
1785     while (i > 0) {
1786         i--;
1787         const flat_binder_object* flat
1788             = reinterpret_cast<flat_binder_object*>(mData+mObjects[i]);
1789         if (flat->hdr.type == BINDER_TYPE_FD) {
1790             //ALOGI("Closing fd: %ld", flat->handle);
1791             close(flat->handle);
1792         }
1793     }
1794 }
1795 
ipcData() const1796 uintptr_t Parcel::ipcData() const
1797 {
1798     return reinterpret_cast<uintptr_t>(mData);
1799 }
1800 
ipcDataSize() const1801 size_t Parcel::ipcDataSize() const
1802 {
1803     return mDataSize > mDataPos ? mDataSize : mDataPos;
1804 }
1805 
ipcObjects() const1806 uintptr_t Parcel::ipcObjects() const
1807 {
1808     return reinterpret_cast<uintptr_t>(mObjects);
1809 }
1810 
ipcObjectsCount() const1811 size_t Parcel::ipcObjectsCount() const
1812 {
1813     return mObjectsSize;
1814 }
1815 
1816 #define BUFFER_ALIGNMENT_BYTES 8
ipcBufferSize() const1817 size_t Parcel::ipcBufferSize() const
1818 {
1819     size_t totalBuffersSize = 0;
1820     // Add size for BINDER_TYPE_PTR
1821     size_t i = mObjectsSize;
1822     while (i > 0) {
1823         i--;
1824         const binder_buffer_object* buffer
1825             = reinterpret_cast<binder_buffer_object*>(mData+mObjects[i]);
1826         if (isBuffer(*buffer)) {
1827             /* The binder kernel driver requires each buffer to be 8-byte
1828              * aligned */
1829             size_t alignedSize = (buffer->length + (BUFFER_ALIGNMENT_BYTES - 1))
1830                     & ~(BUFFER_ALIGNMENT_BYTES - 1);
1831             if (alignedSize > SIZE_MAX - totalBuffersSize) {
1832                 ALOGE("ipcBuffersSize(): invalid buffer sizes.");
1833                 return 0;
1834             }
1835             totalBuffersSize += alignedSize;
1836         }
1837     }
1838     return totalBuffersSize;
1839 }
1840 
ipcSetDataReference(const uint8_t * data,size_t dataSize,const binder_size_t * objects,size_t objectsCount,release_func relFunc,void * relCookie)1841 void Parcel::ipcSetDataReference(const uint8_t* data, size_t dataSize,
1842     const binder_size_t* objects, size_t objectsCount, release_func relFunc, void* relCookie)
1843 {
1844     binder_size_t minOffset = 0;
1845     freeDataNoInit();
1846     mError = NO_ERROR;
1847     mData = const_cast<uint8_t*>(data);
1848     mDataSize = mDataCapacity = dataSize;
1849     //ALOGI("setDataReference Setting data size of %p to %lu (pid=%d)", this, mDataSize, getpid());
1850     mDataPos = 0;
1851     ALOGV("setDataReference Setting data pos of %p to %zu", this, mDataPos);
1852     mObjects = const_cast<binder_size_t*>(objects);
1853     mObjectsSize = mObjectsCapacity = objectsCount;
1854     mNextObjectHint = 0;
1855     clearCache();
1856     mNumRef = 0;
1857     mOwner = relFunc;
1858     mOwnerCookie = relCookie;
1859     for (size_t i = 0; i < mObjectsSize; i++) {
1860         binder_size_t offset = mObjects[i];
1861         if (offset < minOffset) {
1862             ALOGE("%s: bad object offset %" PRIu64 " < %" PRIu64 "\n",
1863                   __func__, (uint64_t)offset, (uint64_t)minOffset);
1864             mObjectsSize = 0;
1865             break;
1866         }
1867         minOffset = offset + sizeof(flat_binder_object);
1868     }
1869     scanForFds();
1870 }
1871 
print(TextOutput & to,uint32_t) const1872 void Parcel::print(TextOutput& to, uint32_t /*flags*/) const
1873 {
1874     to << "Parcel(";
1875 
1876     if (errorCheck() != NO_ERROR) {
1877         const status_t err = errorCheck();
1878         to << "Error: " << (void*)(intptr_t)err << " \"" << strerror(-err) << "\"";
1879     } else if (dataSize() > 0) {
1880         const uint8_t* DATA = data();
1881         to << indent << HexDump(DATA, dataSize()) << dedent;
1882         const binder_size_t* OBJS = objects();
1883         const size_t N = objectsCount();
1884         for (size_t i=0; i<N; i++) {
1885             const flat_binder_object* flat
1886                 = reinterpret_cast<const flat_binder_object*>(DATA+OBJS[i]);
1887             if (flat->hdr.type == BINDER_TYPE_PTR) {
1888                 const binder_buffer_object* buffer
1889                     = reinterpret_cast<const binder_buffer_object*>(DATA+OBJS[i]);
1890                 if(isBuffer(*buffer)) {
1891                     HexDump bufferDump((const uint8_t*)buffer->buffer, (size_t)buffer->length);
1892                     bufferDump.setSingleLineCutoff(0);
1893                     to << endl << "Object #" << i << " @ " << (void*)OBJS[i] << " (buffer size " << buffer->length << "):";
1894                     to << indent << bufferDump << dedent;
1895                 } else {
1896                     to << endl << "Object #" << i << " @ " << (void*)OBJS[i];
1897                 }
1898             } else {
1899                 to << endl << "Object #" << i << " @ " << (void*)OBJS[i] << ": "
1900                     << TypeCode(flat->hdr.type & 0x7f7f7f00)
1901                     << " = " << flat->binder;
1902             }
1903         }
1904     } else {
1905         to << "NULL";
1906     }
1907 
1908     to << ")";
1909 }
1910 
releaseObjects()1911 void Parcel::releaseObjects()
1912 {
1913     const sp<ProcessState> proc(ProcessState::self());
1914     size_t i = mObjectsSize;
1915     uint8_t* const data = mData;
1916     binder_size_t* const objects = mObjects;
1917     while (i > 0) {
1918         i--;
1919         const flat_binder_object* flat
1920             = reinterpret_cast<flat_binder_object*>(data+objects[i]);
1921         release_object(proc, *flat, this);
1922     }
1923 }
1924 
acquireObjects()1925 void Parcel::acquireObjects()
1926 {
1927     const sp<ProcessState> proc(ProcessState::self());
1928     size_t i = mObjectsSize;
1929     uint8_t* const data = mData;
1930     binder_size_t* const objects = mObjects;
1931     while (i > 0) {
1932         i--;
1933         const binder_object_header* flat
1934             = reinterpret_cast<binder_object_header*>(data+objects[i]);
1935         acquire_object(proc, *flat, this);
1936     }
1937 }
1938 
freeData()1939 void Parcel::freeData()
1940 {
1941     freeDataNoInit();
1942     initState();
1943 }
1944 
freeDataNoInit()1945 void Parcel::freeDataNoInit()
1946 {
1947     if (mOwner) {
1948         LOG_ALLOC("Parcel %p: freeing other owner data", this);
1949         //ALOGI("Freeing data ref of %p (pid=%d)", this, getpid());
1950         mOwner(this, mData, mDataSize, mObjects, mObjectsSize, mOwnerCookie);
1951     } else {
1952         LOG_ALLOC("Parcel %p: freeing allocated data", this);
1953         releaseObjects();
1954         if (mData) {
1955             LOG_ALLOC("Parcel %p: freeing with %zu capacity", this, mDataCapacity);
1956             pthread_mutex_lock(&gParcelGlobalAllocSizeLock);
1957             if (mDataCapacity <= gParcelGlobalAllocSize) {
1958               gParcelGlobalAllocSize = gParcelGlobalAllocSize - mDataCapacity;
1959             } else {
1960               gParcelGlobalAllocSize = 0;
1961             }
1962             if (gParcelGlobalAllocCount > 0) {
1963               gParcelGlobalAllocCount--;
1964             }
1965             pthread_mutex_unlock(&gParcelGlobalAllocSizeLock);
1966             free(mData);
1967         }
1968         if (mObjects) free(mObjects);
1969     }
1970 }
1971 
growData(size_t len)1972 status_t Parcel::growData(size_t len)
1973 {
1974     if (len > INT32_MAX) {
1975         // don't accept size_t values which may have come from an
1976         // inadvertent conversion from a negative int.
1977         return BAD_VALUE;
1978     }
1979 
1980     size_t newSize = ((mDataSize+len)*3)/2;
1981     return (newSize <= mDataSize)
1982             ? (status_t) NO_MEMORY
1983             : continueWrite(newSize);
1984 }
1985 
restartWrite(size_t desired)1986 status_t Parcel::restartWrite(size_t desired)
1987 {
1988     if (desired > INT32_MAX) {
1989         // don't accept size_t values which may have come from an
1990         // inadvertent conversion from a negative int.
1991         return BAD_VALUE;
1992     }
1993 
1994     if (mOwner) {
1995         freeData();
1996         return continueWrite(desired);
1997     }
1998 
1999     uint8_t* data = (uint8_t*)realloc(mData, desired);
2000     if (!data && desired > mDataCapacity) {
2001         mError = NO_MEMORY;
2002         return NO_MEMORY;
2003     }
2004 
2005     releaseObjects();
2006 
2007     if (data) {
2008         LOG_ALLOC("Parcel %p: restart from %zu to %zu capacity", this, mDataCapacity, desired);
2009         pthread_mutex_lock(&gParcelGlobalAllocSizeLock);
2010         gParcelGlobalAllocSize += desired;
2011         gParcelGlobalAllocSize -= mDataCapacity;
2012         if (!mData) {
2013             gParcelGlobalAllocCount++;
2014         }
2015         pthread_mutex_unlock(&gParcelGlobalAllocSizeLock);
2016         mData = data;
2017         mDataCapacity = desired;
2018     }
2019 
2020     mDataSize = mDataPos = 0;
2021     ALOGV("restartWrite Setting data size of %p to %zu", this, mDataSize);
2022     ALOGV("restartWrite Setting data pos of %p to %zu", this, mDataPos);
2023 
2024     free(mObjects);
2025     mObjects = nullptr;
2026     mObjectsSize = mObjectsCapacity = 0;
2027     mNextObjectHint = 0;
2028     mHasFds = false;
2029     clearCache();
2030     mNumRef = 0;
2031     mFdsKnown = true;
2032     mAllowFds = true;
2033 
2034     return NO_ERROR;
2035 }
2036 
continueWrite(size_t desired)2037 status_t Parcel::continueWrite(size_t desired)
2038 {
2039     if (desired > INT32_MAX) {
2040         // don't accept size_t values which may have come from an
2041         // inadvertent conversion from a negative int.
2042         return BAD_VALUE;
2043     }
2044 
2045     // If shrinking, first adjust for any objects that appear
2046     // after the new data size.
2047     size_t objectsSize = mObjectsSize;
2048     if (desired < mDataSize) {
2049         if (desired == 0) {
2050             objectsSize = 0;
2051         } else {
2052             while (objectsSize > 0) {
2053                 if (mObjects[objectsSize-1] < desired)
2054                     break;
2055                 objectsSize--;
2056             }
2057         }
2058     }
2059 
2060     if (mOwner) {
2061         // If the size is going to zero, just release the owner's data.
2062         if (desired == 0) {
2063             freeData();
2064             return NO_ERROR;
2065         }
2066 
2067         // If there is a different owner, we need to take
2068         // posession.
2069         uint8_t* data = (uint8_t*)malloc(desired);
2070         if (!data) {
2071             mError = NO_MEMORY;
2072             return NO_MEMORY;
2073         }
2074         binder_size_t* objects = nullptr;
2075 
2076         if (objectsSize) {
2077             objects = (binder_size_t*)calloc(objectsSize, sizeof(binder_size_t));
2078             if (!objects) {
2079                 free(data);
2080 
2081                 mError = NO_MEMORY;
2082                 return NO_MEMORY;
2083             }
2084 
2085             // Little hack to only acquire references on objects
2086             // we will be keeping.
2087             size_t oldObjectsSize = mObjectsSize;
2088             mObjectsSize = objectsSize;
2089             acquireObjects();
2090             mObjectsSize = oldObjectsSize;
2091         }
2092 
2093         if (mData) {
2094             memcpy(data, mData, mDataSize < desired ? mDataSize : desired);
2095         }
2096         if (objects && mObjects) {
2097             memcpy(objects, mObjects, objectsSize*sizeof(binder_size_t));
2098         }
2099         //ALOGI("Freeing data ref of %p (pid=%d)", this, getpid());
2100         mOwner(this, mData, mDataSize, mObjects, mObjectsSize, mOwnerCookie);
2101         mOwner = nullptr;
2102 
2103         LOG_ALLOC("Parcel %p: taking ownership of %zu capacity", this, desired);
2104         pthread_mutex_lock(&gParcelGlobalAllocSizeLock);
2105         gParcelGlobalAllocSize += desired;
2106         gParcelGlobalAllocCount++;
2107         pthread_mutex_unlock(&gParcelGlobalAllocSizeLock);
2108 
2109         mData = data;
2110         mObjects = objects;
2111         mDataSize = (mDataSize < desired) ? mDataSize : desired;
2112         ALOGV("continueWrite Setting data size of %p to %zu", this, mDataSize);
2113         mDataCapacity = desired;
2114         mObjectsSize = mObjectsCapacity = objectsSize;
2115         mNextObjectHint = 0;
2116 
2117         clearCache();
2118     } else if (mData) {
2119         if (objectsSize < mObjectsSize) {
2120             // Need to release refs on any objects we are dropping.
2121             const sp<ProcessState> proc(ProcessState::self());
2122             for (size_t i=objectsSize; i<mObjectsSize; i++) {
2123                 const flat_binder_object* flat
2124                     = reinterpret_cast<flat_binder_object*>(mData+mObjects[i]);
2125                 if (flat->hdr.type == BINDER_TYPE_FD) {
2126                     // will need to rescan because we may have lopped off the only FDs
2127                     mFdsKnown = false;
2128                 }
2129                 release_object(proc, *flat, this);
2130             }
2131             binder_size_t* objects =
2132                 (binder_size_t*)realloc(mObjects, objectsSize*sizeof(binder_size_t));
2133             if (objects) {
2134                 mObjects = objects;
2135             }
2136             mObjectsSize = objectsSize;
2137             mNextObjectHint = 0;
2138 
2139             clearCache();
2140         }
2141 
2142         // We own the data, so we can just do a realloc().
2143         if (desired > mDataCapacity) {
2144             uint8_t* data = (uint8_t*)realloc(mData, desired);
2145             if (data) {
2146                 LOG_ALLOC("Parcel %p: continue from %zu to %zu capacity", this, mDataCapacity,
2147                         desired);
2148                 pthread_mutex_lock(&gParcelGlobalAllocSizeLock);
2149                 gParcelGlobalAllocSize += desired;
2150                 gParcelGlobalAllocSize -= mDataCapacity;
2151                 pthread_mutex_unlock(&gParcelGlobalAllocSizeLock);
2152                 mData = data;
2153                 mDataCapacity = desired;
2154             } else {
2155                 mError = NO_MEMORY;
2156                 return NO_MEMORY;
2157             }
2158         } else {
2159             if (mDataSize > desired) {
2160                 mDataSize = desired;
2161                 ALOGV("continueWrite Setting data size of %p to %zu", this, mDataSize);
2162             }
2163             if (mDataPos > desired) {
2164                 mDataPos = desired;
2165                 ALOGV("continueWrite Setting data pos of %p to %zu", this, mDataPos);
2166             }
2167         }
2168 
2169     } else {
2170         // This is the first data.  Easy!
2171         uint8_t* data = (uint8_t*)malloc(desired);
2172         if (!data) {
2173             mError = NO_MEMORY;
2174             return NO_MEMORY;
2175         }
2176 
2177         if(!(mDataCapacity == 0 && mObjects == nullptr
2178              && mObjectsCapacity == 0)) {
2179             ALOGE("continueWrite: %zu/%p/%zu/%zu", mDataCapacity, mObjects, mObjectsCapacity, desired);
2180         }
2181 
2182         LOG_ALLOC("Parcel %p: allocating with %zu capacity", this, desired);
2183         pthread_mutex_lock(&gParcelGlobalAllocSizeLock);
2184         gParcelGlobalAllocSize += desired;
2185         gParcelGlobalAllocCount++;
2186         pthread_mutex_unlock(&gParcelGlobalAllocSizeLock);
2187 
2188         mData = data;
2189         mDataSize = mDataPos = 0;
2190         ALOGV("continueWrite Setting data size of %p to %zu", this, mDataSize);
2191         ALOGV("continueWrite Setting data pos of %p to %zu", this, mDataPos);
2192         mDataCapacity = desired;
2193     }
2194 
2195     return NO_ERROR;
2196 }
2197 
initState()2198 void Parcel::initState()
2199 {
2200     LOG_ALLOC("Parcel %p: initState", this);
2201     mError = NO_ERROR;
2202     mData = nullptr;
2203     mDataSize = 0;
2204     mDataCapacity = 0;
2205     mDataPos = 0;
2206     ALOGV("initState Setting data size of %p to %zu", this, mDataSize);
2207     ALOGV("initState Setting data pos of %p to %zu", this, mDataPos);
2208     mObjects = nullptr;
2209     mObjectsSize = 0;
2210     mObjectsCapacity = 0;
2211     mNextObjectHint = 0;
2212     mHasFds = false;
2213     mFdsKnown = true;
2214     mAllowFds = true;
2215     mOwner = nullptr;
2216     clearCache();
2217     mNumRef = 0;
2218 
2219     // racing multiple init leads only to multiple identical write
2220     if (gMaxFds == 0) {
2221         struct rlimit result;
2222         if (!getrlimit(RLIMIT_NOFILE, &result)) {
2223             gMaxFds = (size_t)result.rlim_cur;
2224             //ALOGI("parcel fd limit set to %zu", gMaxFds);
2225         } else {
2226             ALOGW("Unable to getrlimit: %s", strerror(errno));
2227             gMaxFds = 1024;
2228         }
2229     }
2230 }
2231 
scanForFds() const2232 void Parcel::scanForFds() const
2233 {
2234     bool hasFds = false;
2235     for (size_t i=0; i<mObjectsSize; i++) {
2236         const flat_binder_object* flat
2237             = reinterpret_cast<const flat_binder_object*>(mData + mObjects[i]);
2238         if (flat->hdr.type == BINDER_TYPE_FD) {
2239             hasFds = true;
2240             break;
2241         }
2242     }
2243     mHasFds = hasFds;
2244     mFdsKnown = true;
2245 }
2246 
2247 }; // namespace hardware
2248 }; // namespace android
2249