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 "Parcel"
18 //#define LOG_NDEBUG 0
19
20 #include <errno.h>
21 #include <fcntl.h>
22 #include <inttypes.h>
23 #include <linux/sched.h>
24 #include <pthread.h>
25 #include <stdint.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <sys/mman.h>
29 #include <sys/stat.h>
30 #include <sys/types.h>
31 #include <sys/resource.h>
32 #include <unistd.h>
33
34 #include <binder/Binder.h>
35 #include <binder/BpBinder.h>
36 #include <binder/IPCThreadState.h>
37 #include <binder/Parcel.h>
38 #include <binder/ProcessState.h>
39 #include <binder/Stability.h>
40 #include <binder/Status.h>
41 #include <binder/TextOutput.h>
42
43 #include <cutils/ashmem.h>
44 #include <cutils/compiler.h>
45 #include <utils/Flattenable.h>
46 #include <utils/Log.h>
47 #include <utils/String16.h>
48 #include <utils/String8.h>
49 #include <utils/misc.h>
50
51 #include "RpcState.h"
52 #include "Static.h"
53 #include "Utils.h"
54 #include "binder_module.h"
55
56 #define LOG_REFS(...)
57 //#define LOG_REFS(...) ALOG(LOG_DEBUG, LOG_TAG, __VA_ARGS__)
58 #define LOG_ALLOC(...)
59 //#define LOG_ALLOC(...) ALOG(LOG_DEBUG, LOG_TAG, __VA_ARGS__)
60
61 // ---------------------------------------------------------------------------
62
63 // This macro should never be used at runtime, as a too large value
64 // of s could cause an integer overflow. Instead, you should always
65 // use the wrapper function pad_size()
66 #define PAD_SIZE_UNSAFE(s) (((s) + 3) & ~3UL)
67
pad_size(size_t s)68 static size_t pad_size(size_t s) {
69 if (s > (std::numeric_limits<size_t>::max() - 3)) {
70 LOG_ALWAYS_FATAL("pad size too big %zu", s);
71 }
72 return PAD_SIZE_UNSAFE(s);
73 }
74
75 // Note: must be kept in sync with android/os/StrictMode.java's PENALTY_GATHER
76 #define STRICT_MODE_PENALTY_GATHER (1 << 31)
77
78 namespace android {
79
80 // many things compile this into prebuilts on the stack
81 #ifdef __LP64__
82 static_assert(sizeof(Parcel) == 120);
83 #else
84 static_assert(sizeof(Parcel) == 60);
85 #endif
86
87 static std::atomic<size_t> gParcelGlobalAllocCount;
88 static std::atomic<size_t> gParcelGlobalAllocSize;
89
90 static size_t gMaxFds = 0;
91
92 // Maximum size of a blob to transfer in-place.
93 static const size_t BLOB_INPLACE_LIMIT = 16 * 1024;
94
95 enum {
96 BLOB_INPLACE = 0,
97 BLOB_ASHMEM_IMMUTABLE = 1,
98 BLOB_ASHMEM_MUTABLE = 2,
99 };
100
acquire_object(const sp<ProcessState> & proc,const flat_binder_object & obj,const void * who)101 static void acquire_object(const sp<ProcessState>& proc, const flat_binder_object& obj,
102 const void* who) {
103 switch (obj.hdr.type) {
104 case BINDER_TYPE_BINDER:
105 if (obj.binder) {
106 LOG_REFS("Parcel %p acquiring reference on local %llu", who, obj.cookie);
107 reinterpret_cast<IBinder*>(obj.cookie)->incStrong(who);
108 }
109 return;
110 case BINDER_TYPE_HANDLE: {
111 const sp<IBinder> b = proc->getStrongProxyForHandle(obj.handle);
112 if (b != nullptr) {
113 LOG_REFS("Parcel %p acquiring reference on remote %p", who, b.get());
114 b->incStrong(who);
115 }
116 return;
117 }
118 case BINDER_TYPE_FD: {
119 return;
120 }
121 }
122
123 ALOGD("Invalid object type 0x%08x", obj.hdr.type);
124 }
125
release_object(const sp<ProcessState> & proc,const flat_binder_object & obj,const void * who)126 static void release_object(const sp<ProcessState>& proc, const flat_binder_object& obj,
127 const void* who) {
128 switch (obj.hdr.type) {
129 case BINDER_TYPE_BINDER:
130 if (obj.binder) {
131 LOG_REFS("Parcel %p releasing reference on local %llu", who, obj.cookie);
132 reinterpret_cast<IBinder*>(obj.cookie)->decStrong(who);
133 }
134 return;
135 case BINDER_TYPE_HANDLE: {
136 const sp<IBinder> b = proc->getStrongProxyForHandle(obj.handle);
137 if (b != nullptr) {
138 LOG_REFS("Parcel %p releasing reference on remote %p", who, b.get());
139 b->decStrong(who);
140 }
141 return;
142 }
143 case BINDER_TYPE_FD: {
144 if (obj.cookie != 0) { // owned
145 close(obj.handle);
146 }
147 return;
148 }
149 }
150
151 ALOGE("Invalid object type 0x%08x", obj.hdr.type);
152 }
153
finishFlattenBinder(const sp<IBinder> & binder)154 status_t Parcel::finishFlattenBinder(const sp<IBinder>& binder)
155 {
156 internal::Stability::tryMarkCompilationUnit(binder.get());
157 int16_t rep = internal::Stability::getRepr(binder.get());
158 return writeInt32(rep);
159 }
160
finishUnflattenBinder(const sp<IBinder> & binder,sp<IBinder> * out) const161 status_t Parcel::finishUnflattenBinder(
162 const sp<IBinder>& binder, sp<IBinder>* out) const
163 {
164 int32_t stability;
165 status_t status = readInt32(&stability);
166 if (status != OK) return status;
167
168 status = internal::Stability::setRepr(binder.get(), static_cast<int16_t>(stability),
169 true /*log*/);
170 if (status != OK) return status;
171
172 *out = binder;
173 return OK;
174 }
175
schedPolicyMask(int policy,int priority)176 static constexpr inline int schedPolicyMask(int policy, int priority) {
177 return (priority & FLAT_BINDER_FLAG_PRIORITY_MASK) | ((policy & 3) << FLAT_BINDER_FLAG_SCHED_POLICY_SHIFT);
178 }
179
flattenBinder(const sp<IBinder> & binder)180 status_t Parcel::flattenBinder(const sp<IBinder>& binder) {
181 BBinder* local = nullptr;
182 if (binder) local = binder->localBinder();
183 if (local) local->setParceled();
184
185 if (isForRpc()) {
186 if (binder) {
187 status_t status = writeInt32(1); // non-null
188 if (status != OK) return status;
189 uint64_t address;
190 // TODO(b/167966510): need to undo this if the Parcel is not sent
191 status = mSession->state()->onBinderLeaving(mSession, binder, &address);
192 if (status != OK) return status;
193 status = writeUint64(address);
194 if (status != OK) return status;
195 } else {
196 status_t status = writeInt32(0); // null
197 if (status != OK) return status;
198 }
199 return finishFlattenBinder(binder);
200 }
201
202 flat_binder_object obj;
203
204 int schedBits = 0;
205 if (!IPCThreadState::self()->backgroundSchedulingDisabled()) {
206 schedBits = schedPolicyMask(SCHED_NORMAL, 19);
207 }
208
209 if (binder != nullptr) {
210 if (!local) {
211 BpBinder *proxy = binder->remoteBinder();
212 if (proxy == nullptr) {
213 ALOGE("null proxy");
214 } else {
215 if (proxy->isRpcBinder()) {
216 ALOGE("Sending a socket binder over kernel binder is prohibited");
217 return INVALID_OPERATION;
218 }
219 }
220 const int32_t handle = proxy ? proxy->getPrivateAccessor().binderHandle() : 0;
221 obj.hdr.type = BINDER_TYPE_HANDLE;
222 obj.binder = 0; /* Don't pass uninitialized stack data to a remote process */
223 obj.flags = 0;
224 obj.handle = handle;
225 obj.cookie = 0;
226 } else {
227 int policy = local->getMinSchedulerPolicy();
228 int priority = local->getMinSchedulerPriority();
229
230 if (policy != 0 || priority != 0) {
231 // override value, since it is set explicitly
232 schedBits = schedPolicyMask(policy, priority);
233 }
234 obj.flags = FLAT_BINDER_FLAG_ACCEPTS_FDS;
235 if (local->isRequestingSid()) {
236 obj.flags |= FLAT_BINDER_FLAG_TXN_SECURITY_CTX;
237 }
238 if (local->isInheritRt()) {
239 obj.flags |= FLAT_BINDER_FLAG_INHERIT_RT;
240 }
241 obj.hdr.type = BINDER_TYPE_BINDER;
242 obj.binder = reinterpret_cast<uintptr_t>(local->getWeakRefs());
243 obj.cookie = reinterpret_cast<uintptr_t>(local);
244 }
245 } else {
246 obj.hdr.type = BINDER_TYPE_BINDER;
247 obj.flags = 0;
248 obj.binder = 0;
249 obj.cookie = 0;
250 }
251
252 obj.flags |= schedBits;
253
254 status_t status = writeObject(obj, false);
255 if (status != OK) return status;
256
257 return finishFlattenBinder(binder);
258 }
259
unflattenBinder(sp<IBinder> * out) const260 status_t Parcel::unflattenBinder(sp<IBinder>* out) const
261 {
262 if (isForRpc()) {
263 LOG_ALWAYS_FATAL_IF(mSession == nullptr, "RpcSession required to read from remote parcel");
264
265 int32_t isPresent;
266 status_t status = readInt32(&isPresent);
267 if (status != OK) return status;
268
269 sp<IBinder> binder;
270
271 if (isPresent & 1) {
272 uint64_t addr;
273 if (status_t status = readUint64(&addr); status != OK) return status;
274 if (status_t status = mSession->state()->onBinderEntering(mSession, addr, &binder);
275 status != OK)
276 return status;
277 if (status_t status = mSession->state()->flushExcessBinderRefs(mSession, addr, binder);
278 status != OK)
279 return status;
280 }
281
282 return finishUnflattenBinder(binder, out);
283 }
284
285 const flat_binder_object* flat = readObject(false);
286
287 if (flat) {
288 switch (flat->hdr.type) {
289 case BINDER_TYPE_BINDER: {
290 sp<IBinder> binder =
291 sp<IBinder>::fromExisting(reinterpret_cast<IBinder*>(flat->cookie));
292 return finishUnflattenBinder(binder, out);
293 }
294 case BINDER_TYPE_HANDLE: {
295 sp<IBinder> binder =
296 ProcessState::self()->getStrongProxyForHandle(flat->handle);
297 return finishUnflattenBinder(binder, out);
298 }
299 }
300 }
301 return BAD_TYPE;
302 }
303
304 // ---------------------------------------------------------------------------
305
Parcel()306 Parcel::Parcel()
307 {
308 LOG_ALLOC("Parcel %p: constructing", this);
309 initState();
310 }
311
~Parcel()312 Parcel::~Parcel()
313 {
314 freeDataNoInit();
315 LOG_ALLOC("Parcel %p: destroyed", this);
316 }
317
getGlobalAllocSize()318 size_t Parcel::getGlobalAllocSize() {
319 return gParcelGlobalAllocSize.load();
320 }
321
getGlobalAllocCount()322 size_t Parcel::getGlobalAllocCount() {
323 return gParcelGlobalAllocCount.load();
324 }
325
data() const326 const uint8_t* Parcel::data() const
327 {
328 return mData;
329 }
330
dataSize() const331 size_t Parcel::dataSize() const
332 {
333 return (mDataSize > mDataPos ? mDataSize : mDataPos);
334 }
335
dataAvail() const336 size_t Parcel::dataAvail() const
337 {
338 size_t result = dataSize() - dataPosition();
339 if (result > INT32_MAX) {
340 LOG_ALWAYS_FATAL("result too big: %zu", result);
341 }
342 return result;
343 }
344
dataPosition() const345 size_t Parcel::dataPosition() const
346 {
347 return mDataPos;
348 }
349
dataCapacity() const350 size_t Parcel::dataCapacity() const
351 {
352 return mDataCapacity;
353 }
354
setDataSize(size_t size)355 status_t Parcel::setDataSize(size_t size)
356 {
357 if (size > INT32_MAX) {
358 // don't accept size_t values which may have come from an
359 // inadvertent conversion from a negative int.
360 return BAD_VALUE;
361 }
362
363 status_t err;
364 err = continueWrite(size);
365 if (err == NO_ERROR) {
366 mDataSize = size;
367 ALOGV("setDataSize Setting data size of %p to %zu", this, mDataSize);
368 }
369 return err;
370 }
371
setDataPosition(size_t pos) const372 void Parcel::setDataPosition(size_t pos) const
373 {
374 if (pos > INT32_MAX) {
375 // don't accept size_t values which may have come from an
376 // inadvertent conversion from a negative int.
377 LOG_ALWAYS_FATAL("pos too big: %zu", pos);
378 }
379
380 mDataPos = pos;
381 mNextObjectHint = 0;
382 mObjectsSorted = false;
383 }
384
setDataCapacity(size_t size)385 status_t Parcel::setDataCapacity(size_t size)
386 {
387 if (size > INT32_MAX) {
388 // don't accept size_t values which may have come from an
389 // inadvertent conversion from a negative int.
390 return BAD_VALUE;
391 }
392
393 if (size > mDataCapacity) return continueWrite(size);
394 return NO_ERROR;
395 }
396
setData(const uint8_t * buffer,size_t len)397 status_t Parcel::setData(const uint8_t* buffer, size_t len)
398 {
399 if (len > INT32_MAX) {
400 // don't accept size_t values which may have come from an
401 // inadvertent conversion from a negative int.
402 return BAD_VALUE;
403 }
404
405 status_t err = restartWrite(len);
406 if (err == NO_ERROR) {
407 memcpy(const_cast<uint8_t*>(data()), buffer, len);
408 mDataSize = len;
409 mFdsKnown = false;
410 }
411 return err;
412 }
413
appendFrom(const Parcel * parcel,size_t offset,size_t len)414 status_t Parcel::appendFrom(const Parcel *parcel, size_t offset, size_t len)
415 {
416 if (mSession != parcel->mSession) {
417 ALOGE("Cannot append Parcel from one context to another. They may be different formats, "
418 "and objects are specific to a context.");
419 return BAD_TYPE;
420 }
421
422 status_t err;
423 const uint8_t *data = parcel->mData;
424 const binder_size_t *objects = parcel->mObjects;
425 size_t size = parcel->mObjectsSize;
426 int startPos = mDataPos;
427 int firstIndex = -1, lastIndex = -2;
428
429 if (len == 0) {
430 return NO_ERROR;
431 }
432
433 if (len > 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 // range checks against the source parcel size
440 if ((offset > parcel->mDataSize)
441 || (len > parcel->mDataSize)
442 || (offset + len > parcel->mDataSize)) {
443 return BAD_VALUE;
444 }
445
446 // Count objects in range
447 for (int i = 0; i < (int) size; i++) {
448 size_t off = objects[i];
449 if ((off >= offset) && (off + sizeof(flat_binder_object) <= offset + len)) {
450 if (firstIndex == -1) {
451 firstIndex = i;
452 }
453 lastIndex = i;
454 }
455 }
456 int numObjects = lastIndex - firstIndex + 1;
457
458 if ((mDataSize+len) > mDataCapacity) {
459 // grow data
460 err = growData(len);
461 if (err != NO_ERROR) {
462 return err;
463 }
464 }
465
466 // append data
467 memcpy(mData + mDataPos, data + offset, len);
468 mDataPos += len;
469 mDataSize += len;
470
471 err = NO_ERROR;
472
473 if (numObjects > 0) {
474 const sp<ProcessState> proc(ProcessState::self());
475 // grow objects
476 if (mObjectsCapacity < mObjectsSize + numObjects) {
477 if ((size_t) numObjects > SIZE_MAX - mObjectsSize) return NO_MEMORY; // overflow
478 if (mObjectsSize + numObjects > SIZE_MAX / 3) return NO_MEMORY; // overflow
479 size_t newSize = ((mObjectsSize + numObjects)*3)/2;
480 if (newSize > SIZE_MAX / sizeof(binder_size_t)) return NO_MEMORY; // overflow
481 binder_size_t *objects =
482 (binder_size_t*)realloc(mObjects, newSize*sizeof(binder_size_t));
483 if (objects == (binder_size_t*)nullptr) {
484 return NO_MEMORY;
485 }
486 mObjects = objects;
487 mObjectsCapacity = newSize;
488 }
489
490 // append and acquire objects
491 int idx = mObjectsSize;
492 for (int i = firstIndex; i <= lastIndex; i++) {
493 size_t off = objects[i] - offset + startPos;
494 mObjects[idx++] = off;
495 mObjectsSize++;
496
497 flat_binder_object* flat
498 = reinterpret_cast<flat_binder_object*>(mData + off);
499 acquire_object(proc, *flat, this);
500
501 if (flat->hdr.type == BINDER_TYPE_FD) {
502 // If this is a file descriptor, we need to dup it so the
503 // new Parcel now owns its own fd, and can declare that we
504 // officially know we have fds.
505 flat->handle = fcntl(flat->handle, F_DUPFD_CLOEXEC, 0);
506 flat->cookie = 1;
507 mHasFds = mFdsKnown = true;
508 if (!mAllowFds) {
509 err = FDS_NOT_ALLOWED;
510 }
511 }
512 }
513 }
514
515 return err;
516 }
517
compareData(const Parcel & other)518 int Parcel::compareData(const Parcel& other) {
519 size_t size = dataSize();
520 if (size != other.dataSize()) {
521 return size < other.dataSize() ? -1 : 1;
522 }
523 return memcmp(data(), other.data(), size);
524 }
525
compareDataInRange(size_t thisOffset,const Parcel & other,size_t otherOffset,size_t len,int * result) const526 status_t Parcel::compareDataInRange(size_t thisOffset, const Parcel& other, size_t otherOffset,
527 size_t len, int* result) const {
528 if (len > INT32_MAX || thisOffset > INT32_MAX || otherOffset > INT32_MAX) {
529 // Don't accept size_t values which may have come from an inadvertent conversion from a
530 // negative int.
531 return BAD_VALUE;
532 }
533 size_t thisLimit;
534 if (__builtin_add_overflow(thisOffset, len, &thisLimit) || thisLimit > mDataSize) {
535 return BAD_VALUE;
536 }
537 size_t otherLimit;
538 if (__builtin_add_overflow(otherOffset, len, &otherLimit) || otherLimit > other.mDataSize) {
539 return BAD_VALUE;
540 }
541 *result = memcmp(data() + thisOffset, other.data() + otherOffset, len);
542 return NO_ERROR;
543 }
544
allowFds() const545 bool Parcel::allowFds() const
546 {
547 return mAllowFds;
548 }
549
pushAllowFds(bool allowFds)550 bool Parcel::pushAllowFds(bool allowFds)
551 {
552 const bool origValue = mAllowFds;
553 if (!allowFds) {
554 mAllowFds = false;
555 }
556 return origValue;
557 }
558
restoreAllowFds(bool lastValue)559 void Parcel::restoreAllowFds(bool lastValue)
560 {
561 mAllowFds = lastValue;
562 }
563
hasFileDescriptors() const564 bool Parcel::hasFileDescriptors() const
565 {
566 if (!mFdsKnown) {
567 scanForFds();
568 }
569 return mHasFds;
570 }
571
debugReadAllStrongBinders() const572 std::vector<sp<IBinder>> Parcel::debugReadAllStrongBinders() const {
573 std::vector<sp<IBinder>> ret;
574
575 size_t initPosition = dataPosition();
576 for (size_t i = 0; i < mObjectsSize; i++) {
577 binder_size_t offset = mObjects[i];
578 const flat_binder_object* flat =
579 reinterpret_cast<const flat_binder_object*>(mData + offset);
580 if (flat->hdr.type != BINDER_TYPE_BINDER) continue;
581
582 setDataPosition(offset);
583
584 sp<IBinder> binder = readStrongBinder();
585 if (binder != nullptr) ret.push_back(binder);
586 }
587
588 setDataPosition(initPosition);
589 return ret;
590 }
591
debugReadAllFileDescriptors() const592 std::vector<int> Parcel::debugReadAllFileDescriptors() const {
593 std::vector<int> ret;
594
595 size_t initPosition = dataPosition();
596 for (size_t i = 0; i < mObjectsSize; i++) {
597 binder_size_t offset = mObjects[i];
598 const flat_binder_object* flat =
599 reinterpret_cast<const flat_binder_object*>(mData + offset);
600 if (flat->hdr.type != BINDER_TYPE_FD) continue;
601
602 setDataPosition(offset);
603
604 int fd = readFileDescriptor();
605 LOG_ALWAYS_FATAL_IF(fd == -1);
606 ret.push_back(fd);
607 }
608
609 setDataPosition(initPosition);
610 return ret;
611 }
612
hasFileDescriptorsInRange(size_t offset,size_t len,bool * result) const613 status_t Parcel::hasFileDescriptorsInRange(size_t offset, size_t len, bool* result) const {
614 if (len > INT32_MAX || offset > INT32_MAX) {
615 // Don't accept size_t values which may have come from an inadvertent conversion from a
616 // negative int.
617 return BAD_VALUE;
618 }
619 size_t limit;
620 if (__builtin_add_overflow(offset, len, &limit) || limit > mDataSize) {
621 return BAD_VALUE;
622 }
623 *result = false;
624 for (size_t i = 0; i < mObjectsSize; i++) {
625 size_t pos = mObjects[i];
626 if (pos < offset) continue;
627 if (pos + sizeof(flat_binder_object) > offset + len) {
628 if (mObjectsSorted) break;
629 else continue;
630 }
631 const flat_binder_object* flat = reinterpret_cast<const flat_binder_object*>(mData + pos);
632 if (flat->hdr.type == BINDER_TYPE_FD) {
633 *result = true;
634 break;
635 }
636 }
637 return NO_ERROR;
638 }
639
markSensitive() const640 void Parcel::markSensitive() const
641 {
642 mDeallocZero = true;
643 }
644
markForBinder(const sp<IBinder> & binder)645 void Parcel::markForBinder(const sp<IBinder>& binder) {
646 LOG_ALWAYS_FATAL_IF(mData != nullptr, "format must be set before data is written");
647
648 if (binder && binder->remoteBinder() && binder->remoteBinder()->isRpcBinder()) {
649 markForRpc(binder->remoteBinder()->getPrivateAccessor().rpcSession());
650 }
651 }
652
markForRpc(const sp<RpcSession> & session)653 void Parcel::markForRpc(const sp<RpcSession>& session) {
654 LOG_ALWAYS_FATAL_IF(mData != nullptr && mOwner == nullptr,
655 "format must be set before data is written OR on IPC data");
656
657 LOG_ALWAYS_FATAL_IF(session == nullptr, "markForRpc requires session");
658 mSession = session;
659 }
660
isForRpc() const661 bool Parcel::isForRpc() const {
662 return mSession != nullptr;
663 }
664
updateWorkSourceRequestHeaderPosition() const665 void Parcel::updateWorkSourceRequestHeaderPosition() const {
666 // Only update the request headers once. We only want to point
667 // to the first headers read/written.
668 if (!mRequestHeaderPresent) {
669 mWorkSourceRequestHeaderPosition = dataPosition();
670 mRequestHeaderPresent = true;
671 }
672 }
673
674 #if defined(__ANDROID_VNDK__)
675 constexpr int32_t kHeader = B_PACK_CHARS('V', 'N', 'D', 'R');
676 #elif defined(__ANDROID_RECOVERY__)
677 constexpr int32_t kHeader = B_PACK_CHARS('R', 'E', 'C', 'O');
678 #else
679 constexpr int32_t kHeader = B_PACK_CHARS('S', 'Y', 'S', 'T');
680 #endif
681
682 // Write RPC headers. (previously just the interface token)
writeInterfaceToken(const String16 & interface)683 status_t Parcel::writeInterfaceToken(const String16& interface)
684 {
685 return writeInterfaceToken(interface.string(), interface.size());
686 }
687
writeInterfaceToken(const char16_t * str,size_t len)688 status_t Parcel::writeInterfaceToken(const char16_t* str, size_t len) {
689 if (CC_LIKELY(!isForRpc())) {
690 const IPCThreadState* threadState = IPCThreadState::self();
691 writeInt32(threadState->getStrictModePolicy() | STRICT_MODE_PENALTY_GATHER);
692 updateWorkSourceRequestHeaderPosition();
693 writeInt32(threadState->shouldPropagateWorkSource() ? threadState->getCallingWorkSourceUid()
694 : IPCThreadState::kUnsetWorkSource);
695 writeInt32(kHeader);
696 }
697
698 // currently the interface identification token is just its name as a string
699 return writeString16(str, len);
700 }
701
replaceCallingWorkSourceUid(uid_t uid)702 bool Parcel::replaceCallingWorkSourceUid(uid_t uid)
703 {
704 if (!mRequestHeaderPresent) {
705 return false;
706 }
707
708 const size_t initialPosition = dataPosition();
709 setDataPosition(mWorkSourceRequestHeaderPosition);
710 status_t err = writeInt32(uid);
711 setDataPosition(initialPosition);
712 return err == NO_ERROR;
713 }
714
readCallingWorkSourceUid() const715 uid_t Parcel::readCallingWorkSourceUid() const
716 {
717 if (!mRequestHeaderPresent) {
718 return IPCThreadState::kUnsetWorkSource;
719 }
720
721 const size_t initialPosition = dataPosition();
722 setDataPosition(mWorkSourceRequestHeaderPosition);
723 uid_t uid = readInt32();
724 setDataPosition(initialPosition);
725 return uid;
726 }
727
checkInterface(IBinder * binder) const728 bool Parcel::checkInterface(IBinder* binder) const
729 {
730 return enforceInterface(binder->getInterfaceDescriptor());
731 }
732
enforceInterface(const String16 & interface,IPCThreadState * threadState) const733 bool Parcel::enforceInterface(const String16& interface,
734 IPCThreadState* threadState) const
735 {
736 return enforceInterface(interface.string(), interface.size(), threadState);
737 }
738
enforceInterface(const char16_t * interface,size_t len,IPCThreadState * threadState) const739 bool Parcel::enforceInterface(const char16_t* interface,
740 size_t len,
741 IPCThreadState* threadState) const
742 {
743 if (CC_LIKELY(!isForRpc())) {
744 // StrictModePolicy.
745 int32_t strictPolicy = readInt32();
746 if (threadState == nullptr) {
747 threadState = IPCThreadState::self();
748 }
749 if ((threadState->getLastTransactionBinderFlags() & IBinder::FLAG_ONEWAY) != 0) {
750 // For one-way calls, the callee is running entirely
751 // disconnected from the caller, so disable StrictMode entirely.
752 // Not only does disk/network usage not impact the caller, but
753 // there's no way to communicate back violations anyway.
754 threadState->setStrictModePolicy(0);
755 } else {
756 threadState->setStrictModePolicy(strictPolicy);
757 }
758 // WorkSource.
759 updateWorkSourceRequestHeaderPosition();
760 int32_t workSource = readInt32();
761 threadState->setCallingWorkSourceUidWithoutPropagation(workSource);
762 // vendor header
763 int32_t header = readInt32();
764 if (header != kHeader) {
765 ALOGE("Expecting header 0x%x but found 0x%x. Mixing copies of libbinder?", kHeader,
766 header);
767 return false;
768 }
769 }
770
771 // Interface descriptor.
772 size_t parcel_interface_len;
773 const char16_t* parcel_interface = readString16Inplace(&parcel_interface_len);
774 if (len == parcel_interface_len &&
775 (!len || !memcmp(parcel_interface, interface, len * sizeof (char16_t)))) {
776 return true;
777 } else {
778 ALOGW("**** enforceInterface() expected '%s' but read '%s'",
779 String8(interface, len).string(),
780 String8(parcel_interface, parcel_interface_len).string());
781 return false;
782 }
783 }
784
enforceNoDataAvail() const785 binder::Status Parcel::enforceNoDataAvail() const {
786 const auto n = dataAvail();
787 if (n == 0) {
788 return binder::Status::ok();
789 }
790 return binder::Status::
791 fromExceptionCode(binder::Status::Exception::EX_BAD_PARCELABLE,
792 String8::format("Parcel data not fully consumed, unread size: %zu",
793 n));
794 }
795
objectsCount() const796 size_t Parcel::objectsCount() const
797 {
798 return mObjectsSize;
799 }
800
errorCheck() const801 status_t Parcel::errorCheck() const
802 {
803 return mError;
804 }
805
setError(status_t err)806 void Parcel::setError(status_t err)
807 {
808 mError = err;
809 }
810
finishWrite(size_t len)811 status_t Parcel::finishWrite(size_t len)
812 {
813 if (len > INT32_MAX) {
814 // don't accept size_t values which may have come from an
815 // inadvertent conversion from a negative int.
816 return BAD_VALUE;
817 }
818
819 //printf("Finish write of %d\n", len);
820 mDataPos += len;
821 ALOGV("finishWrite Setting data pos of %p to %zu", this, mDataPos);
822 if (mDataPos > mDataSize) {
823 mDataSize = mDataPos;
824 ALOGV("finishWrite Setting data size of %p to %zu", this, mDataSize);
825 }
826 //printf("New pos=%d, size=%d\n", mDataPos, mDataSize);
827 return NO_ERROR;
828 }
829
writeUnpadded(const void * data,size_t len)830 status_t Parcel::writeUnpadded(const void* data, size_t len)
831 {
832 if (len > INT32_MAX) {
833 // don't accept size_t values which may have come from an
834 // inadvertent conversion from a negative int.
835 return BAD_VALUE;
836 }
837
838 size_t end = mDataPos + len;
839 if (end < mDataPos) {
840 // integer overflow
841 return BAD_VALUE;
842 }
843
844 if (end <= mDataCapacity) {
845 restart_write:
846 memcpy(mData+mDataPos, data, len);
847 return finishWrite(len);
848 }
849
850 status_t err = growData(len);
851 if (err == NO_ERROR) goto restart_write;
852 return err;
853 }
854
write(const void * data,size_t len)855 status_t Parcel::write(const void* data, size_t len)
856 {
857 if (len > INT32_MAX) {
858 // don't accept size_t values which may have come from an
859 // inadvertent conversion from a negative int.
860 return BAD_VALUE;
861 }
862
863 void* const d = writeInplace(len);
864 if (d) {
865 memcpy(d, data, len);
866 return NO_ERROR;
867 }
868 return mError;
869 }
870
writeInplace(size_t len)871 void* Parcel::writeInplace(size_t len)
872 {
873 if (len > INT32_MAX) {
874 // don't accept size_t values which may have come from an
875 // inadvertent conversion from a negative int.
876 return nullptr;
877 }
878
879 const size_t padded = pad_size(len);
880
881 // check for integer overflow
882 if (mDataPos+padded < mDataPos) {
883 return nullptr;
884 }
885
886 if ((mDataPos+padded) <= mDataCapacity) {
887 restart_write:
888 //printf("Writing %ld bytes, padded to %ld\n", len, padded);
889 uint8_t* const data = mData+mDataPos;
890
891 // Need to pad at end?
892 if (padded != len) {
893 #if BYTE_ORDER == BIG_ENDIAN
894 static const uint32_t mask[4] = {
895 0x00000000, 0xffffff00, 0xffff0000, 0xff000000
896 };
897 #endif
898 #if BYTE_ORDER == LITTLE_ENDIAN
899 static const uint32_t mask[4] = {
900 0x00000000, 0x00ffffff, 0x0000ffff, 0x000000ff
901 };
902 #endif
903 //printf("Applying pad mask: %p to %p\n", (void*)mask[padded-len],
904 // *reinterpret_cast<void**>(data+padded-4));
905 *reinterpret_cast<uint32_t*>(data+padded-4) &= mask[padded-len];
906 }
907
908 finishWrite(padded);
909 return data;
910 }
911
912 status_t err = growData(padded);
913 if (err == NO_ERROR) goto restart_write;
914 return nullptr;
915 }
916
writeUtf8AsUtf16(const std::string & str)917 status_t Parcel::writeUtf8AsUtf16(const std::string& str) {
918 const uint8_t* strData = (uint8_t*)str.data();
919 const size_t strLen= str.length();
920 const ssize_t utf16Len = utf8_to_utf16_length(strData, strLen);
921 if (utf16Len < 0 || utf16Len > std::numeric_limits<int32_t>::max()) {
922 return BAD_VALUE;
923 }
924
925 status_t err = writeInt32(utf16Len);
926 if (err) {
927 return err;
928 }
929
930 // Allocate enough bytes to hold our converted string and its terminating NULL.
931 void* dst = writeInplace((utf16Len + 1) * sizeof(char16_t));
932 if (!dst) {
933 return NO_MEMORY;
934 }
935
936 utf8_to_utf16(strData, strLen, (char16_t*)dst, (size_t) utf16Len + 1);
937
938 return NO_ERROR;
939 }
940
941
writeUtf8AsUtf16(const std::optional<std::string> & str)942 status_t Parcel::writeUtf8AsUtf16(const std::optional<std::string>& str) { return writeData(str); }
writeUtf8AsUtf16(const std::unique_ptr<std::string> & str)943 status_t Parcel::writeUtf8AsUtf16(const std::unique_ptr<std::string>& str) { return writeData(str); }
944
writeString16(const std::optional<String16> & str)945 status_t Parcel::writeString16(const std::optional<String16>& str) { return writeData(str); }
writeString16(const std::unique_ptr<String16> & str)946 status_t Parcel::writeString16(const std::unique_ptr<String16>& str) { return writeData(str); }
947
writeByteVector(const std::vector<int8_t> & val)948 status_t Parcel::writeByteVector(const std::vector<int8_t>& val) { return writeData(val); }
writeByteVector(const std::optional<std::vector<int8_t>> & val)949 status_t Parcel::writeByteVector(const std::optional<std::vector<int8_t>>& val) { return writeData(val); }
writeByteVector(const std::unique_ptr<std::vector<int8_t>> & val)950 status_t Parcel::writeByteVector(const std::unique_ptr<std::vector<int8_t>>& val) { return writeData(val); }
writeByteVector(const std::vector<uint8_t> & val)951 status_t Parcel::writeByteVector(const std::vector<uint8_t>& val) { return writeData(val); }
writeByteVector(const std::optional<std::vector<uint8_t>> & val)952 status_t Parcel::writeByteVector(const std::optional<std::vector<uint8_t>>& val) { return writeData(val); }
writeByteVector(const std::unique_ptr<std::vector<uint8_t>> & val)953 status_t Parcel::writeByteVector(const std::unique_ptr<std::vector<uint8_t>>& val){ return writeData(val); }
writeInt32Vector(const std::vector<int32_t> & val)954 status_t Parcel::writeInt32Vector(const std::vector<int32_t>& val) { return writeData(val); }
writeInt32Vector(const std::optional<std::vector<int32_t>> & val)955 status_t Parcel::writeInt32Vector(const std::optional<std::vector<int32_t>>& val) { return writeData(val); }
writeInt32Vector(const std::unique_ptr<std::vector<int32_t>> & val)956 status_t Parcel::writeInt32Vector(const std::unique_ptr<std::vector<int32_t>>& val) { return writeData(val); }
writeInt64Vector(const std::vector<int64_t> & val)957 status_t Parcel::writeInt64Vector(const std::vector<int64_t>& val) { return writeData(val); }
writeInt64Vector(const std::optional<std::vector<int64_t>> & val)958 status_t Parcel::writeInt64Vector(const std::optional<std::vector<int64_t>>& val) { return writeData(val); }
writeInt64Vector(const std::unique_ptr<std::vector<int64_t>> & val)959 status_t Parcel::writeInt64Vector(const std::unique_ptr<std::vector<int64_t>>& val) { return writeData(val); }
writeUint64Vector(const std::vector<uint64_t> & val)960 status_t Parcel::writeUint64Vector(const std::vector<uint64_t>& val) { return writeData(val); }
writeUint64Vector(const std::optional<std::vector<uint64_t>> & val)961 status_t Parcel::writeUint64Vector(const std::optional<std::vector<uint64_t>>& val) { return writeData(val); }
writeUint64Vector(const std::unique_ptr<std::vector<uint64_t>> & val)962 status_t Parcel::writeUint64Vector(const std::unique_ptr<std::vector<uint64_t>>& val) { return writeData(val); }
writeFloatVector(const std::vector<float> & val)963 status_t Parcel::writeFloatVector(const std::vector<float>& val) { return writeData(val); }
writeFloatVector(const std::optional<std::vector<float>> & val)964 status_t Parcel::writeFloatVector(const std::optional<std::vector<float>>& val) { return writeData(val); }
writeFloatVector(const std::unique_ptr<std::vector<float>> & val)965 status_t Parcel::writeFloatVector(const std::unique_ptr<std::vector<float>>& val) { return writeData(val); }
writeDoubleVector(const std::vector<double> & val)966 status_t Parcel::writeDoubleVector(const std::vector<double>& val) { return writeData(val); }
writeDoubleVector(const std::optional<std::vector<double>> & val)967 status_t Parcel::writeDoubleVector(const std::optional<std::vector<double>>& val) { return writeData(val); }
writeDoubleVector(const std::unique_ptr<std::vector<double>> & val)968 status_t Parcel::writeDoubleVector(const std::unique_ptr<std::vector<double>>& val) { return writeData(val); }
writeBoolVector(const std::vector<bool> & val)969 status_t Parcel::writeBoolVector(const std::vector<bool>& val) { return writeData(val); }
writeBoolVector(const std::optional<std::vector<bool>> & val)970 status_t Parcel::writeBoolVector(const std::optional<std::vector<bool>>& val) { return writeData(val); }
writeBoolVector(const std::unique_ptr<std::vector<bool>> & val)971 status_t Parcel::writeBoolVector(const std::unique_ptr<std::vector<bool>>& val) { return writeData(val); }
writeCharVector(const std::vector<char16_t> & val)972 status_t Parcel::writeCharVector(const std::vector<char16_t>& val) { return writeData(val); }
writeCharVector(const std::optional<std::vector<char16_t>> & val)973 status_t Parcel::writeCharVector(const std::optional<std::vector<char16_t>>& val) { return writeData(val); }
writeCharVector(const std::unique_ptr<std::vector<char16_t>> & val)974 status_t Parcel::writeCharVector(const std::unique_ptr<std::vector<char16_t>>& val) { return writeData(val); }
975
writeString16Vector(const std::vector<String16> & val)976 status_t Parcel::writeString16Vector(const std::vector<String16>& val) { return writeData(val); }
writeString16Vector(const std::optional<std::vector<std::optional<String16>>> & val)977 status_t Parcel::writeString16Vector(
978 const std::optional<std::vector<std::optional<String16>>>& val) { return writeData(val); }
writeString16Vector(const std::unique_ptr<std::vector<std::unique_ptr<String16>>> & val)979 status_t Parcel::writeString16Vector(
980 const std::unique_ptr<std::vector<std::unique_ptr<String16>>>& val) { return writeData(val); }
writeUtf8VectorAsUtf16Vector(const std::optional<std::vector<std::optional<std::string>>> & val)981 status_t Parcel::writeUtf8VectorAsUtf16Vector(
982 const std::optional<std::vector<std::optional<std::string>>>& val) { return writeData(val); }
writeUtf8VectorAsUtf16Vector(const std::unique_ptr<std::vector<std::unique_ptr<std::string>>> & val)983 status_t Parcel::writeUtf8VectorAsUtf16Vector(
984 const std::unique_ptr<std::vector<std::unique_ptr<std::string>>>& val) { return writeData(val); }
writeUtf8VectorAsUtf16Vector(const std::vector<std::string> & val)985 status_t Parcel::writeUtf8VectorAsUtf16Vector(const std::vector<std::string>& val) { return writeData(val); }
986
writeUniqueFileDescriptorVector(const std::vector<base::unique_fd> & val)987 status_t Parcel::writeUniqueFileDescriptorVector(const std::vector<base::unique_fd>& val) { return writeData(val); }
writeUniqueFileDescriptorVector(const std::optional<std::vector<base::unique_fd>> & val)988 status_t Parcel::writeUniqueFileDescriptorVector(const std::optional<std::vector<base::unique_fd>>& val) { return writeData(val); }
writeUniqueFileDescriptorVector(const std::unique_ptr<std::vector<base::unique_fd>> & val)989 status_t Parcel::writeUniqueFileDescriptorVector(const std::unique_ptr<std::vector<base::unique_fd>>& val) { return writeData(val); }
990
writeStrongBinderVector(const std::vector<sp<IBinder>> & val)991 status_t Parcel::writeStrongBinderVector(const std::vector<sp<IBinder>>& val) { return writeData(val); }
writeStrongBinderVector(const std::optional<std::vector<sp<IBinder>>> & val)992 status_t Parcel::writeStrongBinderVector(const std::optional<std::vector<sp<IBinder>>>& val) { return writeData(val); }
writeStrongBinderVector(const std::unique_ptr<std::vector<sp<IBinder>>> & val)993 status_t Parcel::writeStrongBinderVector(const std::unique_ptr<std::vector<sp<IBinder>>>& val) { return writeData(val); }
994
writeParcelable(const Parcelable & parcelable)995 status_t Parcel::writeParcelable(const Parcelable& parcelable) { return writeData(parcelable); }
996
readUtf8FromUtf16(std::optional<std::string> * str) const997 status_t Parcel::readUtf8FromUtf16(std::optional<std::string>* str) const { return readData(str); }
readUtf8FromUtf16(std::unique_ptr<std::string> * str) const998 status_t Parcel::readUtf8FromUtf16(std::unique_ptr<std::string>* str) const { return readData(str); }
999
readString16(std::optional<String16> * pArg) const1000 status_t Parcel::readString16(std::optional<String16>* pArg) const { return readData(pArg); }
readString16(std::unique_ptr<String16> * pArg) const1001 status_t Parcel::readString16(std::unique_ptr<String16>* pArg) const { return readData(pArg); }
1002
readByteVector(std::vector<int8_t> * val) const1003 status_t Parcel::readByteVector(std::vector<int8_t>* val) const { return readData(val); }
readByteVector(std::vector<uint8_t> * val) const1004 status_t Parcel::readByteVector(std::vector<uint8_t>* val) const { return readData(val); }
readByteVector(std::optional<std::vector<int8_t>> * val) const1005 status_t Parcel::readByteVector(std::optional<std::vector<int8_t>>* val) const { return readData(val); }
readByteVector(std::unique_ptr<std::vector<int8_t>> * val) const1006 status_t Parcel::readByteVector(std::unique_ptr<std::vector<int8_t>>* val) const { return readData(val); }
readByteVector(std::optional<std::vector<uint8_t>> * val) const1007 status_t Parcel::readByteVector(std::optional<std::vector<uint8_t>>* val) const { return readData(val); }
readByteVector(std::unique_ptr<std::vector<uint8_t>> * val) const1008 status_t Parcel::readByteVector(std::unique_ptr<std::vector<uint8_t>>* val) const { return readData(val); }
readInt32Vector(std::optional<std::vector<int32_t>> * val) const1009 status_t Parcel::readInt32Vector(std::optional<std::vector<int32_t>>* val) const { return readData(val); }
readInt32Vector(std::unique_ptr<std::vector<int32_t>> * val) const1010 status_t Parcel::readInt32Vector(std::unique_ptr<std::vector<int32_t>>* val) const { return readData(val); }
readInt32Vector(std::vector<int32_t> * val) const1011 status_t Parcel::readInt32Vector(std::vector<int32_t>* val) const { return readData(val); }
readInt64Vector(std::optional<std::vector<int64_t>> * val) const1012 status_t Parcel::readInt64Vector(std::optional<std::vector<int64_t>>* val) const { return readData(val); }
readInt64Vector(std::unique_ptr<std::vector<int64_t>> * val) const1013 status_t Parcel::readInt64Vector(std::unique_ptr<std::vector<int64_t>>* val) const { return readData(val); }
readInt64Vector(std::vector<int64_t> * val) const1014 status_t Parcel::readInt64Vector(std::vector<int64_t>* val) const { return readData(val); }
readUint64Vector(std::optional<std::vector<uint64_t>> * val) const1015 status_t Parcel::readUint64Vector(std::optional<std::vector<uint64_t>>* val) const { return readData(val); }
readUint64Vector(std::unique_ptr<std::vector<uint64_t>> * val) const1016 status_t Parcel::readUint64Vector(std::unique_ptr<std::vector<uint64_t>>* val) const { return readData(val); }
readUint64Vector(std::vector<uint64_t> * val) const1017 status_t Parcel::readUint64Vector(std::vector<uint64_t>* val) const { return readData(val); }
readFloatVector(std::optional<std::vector<float>> * val) const1018 status_t Parcel::readFloatVector(std::optional<std::vector<float>>* val) const { return readData(val); }
readFloatVector(std::unique_ptr<std::vector<float>> * val) const1019 status_t Parcel::readFloatVector(std::unique_ptr<std::vector<float>>* val) const { return readData(val); }
readFloatVector(std::vector<float> * val) const1020 status_t Parcel::readFloatVector(std::vector<float>* val) const { return readData(val); }
readDoubleVector(std::optional<std::vector<double>> * val) const1021 status_t Parcel::readDoubleVector(std::optional<std::vector<double>>* val) const { return readData(val); }
readDoubleVector(std::unique_ptr<std::vector<double>> * val) const1022 status_t Parcel::readDoubleVector(std::unique_ptr<std::vector<double>>* val) const { return readData(val); }
readDoubleVector(std::vector<double> * val) const1023 status_t Parcel::readDoubleVector(std::vector<double>* val) const { return readData(val); }
readBoolVector(std::optional<std::vector<bool>> * val) const1024 status_t Parcel::readBoolVector(std::optional<std::vector<bool>>* val) const { return readData(val); }
readBoolVector(std::unique_ptr<std::vector<bool>> * val) const1025 status_t Parcel::readBoolVector(std::unique_ptr<std::vector<bool>>* val) const { return readData(val); }
readBoolVector(std::vector<bool> * val) const1026 status_t Parcel::readBoolVector(std::vector<bool>* val) const { return readData(val); }
readCharVector(std::optional<std::vector<char16_t>> * val) const1027 status_t Parcel::readCharVector(std::optional<std::vector<char16_t>>* val) const { return readData(val); }
readCharVector(std::unique_ptr<std::vector<char16_t>> * val) const1028 status_t Parcel::readCharVector(std::unique_ptr<std::vector<char16_t>>* val) const { return readData(val); }
readCharVector(std::vector<char16_t> * val) const1029 status_t Parcel::readCharVector(std::vector<char16_t>* val) const { return readData(val); }
1030
readString16Vector(std::optional<std::vector<std::optional<String16>>> * val) const1031 status_t Parcel::readString16Vector(
1032 std::optional<std::vector<std::optional<String16>>>* val) const { return readData(val); }
readString16Vector(std::unique_ptr<std::vector<std::unique_ptr<String16>>> * val) const1033 status_t Parcel::readString16Vector(
1034 std::unique_ptr<std::vector<std::unique_ptr<String16>>>* val) const { return readData(val); }
readString16Vector(std::vector<String16> * val) const1035 status_t Parcel::readString16Vector(std::vector<String16>* val) const { return readData(val); }
readUtf8VectorFromUtf16Vector(std::optional<std::vector<std::optional<std::string>>> * val) const1036 status_t Parcel::readUtf8VectorFromUtf16Vector(
1037 std::optional<std::vector<std::optional<std::string>>>* val) const { return readData(val); }
readUtf8VectorFromUtf16Vector(std::unique_ptr<std::vector<std::unique_ptr<std::string>>> * val) const1038 status_t Parcel::readUtf8VectorFromUtf16Vector(
1039 std::unique_ptr<std::vector<std::unique_ptr<std::string>>>* val) const { return readData(val); }
readUtf8VectorFromUtf16Vector(std::vector<std::string> * val) const1040 status_t Parcel::readUtf8VectorFromUtf16Vector(std::vector<std::string>* val) const { return readData(val); }
1041
readUniqueFileDescriptorVector(std::optional<std::vector<base::unique_fd>> * val) const1042 status_t Parcel::readUniqueFileDescriptorVector(std::optional<std::vector<base::unique_fd>>* val) const { return readData(val); }
readUniqueFileDescriptorVector(std::unique_ptr<std::vector<base::unique_fd>> * val) const1043 status_t Parcel::readUniqueFileDescriptorVector(std::unique_ptr<std::vector<base::unique_fd>>* val) const { return readData(val); }
readUniqueFileDescriptorVector(std::vector<base::unique_fd> * val) const1044 status_t Parcel::readUniqueFileDescriptorVector(std::vector<base::unique_fd>* val) const { return readData(val); }
1045
readStrongBinderVector(std::optional<std::vector<sp<IBinder>>> * val) const1046 status_t Parcel::readStrongBinderVector(std::optional<std::vector<sp<IBinder>>>* val) const { return readData(val); }
readStrongBinderVector(std::unique_ptr<std::vector<sp<IBinder>>> * val) const1047 status_t Parcel::readStrongBinderVector(std::unique_ptr<std::vector<sp<IBinder>>>* val) const { return readData(val); }
readStrongBinderVector(std::vector<sp<IBinder>> * val) const1048 status_t Parcel::readStrongBinderVector(std::vector<sp<IBinder>>* val) const { return readData(val); }
1049
readParcelable(Parcelable * parcelable) const1050 status_t Parcel::readParcelable(Parcelable* parcelable) const { return readData(parcelable); }
1051
writeInt32(int32_t val)1052 status_t Parcel::writeInt32(int32_t val)
1053 {
1054 return writeAligned(val);
1055 }
1056
writeUint32(uint32_t val)1057 status_t Parcel::writeUint32(uint32_t val)
1058 {
1059 return writeAligned(val);
1060 }
1061
writeInt32Array(size_t len,const int32_t * val)1062 status_t Parcel::writeInt32Array(size_t len, const int32_t *val) {
1063 if (len > INT32_MAX) {
1064 // don't accept size_t values which may have come from an
1065 // inadvertent conversion from a negative int.
1066 return BAD_VALUE;
1067 }
1068
1069 if (!val) {
1070 return writeInt32(-1);
1071 }
1072 status_t ret = writeInt32(static_cast<uint32_t>(len));
1073 if (ret == NO_ERROR) {
1074 ret = write(val, len * sizeof(*val));
1075 }
1076 return ret;
1077 }
writeByteArray(size_t len,const uint8_t * val)1078 status_t Parcel::writeByteArray(size_t len, const uint8_t *val) {
1079 if (len > INT32_MAX) {
1080 // don't accept size_t values which may have come from an
1081 // inadvertent conversion from a negative int.
1082 return BAD_VALUE;
1083 }
1084
1085 if (!val) {
1086 return writeInt32(-1);
1087 }
1088 status_t ret = writeInt32(static_cast<uint32_t>(len));
1089 if (ret == NO_ERROR) {
1090 ret = write(val, len * sizeof(*val));
1091 }
1092 return ret;
1093 }
1094
writeBool(bool val)1095 status_t Parcel::writeBool(bool val)
1096 {
1097 return writeInt32(int32_t(val));
1098 }
1099
writeChar(char16_t val)1100 status_t Parcel::writeChar(char16_t val)
1101 {
1102 return writeInt32(int32_t(val));
1103 }
1104
writeByte(int8_t val)1105 status_t Parcel::writeByte(int8_t val)
1106 {
1107 return writeInt32(int32_t(val));
1108 }
1109
writeInt64(int64_t val)1110 status_t Parcel::writeInt64(int64_t val)
1111 {
1112 return writeAligned(val);
1113 }
1114
writeUint64(uint64_t val)1115 status_t Parcel::writeUint64(uint64_t val)
1116 {
1117 return writeAligned(val);
1118 }
1119
writePointer(uintptr_t val)1120 status_t Parcel::writePointer(uintptr_t val)
1121 {
1122 return writeAligned<binder_uintptr_t>(val);
1123 }
1124
writeFloat(float val)1125 status_t Parcel::writeFloat(float val)
1126 {
1127 return writeAligned(val);
1128 }
1129
1130 #if defined(__mips__) && defined(__mips_hard_float)
1131
writeDouble(double val)1132 status_t Parcel::writeDouble(double val)
1133 {
1134 union {
1135 double d;
1136 unsigned long long ll;
1137 } u;
1138 u.d = val;
1139 return writeAligned(u.ll);
1140 }
1141
1142 #else
1143
writeDouble(double val)1144 status_t Parcel::writeDouble(double val)
1145 {
1146 return writeAligned(val);
1147 }
1148
1149 #endif
1150
writeCString(const char * str)1151 status_t Parcel::writeCString(const char* str)
1152 {
1153 return write(str, strlen(str)+1);
1154 }
1155
writeString8(const String8 & str)1156 status_t Parcel::writeString8(const String8& str)
1157 {
1158 return writeString8(str.string(), str.size());
1159 }
1160
writeString8(const char * str,size_t len)1161 status_t Parcel::writeString8(const char* str, size_t len)
1162 {
1163 if (str == nullptr) return writeInt32(-1);
1164
1165 // NOTE: Keep this logic in sync with android_os_Parcel.cpp
1166 status_t err = writeInt32(len);
1167 if (err == NO_ERROR) {
1168 uint8_t* data = (uint8_t*)writeInplace(len+sizeof(char));
1169 if (data) {
1170 memcpy(data, str, len);
1171 *reinterpret_cast<char*>(data+len) = 0;
1172 return NO_ERROR;
1173 }
1174 err = mError;
1175 }
1176 return err;
1177 }
1178
writeString16(const String16 & str)1179 status_t Parcel::writeString16(const String16& str)
1180 {
1181 return writeString16(str.string(), str.size());
1182 }
1183
writeString16(const char16_t * str,size_t len)1184 status_t Parcel::writeString16(const char16_t* str, size_t len)
1185 {
1186 if (str == nullptr) return writeInt32(-1);
1187
1188 // NOTE: Keep this logic in sync with android_os_Parcel.cpp
1189 status_t err = writeInt32(len);
1190 if (err == NO_ERROR) {
1191 len *= sizeof(char16_t);
1192 uint8_t* data = (uint8_t*)writeInplace(len+sizeof(char16_t));
1193 if (data) {
1194 memcpy(data, str, len);
1195 *reinterpret_cast<char16_t*>(data+len) = 0;
1196 return NO_ERROR;
1197 }
1198 err = mError;
1199 }
1200 return err;
1201 }
1202
writeStrongBinder(const sp<IBinder> & val)1203 status_t Parcel::writeStrongBinder(const sp<IBinder>& val)
1204 {
1205 return flattenBinder(val);
1206 }
1207
1208
writeRawNullableParcelable(const Parcelable * parcelable)1209 status_t Parcel::writeRawNullableParcelable(const Parcelable* parcelable) {
1210 if (!parcelable) {
1211 return writeInt32(0);
1212 }
1213
1214 return writeParcelable(*parcelable);
1215 }
1216
writeNativeHandle(const native_handle * handle)1217 status_t Parcel::writeNativeHandle(const native_handle* handle)
1218 {
1219 if (!handle || handle->version != sizeof(native_handle))
1220 return BAD_TYPE;
1221
1222 status_t err;
1223 err = writeInt32(handle->numFds);
1224 if (err != NO_ERROR) return err;
1225
1226 err = writeInt32(handle->numInts);
1227 if (err != NO_ERROR) return err;
1228
1229 for (int i=0 ; err==NO_ERROR && i<handle->numFds ; i++)
1230 err = writeDupFileDescriptor(handle->data[i]);
1231
1232 if (err != NO_ERROR) {
1233 ALOGD("write native handle, write dup fd failed");
1234 return err;
1235 }
1236 err = write(handle->data + handle->numFds, sizeof(int)*handle->numInts);
1237 return err;
1238 }
1239
writeFileDescriptor(int fd,bool takeOwnership)1240 status_t Parcel::writeFileDescriptor(int fd, bool takeOwnership)
1241 {
1242 if (isForRpc()) {
1243 ALOGE("Cannot write file descriptor to remote binder.");
1244 return BAD_TYPE;
1245 }
1246
1247 flat_binder_object obj;
1248 obj.hdr.type = BINDER_TYPE_FD;
1249 obj.flags = 0x7f | FLAT_BINDER_FLAG_ACCEPTS_FDS;
1250 obj.binder = 0; /* Don't pass uninitialized stack data to a remote process */
1251 obj.handle = fd;
1252 obj.cookie = takeOwnership ? 1 : 0;
1253 return writeObject(obj, true);
1254 }
1255
writeDupFileDescriptor(int fd)1256 status_t Parcel::writeDupFileDescriptor(int fd)
1257 {
1258 int dupFd = fcntl(fd, F_DUPFD_CLOEXEC, 0);
1259 if (dupFd < 0) {
1260 return -errno;
1261 }
1262 status_t err = writeFileDescriptor(dupFd, true /*takeOwnership*/);
1263 if (err != OK) {
1264 close(dupFd);
1265 }
1266 return err;
1267 }
1268
writeParcelFileDescriptor(int fd,bool takeOwnership)1269 status_t Parcel::writeParcelFileDescriptor(int fd, bool takeOwnership)
1270 {
1271 writeInt32(0);
1272 return writeFileDescriptor(fd, takeOwnership);
1273 }
1274
writeDupParcelFileDescriptor(int fd)1275 status_t Parcel::writeDupParcelFileDescriptor(int fd)
1276 {
1277 int dupFd = fcntl(fd, F_DUPFD_CLOEXEC, 0);
1278 if (dupFd < 0) {
1279 return -errno;
1280 }
1281 status_t err = writeParcelFileDescriptor(dupFd, true /*takeOwnership*/);
1282 if (err != OK) {
1283 close(dupFd);
1284 }
1285 return err;
1286 }
1287
writeUniqueFileDescriptor(const base::unique_fd & fd)1288 status_t Parcel::writeUniqueFileDescriptor(const base::unique_fd& fd) {
1289 return writeDupFileDescriptor(fd.get());
1290 }
1291
writeBlob(size_t len,bool mutableCopy,WritableBlob * outBlob)1292 status_t Parcel::writeBlob(size_t len, bool mutableCopy, WritableBlob* outBlob)
1293 {
1294 if (len > INT32_MAX) {
1295 // don't accept size_t values which may have come from an
1296 // inadvertent conversion from a negative int.
1297 return BAD_VALUE;
1298 }
1299
1300 status_t status;
1301 if (!mAllowFds || len <= BLOB_INPLACE_LIMIT) {
1302 ALOGV("writeBlob: write in place");
1303 status = writeInt32(BLOB_INPLACE);
1304 if (status) return status;
1305
1306 void* ptr = writeInplace(len);
1307 if (!ptr) return NO_MEMORY;
1308
1309 outBlob->init(-1, ptr, len, false);
1310 return NO_ERROR;
1311 }
1312
1313 ALOGV("writeBlob: write to ashmem");
1314 int fd = ashmem_create_region("Parcel Blob", len);
1315 if (fd < 0) return NO_MEMORY;
1316
1317 int result = ashmem_set_prot_region(fd, PROT_READ | PROT_WRITE);
1318 if (result < 0) {
1319 status = result;
1320 } else {
1321 void* ptr = ::mmap(nullptr, len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
1322 if (ptr == MAP_FAILED) {
1323 status = -errno;
1324 } else {
1325 if (!mutableCopy) {
1326 result = ashmem_set_prot_region(fd, PROT_READ);
1327 }
1328 if (result < 0) {
1329 status = result;
1330 } else {
1331 status = writeInt32(mutableCopy ? BLOB_ASHMEM_MUTABLE : BLOB_ASHMEM_IMMUTABLE);
1332 if (!status) {
1333 status = writeFileDescriptor(fd, true /*takeOwnership*/);
1334 if (!status) {
1335 outBlob->init(fd, ptr, len, mutableCopy);
1336 return NO_ERROR;
1337 }
1338 }
1339 }
1340 }
1341 ::munmap(ptr, len);
1342 }
1343 ::close(fd);
1344 return status;
1345 }
1346
writeDupImmutableBlobFileDescriptor(int fd)1347 status_t Parcel::writeDupImmutableBlobFileDescriptor(int fd)
1348 {
1349 // Must match up with what's done in writeBlob.
1350 if (!mAllowFds) return FDS_NOT_ALLOWED;
1351 status_t status = writeInt32(BLOB_ASHMEM_IMMUTABLE);
1352 if (status) return status;
1353 return writeDupFileDescriptor(fd);
1354 }
1355
write(const FlattenableHelperInterface & val)1356 status_t Parcel::write(const FlattenableHelperInterface& val)
1357 {
1358 status_t err;
1359
1360 // size if needed
1361 const size_t len = val.getFlattenedSize();
1362 const size_t fd_count = val.getFdCount();
1363
1364 if ((len > INT32_MAX) || (fd_count >= gMaxFds)) {
1365 // don't accept size_t values which may have come from an
1366 // inadvertent conversion from a negative int.
1367 return BAD_VALUE;
1368 }
1369
1370 err = this->writeInt32(len);
1371 if (err) return err;
1372
1373 err = this->writeInt32(fd_count);
1374 if (err) return err;
1375
1376 // payload
1377 void* const buf = this->writeInplace(len);
1378 if (buf == nullptr)
1379 return BAD_VALUE;
1380
1381 int* fds = nullptr;
1382 if (fd_count) {
1383 fds = new (std::nothrow) int[fd_count];
1384 if (fds == nullptr) {
1385 ALOGE("write: failed to allocate requested %zu fds", fd_count);
1386 return BAD_VALUE;
1387 }
1388 }
1389
1390 err = val.flatten(buf, len, fds, fd_count);
1391 for (size_t i=0 ; i<fd_count && err==NO_ERROR ; i++) {
1392 err = this->writeDupFileDescriptor( fds[i] );
1393 }
1394
1395 if (fd_count) {
1396 delete [] fds;
1397 }
1398
1399 return err;
1400 }
1401
writeObject(const flat_binder_object & val,bool nullMetaData)1402 status_t Parcel::writeObject(const flat_binder_object& val, bool nullMetaData)
1403 {
1404 const bool enoughData = (mDataPos+sizeof(val)) <= mDataCapacity;
1405 const bool enoughObjects = mObjectsSize < mObjectsCapacity;
1406 if (enoughData && enoughObjects) {
1407 restart_write:
1408 *reinterpret_cast<flat_binder_object*>(mData+mDataPos) = val;
1409
1410 // remember if it's a file descriptor
1411 if (val.hdr.type == BINDER_TYPE_FD) {
1412 if (!mAllowFds) {
1413 // fail before modifying our object index
1414 return FDS_NOT_ALLOWED;
1415 }
1416 mHasFds = mFdsKnown = true;
1417 }
1418
1419 // Need to write meta-data?
1420 if (nullMetaData || val.binder != 0) {
1421 mObjects[mObjectsSize] = mDataPos;
1422 acquire_object(ProcessState::self(), val, this);
1423 mObjectsSize++;
1424 }
1425
1426 return finishWrite(sizeof(flat_binder_object));
1427 }
1428
1429 if (!enoughData) {
1430 const status_t err = growData(sizeof(val));
1431 if (err != NO_ERROR) return err;
1432 }
1433 if (!enoughObjects) {
1434 if (mObjectsSize > SIZE_MAX - 2) return NO_MEMORY; // overflow
1435 if ((mObjectsSize + 2) > SIZE_MAX / 3) return NO_MEMORY; // overflow
1436 size_t newSize = ((mObjectsSize+2)*3)/2;
1437 if (newSize > SIZE_MAX / sizeof(binder_size_t)) return NO_MEMORY; // overflow
1438 binder_size_t* objects = (binder_size_t*)realloc(mObjects, newSize*sizeof(binder_size_t));
1439 if (objects == nullptr) return NO_MEMORY;
1440 mObjects = objects;
1441 mObjectsCapacity = newSize;
1442 }
1443
1444 goto restart_write;
1445 }
1446
writeNoException()1447 status_t Parcel::writeNoException()
1448 {
1449 binder::Status status;
1450 return status.writeToParcel(this);
1451 }
1452
validateReadData(size_t upperBound) const1453 status_t Parcel::validateReadData(size_t upperBound) const
1454 {
1455 // Don't allow non-object reads on object data
1456 if (mObjectsSorted || mObjectsSize <= 1) {
1457 data_sorted:
1458 // Expect to check only against the next object
1459 if (mNextObjectHint < mObjectsSize && upperBound > mObjects[mNextObjectHint]) {
1460 // For some reason the current read position is greater than the next object
1461 // hint. Iterate until we find the right object
1462 size_t nextObject = mNextObjectHint;
1463 do {
1464 if (mDataPos < mObjects[nextObject] + sizeof(flat_binder_object)) {
1465 // Requested info overlaps with an object
1466 ALOGE("Attempt to read from protected data in Parcel %p", this);
1467 return PERMISSION_DENIED;
1468 }
1469 nextObject++;
1470 } while (nextObject < mObjectsSize && upperBound > mObjects[nextObject]);
1471 mNextObjectHint = nextObject;
1472 }
1473 return NO_ERROR;
1474 }
1475 // Quickly determine if mObjects is sorted.
1476 binder_size_t* currObj = mObjects + mObjectsSize - 1;
1477 binder_size_t* prevObj = currObj;
1478 while (currObj > mObjects) {
1479 prevObj--;
1480 if(*prevObj > *currObj) {
1481 goto data_unsorted;
1482 }
1483 currObj--;
1484 }
1485 mObjectsSorted = true;
1486 goto data_sorted;
1487
1488 data_unsorted:
1489 // Insertion Sort mObjects
1490 // Great for mostly sorted lists. If randomly sorted or reverse ordered mObjects become common,
1491 // switch to std::sort(mObjects, mObjects + mObjectsSize);
1492 for (binder_size_t* iter0 = mObjects + 1; iter0 < mObjects + mObjectsSize; iter0++) {
1493 binder_size_t temp = *iter0;
1494 binder_size_t* iter1 = iter0 - 1;
1495 while (iter1 >= mObjects && *iter1 > temp) {
1496 *(iter1 + 1) = *iter1;
1497 iter1--;
1498 }
1499 *(iter1 + 1) = temp;
1500 }
1501 mNextObjectHint = 0;
1502 mObjectsSorted = true;
1503 goto data_sorted;
1504 }
1505
read(void * outData,size_t len) const1506 status_t Parcel::read(void* outData, size_t len) const
1507 {
1508 if (len > INT32_MAX) {
1509 // don't accept size_t values which may have come from an
1510 // inadvertent conversion from a negative int.
1511 return BAD_VALUE;
1512 }
1513
1514 if ((mDataPos+pad_size(len)) >= mDataPos && (mDataPos+pad_size(len)) <= mDataSize
1515 && len <= pad_size(len)) {
1516 if (mObjectsSize > 0) {
1517 status_t err = validateReadData(mDataPos + pad_size(len));
1518 if(err != NO_ERROR) {
1519 // Still increment the data position by the expected length
1520 mDataPos += pad_size(len);
1521 ALOGV("read Setting data pos of %p to %zu", this, mDataPos);
1522 return err;
1523 }
1524 }
1525 memcpy(outData, mData+mDataPos, len);
1526 mDataPos += pad_size(len);
1527 ALOGV("read Setting data pos of %p to %zu", this, mDataPos);
1528 return NO_ERROR;
1529 }
1530 return NOT_ENOUGH_DATA;
1531 }
1532
readInplace(size_t len) const1533 const void* Parcel::readInplace(size_t len) const
1534 {
1535 if (len > INT32_MAX) {
1536 // don't accept size_t values which may have come from an
1537 // inadvertent conversion from a negative int.
1538 return nullptr;
1539 }
1540
1541 if ((mDataPos+pad_size(len)) >= mDataPos && (mDataPos+pad_size(len)) <= mDataSize
1542 && len <= pad_size(len)) {
1543 if (mObjectsSize > 0) {
1544 status_t err = validateReadData(mDataPos + pad_size(len));
1545 if(err != NO_ERROR) {
1546 // Still increment the data position by the expected length
1547 mDataPos += pad_size(len);
1548 ALOGV("readInplace Setting data pos of %p to %zu", this, mDataPos);
1549 return nullptr;
1550 }
1551 }
1552
1553 const void* data = mData+mDataPos;
1554 mDataPos += pad_size(len);
1555 ALOGV("readInplace Setting data pos of %p to %zu", this, mDataPos);
1556 return data;
1557 }
1558 return nullptr;
1559 }
1560
readOutVectorSizeWithCheck(size_t elmSize,int32_t * size) const1561 status_t Parcel::readOutVectorSizeWithCheck(size_t elmSize, int32_t* size) const {
1562 if (status_t status = readInt32(size); status != OK) return status;
1563 if (*size < 0) return OK; // may be null, client to handle
1564
1565 LOG_ALWAYS_FATAL_IF(elmSize > INT32_MAX, "Cannot have element as big as %zu", elmSize);
1566
1567 // approximation, can't know max element size (e.g. if it makes heap
1568 // allocations)
1569 static_assert(sizeof(int) == sizeof(int32_t), "Android is LP64");
1570 int32_t allocationSize;
1571 if (__builtin_smul_overflow(elmSize, *size, &allocationSize)) return NO_MEMORY;
1572
1573 // High limit of 1MB since something this big could never be returned. Could
1574 // probably scope this down, but might impact very specific usecases.
1575 constexpr int32_t kMaxAllocationSize = 1 * 1000 * 1000;
1576
1577 if (allocationSize >= kMaxAllocationSize) {
1578 return NO_MEMORY;
1579 }
1580
1581 return OK;
1582 }
1583
1584 template<class T>
readAligned(T * pArg) const1585 status_t Parcel::readAligned(T *pArg) const {
1586 static_assert(PAD_SIZE_UNSAFE(sizeof(T)) == sizeof(T));
1587 static_assert(std::is_trivially_copyable_v<T>);
1588
1589 if ((mDataPos+sizeof(T)) <= mDataSize) {
1590 if (mObjectsSize > 0) {
1591 status_t err = validateReadData(mDataPos + sizeof(T));
1592 if(err != NO_ERROR) {
1593 // Still increment the data position by the expected length
1594 mDataPos += sizeof(T);
1595 return err;
1596 }
1597 }
1598
1599 memcpy(pArg, mData + mDataPos, sizeof(T));
1600 mDataPos += sizeof(T);
1601 return NO_ERROR;
1602 } else {
1603 return NOT_ENOUGH_DATA;
1604 }
1605 }
1606
1607 template<class T>
readAligned() const1608 T Parcel::readAligned() const {
1609 T result;
1610 if (readAligned(&result) != NO_ERROR) {
1611 result = 0;
1612 }
1613
1614 return result;
1615 }
1616
1617 template<class T>
writeAligned(T val)1618 status_t Parcel::writeAligned(T val) {
1619 static_assert(PAD_SIZE_UNSAFE(sizeof(T)) == sizeof(T));
1620 static_assert(std::is_trivially_copyable_v<T>);
1621
1622 if ((mDataPos+sizeof(val)) <= mDataCapacity) {
1623 restart_write:
1624 memcpy(mData + mDataPos, &val, sizeof(val));
1625 return finishWrite(sizeof(val));
1626 }
1627
1628 status_t err = growData(sizeof(val));
1629 if (err == NO_ERROR) goto restart_write;
1630 return err;
1631 }
1632
readInt32(int32_t * pArg) const1633 status_t Parcel::readInt32(int32_t *pArg) const
1634 {
1635 return readAligned(pArg);
1636 }
1637
readInt32() const1638 int32_t Parcel::readInt32() const
1639 {
1640 return readAligned<int32_t>();
1641 }
1642
readUint32(uint32_t * pArg) const1643 status_t Parcel::readUint32(uint32_t *pArg) const
1644 {
1645 return readAligned(pArg);
1646 }
1647
readUint32() const1648 uint32_t Parcel::readUint32() const
1649 {
1650 return readAligned<uint32_t>();
1651 }
1652
readInt64(int64_t * pArg) const1653 status_t Parcel::readInt64(int64_t *pArg) const
1654 {
1655 return readAligned(pArg);
1656 }
1657
1658
readInt64() const1659 int64_t Parcel::readInt64() const
1660 {
1661 return readAligned<int64_t>();
1662 }
1663
readUint64(uint64_t * pArg) const1664 status_t Parcel::readUint64(uint64_t *pArg) const
1665 {
1666 return readAligned(pArg);
1667 }
1668
readUint64() const1669 uint64_t Parcel::readUint64() const
1670 {
1671 return readAligned<uint64_t>();
1672 }
1673
readPointer(uintptr_t * pArg) const1674 status_t Parcel::readPointer(uintptr_t *pArg) const
1675 {
1676 status_t ret;
1677 binder_uintptr_t ptr;
1678 ret = readAligned(&ptr);
1679 if (!ret)
1680 *pArg = ptr;
1681 return ret;
1682 }
1683
readPointer() const1684 uintptr_t Parcel::readPointer() const
1685 {
1686 return readAligned<binder_uintptr_t>();
1687 }
1688
1689
readFloat(float * pArg) const1690 status_t Parcel::readFloat(float *pArg) const
1691 {
1692 return readAligned(pArg);
1693 }
1694
1695
readFloat() const1696 float Parcel::readFloat() const
1697 {
1698 return readAligned<float>();
1699 }
1700
1701 #if defined(__mips__) && defined(__mips_hard_float)
1702
readDouble(double * pArg) const1703 status_t Parcel::readDouble(double *pArg) const
1704 {
1705 union {
1706 double d;
1707 unsigned long long ll;
1708 } u;
1709 u.d = 0;
1710 status_t status;
1711 status = readAligned(&u.ll);
1712 *pArg = u.d;
1713 return status;
1714 }
1715
readDouble() const1716 double Parcel::readDouble() const
1717 {
1718 union {
1719 double d;
1720 unsigned long long ll;
1721 } u;
1722 u.ll = readAligned<unsigned long long>();
1723 return u.d;
1724 }
1725
1726 #else
1727
readDouble(double * pArg) const1728 status_t Parcel::readDouble(double *pArg) const
1729 {
1730 return readAligned(pArg);
1731 }
1732
readDouble() const1733 double Parcel::readDouble() const
1734 {
1735 return readAligned<double>();
1736 }
1737
1738 #endif
1739
readBool(bool * pArg) const1740 status_t Parcel::readBool(bool *pArg) const
1741 {
1742 int32_t tmp = 0;
1743 status_t ret = readInt32(&tmp);
1744 *pArg = (tmp != 0);
1745 return ret;
1746 }
1747
readBool() const1748 bool Parcel::readBool() const
1749 {
1750 return readInt32() != 0;
1751 }
1752
readChar(char16_t * pArg) const1753 status_t Parcel::readChar(char16_t *pArg) const
1754 {
1755 int32_t tmp = 0;
1756 status_t ret = readInt32(&tmp);
1757 *pArg = char16_t(tmp);
1758 return ret;
1759 }
1760
readChar() const1761 char16_t Parcel::readChar() const
1762 {
1763 return char16_t(readInt32());
1764 }
1765
readByte(int8_t * pArg) const1766 status_t Parcel::readByte(int8_t *pArg) const
1767 {
1768 int32_t tmp = 0;
1769 status_t ret = readInt32(&tmp);
1770 *pArg = int8_t(tmp);
1771 return ret;
1772 }
1773
readByte() const1774 int8_t Parcel::readByte() const
1775 {
1776 return int8_t(readInt32());
1777 }
1778
readUtf8FromUtf16(std::string * str) const1779 status_t Parcel::readUtf8FromUtf16(std::string* str) const {
1780 size_t utf16Size = 0;
1781 const char16_t* src = readString16Inplace(&utf16Size);
1782 if (!src) {
1783 return UNEXPECTED_NULL;
1784 }
1785
1786 // Save ourselves the trouble, we're done.
1787 if (utf16Size == 0u) {
1788 str->clear();
1789 return NO_ERROR;
1790 }
1791
1792 // Allow for closing '\0'
1793 ssize_t utf8Size = utf16_to_utf8_length(src, utf16Size) + 1;
1794 if (utf8Size < 1) {
1795 return BAD_VALUE;
1796 }
1797 // Note that while it is probably safe to assume string::resize keeps a
1798 // spare byte around for the trailing null, we still pass the size including the trailing null
1799 str->resize(utf8Size);
1800 utf16_to_utf8(src, utf16Size, &((*str)[0]), utf8Size);
1801 str->resize(utf8Size - 1);
1802 return NO_ERROR;
1803 }
1804
readCString() const1805 const char* Parcel::readCString() const
1806 {
1807 if (mDataPos < mDataSize) {
1808 const size_t avail = mDataSize-mDataPos;
1809 const char* str = reinterpret_cast<const char*>(mData+mDataPos);
1810 // is the string's trailing NUL within the parcel's valid bounds?
1811 const char* eos = reinterpret_cast<const char*>(memchr(str, 0, avail));
1812 if (eos) {
1813 const size_t len = eos - str;
1814 mDataPos += pad_size(len+1);
1815 ALOGV("readCString Setting data pos of %p to %zu", this, mDataPos);
1816 return str;
1817 }
1818 }
1819 return nullptr;
1820 }
1821
readString8() const1822 String8 Parcel::readString8() const
1823 {
1824 size_t len;
1825 const char* str = readString8Inplace(&len);
1826 if (str) return String8(str, len);
1827 ALOGE("Reading a NULL string not supported here.");
1828 return String8();
1829 }
1830
readString8(String8 * pArg) const1831 status_t Parcel::readString8(String8* pArg) const
1832 {
1833 size_t len;
1834 const char* str = readString8Inplace(&len);
1835 if (str) {
1836 pArg->setTo(str, len);
1837 return 0;
1838 } else {
1839 *pArg = String8();
1840 return UNEXPECTED_NULL;
1841 }
1842 }
1843
readString8Inplace(size_t * outLen) const1844 const char* Parcel::readString8Inplace(size_t* outLen) const
1845 {
1846 int32_t size = readInt32();
1847 // watch for potential int overflow from size+1
1848 if (size >= 0 && size < INT32_MAX) {
1849 *outLen = size;
1850 const char* str = (const char*)readInplace(size+1);
1851 if (str != nullptr) {
1852 if (str[size] == '\0') {
1853 return str;
1854 }
1855 android_errorWriteLog(0x534e4554, "172655291");
1856 }
1857 }
1858 *outLen = 0;
1859 return nullptr;
1860 }
1861
readString16() const1862 String16 Parcel::readString16() const
1863 {
1864 size_t len;
1865 const char16_t* str = readString16Inplace(&len);
1866 if (str) return String16(str, len);
1867 ALOGE("Reading a NULL string not supported here.");
1868 return String16();
1869 }
1870
1871
readString16(String16 * pArg) const1872 status_t Parcel::readString16(String16* pArg) const
1873 {
1874 size_t len;
1875 const char16_t* str = readString16Inplace(&len);
1876 if (str) {
1877 pArg->setTo(str, len);
1878 return 0;
1879 } else {
1880 *pArg = String16();
1881 return UNEXPECTED_NULL;
1882 }
1883 }
1884
readString16Inplace(size_t * outLen) const1885 const char16_t* Parcel::readString16Inplace(size_t* outLen) const
1886 {
1887 int32_t size = readInt32();
1888 // watch for potential int overflow from size+1
1889 if (size >= 0 && size < INT32_MAX) {
1890 *outLen = size;
1891 const char16_t* str = (const char16_t*)readInplace((size+1)*sizeof(char16_t));
1892 if (str != nullptr) {
1893 if (str[size] == u'\0') {
1894 return str;
1895 }
1896 android_errorWriteLog(0x534e4554, "172655291");
1897 }
1898 }
1899 *outLen = 0;
1900 return nullptr;
1901 }
1902
readStrongBinder(sp<IBinder> * val) const1903 status_t Parcel::readStrongBinder(sp<IBinder>* val) const
1904 {
1905 status_t status = readNullableStrongBinder(val);
1906 if (status == OK && !val->get()) {
1907 ALOGW("Expecting binder but got null!");
1908 status = UNEXPECTED_NULL;
1909 }
1910 return status;
1911 }
1912
readNullableStrongBinder(sp<IBinder> * val) const1913 status_t Parcel::readNullableStrongBinder(sp<IBinder>* val) const
1914 {
1915 return unflattenBinder(val);
1916 }
1917
readStrongBinder() const1918 sp<IBinder> Parcel::readStrongBinder() const
1919 {
1920 sp<IBinder> val;
1921 // Note that a lot of code in Android reads binders by hand with this
1922 // method, and that code has historically been ok with getting nullptr
1923 // back (while ignoring error codes).
1924 readNullableStrongBinder(&val);
1925 return val;
1926 }
1927
readExceptionCode() const1928 int32_t Parcel::readExceptionCode() const
1929 {
1930 binder::Status status;
1931 status.readFromParcel(*this);
1932 return status.exceptionCode();
1933 }
1934
readNativeHandle() const1935 native_handle* Parcel::readNativeHandle() const
1936 {
1937 int numFds, numInts;
1938 status_t err;
1939 err = readInt32(&numFds);
1940 if (err != NO_ERROR) return nullptr;
1941 err = readInt32(&numInts);
1942 if (err != NO_ERROR) return nullptr;
1943
1944 native_handle* h = native_handle_create(numFds, numInts);
1945 if (!h) {
1946 return nullptr;
1947 }
1948
1949 for (int i=0 ; err==NO_ERROR && i<numFds ; i++) {
1950 h->data[i] = fcntl(readFileDescriptor(), F_DUPFD_CLOEXEC, 0);
1951 if (h->data[i] < 0) {
1952 for (int j = 0; j < i; j++) {
1953 close(h->data[j]);
1954 }
1955 native_handle_delete(h);
1956 return nullptr;
1957 }
1958 }
1959 err = read(h->data + numFds, sizeof(int)*numInts);
1960 if (err != NO_ERROR) {
1961 native_handle_close(h);
1962 native_handle_delete(h);
1963 h = nullptr;
1964 }
1965 return h;
1966 }
1967
readFileDescriptor() const1968 int Parcel::readFileDescriptor() const
1969 {
1970 const flat_binder_object* flat = readObject(true);
1971
1972 if (flat && flat->hdr.type == BINDER_TYPE_FD) {
1973 return flat->handle;
1974 }
1975
1976 return BAD_TYPE;
1977 }
1978
readParcelFileDescriptor() const1979 int Parcel::readParcelFileDescriptor() const
1980 {
1981 int32_t hasComm = readInt32();
1982 int fd = readFileDescriptor();
1983 if (hasComm != 0) {
1984 // detach (owned by the binder driver)
1985 int comm = readFileDescriptor();
1986
1987 // warning: this must be kept in sync with:
1988 // frameworks/base/core/java/android/os/ParcelFileDescriptor.java
1989 enum ParcelFileDescriptorStatus {
1990 DETACHED = 2,
1991 };
1992
1993 #if BYTE_ORDER == BIG_ENDIAN
1994 const int32_t message = ParcelFileDescriptorStatus::DETACHED;
1995 #endif
1996 #if BYTE_ORDER == LITTLE_ENDIAN
1997 const int32_t message = __builtin_bswap32(ParcelFileDescriptorStatus::DETACHED);
1998 #endif
1999
2000 ssize_t written = TEMP_FAILURE_RETRY(
2001 ::write(comm, &message, sizeof(message)));
2002
2003 if (written != sizeof(message)) {
2004 ALOGW("Failed to detach ParcelFileDescriptor written: %zd err: %s",
2005 written, strerror(errno));
2006 return BAD_TYPE;
2007 }
2008 }
2009 return fd;
2010 }
2011
readUniqueFileDescriptor(base::unique_fd * val) const2012 status_t Parcel::readUniqueFileDescriptor(base::unique_fd* val) const
2013 {
2014 int got = readFileDescriptor();
2015
2016 if (got == BAD_TYPE) {
2017 return BAD_TYPE;
2018 }
2019
2020 val->reset(fcntl(got, F_DUPFD_CLOEXEC, 0));
2021
2022 if (val->get() < 0) {
2023 return BAD_VALUE;
2024 }
2025
2026 return OK;
2027 }
2028
readUniqueParcelFileDescriptor(base::unique_fd * val) const2029 status_t Parcel::readUniqueParcelFileDescriptor(base::unique_fd* val) const
2030 {
2031 int got = readParcelFileDescriptor();
2032
2033 if (got == BAD_TYPE) {
2034 return BAD_TYPE;
2035 }
2036
2037 val->reset(fcntl(got, F_DUPFD_CLOEXEC, 0));
2038
2039 if (val->get() < 0) {
2040 return BAD_VALUE;
2041 }
2042
2043 return OK;
2044 }
2045
readBlob(size_t len,ReadableBlob * outBlob) const2046 status_t Parcel::readBlob(size_t len, ReadableBlob* outBlob) const
2047 {
2048 int32_t blobType;
2049 status_t status = readInt32(&blobType);
2050 if (status) return status;
2051
2052 if (blobType == BLOB_INPLACE) {
2053 ALOGV("readBlob: read in place");
2054 const void* ptr = readInplace(len);
2055 if (!ptr) return BAD_VALUE;
2056
2057 outBlob->init(-1, const_cast<void*>(ptr), len, false);
2058 return NO_ERROR;
2059 }
2060
2061 ALOGV("readBlob: read from ashmem");
2062 bool isMutable = (blobType == BLOB_ASHMEM_MUTABLE);
2063 int fd = readFileDescriptor();
2064 if (fd == int(BAD_TYPE)) return BAD_VALUE;
2065
2066 if (!ashmem_valid(fd)) {
2067 ALOGE("invalid fd");
2068 return BAD_VALUE;
2069 }
2070 int size = ashmem_get_size_region(fd);
2071 if (size < 0 || size_t(size) < len) {
2072 ALOGE("request size %zu does not match fd size %d", len, size);
2073 return BAD_VALUE;
2074 }
2075 void* ptr = ::mmap(nullptr, len, isMutable ? PROT_READ | PROT_WRITE : PROT_READ,
2076 MAP_SHARED, fd, 0);
2077 if (ptr == MAP_FAILED) return NO_MEMORY;
2078
2079 outBlob->init(fd, ptr, len, isMutable);
2080 return NO_ERROR;
2081 }
2082
read(FlattenableHelperInterface & val) const2083 status_t Parcel::read(FlattenableHelperInterface& val) const
2084 {
2085 // size
2086 const size_t len = this->readInt32();
2087 const size_t fd_count = this->readInt32();
2088
2089 if ((len > INT32_MAX) || (fd_count >= gMaxFds)) {
2090 // don't accept size_t values which may have come from an
2091 // inadvertent conversion from a negative int.
2092 return BAD_VALUE;
2093 }
2094
2095 // payload
2096 void const* const buf = this->readInplace(pad_size(len));
2097 if (buf == nullptr)
2098 return BAD_VALUE;
2099
2100 int* fds = nullptr;
2101 if (fd_count) {
2102 fds = new (std::nothrow) int[fd_count];
2103 if (fds == nullptr) {
2104 ALOGE("read: failed to allocate requested %zu fds", fd_count);
2105 return BAD_VALUE;
2106 }
2107 }
2108
2109 status_t err = NO_ERROR;
2110 for (size_t i=0 ; i<fd_count && err==NO_ERROR ; i++) {
2111 int fd = this->readFileDescriptor();
2112 if (fd < 0 || ((fds[i] = fcntl(fd, F_DUPFD_CLOEXEC, 0)) < 0)) {
2113 err = BAD_VALUE;
2114 ALOGE("fcntl(F_DUPFD_CLOEXEC) failed in Parcel::read, i is %zu, fds[i] is %d, fd_count is %zu, error: %s",
2115 i, fds[i], fd_count, strerror(fd < 0 ? -fd : errno));
2116 // Close all the file descriptors that were dup-ed.
2117 for (size_t j=0; j<i ;j++) {
2118 close(fds[j]);
2119 }
2120 }
2121 }
2122
2123 if (err == NO_ERROR) {
2124 err = val.unflatten(buf, len, fds, fd_count);
2125 }
2126
2127 if (fd_count) {
2128 delete [] fds;
2129 }
2130
2131 return err;
2132 }
readObject(bool nullMetaData) const2133 const flat_binder_object* Parcel::readObject(bool nullMetaData) const
2134 {
2135 const size_t DPOS = mDataPos;
2136 if ((DPOS+sizeof(flat_binder_object)) <= mDataSize) {
2137 const flat_binder_object* obj
2138 = reinterpret_cast<const flat_binder_object*>(mData+DPOS);
2139 mDataPos = DPOS + sizeof(flat_binder_object);
2140 if (!nullMetaData && (obj->cookie == 0 && obj->binder == 0)) {
2141 // When transferring a NULL object, we don't write it into
2142 // the object list, so we don't want to check for it when
2143 // reading.
2144 ALOGV("readObject Setting data pos of %p to %zu", this, mDataPos);
2145 return obj;
2146 }
2147
2148 // Ensure that this object is valid...
2149 binder_size_t* const OBJS = mObjects;
2150 const size_t N = mObjectsSize;
2151 size_t opos = mNextObjectHint;
2152
2153 if (N > 0) {
2154 ALOGV("Parcel %p looking for obj at %zu, hint=%zu",
2155 this, DPOS, opos);
2156
2157 // Start at the current hint position, looking for an object at
2158 // the current data position.
2159 if (opos < N) {
2160 while (opos < (N-1) && OBJS[opos] < DPOS) {
2161 opos++;
2162 }
2163 } else {
2164 opos = N-1;
2165 }
2166 if (OBJS[opos] == DPOS) {
2167 // Found it!
2168 ALOGV("Parcel %p found obj %zu at index %zu with forward search",
2169 this, DPOS, opos);
2170 mNextObjectHint = opos+1;
2171 ALOGV("readObject Setting data pos of %p to %zu", this, mDataPos);
2172 return obj;
2173 }
2174
2175 // Look backwards for it...
2176 while (opos > 0 && OBJS[opos] > DPOS) {
2177 opos--;
2178 }
2179 if (OBJS[opos] == DPOS) {
2180 // Found it!
2181 ALOGV("Parcel %p found obj %zu at index %zu with backward search",
2182 this, DPOS, opos);
2183 mNextObjectHint = opos+1;
2184 ALOGV("readObject Setting data pos of %p to %zu", this, mDataPos);
2185 return obj;
2186 }
2187 }
2188 ALOGW("Attempt to read object from Parcel %p at offset %zu that is not in the object list",
2189 this, DPOS);
2190 }
2191 return nullptr;
2192 }
2193
closeFileDescriptors()2194 void Parcel::closeFileDescriptors()
2195 {
2196 size_t i = mObjectsSize;
2197 if (i > 0) {
2198 //ALOGI("Closing file descriptors for %zu objects...", i);
2199 }
2200 while (i > 0) {
2201 i--;
2202 const flat_binder_object* flat
2203 = reinterpret_cast<flat_binder_object*>(mData+mObjects[i]);
2204 if (flat->hdr.type == BINDER_TYPE_FD) {
2205 //ALOGI("Closing fd: %ld", flat->handle);
2206 close(flat->handle);
2207 }
2208 }
2209 }
2210
ipcData() const2211 uintptr_t Parcel::ipcData() const
2212 {
2213 return reinterpret_cast<uintptr_t>(mData);
2214 }
2215
ipcDataSize() const2216 size_t Parcel::ipcDataSize() const
2217 {
2218 return (mDataSize > mDataPos ? mDataSize : mDataPos);
2219 }
2220
ipcObjects() const2221 uintptr_t Parcel::ipcObjects() const
2222 {
2223 return reinterpret_cast<uintptr_t>(mObjects);
2224 }
2225
ipcObjectsCount() const2226 size_t Parcel::ipcObjectsCount() const
2227 {
2228 return mObjectsSize;
2229 }
2230
ipcSetDataReference(const uint8_t * data,size_t dataSize,const binder_size_t * objects,size_t objectsCount,release_func relFunc)2231 void Parcel::ipcSetDataReference(const uint8_t* data, size_t dataSize,
2232 const binder_size_t* objects, size_t objectsCount, release_func relFunc)
2233 {
2234 // this code uses 'mOwner == nullptr' to understand whether it owns memory
2235 LOG_ALWAYS_FATAL_IF(relFunc == nullptr, "must provide cleanup function");
2236
2237 freeData();
2238
2239 mData = const_cast<uint8_t*>(data);
2240 mDataSize = mDataCapacity = dataSize;
2241 mObjects = const_cast<binder_size_t*>(objects);
2242 mObjectsSize = mObjectsCapacity = objectsCount;
2243 mOwner = relFunc;
2244
2245 binder_size_t minOffset = 0;
2246 for (size_t i = 0; i < mObjectsSize; i++) {
2247 binder_size_t offset = mObjects[i];
2248 if (offset < minOffset) {
2249 ALOGE("%s: bad object offset %" PRIu64 " < %" PRIu64 "\n",
2250 __func__, (uint64_t)offset, (uint64_t)minOffset);
2251 mObjectsSize = 0;
2252 break;
2253 }
2254 const flat_binder_object* flat
2255 = reinterpret_cast<const flat_binder_object*>(mData + offset);
2256 uint32_t type = flat->hdr.type;
2257 if (!(type == BINDER_TYPE_BINDER || type == BINDER_TYPE_HANDLE ||
2258 type == BINDER_TYPE_FD)) {
2259 // We should never receive other types (eg BINDER_TYPE_FDA) as long as we don't support
2260 // them in libbinder. If we do receive them, it probably means a kernel bug; try to
2261 // recover gracefully by clearing out the objects.
2262 android_errorWriteLog(0x534e4554, "135930648");
2263 android_errorWriteLog(0x534e4554, "203847542");
2264 ALOGE("%s: unsupported type object (%" PRIu32 ") at offset %" PRIu64 "\n",
2265 __func__, type, (uint64_t)offset);
2266
2267 // WARNING: callers of ipcSetDataReference need to make sure they
2268 // don't rely on mObjectsSize in their release_func.
2269 mObjectsSize = 0;
2270 break;
2271 }
2272 minOffset = offset + sizeof(flat_binder_object);
2273 }
2274 scanForFds();
2275 }
2276
print(TextOutput & to,uint32_t) const2277 void Parcel::print(TextOutput& to, uint32_t /*flags*/) const
2278 {
2279 to << "Parcel(";
2280
2281 if (errorCheck() != NO_ERROR) {
2282 const status_t err = errorCheck();
2283 to << "Error: " << (void*)(intptr_t)err << " \"" << strerror(-err) << "\"";
2284 } else if (dataSize() > 0) {
2285 const uint8_t* DATA = data();
2286 to << indent << HexDump(DATA, dataSize()) << dedent;
2287 const binder_size_t* OBJS = mObjects;
2288 const size_t N = objectsCount();
2289 for (size_t i=0; i<N; i++) {
2290 const flat_binder_object* flat
2291 = reinterpret_cast<const flat_binder_object*>(DATA+OBJS[i]);
2292 to << endl << "Object #" << i << " @ " << (void*)OBJS[i] << ": "
2293 << TypeCode(flat->hdr.type & 0x7f7f7f00)
2294 << " = " << flat->binder;
2295 }
2296 } else {
2297 to << "NULL";
2298 }
2299
2300 to << ")";
2301 }
2302
releaseObjects()2303 void Parcel::releaseObjects()
2304 {
2305 size_t i = mObjectsSize;
2306 if (i == 0) {
2307 return;
2308 }
2309 sp<ProcessState> proc(ProcessState::self());
2310 uint8_t* const data = mData;
2311 binder_size_t* const objects = mObjects;
2312 while (i > 0) {
2313 i--;
2314 const flat_binder_object* flat
2315 = reinterpret_cast<flat_binder_object*>(data+objects[i]);
2316 release_object(proc, *flat, this);
2317 }
2318 }
2319
acquireObjects()2320 void Parcel::acquireObjects()
2321 {
2322 size_t i = mObjectsSize;
2323 if (i == 0) {
2324 return;
2325 }
2326 const sp<ProcessState> proc(ProcessState::self());
2327 uint8_t* const data = mData;
2328 binder_size_t* const objects = mObjects;
2329 while (i > 0) {
2330 i--;
2331 const flat_binder_object* flat
2332 = reinterpret_cast<flat_binder_object*>(data+objects[i]);
2333 acquire_object(proc, *flat, this);
2334 }
2335 }
2336
freeData()2337 void Parcel::freeData()
2338 {
2339 freeDataNoInit();
2340 initState();
2341 }
2342
freeDataNoInit()2343 void Parcel::freeDataNoInit()
2344 {
2345 if (mOwner) {
2346 LOG_ALLOC("Parcel %p: freeing other owner data", this);
2347 //ALOGI("Freeing data ref of %p (pid=%d)", this, getpid());
2348 mOwner(this, mData, mDataSize, mObjects, mObjectsSize);
2349 } else {
2350 LOG_ALLOC("Parcel %p: freeing allocated data", this);
2351 releaseObjects();
2352 if (mData) {
2353 LOG_ALLOC("Parcel %p: freeing with %zu capacity", this, mDataCapacity);
2354 gParcelGlobalAllocSize -= mDataCapacity;
2355 gParcelGlobalAllocCount--;
2356 if (mDeallocZero) {
2357 zeroMemory(mData, mDataSize);
2358 }
2359 free(mData);
2360 }
2361 if (mObjects) free(mObjects);
2362 }
2363 }
2364
growData(size_t len)2365 status_t Parcel::growData(size_t len)
2366 {
2367 if (len > INT32_MAX) {
2368 // don't accept size_t values which may have come from an
2369 // inadvertent conversion from a negative int.
2370 return BAD_VALUE;
2371 }
2372
2373 if (len > SIZE_MAX - mDataSize) return NO_MEMORY; // overflow
2374 if (mDataSize + len > SIZE_MAX / 3) return NO_MEMORY; // overflow
2375 size_t newSize = ((mDataSize+len)*3)/2;
2376 return (newSize <= mDataSize)
2377 ? (status_t) NO_MEMORY
2378 : continueWrite(std::max(newSize, (size_t) 128));
2379 }
2380
reallocZeroFree(uint8_t * data,size_t oldCapacity,size_t newCapacity,bool zero)2381 static uint8_t* reallocZeroFree(uint8_t* data, size_t oldCapacity, size_t newCapacity, bool zero) {
2382 if (!zero) {
2383 return (uint8_t*)realloc(data, newCapacity);
2384 }
2385 uint8_t* newData = (uint8_t*)malloc(newCapacity);
2386 if (!newData) {
2387 return nullptr;
2388 }
2389
2390 memcpy(newData, data, std::min(oldCapacity, newCapacity));
2391 zeroMemory(data, oldCapacity);
2392 free(data);
2393 return newData;
2394 }
2395
restartWrite(size_t desired)2396 status_t Parcel::restartWrite(size_t desired)
2397 {
2398 if (desired > INT32_MAX) {
2399 // don't accept size_t values which may have come from an
2400 // inadvertent conversion from a negative int.
2401 return BAD_VALUE;
2402 }
2403
2404 if (mOwner) {
2405 freeData();
2406 return continueWrite(desired);
2407 }
2408
2409 uint8_t* data = reallocZeroFree(mData, mDataCapacity, desired, mDeallocZero);
2410 if (!data && desired > mDataCapacity) {
2411 mError = NO_MEMORY;
2412 return NO_MEMORY;
2413 }
2414
2415 releaseObjects();
2416
2417 if (data || desired == 0) {
2418 LOG_ALLOC("Parcel %p: restart from %zu to %zu capacity", this, mDataCapacity, desired);
2419 if (mDataCapacity > desired) {
2420 gParcelGlobalAllocSize -= (mDataCapacity - desired);
2421 } else {
2422 gParcelGlobalAllocSize += (desired - mDataCapacity);
2423 }
2424
2425 if (!mData) {
2426 gParcelGlobalAllocCount++;
2427 }
2428 mData = data;
2429 mDataCapacity = desired;
2430 }
2431
2432 mDataSize = mDataPos = 0;
2433 ALOGV("restartWrite Setting data size of %p to %zu", this, mDataSize);
2434 ALOGV("restartWrite Setting data pos of %p to %zu", this, mDataPos);
2435
2436 free(mObjects);
2437 mObjects = nullptr;
2438 mObjectsSize = mObjectsCapacity = 0;
2439 mNextObjectHint = 0;
2440 mObjectsSorted = false;
2441 mHasFds = false;
2442 mFdsKnown = true;
2443 mAllowFds = true;
2444
2445 return NO_ERROR;
2446 }
2447
continueWrite(size_t desired)2448 status_t Parcel::continueWrite(size_t desired)
2449 {
2450 if (desired > INT32_MAX) {
2451 // don't accept size_t values which may have come from an
2452 // inadvertent conversion from a negative int.
2453 return BAD_VALUE;
2454 }
2455
2456 // If shrinking, first adjust for any objects that appear
2457 // after the new data size.
2458 size_t objectsSize = mObjectsSize;
2459 if (desired < mDataSize) {
2460 if (desired == 0) {
2461 objectsSize = 0;
2462 } else {
2463 while (objectsSize > 0) {
2464 if (mObjects[objectsSize-1] < desired)
2465 break;
2466 objectsSize--;
2467 }
2468 }
2469 }
2470
2471 if (mOwner) {
2472 // If the size is going to zero, just release the owner's data.
2473 if (desired == 0) {
2474 freeData();
2475 return NO_ERROR;
2476 }
2477
2478 // If there is a different owner, we need to take
2479 // posession.
2480 uint8_t* data = (uint8_t*)malloc(desired);
2481 if (!data) {
2482 mError = NO_MEMORY;
2483 return NO_MEMORY;
2484 }
2485 binder_size_t* objects = nullptr;
2486
2487 if (objectsSize) {
2488 objects = (binder_size_t*)calloc(objectsSize, sizeof(binder_size_t));
2489 if (!objects) {
2490 free(data);
2491
2492 mError = NO_MEMORY;
2493 return NO_MEMORY;
2494 }
2495
2496 // Little hack to only acquire references on objects
2497 // we will be keeping.
2498 size_t oldObjectsSize = mObjectsSize;
2499 mObjectsSize = objectsSize;
2500 acquireObjects();
2501 mObjectsSize = oldObjectsSize;
2502 }
2503
2504 if (mData) {
2505 memcpy(data, mData, mDataSize < desired ? mDataSize : desired);
2506 }
2507 if (objects && mObjects) {
2508 memcpy(objects, mObjects, objectsSize*sizeof(binder_size_t));
2509 }
2510 //ALOGI("Freeing data ref of %p (pid=%d)", this, getpid());
2511 mOwner(this, mData, mDataSize, mObjects, mObjectsSize);
2512 mOwner = nullptr;
2513
2514 LOG_ALLOC("Parcel %p: taking ownership of %zu capacity", this, desired);
2515 gParcelGlobalAllocSize += desired;
2516 gParcelGlobalAllocCount++;
2517
2518 mData = data;
2519 mObjects = objects;
2520 mDataSize = (mDataSize < desired) ? mDataSize : desired;
2521 ALOGV("continueWrite Setting data size of %p to %zu", this, mDataSize);
2522 mDataCapacity = desired;
2523 mObjectsSize = mObjectsCapacity = objectsSize;
2524 mNextObjectHint = 0;
2525 mObjectsSorted = false;
2526
2527 } else if (mData) {
2528 if (objectsSize < mObjectsSize) {
2529 // Need to release refs on any objects we are dropping.
2530 const sp<ProcessState> proc(ProcessState::self());
2531 for (size_t i=objectsSize; i<mObjectsSize; i++) {
2532 const flat_binder_object* flat
2533 = reinterpret_cast<flat_binder_object*>(mData+mObjects[i]);
2534 if (flat->hdr.type == BINDER_TYPE_FD) {
2535 // will need to rescan because we may have lopped off the only FDs
2536 mFdsKnown = false;
2537 }
2538 release_object(proc, *flat, this);
2539 }
2540
2541 if (objectsSize == 0) {
2542 free(mObjects);
2543 mObjects = nullptr;
2544 mObjectsCapacity = 0;
2545 } else {
2546 binder_size_t* objects =
2547 (binder_size_t*)realloc(mObjects, objectsSize*sizeof(binder_size_t));
2548 if (objects) {
2549 mObjects = objects;
2550 mObjectsCapacity = objectsSize;
2551 }
2552 }
2553 mObjectsSize = objectsSize;
2554 mNextObjectHint = 0;
2555 mObjectsSorted = false;
2556 }
2557
2558 // We own the data, so we can just do a realloc().
2559 if (desired > mDataCapacity) {
2560 uint8_t* data = reallocZeroFree(mData, mDataCapacity, desired, mDeallocZero);
2561 if (data) {
2562 LOG_ALLOC("Parcel %p: continue from %zu to %zu capacity", this, mDataCapacity,
2563 desired);
2564 gParcelGlobalAllocSize += desired;
2565 gParcelGlobalAllocSize -= mDataCapacity;
2566 mData = data;
2567 mDataCapacity = desired;
2568 } else {
2569 mError = NO_MEMORY;
2570 return NO_MEMORY;
2571 }
2572 } else {
2573 if (mDataSize > desired) {
2574 mDataSize = desired;
2575 ALOGV("continueWrite Setting data size of %p to %zu", this, mDataSize);
2576 }
2577 if (mDataPos > desired) {
2578 mDataPos = desired;
2579 ALOGV("continueWrite Setting data pos of %p to %zu", this, mDataPos);
2580 }
2581 }
2582
2583 } else {
2584 // This is the first data. Easy!
2585 uint8_t* data = (uint8_t*)malloc(desired);
2586 if (!data) {
2587 mError = NO_MEMORY;
2588 return NO_MEMORY;
2589 }
2590
2591 if(!(mDataCapacity == 0 && mObjects == nullptr
2592 && mObjectsCapacity == 0)) {
2593 ALOGE("continueWrite: %zu/%p/%zu/%zu", mDataCapacity, mObjects, mObjectsCapacity, desired);
2594 }
2595
2596 LOG_ALLOC("Parcel %p: allocating with %zu capacity", this, desired);
2597 gParcelGlobalAllocSize += desired;
2598 gParcelGlobalAllocCount++;
2599
2600 mData = data;
2601 mDataSize = mDataPos = 0;
2602 ALOGV("continueWrite Setting data size of %p to %zu", this, mDataSize);
2603 ALOGV("continueWrite Setting data pos of %p to %zu", this, mDataPos);
2604 mDataCapacity = desired;
2605 }
2606
2607 return NO_ERROR;
2608 }
2609
initState()2610 void Parcel::initState()
2611 {
2612 LOG_ALLOC("Parcel %p: initState", this);
2613 mError = NO_ERROR;
2614 mData = nullptr;
2615 mDataSize = 0;
2616 mDataCapacity = 0;
2617 mDataPos = 0;
2618 ALOGV("initState Setting data size of %p to %zu", this, mDataSize);
2619 ALOGV("initState Setting data pos of %p to %zu", this, mDataPos);
2620 mSession = nullptr;
2621 mObjects = nullptr;
2622 mObjectsSize = 0;
2623 mObjectsCapacity = 0;
2624 mNextObjectHint = 0;
2625 mObjectsSorted = false;
2626 mHasFds = false;
2627 mFdsKnown = true;
2628 mAllowFds = true;
2629 mDeallocZero = false;
2630 mOwner = nullptr;
2631 mWorkSourceRequestHeaderPosition = 0;
2632 mRequestHeaderPresent = false;
2633
2634 // racing multiple init leads only to multiple identical write
2635 if (gMaxFds == 0) {
2636 struct rlimit result;
2637 if (!getrlimit(RLIMIT_NOFILE, &result)) {
2638 gMaxFds = (size_t)result.rlim_cur;
2639 //ALOGI("parcel fd limit set to %zu", gMaxFds);
2640 } else {
2641 ALOGW("Unable to getrlimit: %s", strerror(errno));
2642 gMaxFds = 1024;
2643 }
2644 }
2645 }
2646
scanForFds() const2647 void Parcel::scanForFds() const {
2648 status_t status = hasFileDescriptorsInRange(0, dataSize(), &mHasFds);
2649 ALOGE_IF(status != NO_ERROR, "Error %d calling hasFileDescriptorsInRange()", status);
2650 mFdsKnown = true;
2651 }
2652
getBlobAshmemSize() const2653 size_t Parcel::getBlobAshmemSize() const
2654 {
2655 // This used to return the size of all blobs that were written to ashmem, now we're returning
2656 // the ashmem currently referenced by this Parcel, which should be equivalent.
2657 // TODO(b/202029388): Remove method once ABI can be changed.
2658 return getOpenAshmemSize();
2659 }
2660
getOpenAshmemSize() const2661 size_t Parcel::getOpenAshmemSize() const
2662 {
2663 size_t openAshmemSize = 0;
2664 for (size_t i = 0; i < mObjectsSize; i++) {
2665 const flat_binder_object* flat =
2666 reinterpret_cast<const flat_binder_object*>(mData + mObjects[i]);
2667
2668 // cookie is compared against zero for historical reasons
2669 // > obj.cookie = takeOwnership ? 1 : 0;
2670 if (flat->hdr.type == BINDER_TYPE_FD && flat->cookie != 0 && ashmem_valid(flat->handle)) {
2671 int size = ashmem_get_size_region(flat->handle);
2672 if (__builtin_add_overflow(openAshmemSize, size, &openAshmemSize)) {
2673 ALOGE("Overflow when computing ashmem size.");
2674 return SIZE_MAX;
2675 }
2676 }
2677 }
2678 return openAshmemSize;
2679 }
2680
2681 // --- Parcel::Blob ---
2682
Blob()2683 Parcel::Blob::Blob() :
2684 mFd(-1), mData(nullptr), mSize(0), mMutable(false) {
2685 }
2686
~Blob()2687 Parcel::Blob::~Blob() {
2688 release();
2689 }
2690
release()2691 void Parcel::Blob::release() {
2692 if (mFd != -1 && mData) {
2693 ::munmap(mData, mSize);
2694 }
2695 clear();
2696 }
2697
init(int fd,void * data,size_t size,bool isMutable)2698 void Parcel::Blob::init(int fd, void* data, size_t size, bool isMutable) {
2699 mFd = fd;
2700 mData = data;
2701 mSize = size;
2702 mMutable = isMutable;
2703 }
2704
clear()2705 void Parcel::Blob::clear() {
2706 mFd = -1;
2707 mData = nullptr;
2708 mSize = 0;
2709 mMutable = false;
2710 }
2711
2712 } // namespace android
2713