OSDN Git Service

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