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/Debug.h>
41 #include <utils/Log.h>
42 #include <utils/misc.h>
43 #include <utils/String8.h>
44 #include <utils/String16.h>
45
46 #include "binder_kernel.h"
47 #include <hwbinder/Static.h>
48 #include "TextOutput.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
359 // Write RPC headers. (previously just the interface token)
writeInterfaceToken(const char * interface)360 status_t Parcel::writeInterfaceToken(const char* interface)
361 {
362 // currently the interface identification token is just its name as a string
363 return writeCString(interface);
364 }
365
enforceInterface(const char * interface) const366 bool Parcel::enforceInterface(const char* interface) const
367 {
368 const char* str = readCString();
369 if (str != nullptr && strcmp(str, interface) == 0) {
370 return true;
371 } else {
372 ALOGW("**** enforceInterface() expected '%s' but read '%s'",
373 interface, (str ? str : "<empty string>"));
374 return false;
375 }
376 }
377
objects() const378 const binder_size_t* Parcel::objects() const
379 {
380 return mObjects;
381 }
382
objectsCount() const383 size_t Parcel::objectsCount() const
384 {
385 return mObjectsSize;
386 }
387
errorCheck() const388 status_t Parcel::errorCheck() const
389 {
390 return mError;
391 }
392
setError(status_t err)393 void Parcel::setError(status_t err)
394 {
395 mError = err;
396 }
397
finishWrite(size_t len)398 status_t Parcel::finishWrite(size_t len)
399 {
400 if (len > INT32_MAX) {
401 // don't accept size_t values which may have come from an
402 // inadvertent conversion from a negative int.
403 return BAD_VALUE;
404 }
405
406 //printf("Finish write of %d\n", len);
407 mDataPos += len;
408 ALOGV("finishWrite Setting data pos of %p to %zu", this, mDataPos);
409 if (mDataPos > mDataSize) {
410 mDataSize = mDataPos;
411 ALOGV("finishWrite Setting data size of %p to %zu", this, mDataSize);
412 }
413 //printf("New pos=%d, size=%d\n", mDataPos, mDataSize);
414 return NO_ERROR;
415 }
416
writeUnpadded(const void * data,size_t len)417 status_t Parcel::writeUnpadded(const void* data, size_t len)
418 {
419 if (len > INT32_MAX) {
420 // don't accept size_t values which may have come from an
421 // inadvertent conversion from a negative int.
422 return BAD_VALUE;
423 }
424
425 size_t end = mDataPos + len;
426 if (end < mDataPos) {
427 // integer overflow
428 return BAD_VALUE;
429 }
430
431 if (end <= mDataCapacity) {
432 restart_write:
433 memcpy(mData+mDataPos, data, len);
434 return finishWrite(len);
435 }
436
437 status_t err = growData(len);
438 if (err == NO_ERROR) goto restart_write;
439 return err;
440 }
441
write(const void * data,size_t len)442 status_t Parcel::write(const void* data, size_t len)
443 {
444 if (len > INT32_MAX) {
445 // don't accept size_t values which may have come from an
446 // inadvertent conversion from a negative int.
447 return BAD_VALUE;
448 }
449
450 void* const d = writeInplace(len);
451 if (d) {
452 memcpy(d, data, len);
453 return NO_ERROR;
454 }
455 return mError;
456 }
457
writeInplace(size_t len)458 void* Parcel::writeInplace(size_t len)
459 {
460 if (len > INT32_MAX) {
461 // don't accept size_t values which may have come from an
462 // inadvertent conversion from a negative int.
463 return nullptr;
464 }
465
466 const size_t padded = pad_size(len);
467
468 // validate for integer overflow
469 if (mDataPos+padded < mDataPos) {
470 return nullptr;
471 }
472
473 if ((mDataPos+padded) <= mDataCapacity) {
474 restart_write:
475 //printf("Writing %ld bytes, padded to %ld\n", len, padded);
476 uint8_t* const data = mData+mDataPos;
477
478 // Need to pad at end?
479 if (padded != len) {
480 #if BYTE_ORDER == BIG_ENDIAN
481 static const uint32_t mask[4] = {
482 0x00000000, 0xffffff00, 0xffff0000, 0xff000000
483 };
484 #endif
485 #if BYTE_ORDER == LITTLE_ENDIAN
486 static const uint32_t mask[4] = {
487 0x00000000, 0x00ffffff, 0x0000ffff, 0x000000ff
488 };
489 #endif
490 //printf("Applying pad mask: %p to %p\n", (void*)mask[padded-len],
491 // *reinterpret_cast<void**>(data+padded-4));
492 *reinterpret_cast<uint32_t*>(data+padded-4) &= mask[padded-len];
493 }
494
495 finishWrite(padded);
496 return data;
497 }
498
499 status_t err = growData(padded);
500 if (err == NO_ERROR) goto restart_write;
501 return nullptr;
502 }
503
writeInt8(int8_t val)504 status_t Parcel::writeInt8(int8_t val)
505 {
506 return write(&val, sizeof(val));
507 }
508
writeUint8(uint8_t val)509 status_t Parcel::writeUint8(uint8_t val)
510 {
511 return write(&val, sizeof(val));
512 }
513
writeInt16(int16_t val)514 status_t Parcel::writeInt16(int16_t val)
515 {
516 return write(&val, sizeof(val));
517 }
518
writeUint16(uint16_t val)519 status_t Parcel::writeUint16(uint16_t val)
520 {
521 return write(&val, sizeof(val));
522 }
523
writeInt32(int32_t val)524 status_t Parcel::writeInt32(int32_t val)
525 {
526 return writeAligned(val);
527 }
528
writeUint32(uint32_t val)529 status_t Parcel::writeUint32(uint32_t val)
530 {
531 return writeAligned(val);
532 }
533
writeBool(bool val)534 status_t Parcel::writeBool(bool val)
535 {
536 return writeInt8(int8_t(val));
537 }
writeInt64(int64_t val)538 status_t Parcel::writeInt64(int64_t val)
539 {
540 return writeAligned(val);
541 }
542
writeUint64(uint64_t val)543 status_t Parcel::writeUint64(uint64_t val)
544 {
545 return writeAligned(val);
546 }
547
writePointer(uintptr_t val)548 status_t Parcel::writePointer(uintptr_t val)
549 {
550 return writeAligned<binder_uintptr_t>(val);
551 }
552
writeFloat(float val)553 status_t Parcel::writeFloat(float val)
554 {
555 return writeAligned(val);
556 }
557
558 #if defined(__mips__) && defined(__mips_hard_float)
559
writeDouble(double val)560 status_t Parcel::writeDouble(double val)
561 {
562 union {
563 double d;
564 unsigned long long ll;
565 } u;
566 u.d = val;
567 return writeAligned(u.ll);
568 }
569
570 #else
571
writeDouble(double val)572 status_t Parcel::writeDouble(double val)
573 {
574 return writeAligned(val);
575 }
576
577 #endif
578
writeCString(const char * str)579 status_t Parcel::writeCString(const char* str)
580 {
581 return write(str, strlen(str)+1);
582 }
writeString16(const std::unique_ptr<String16> & str)583 status_t Parcel::writeString16(const std::unique_ptr<String16>& str)
584 {
585 if (!str) {
586 return writeInt32(-1);
587 }
588
589 return writeString16(*str);
590 }
591
writeString16(const String16 & str)592 status_t Parcel::writeString16(const String16& str)
593 {
594 return writeString16(str.string(), str.size());
595 }
596
writeString16(const char16_t * str,size_t len)597 status_t Parcel::writeString16(const char16_t* str, size_t len)
598 {
599 if (str == nullptr) return writeInt32(-1);
600
601 status_t err = writeInt32(len);
602 if (err == NO_ERROR) {
603 len *= sizeof(char16_t);
604 uint8_t* data = (uint8_t*)writeInplace(len+sizeof(char16_t));
605 if (data) {
606 memcpy(data, str, len);
607 *reinterpret_cast<char16_t*>(data+len) = 0;
608 return NO_ERROR;
609 }
610 err = mError;
611 }
612 return err;
613 }
writeStrongBinder(const sp<IBinder> & val)614 status_t Parcel::writeStrongBinder(const sp<IBinder>& val)
615 {
616 return flatten_binder(ProcessState::self(), val, this);
617 }
618
619 template <typename T>
writeObject(const T & val)620 status_t Parcel::writeObject(const T& val)
621 {
622 const bool enoughData = (mDataPos+sizeof(val)) <= mDataCapacity;
623 const bool enoughObjects = mObjectsSize < mObjectsCapacity;
624 if (enoughData && enoughObjects) {
625 restart_write:
626 *reinterpret_cast<T*>(mData+mDataPos) = val;
627
628 const binder_object_header* hdr = reinterpret_cast<binder_object_header*>(mData+mDataPos);
629 switch (hdr->type) {
630 case BINDER_TYPE_BINDER:
631 case BINDER_TYPE_WEAK_BINDER:
632 case BINDER_TYPE_HANDLE:
633 case BINDER_TYPE_WEAK_HANDLE: {
634 const flat_binder_object *fbo = reinterpret_cast<const flat_binder_object*>(hdr);
635 if (fbo->binder != 0) {
636 mObjects[mObjectsSize++] = mDataPos;
637 acquire_binder_object(ProcessState::self(), *fbo, this);
638 }
639 break;
640 }
641 case BINDER_TYPE_FD: {
642 // remember if it's a file descriptor
643 if (!mAllowFds) {
644 // fail before modifying our object index
645 return FDS_NOT_ALLOWED;
646 }
647 mHasFds = mFdsKnown = true;
648 mObjects[mObjectsSize++] = mDataPos;
649 break;
650 }
651 case BINDER_TYPE_FDA:
652 mObjects[mObjectsSize++] = mDataPos;
653 break;
654 case BINDER_TYPE_PTR: {
655 const binder_buffer_object *buffer_obj = reinterpret_cast<
656 const binder_buffer_object*>(hdr);
657 if ((void *)buffer_obj->buffer != nullptr) {
658 mObjects[mObjectsSize++] = mDataPos;
659 }
660 break;
661 }
662 default: {
663 ALOGE("writeObject: unknown type %d", hdr->type);
664 break;
665 }
666 }
667 return finishWrite(sizeof(val));
668 }
669
670 if (!enoughData) {
671 const status_t err = growData(sizeof(val));
672 if (err != NO_ERROR) return err;
673 }
674 if (!enoughObjects) {
675 if (mObjectsSize > SIZE_MAX - 2) return NO_MEMORY; // overflow
676 if (mObjectsSize + 2 > SIZE_MAX / 3) return NO_MEMORY; // overflow
677 size_t newSize = ((mObjectsSize+2)*3)/2;
678 if (newSize > SIZE_MAX / sizeof(binder_size_t)) return NO_MEMORY; // overflow
679 binder_size_t* objects = (binder_size_t*)realloc(mObjects, newSize*sizeof(binder_size_t));
680 if (objects == nullptr) return NO_MEMORY;
681 mObjects = objects;
682 mObjectsCapacity = newSize;
683 }
684
685 goto restart_write;
686 }
687
688 template status_t Parcel::writeObject<flat_binder_object>(const flat_binder_object& val);
689 template status_t Parcel::writeObject<binder_fd_object>(const binder_fd_object& val);
690 template status_t Parcel::writeObject<binder_buffer_object>(const binder_buffer_object& val);
691 template status_t Parcel::writeObject<binder_fd_array_object>(const binder_fd_array_object& val);
692
validateBufferChild(size_t child_buffer_handle,size_t child_offset) const693 bool Parcel::validateBufferChild(size_t child_buffer_handle,
694 size_t child_offset) const {
695 if (child_buffer_handle >= mObjectsSize)
696 return false;
697 binder_buffer_object *child = reinterpret_cast<binder_buffer_object*>
698 (mData + mObjects[child_buffer_handle]);
699 if (child->hdr.type != BINDER_TYPE_PTR || child_offset > child->length) {
700 // Parent object not a buffer, or not large enough
701 LOG_BUFFER("writeEmbeddedReference found weird child. "
702 "child_offset = %zu, child->length = %zu",
703 child_offset, (size_t)child->length);
704 return false;
705 }
706 return true;
707 }
708
validateBufferParent(size_t parent_buffer_handle,size_t parent_offset) const709 bool Parcel::validateBufferParent(size_t parent_buffer_handle,
710 size_t parent_offset) const {
711 if (parent_buffer_handle >= mObjectsSize)
712 return false;
713 binder_buffer_object *parent = reinterpret_cast<binder_buffer_object*>
714 (mData + mObjects[parent_buffer_handle]);
715 if (parent->hdr.type != BINDER_TYPE_PTR ||
716 sizeof(binder_uintptr_t) > parent->length ||
717 parent_offset > parent->length - sizeof(binder_uintptr_t)) {
718 // Parent object not a buffer, or not large enough
719 return false;
720 }
721 return true;
722 }
writeEmbeddedBuffer(const void * buffer,size_t length,size_t * handle,size_t parent_buffer_handle,size_t parent_offset)723 status_t Parcel::writeEmbeddedBuffer(
724 const void *buffer, size_t length, size_t *handle,
725 size_t parent_buffer_handle, size_t parent_offset) {
726 LOG_BUFFER("writeEmbeddedBuffer(%p, %zu, parent = (%zu, %zu)) -> %zu",
727 buffer, length, parent_buffer_handle,
728 parent_offset, mObjectsSize);
729 if(!validateBufferParent(parent_buffer_handle, parent_offset))
730 return BAD_VALUE;
731 binder_buffer_object obj = {
732 .hdr = { .type = BINDER_TYPE_PTR },
733 .flags = BINDER_BUFFER_FLAG_HAS_PARENT,
734 .buffer = reinterpret_cast<binder_uintptr_t>(buffer),
735 .length = length,
736 .parent = parent_buffer_handle,
737 .parent_offset = parent_offset,
738 };
739 if (handle != nullptr) {
740 // We use an index into mObjects as a handle
741 *handle = mObjectsSize;
742 }
743 return writeObject(obj);
744 }
745
writeBuffer(const void * buffer,size_t length,size_t * handle)746 status_t Parcel::writeBuffer(const void *buffer, size_t length, size_t *handle)
747 {
748 LOG_BUFFER("writeBuffer(%p, %zu) -> %zu",
749 buffer, length, mObjectsSize);
750 binder_buffer_object obj {
751 .hdr = { .type = BINDER_TYPE_PTR },
752 .flags = 0,
753 .buffer = reinterpret_cast<binder_uintptr_t>(buffer),
754 .length = length,
755 };
756 if (handle != nullptr) {
757 // We use an index into mObjects as a handle
758 *handle = mObjectsSize;
759 }
760 return writeObject(obj);
761 }
762
clearCache() const763 void Parcel::clearCache() const {
764 LOG_BUFFER("clearing cache.");
765 mBufCachePos = 0;
766 mBufCache.clear();
767 }
768
updateCache() const769 void Parcel::updateCache() const {
770 if(mBufCachePos == mObjectsSize)
771 return;
772 LOG_BUFFER("updating cache from %zu to %zu", mBufCachePos, mObjectsSize);
773 for(size_t i = mBufCachePos; i < mObjectsSize; i++) {
774 binder_size_t dataPos = mObjects[i];
775 binder_buffer_object *obj =
776 reinterpret_cast<binder_buffer_object*>(mData+dataPos);
777 if(obj->hdr.type != BINDER_TYPE_PTR)
778 continue;
779 BufferInfo ifo;
780 ifo.index = i;
781 ifo.buffer = obj->buffer;
782 ifo.bufend = obj->buffer + obj->length;
783 mBufCache.push_back(ifo);
784 }
785 mBufCachePos = mObjectsSize;
786 }
787
788 /* 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) const789 status_t Parcel::findBuffer(const void *ptr, size_t length, bool *found,
790 size_t *handle, size_t *offset) const {
791 if(found == nullptr)
792 return UNKNOWN_ERROR;
793 updateCache();
794 binder_uintptr_t ptrVal = reinterpret_cast<binder_uintptr_t>(ptr);
795 // true if the pointer is in some buffer, but the length is too big
796 // so that ptr + length doesn't fit into the buffer.
797 bool suspectRejectBadPointer = false;
798 LOG_BUFFER("findBuffer examining %zu objects.", mObjectsSize);
799 for(auto entry = mBufCache.rbegin(); entry != mBufCache.rend(); ++entry ) {
800 if(entry->buffer <= ptrVal && ptrVal < entry->bufend) {
801 // might have found it.
802 if(ptrVal + length <= entry->bufend) {
803 *found = true;
804 if(handle != nullptr) *handle = entry->index;
805 if(offset != nullptr) *offset = ptrVal - entry->buffer;
806 LOG_BUFFER(" findBuffer has a match at %zu!", entry->index);
807 return OK;
808 } else {
809 suspectRejectBadPointer = true;
810 }
811 }
812 }
813 LOG_BUFFER("findBuffer did not find for ptr = %p.", ptr);
814 *found = false;
815 return suspectRejectBadPointer ? BAD_VALUE : OK;
816 }
817
818 /* findBuffer with the assumption that ptr = .buffer (so it points to top
819 * of the buffer, aka offset 0).
820 * */
quickFindBuffer(const void * ptr,size_t * handle) const821 status_t Parcel::quickFindBuffer(const void *ptr, size_t *handle) const {
822 updateCache();
823 binder_uintptr_t ptrVal = reinterpret_cast<binder_uintptr_t>(ptr);
824 LOG_BUFFER("quickFindBuffer examining %zu objects.", mObjectsSize);
825 for(auto entry = mBufCache.rbegin(); entry != mBufCache.rend(); ++entry ) {
826 if(entry->buffer == ptrVal) {
827 if(handle != nullptr) *handle = entry->index;
828 return OK;
829 }
830 }
831 LOG_BUFFER("quickFindBuffer did not find for ptr = %p.", ptr);
832 return NO_INIT;
833 }
834
writeNativeHandleNoDup(const native_handle_t * handle,bool embedded,size_t parent_buffer_handle,size_t parent_offset)835 status_t Parcel::writeNativeHandleNoDup(const native_handle_t *handle,
836 bool embedded,
837 size_t parent_buffer_handle,
838 size_t parent_offset)
839 {
840 size_t buffer_handle;
841 status_t status = OK;
842
843 if (handle == nullptr) {
844 status = writeUint64(0);
845 return status;
846 }
847
848 size_t native_handle_size = sizeof(native_handle_t)
849 + handle->numFds * sizeof(int) + handle->numInts * sizeof(int);
850 writeUint64(native_handle_size);
851
852 if (embedded) {
853 status = writeEmbeddedBuffer((void*) handle,
854 native_handle_size, &buffer_handle,
855 parent_buffer_handle, parent_offset);
856 } else {
857 status = writeBuffer((void*) handle, native_handle_size, &buffer_handle);
858 }
859
860 if (status != OK) {
861 return status;
862 }
863
864 struct binder_fd_array_object fd_array {
865 .hdr = { .type = BINDER_TYPE_FDA },
866 .num_fds = static_cast<binder_size_t>(handle->numFds),
867 .parent = buffer_handle,
868 .parent_offset = offsetof(native_handle_t, data),
869 };
870
871 return writeObject(fd_array);
872 }
873
writeNativeHandleNoDup(const native_handle_t * handle)874 status_t Parcel::writeNativeHandleNoDup(const native_handle_t *handle)
875 {
876 return writeNativeHandleNoDup(handle, false /* embedded */);
877 }
878
writeEmbeddedNativeHandle(const native_handle_t * handle,size_t parent_buffer_handle,size_t parent_offset)879 status_t Parcel::writeEmbeddedNativeHandle(const native_handle_t *handle,
880 size_t parent_buffer_handle,
881 size_t parent_offset)
882 {
883 return writeNativeHandleNoDup(handle, true /* embedded */,
884 parent_buffer_handle, parent_offset);
885 }
886
read(void * outData,size_t len) const887 status_t Parcel::read(void* outData, size_t len) const
888 {
889 if (len > INT32_MAX) {
890 // don't accept size_t values which may have come from an
891 // inadvertent conversion from a negative int.
892 return BAD_VALUE;
893 }
894
895 if ((mDataPos+pad_size(len)) >= mDataPos && (mDataPos+pad_size(len)) <= mDataSize
896 && len <= pad_size(len)) {
897 memcpy(outData, mData+mDataPos, len);
898 mDataPos += pad_size(len);
899 ALOGV("read Setting data pos of %p to %zu", this, mDataPos);
900 return NO_ERROR;
901 }
902 return NOT_ENOUGH_DATA;
903 }
904
readInplace(size_t len) const905 const void* Parcel::readInplace(size_t len) const
906 {
907 if (len > INT32_MAX) {
908 // don't accept size_t values which may have come from an
909 // inadvertent conversion from a negative int.
910 return nullptr;
911 }
912
913 if ((mDataPos+pad_size(len)) >= mDataPos && (mDataPos+pad_size(len)) <= mDataSize
914 && len <= pad_size(len)) {
915 const void* data = mData+mDataPos;
916 mDataPos += pad_size(len);
917 ALOGV("readInplace Setting data pos of %p to %zu", this, mDataPos);
918 return data;
919 }
920 return nullptr;
921 }
922
923 template<class T>
readAligned(T * pArg) const924 status_t Parcel::readAligned(T *pArg) const {
925 COMPILE_TIME_ASSERT_FUNCTION_SCOPE(PAD_SIZE_UNSAFE(sizeof(T)) == sizeof(T));
926
927 if ((mDataPos+sizeof(T)) <= mDataSize) {
928 const void* data = mData+mDataPos;
929 mDataPos += sizeof(T);
930 *pArg = *reinterpret_cast<const T*>(data);
931 return NO_ERROR;
932 } else {
933 return NOT_ENOUGH_DATA;
934 }
935 }
936
937 template<class T>
readAligned() const938 T Parcel::readAligned() const {
939 T result;
940 if (readAligned(&result) != NO_ERROR) {
941 result = 0;
942 }
943
944 return result;
945 }
946
947 template<class T>
writeAligned(T val)948 status_t Parcel::writeAligned(T val) {
949 COMPILE_TIME_ASSERT_FUNCTION_SCOPE(PAD_SIZE_UNSAFE(sizeof(T)) == sizeof(T));
950
951 if ((mDataPos+sizeof(val)) <= mDataCapacity) {
952 restart_write:
953 *reinterpret_cast<T*>(mData+mDataPos) = val;
954 return finishWrite(sizeof(val));
955 }
956
957 status_t err = growData(sizeof(val));
958 if (err == NO_ERROR) goto restart_write;
959 return err;
960 }
961
readInt8(int8_t * pArg) const962 status_t Parcel::readInt8(int8_t *pArg) const
963 {
964 return read(pArg, sizeof(*pArg));
965 }
966
readUint8(uint8_t * pArg) const967 status_t Parcel::readUint8(uint8_t *pArg) const
968 {
969 return read(pArg, sizeof(*pArg));
970 }
971
readInt16(int16_t * pArg) const972 status_t Parcel::readInt16(int16_t *pArg) const
973 {
974 return read(pArg, sizeof(*pArg));
975 }
976
readUint16(uint16_t * pArg) const977 status_t Parcel::readUint16(uint16_t *pArg) const
978 {
979 return read(pArg, sizeof(*pArg));
980 }
981
readInt32(int32_t * pArg) const982 status_t Parcel::readInt32(int32_t *pArg) const
983 {
984 return readAligned(pArg);
985 }
986
readInt32() const987 int32_t Parcel::readInt32() const
988 {
989 return readAligned<int32_t>();
990 }
991
readUint32(uint32_t * pArg) const992 status_t Parcel::readUint32(uint32_t *pArg) const
993 {
994 return readAligned(pArg);
995 }
996
readUint32() const997 uint32_t Parcel::readUint32() const
998 {
999 return readAligned<uint32_t>();
1000 }
1001
readInt64(int64_t * pArg) const1002 status_t Parcel::readInt64(int64_t *pArg) const
1003 {
1004 return readAligned(pArg);
1005 }
1006
readInt64() const1007 int64_t Parcel::readInt64() const
1008 {
1009 return readAligned<int64_t>();
1010 }
1011
readUint64(uint64_t * pArg) const1012 status_t Parcel::readUint64(uint64_t *pArg) const
1013 {
1014 return readAligned(pArg);
1015 }
1016
readUint64() const1017 uint64_t Parcel::readUint64() const
1018 {
1019 return readAligned<uint64_t>();
1020 }
1021
readPointer(uintptr_t * pArg) const1022 status_t Parcel::readPointer(uintptr_t *pArg) const
1023 {
1024 status_t ret;
1025 binder_uintptr_t ptr;
1026 ret = readAligned(&ptr);
1027 if (!ret)
1028 *pArg = ptr;
1029 return ret;
1030 }
1031
readPointer() const1032 uintptr_t Parcel::readPointer() const
1033 {
1034 return readAligned<binder_uintptr_t>();
1035 }
1036
1037
readFloat(float * pArg) const1038 status_t Parcel::readFloat(float *pArg) const
1039 {
1040 return readAligned(pArg);
1041 }
1042
1043
readFloat() const1044 float Parcel::readFloat() const
1045 {
1046 return readAligned<float>();
1047 }
1048
1049 #if defined(__mips__) && defined(__mips_hard_float)
1050
readDouble(double * pArg) const1051 status_t Parcel::readDouble(double *pArg) const
1052 {
1053 union {
1054 double d;
1055 unsigned long long ll;
1056 } u;
1057 u.d = 0;
1058 status_t status;
1059 status = readAligned(&u.ll);
1060 *pArg = u.d;
1061 return status;
1062 }
1063
readDouble() const1064 double Parcel::readDouble() const
1065 {
1066 union {
1067 double d;
1068 unsigned long long ll;
1069 } u;
1070 u.ll = readAligned<unsigned long long>();
1071 return u.d;
1072 }
1073
1074 #else
1075
readDouble(double * pArg) const1076 status_t Parcel::readDouble(double *pArg) const
1077 {
1078 return readAligned(pArg);
1079 }
1080
readDouble() const1081 double Parcel::readDouble() const
1082 {
1083 return readAligned<double>();
1084 }
1085
1086 #endif
1087
readBool(bool * pArg) const1088 status_t Parcel::readBool(bool *pArg) const
1089 {
1090 int8_t tmp;
1091 status_t ret = readInt8(&tmp);
1092 *pArg = (tmp != 0);
1093 return ret;
1094 }
1095
readBool() const1096 bool Parcel::readBool() const
1097 {
1098 int8_t tmp;
1099 status_t err = readInt8(&tmp);
1100
1101 if (err != OK) {
1102 return 0;
1103 }
1104
1105 return tmp != 0;
1106 }
1107
readCString() const1108 const char* Parcel::readCString() const
1109 {
1110 if (mDataPos < mDataSize) {
1111 const size_t avail = mDataSize-mDataPos;
1112 const char* str = reinterpret_cast<const char*>(mData+mDataPos);
1113 // is the string's trailing NUL within the parcel's valid bounds?
1114 const char* eos = reinterpret_cast<const char*>(memchr(str, 0, avail));
1115 if (eos) {
1116 const size_t len = eos - str;
1117 mDataPos += pad_size(len+1);
1118 ALOGV("readCString Setting data pos of %p to %zu", this, mDataPos);
1119 return str;
1120 }
1121 }
1122 return nullptr;
1123 }
readString16() const1124 String16 Parcel::readString16() const
1125 {
1126 size_t len;
1127 const char16_t* str = readString16Inplace(&len);
1128 if (str) return String16(str, len);
1129 ALOGE("Reading a NULL string not supported here.");
1130 return String16();
1131 }
1132
readString16(std::unique_ptr<String16> * pArg) const1133 status_t Parcel::readString16(std::unique_ptr<String16>* pArg) const
1134 {
1135 const int32_t start = dataPosition();
1136 int32_t size;
1137 status_t status = readInt32(&size);
1138 pArg->reset();
1139
1140 if (status != OK || size < 0) {
1141 return status;
1142 }
1143
1144 setDataPosition(start);
1145 pArg->reset(new (std::nothrow) String16());
1146
1147 status = readString16(pArg->get());
1148
1149 if (status != OK) {
1150 pArg->reset();
1151 }
1152
1153 return status;
1154 }
1155
readString16(String16 * pArg) const1156 status_t Parcel::readString16(String16* pArg) const
1157 {
1158 size_t len;
1159 const char16_t* str = readString16Inplace(&len);
1160 if (str) {
1161 pArg->setTo(str, len);
1162 return 0;
1163 } else {
1164 *pArg = String16();
1165 return UNEXPECTED_NULL;
1166 }
1167 }
1168
readString16Inplace(size_t * outLen) const1169 const char16_t* Parcel::readString16Inplace(size_t* outLen) const
1170 {
1171 int32_t size = readInt32();
1172 // watch for potential int overflow from size+1
1173 if (size >= 0 && size < INT32_MAX) {
1174 *outLen = size;
1175 const char16_t* str = (const char16_t*)readInplace((size+1)*sizeof(char16_t));
1176 if (str != nullptr) {
1177 return str;
1178 }
1179 }
1180 *outLen = 0;
1181 return nullptr;
1182 }
readStrongBinder(sp<IBinder> * val) const1183 status_t Parcel::readStrongBinder(sp<IBinder>* val) const
1184 {
1185 status_t status = readNullableStrongBinder(val);
1186 if (status == OK && !val->get()) {
1187 status = UNEXPECTED_NULL;
1188 }
1189 return status;
1190 }
1191
readNullableStrongBinder(sp<IBinder> * val) const1192 status_t Parcel::readNullableStrongBinder(sp<IBinder>* val) const
1193 {
1194 return unflatten_binder(ProcessState::self(), *this, val);
1195 }
1196
readStrongBinder() const1197 sp<IBinder> Parcel::readStrongBinder() const
1198 {
1199 sp<IBinder> val;
1200 // Note that a lot of code in Android reads binders by hand with this
1201 // method, and that code has historically been ok with getting nullptr
1202 // back (while ignoring error codes).
1203 readNullableStrongBinder(&val);
1204 return val;
1205 }
1206
1207 template<typename T>
readObject(size_t * objects_offset) const1208 const T* Parcel::readObject(size_t *objects_offset) const
1209 {
1210 const size_t DPOS = mDataPos;
1211 if (objects_offset != nullptr) {
1212 *objects_offset = 0;
1213 }
1214
1215 if ((DPOS+sizeof(T)) <= mDataSize) {
1216 const T* obj = reinterpret_cast<const T*>(mData+DPOS);
1217 mDataPos = DPOS + sizeof(T);
1218 const binder_object_header *hdr = reinterpret_cast<const binder_object_header*>(obj);
1219 switch (hdr->type) {
1220 case BINDER_TYPE_BINDER:
1221 case BINDER_TYPE_WEAK_BINDER:
1222 case BINDER_TYPE_HANDLE:
1223 case BINDER_TYPE_WEAK_HANDLE: {
1224 const flat_binder_object *flat_obj =
1225 reinterpret_cast<const flat_binder_object*>(hdr);
1226 if (flat_obj->cookie == 0 && flat_obj->binder == 0) {
1227 // When transferring a NULL binder object, we don't write it into
1228 // the object list, so we don't want to check for it when
1229 // reading.
1230 ALOGV("readObject Setting data pos of %p to %zu", this, mDataPos);
1231 return obj;
1232 }
1233 break;
1234 }
1235 case BINDER_TYPE_FD:
1236 case BINDER_TYPE_FDA:
1237 // fd (-arrays) must always appear in the meta-data list (eg touched by the kernel)
1238 break;
1239 case BINDER_TYPE_PTR: {
1240 const binder_buffer_object *buffer_obj =
1241 reinterpret_cast<const binder_buffer_object*>(hdr);
1242 if ((void *)buffer_obj->buffer == nullptr) {
1243 // null pointers can be returned directly - they're not written in the
1244 // object list. All non-null buffers must appear in the objects list.
1245 return obj;
1246 }
1247 break;
1248 }
1249 }
1250 // Ensure that this object is valid...
1251 binder_size_t* const OBJS = mObjects;
1252 const size_t N = mObjectsSize;
1253 size_t opos = mNextObjectHint;
1254
1255 if (N > 0) {
1256 ALOGV("Parcel %p looking for obj at %zu, hint=%zu",
1257 this, DPOS, opos);
1258
1259 // Start at the current hint position, looking for an object at
1260 // the current data position.
1261 if (opos < N) {
1262 while (opos < (N-1) && OBJS[opos] < DPOS) {
1263 opos++;
1264 }
1265 } else {
1266 opos = N-1;
1267 }
1268 if (OBJS[opos] == DPOS) {
1269 // Found it!
1270 ALOGV("Parcel %p found obj %zu at index %zu with forward search",
1271 this, DPOS, opos);
1272 mNextObjectHint = opos+1;
1273 ALOGV("readObject Setting data pos of %p to %zu", this, mDataPos);
1274 if (objects_offset != nullptr) {
1275 *objects_offset = opos;
1276 }
1277 return obj;
1278 }
1279
1280 // Look backwards for it...
1281 while (opos > 0 && OBJS[opos] > DPOS) {
1282 opos--;
1283 }
1284 if (OBJS[opos] == DPOS) {
1285 // Found it!
1286 ALOGV("Parcel %p found obj %zu at index %zu with backward search",
1287 this, DPOS, opos);
1288 mNextObjectHint = opos+1;
1289 ALOGV("readObject Setting data pos of %p to %zu", this, mDataPos);
1290 if (objects_offset != nullptr) {
1291 *objects_offset = opos;
1292 }
1293 return obj;
1294 }
1295 }
1296 ALOGW("Attempt to read object from Parcel %p at offset %zu that is not in the object list",
1297 this, DPOS);
1298 }
1299 return nullptr;
1300 }
1301
1302 template const flat_binder_object* Parcel::readObject<flat_binder_object>(size_t *objects_offset) const;
1303
1304 template const binder_fd_object* Parcel::readObject<binder_fd_object>(size_t *objects_offset) const;
1305
1306 template const binder_buffer_object* Parcel::readObject<binder_buffer_object>(size_t *objects_offset) const;
1307
1308 template const binder_fd_array_object* Parcel::readObject<binder_fd_array_object>(size_t *objects_offset) const;
1309
verifyBufferObject(const binder_buffer_object * buffer_obj,size_t size,uint32_t flags,size_t parent,size_t parentOffset) const1310 bool Parcel::verifyBufferObject(const binder_buffer_object *buffer_obj,
1311 size_t size, uint32_t flags, size_t parent,
1312 size_t parentOffset) const {
1313 if (buffer_obj->length != size) {
1314 ALOGE("Buffer length %" PRIu64 " does not match expected size %zu.",
1315 static_cast<uint64_t>(buffer_obj->length), size);
1316 return false;
1317 }
1318
1319 if (buffer_obj->flags != flags) {
1320 ALOGE("Buffer flags 0x%02X do not match expected flags 0x%02X.", buffer_obj->flags, flags);
1321 return false;
1322 }
1323
1324 if (flags & BINDER_BUFFER_FLAG_HAS_PARENT) {
1325 if (buffer_obj->parent != parent) {
1326 ALOGE("Buffer parent %" PRIu64 " does not match expected parent %zu.",
1327 static_cast<uint64_t>(buffer_obj->parent), parent);
1328 return false;
1329 }
1330 if (buffer_obj->parent_offset != parentOffset) {
1331 ALOGE("Buffer parent offset %" PRIu64 " does not match expected offset %zu.",
1332 static_cast<uint64_t>(buffer_obj->parent_offset), parentOffset);
1333 return false;
1334 }
1335 }
1336
1337 return true;
1338 }
1339
readBuffer(size_t buffer_size,size_t * buffer_handle,uint32_t flags,size_t parent,size_t parentOffset,const void ** buffer_out) const1340 status_t Parcel::readBuffer(size_t buffer_size, size_t *buffer_handle,
1341 uint32_t flags, size_t parent, size_t parentOffset,
1342 const void **buffer_out) const {
1343
1344 const binder_buffer_object* buffer_obj = readObject<binder_buffer_object>(buffer_handle);
1345
1346 if (buffer_obj == nullptr || buffer_obj->hdr.type != BINDER_TYPE_PTR) {
1347 return BAD_VALUE;
1348 }
1349
1350 if (!verifyBufferObject(buffer_obj, buffer_size, flags, parent, parentOffset)) {
1351 return BAD_VALUE;
1352 }
1353
1354 // in read side, always use .buffer and .length.
1355 *buffer_out = reinterpret_cast<void*>(buffer_obj->buffer);
1356
1357 return OK;
1358 }
1359
readNullableBuffer(size_t buffer_size,size_t * buffer_handle,const void ** buffer_out) const1360 status_t Parcel::readNullableBuffer(size_t buffer_size, size_t *buffer_handle,
1361 const void **buffer_out) const
1362 {
1363 return readBuffer(buffer_size, buffer_handle,
1364 0 /* flags */, 0 /* parent */, 0 /* parentOffset */,
1365 buffer_out);
1366 }
1367
readBuffer(size_t buffer_size,size_t * buffer_handle,const void ** buffer_out) const1368 status_t Parcel::readBuffer(size_t buffer_size, size_t *buffer_handle,
1369 const void **buffer_out) const
1370 {
1371 status_t status = readNullableBuffer(buffer_size, buffer_handle, buffer_out);
1372 if (status == OK && *buffer_out == nullptr) {
1373 return UNEXPECTED_NULL;
1374 }
1375 return status;
1376 }
1377
1378
readEmbeddedBuffer(size_t buffer_size,size_t * buffer_handle,size_t parent_buffer_handle,size_t parent_offset,const void ** buffer_out) const1379 status_t Parcel::readEmbeddedBuffer(size_t buffer_size,
1380 size_t *buffer_handle,
1381 size_t parent_buffer_handle,
1382 size_t parent_offset,
1383 const void **buffer_out) const
1384 {
1385 status_t status = readNullableEmbeddedBuffer(buffer_size, buffer_handle,
1386 parent_buffer_handle,
1387 parent_offset, buffer_out);
1388 if (status == OK && *buffer_out == nullptr) {
1389 return UNEXPECTED_NULL;
1390 }
1391 return status;
1392 }
1393
readNullableEmbeddedBuffer(size_t buffer_size,size_t * buffer_handle,size_t parent_buffer_handle,size_t parent_offset,const void ** buffer_out) const1394 status_t Parcel::readNullableEmbeddedBuffer(size_t buffer_size,
1395 size_t *buffer_handle,
1396 size_t parent_buffer_handle,
1397 size_t parent_offset,
1398 const void **buffer_out) const
1399 {
1400 return readBuffer(buffer_size, buffer_handle, BINDER_BUFFER_FLAG_HAS_PARENT,
1401 parent_buffer_handle, parent_offset, buffer_out);
1402 }
1403
readEmbeddedNativeHandle(size_t parent_buffer_handle,size_t parent_offset,const native_handle_t ** handle) const1404 status_t Parcel::readEmbeddedNativeHandle(size_t parent_buffer_handle,
1405 size_t parent_offset,
1406 const native_handle_t **handle) const
1407 {
1408 status_t status = readNullableEmbeddedNativeHandle(parent_buffer_handle, parent_offset, handle);
1409 if (status == OK && *handle == nullptr) {
1410 return UNEXPECTED_NULL;
1411 }
1412 return status;
1413 }
1414
readNullableNativeHandleNoDup(const native_handle_t ** handle,bool embedded,size_t parent_buffer_handle,size_t parent_offset) const1415 status_t Parcel::readNullableNativeHandleNoDup(const native_handle_t **handle,
1416 bool embedded,
1417 size_t parent_buffer_handle,
1418 size_t parent_offset) const
1419 {
1420 status_t status;
1421 uint64_t nativeHandleSize;
1422 size_t fdaParent;
1423
1424 status = readUint64(&nativeHandleSize);
1425 if (status != OK || nativeHandleSize == 0) {
1426 *handle = nullptr;
1427 return status;
1428 }
1429
1430 if (nativeHandleSize < sizeof(native_handle_t)) {
1431 ALOGE("Received a native_handle_t size that was too small.");
1432 return BAD_VALUE;
1433 }
1434
1435 if (embedded) {
1436 status = readNullableEmbeddedBuffer(nativeHandleSize, &fdaParent,
1437 parent_buffer_handle, parent_offset,
1438 reinterpret_cast<const void**>(handle));
1439 } else {
1440 status = readNullableBuffer(nativeHandleSize, &fdaParent,
1441 reinterpret_cast<const void**>(handle));
1442 }
1443
1444 if (status != OK) {
1445 return status;
1446 }
1447
1448 int numFds = (*handle)->numFds;
1449 int numInts = (*handle)->numInts;
1450
1451 if (numFds < 0 || numFds > NATIVE_HANDLE_MAX_FDS) {
1452 ALOGE("Received native_handle with invalid number of fds.");
1453 return BAD_VALUE;
1454 }
1455
1456 if (numInts < 0 || numInts > NATIVE_HANDLE_MAX_INTS) {
1457 ALOGE("Received native_handle with invalid number of ints.");
1458 return BAD_VALUE;
1459 }
1460
1461 if (nativeHandleSize != (sizeof(native_handle_t) + ((numFds + numInts) * sizeof(int)))) {
1462 ALOGE("Size of native_handle doesn't match.");
1463 return BAD_VALUE;
1464 }
1465
1466 const binder_fd_array_object* fd_array_obj = readObject<binder_fd_array_object>();
1467
1468 if (fd_array_obj == nullptr || fd_array_obj->hdr.type != BINDER_TYPE_FDA) {
1469 ALOGE("Can't find file-descriptor array object.");
1470 return BAD_VALUE;
1471 }
1472
1473 if (static_cast<int>(fd_array_obj->num_fds) != numFds) {
1474 ALOGE("Number of native handles does not match.");
1475 return BAD_VALUE;
1476 }
1477
1478 if (fd_array_obj->parent != fdaParent) {
1479 ALOGE("Parent handle of file-descriptor array not correct.");
1480 return BAD_VALUE;
1481 }
1482
1483 if (fd_array_obj->parent_offset != offsetof(native_handle_t, data)) {
1484 ALOGE("FD array object not properly offset in parent.");
1485 return BAD_VALUE;
1486 }
1487
1488 return OK;
1489 }
1490
readNullableEmbeddedNativeHandle(size_t parent_buffer_handle,size_t parent_offset,const native_handle_t ** handle) const1491 status_t Parcel::readNullableEmbeddedNativeHandle(size_t parent_buffer_handle,
1492 size_t parent_offset,
1493 const native_handle_t **handle) const
1494 {
1495 return readNullableNativeHandleNoDup(handle, true /* embedded */, parent_buffer_handle,
1496 parent_offset);
1497 }
1498
readNativeHandleNoDup(const native_handle_t ** handle) const1499 status_t Parcel::readNativeHandleNoDup(const native_handle_t **handle) const
1500 {
1501 status_t status = readNullableNativeHandleNoDup(handle);
1502 if (status == OK && *handle == nullptr) {
1503 return UNEXPECTED_NULL;
1504 }
1505 return status;
1506 }
1507
readNullableNativeHandleNoDup(const native_handle_t ** handle) const1508 status_t Parcel::readNullableNativeHandleNoDup(const native_handle_t **handle) const
1509 {
1510 return readNullableNativeHandleNoDup(handle, false /* embedded */);
1511 }
1512
closeFileDescriptors()1513 void Parcel::closeFileDescriptors()
1514 {
1515 size_t i = mObjectsSize;
1516 if (i > 0) {
1517 //ALOGI("Closing file descriptors for %zu objects...", i);
1518 }
1519 while (i > 0) {
1520 i--;
1521 const flat_binder_object* flat
1522 = reinterpret_cast<flat_binder_object*>(mData+mObjects[i]);
1523 if (flat->hdr.type == BINDER_TYPE_FD) {
1524 //ALOGI("Closing fd: %ld", flat->handle);
1525 close(flat->handle);
1526 }
1527 }
1528 }
1529
ipcData() const1530 uintptr_t Parcel::ipcData() const
1531 {
1532 return reinterpret_cast<uintptr_t>(mData);
1533 }
1534
ipcDataSize() const1535 size_t Parcel::ipcDataSize() const
1536 {
1537 return mDataSize > mDataPos ? mDataSize : mDataPos;
1538 }
1539
ipcObjects() const1540 uintptr_t Parcel::ipcObjects() const
1541 {
1542 return reinterpret_cast<uintptr_t>(mObjects);
1543 }
1544
ipcObjectsCount() const1545 size_t Parcel::ipcObjectsCount() const
1546 {
1547 return mObjectsSize;
1548 }
1549
1550 #define BUFFER_ALIGNMENT_BYTES 8
ipcBufferSize() const1551 size_t Parcel::ipcBufferSize() const
1552 {
1553 size_t totalBuffersSize = 0;
1554 // Add size for BINDER_TYPE_PTR
1555 size_t i = mObjectsSize;
1556 while (i > 0) {
1557 i--;
1558 const binder_buffer_object* buffer
1559 = reinterpret_cast<binder_buffer_object*>(mData+mObjects[i]);
1560 if (buffer->hdr.type == BINDER_TYPE_PTR) {
1561 /* The binder kernel driver requires each buffer to be 8-byte
1562 * aligned */
1563 size_t alignedSize = (buffer->length + (BUFFER_ALIGNMENT_BYTES - 1))
1564 & ~(BUFFER_ALIGNMENT_BYTES - 1);
1565 if (alignedSize > SIZE_MAX - totalBuffersSize) {
1566 ALOGE("ipcBuffersSize(): invalid buffer sizes.");
1567 return 0;
1568 }
1569 totalBuffersSize += alignedSize;
1570 }
1571 }
1572 return totalBuffersSize;
1573 }
1574
ipcSetDataReference(const uint8_t * data,size_t dataSize,const binder_size_t * objects,size_t objectsCount,release_func relFunc,void * relCookie)1575 void Parcel::ipcSetDataReference(const uint8_t* data, size_t dataSize,
1576 const binder_size_t* objects, size_t objectsCount, release_func relFunc, void* relCookie)
1577 {
1578 binder_size_t minOffset = 0;
1579 freeDataNoInit();
1580 mError = NO_ERROR;
1581 mData = const_cast<uint8_t*>(data);
1582 mDataSize = mDataCapacity = dataSize;
1583 //ALOGI("setDataReference Setting data size of %p to %lu (pid=%d)", this, mDataSize, getpid());
1584 mDataPos = 0;
1585 ALOGV("setDataReference Setting data pos of %p to %zu", this, mDataPos);
1586 mObjects = const_cast<binder_size_t*>(objects);
1587 mObjectsSize = mObjectsCapacity = objectsCount;
1588 mNextObjectHint = 0;
1589 clearCache();
1590 mOwner = relFunc;
1591 mOwnerCookie = relCookie;
1592 for (size_t i = 0; i < mObjectsSize; i++) {
1593 binder_size_t offset = mObjects[i];
1594 if (offset < minOffset) {
1595 ALOGE("%s: bad object offset %" PRIu64 " < %" PRIu64 "\n",
1596 __func__, (uint64_t)offset, (uint64_t)minOffset);
1597 mObjectsSize = 0;
1598 break;
1599 }
1600 minOffset = offset + sizeof(flat_binder_object);
1601 }
1602 scanForFds();
1603 }
1604
print(TextOutput & to,uint32_t) const1605 void Parcel::print(TextOutput& to, uint32_t /*flags*/) const
1606 {
1607 to << "Parcel(";
1608
1609 if (errorCheck() != NO_ERROR) {
1610 const status_t err = errorCheck();
1611 to << "Error: " << (void*)(intptr_t)err << " \"" << strerror(-err) << "\"";
1612 } else if (dataSize() > 0) {
1613 const uint8_t* DATA = data();
1614 to << indent << HexDump(DATA, dataSize()) << dedent;
1615 const binder_size_t* OBJS = objects();
1616 const size_t N = objectsCount();
1617 for (size_t i=0; i<N; i++) {
1618 const flat_binder_object* flat
1619 = reinterpret_cast<const flat_binder_object*>(DATA+OBJS[i]);
1620 if (flat->hdr.type == BINDER_TYPE_PTR) {
1621 const binder_buffer_object* buffer
1622 = reinterpret_cast<const binder_buffer_object*>(DATA+OBJS[i]);
1623 HexDump bufferDump((const uint8_t*)buffer->buffer, (size_t)buffer->length);
1624 bufferDump.setSingleLineCutoff(0);
1625 to << endl << "Object #" << i << " @ " << (void*)OBJS[i] << " (buffer size " << buffer->length << "):";
1626 to << indent << bufferDump << dedent;
1627 } else {
1628 to << endl << "Object #" << i << " @ " << (void*)OBJS[i] << ": "
1629 << TypeCode(flat->hdr.type & 0x7f7f7f00)
1630 << " = " << flat->binder;
1631 }
1632 }
1633 } else {
1634 to << "NULL";
1635 }
1636
1637 to << ")";
1638 }
1639
releaseObjects()1640 void Parcel::releaseObjects()
1641 {
1642 const sp<ProcessState> proc(ProcessState::self());
1643 size_t i = mObjectsSize;
1644 uint8_t* const data = mData;
1645 binder_size_t* const objects = mObjects;
1646 while (i > 0) {
1647 i--;
1648 const flat_binder_object* flat
1649 = reinterpret_cast<flat_binder_object*>(data+objects[i]);
1650 release_object(proc, *flat, this);
1651 }
1652 }
1653
acquireObjects()1654 void Parcel::acquireObjects()
1655 {
1656 const sp<ProcessState> proc(ProcessState::self());
1657 size_t i = mObjectsSize;
1658 uint8_t* const data = mData;
1659 binder_size_t* const objects = mObjects;
1660 while (i > 0) {
1661 i--;
1662 const binder_object_header* flat
1663 = reinterpret_cast<binder_object_header*>(data+objects[i]);
1664 acquire_object(proc, *flat, this);
1665 }
1666 }
1667
freeData()1668 void Parcel::freeData()
1669 {
1670 freeDataNoInit();
1671 initState();
1672 }
1673
freeDataNoInit()1674 void Parcel::freeDataNoInit()
1675 {
1676 if (mOwner) {
1677 LOG_ALLOC("Parcel %p: freeing other owner data", this);
1678 //ALOGI("Freeing data ref of %p (pid=%d)", this, getpid());
1679 mOwner(this, mData, mDataSize, mObjects, mObjectsSize, mOwnerCookie);
1680 } else {
1681 LOG_ALLOC("Parcel %p: freeing allocated data", this);
1682 releaseObjects();
1683 if (mData) {
1684 LOG_ALLOC("Parcel %p: freeing with %zu capacity", this, mDataCapacity);
1685 gParcelGlobalAllocSize -= mDataCapacity;
1686 gParcelGlobalAllocCount--;
1687 free(mData);
1688 }
1689 if (mObjects) free(mObjects);
1690 }
1691 }
1692
growData(size_t len)1693 status_t Parcel::growData(size_t len)
1694 {
1695 if (len > INT32_MAX) {
1696 // don't accept size_t values which may have come from an
1697 // inadvertent conversion from a negative int.
1698 return BAD_VALUE;
1699 }
1700 if (len > SIZE_MAX - mDataSize) return NO_MEMORY; // overflow
1701 if (mDataSize + len > SIZE_MAX / 3) return NO_MEMORY; // overflow
1702 size_t newSize = ((mDataSize+len)*3)/2;
1703 return continueWrite(newSize);
1704 }
1705
restartWrite(size_t desired)1706 status_t Parcel::restartWrite(size_t desired)
1707 {
1708 if (desired > INT32_MAX) {
1709 // don't accept size_t values which may have come from an
1710 // inadvertent conversion from a negative int.
1711 return BAD_VALUE;
1712 }
1713
1714 if (mOwner) {
1715 freeData();
1716 return continueWrite(desired);
1717 }
1718
1719 uint8_t* data = (uint8_t*)realloc(mData, desired);
1720 if (!data && desired > mDataCapacity) {
1721 mError = NO_MEMORY;
1722 return NO_MEMORY;
1723 }
1724
1725 releaseObjects();
1726
1727 if (data) {
1728 LOG_ALLOC("Parcel %p: restart from %zu to %zu capacity", this, mDataCapacity, desired);
1729 if (mDataCapacity > desired) {
1730 gParcelGlobalAllocSize -= (mDataCapacity - desired);
1731 } else {
1732 gParcelGlobalAllocSize += (desired - mDataCapacity);
1733 }
1734
1735 if (!mData) {
1736 gParcelGlobalAllocCount++;
1737 }
1738 mData = data;
1739 mDataCapacity = desired;
1740 }
1741
1742 mDataSize = mDataPos = 0;
1743 ALOGV("restartWrite Setting data size of %p to %zu", this, mDataSize);
1744 ALOGV("restartWrite Setting data pos of %p to %zu", this, mDataPos);
1745
1746 free(mObjects);
1747 mObjects = nullptr;
1748 mObjectsSize = mObjectsCapacity = 0;
1749 mNextObjectHint = 0;
1750 mHasFds = false;
1751 clearCache();
1752 mFdsKnown = true;
1753 mAllowFds = true;
1754
1755 return NO_ERROR;
1756 }
1757
continueWrite(size_t desired)1758 status_t Parcel::continueWrite(size_t desired)
1759 {
1760 if (desired > INT32_MAX) {
1761 // don't accept size_t values which may have come from an
1762 // inadvertent conversion from a negative int.
1763 return BAD_VALUE;
1764 }
1765
1766 // If shrinking, first adjust for any objects that appear
1767 // after the new data size.
1768 size_t objectsSize = mObjectsSize;
1769 if (desired < mDataSize) {
1770 if (desired == 0) {
1771 objectsSize = 0;
1772 } else {
1773 while (objectsSize > 0) {
1774 if (mObjects[objectsSize-1] < desired)
1775 break;
1776 objectsSize--;
1777 }
1778 }
1779 }
1780
1781 if (mOwner) {
1782 // If the size is going to zero, just release the owner's data.
1783 if (desired == 0) {
1784 freeData();
1785 return NO_ERROR;
1786 }
1787
1788 // If there is a different owner, we need to take
1789 // posession.
1790 uint8_t* data = (uint8_t*)malloc(desired);
1791 if (!data) {
1792 mError = NO_MEMORY;
1793 return NO_MEMORY;
1794 }
1795 binder_size_t* objects = nullptr;
1796
1797 if (objectsSize) {
1798 objects = (binder_size_t*)calloc(objectsSize, sizeof(binder_size_t));
1799 if (!objects) {
1800 free(data);
1801
1802 mError = NO_MEMORY;
1803 return NO_MEMORY;
1804 }
1805
1806 // Little hack to only acquire references on objects
1807 // we will be keeping.
1808 size_t oldObjectsSize = mObjectsSize;
1809 mObjectsSize = objectsSize;
1810 acquireObjects();
1811 mObjectsSize = oldObjectsSize;
1812 }
1813
1814 if (mData) {
1815 memcpy(data, mData, mDataSize < desired ? mDataSize : desired);
1816 }
1817 if (objects && mObjects) {
1818 memcpy(objects, mObjects, objectsSize*sizeof(binder_size_t));
1819 }
1820 //ALOGI("Freeing data ref of %p (pid=%d)", this, getpid());
1821 mOwner(this, mData, mDataSize, mObjects, mObjectsSize, mOwnerCookie);
1822 mOwner = nullptr;
1823
1824 LOG_ALLOC("Parcel %p: taking ownership of %zu capacity", this, desired);
1825 gParcelGlobalAllocSize += desired;
1826 gParcelGlobalAllocCount++;
1827
1828 mData = data;
1829 mObjects = objects;
1830 mDataSize = (mDataSize < desired) ? mDataSize : desired;
1831 ALOGV("continueWrite Setting data size of %p to %zu", this, mDataSize);
1832 mDataCapacity = desired;
1833 mObjectsSize = mObjectsCapacity = objectsSize;
1834 mNextObjectHint = 0;
1835
1836 clearCache();
1837 } else if (mData) {
1838 if (objectsSize < mObjectsSize) {
1839 // Need to release refs on any objects we are dropping.
1840 const sp<ProcessState> proc(ProcessState::self());
1841 for (size_t i=objectsSize; i<mObjectsSize; i++) {
1842 const flat_binder_object* flat
1843 = reinterpret_cast<flat_binder_object*>(mData+mObjects[i]);
1844 if (flat->hdr.type == BINDER_TYPE_FD) {
1845 // will need to rescan because we may have lopped off the only FDs
1846 mFdsKnown = false;
1847 }
1848 release_object(proc, *flat, this);
1849 }
1850 binder_size_t* objects =
1851 (binder_size_t*)realloc(mObjects, objectsSize*sizeof(binder_size_t));
1852 if (objects) {
1853 mObjects = objects;
1854 }
1855 mObjectsSize = objectsSize;
1856 mNextObjectHint = 0;
1857
1858 clearCache();
1859 }
1860
1861 // We own the data, so we can just do a realloc().
1862 if (desired > mDataCapacity) {
1863 uint8_t* data = (uint8_t*)realloc(mData, desired);
1864 if (data) {
1865 LOG_ALLOC("Parcel %p: continue from %zu to %zu capacity", this, mDataCapacity,
1866 desired);
1867 gParcelGlobalAllocSize += desired;
1868 gParcelGlobalAllocSize -= mDataCapacity;
1869 mData = data;
1870 mDataCapacity = desired;
1871 } else {
1872 mError = NO_MEMORY;
1873 return NO_MEMORY;
1874 }
1875 } else {
1876 if (mDataSize > desired) {
1877 mDataSize = desired;
1878 ALOGV("continueWrite Setting data size of %p to %zu", this, mDataSize);
1879 }
1880 if (mDataPos > desired) {
1881 mDataPos = desired;
1882 ALOGV("continueWrite Setting data pos of %p to %zu", this, mDataPos);
1883 }
1884 }
1885
1886 } else {
1887 // This is the first data. Easy!
1888 uint8_t* data = (uint8_t*)malloc(desired);
1889 if (!data) {
1890 mError = NO_MEMORY;
1891 return NO_MEMORY;
1892 }
1893
1894 if(!(mDataCapacity == 0 && mObjects == nullptr
1895 && mObjectsCapacity == 0)) {
1896 ALOGE("continueWrite: %zu/%p/%zu/%zu", mDataCapacity, mObjects, mObjectsCapacity, desired);
1897 }
1898
1899 LOG_ALLOC("Parcel %p: allocating with %zu capacity", this, desired);
1900 gParcelGlobalAllocSize += desired;
1901 gParcelGlobalAllocCount++;
1902
1903 mData = data;
1904 mDataSize = mDataPos = 0;
1905 ALOGV("continueWrite Setting data size of %p to %zu", this, mDataSize);
1906 ALOGV("continueWrite Setting data pos of %p to %zu", this, mDataPos);
1907 mDataCapacity = desired;
1908 }
1909
1910 return NO_ERROR;
1911 }
1912
initState()1913 void Parcel::initState()
1914 {
1915 LOG_ALLOC("Parcel %p: initState", this);
1916 mError = NO_ERROR;
1917 mData = nullptr;
1918 mDataSize = 0;
1919 mDataCapacity = 0;
1920 mDataPos = 0;
1921 ALOGV("initState Setting data size of %p to %zu", this, mDataSize);
1922 ALOGV("initState Setting data pos of %p to %zu", this, mDataPos);
1923 mObjects = nullptr;
1924 mObjectsSize = 0;
1925 mObjectsCapacity = 0;
1926 mNextObjectHint = 0;
1927 mHasFds = false;
1928 mFdsKnown = true;
1929 mAllowFds = true;
1930 mOwner = nullptr;
1931 clearCache();
1932
1933 // racing multiple init leads only to multiple identical write
1934 if (gMaxFds == 0) {
1935 struct rlimit result;
1936 if (!getrlimit(RLIMIT_NOFILE, &result)) {
1937 gMaxFds = (size_t)result.rlim_cur;
1938 //ALOGI("parcel fd limit set to %zu", gMaxFds);
1939 } else {
1940 ALOGW("Unable to getrlimit: %s", strerror(errno));
1941 gMaxFds = 1024;
1942 }
1943 }
1944 }
1945
scanForFds() const1946 void Parcel::scanForFds() const
1947 {
1948 bool hasFds = false;
1949 for (size_t i=0; i<mObjectsSize; i++) {
1950 const flat_binder_object* flat
1951 = reinterpret_cast<const flat_binder_object*>(mData + mObjects[i]);
1952 if (flat->hdr.type == BINDER_TYPE_FD) {
1953 hasFds = true;
1954 break;
1955 }
1956 }
1957 mHasFds = hasFds;
1958 mFdsKnown = true;
1959 }
1960
1961 } // namespace hardware
1962 } // namespace android
1963