OSDN Git Service

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