Sanity check IMemory access versus underlying mmap am: 94b0d4e3ab am: ef6908e2b3 am: 97f49e50de am: 84f488f354 am: ebdad60d6b am: fc598c54d9 am: f9e5e80bc1 am: 15364d3ec0
am: 049c5df3e5

* commit '049c5df3e59a2d56c47deddc6ec20bf1eba4f50e':
  Sanity check IMemory access versus underlying mmap
diff --git a/Android.mk b/Android.mk
index d5860ef..14be920 100644
--- a/Android.mk
+++ b/Android.mk
@@ -23,19 +23,23 @@
     IAppOpsService.cpp \
     IBatteryStats.cpp \
     IInterface.cpp \
+    IMediaResourceMonitor.cpp \
     IMemory.cpp \
     IPCThreadState.cpp \
     IPermissionController.cpp \
     IProcessInfoService.cpp \
-    ProcessInfoService.cpp \
+    IResultReceiver.cpp \
     IServiceManager.cpp \
-    MemoryDealer.cpp \
     MemoryBase.cpp \
+    MemoryDealer.cpp \
     MemoryHeapBase.cpp \
     Parcel.cpp \
     PermissionCache.cpp \
+    PersistableBundle.cpp \
+    ProcessInfoService.cpp \
     ProcessState.cpp \
     Static.cpp \
+    Status.cpp \
     TextOutput.cpp \
 
 LOCAL_PATH:= $(call my-dir)
@@ -43,6 +47,9 @@
 include $(CLEAR_VARS)
 LOCAL_MODULE := libbinder
 LOCAL_SHARED_LIBRARIES := liblog libcutils libutils
+
+LOCAL_CLANG := true
+LOCAL_SANITIZE := integer
 LOCAL_SRC_FILES := $(sources)
 ifneq ($(TARGET_USES_64_BIT_BINDER),true)
 ifneq ($(TARGET_IS_64_BIT),true)
diff --git a/Binder.cpp b/Binder.cpp
index 9d200fb..c4d47ca 100644
--- a/Binder.cpp
+++ b/Binder.cpp
@@ -16,10 +16,11 @@
 
 #include <binder/Binder.h>
 
-#include <stdatomic.h>
+#include <atomic>
 #include <utils/misc.h>
 #include <binder/BpBinder.h>
 #include <binder/IInterface.h>
+#include <binder/IResultReceiver.h>
 #include <binder/Parcel.h>
 
 #include <stdio.h>
@@ -59,6 +60,24 @@
     return false;
 }
 
+
+status_t IBinder::shellCommand(const sp<IBinder>& target, int in, int out, int err,
+    Vector<String16>& args, const sp<IResultReceiver>& resultReceiver)
+{
+    Parcel send;
+    Parcel reply;
+    send.writeFileDescriptor(in);
+    send.writeFileDescriptor(out);
+    send.writeFileDescriptor(err);
+    const size_t numArgs = args.size();
+    send.writeInt32(numArgs);
+    for (size_t i = 0; i < numArgs; i++) {
+        send.writeString16(args[i]);
+    }
+    send.writeStrongBinder(resultReceiver != NULL ? IInterface::asBinder(resultReceiver) : NULL);
+    return target->transact(SHELL_COMMAND_TRANSACTION, send, &reply);
+}
+
 // ---------------------------------------------------------------------------
 
 class BBinder::Extras
@@ -70,9 +89,8 @@
 
 // ---------------------------------------------------------------------------
 
-BBinder::BBinder()
+BBinder::BBinder() : mExtras(nullptr)
 {
-  atomic_init(&mExtras, static_cast<uintptr_t>(0));
 }
 
 bool BBinder::isBinderAlive() const
@@ -130,7 +148,7 @@
     return INVALID_OPERATION;
 }
 
-    status_t BBinder::dump(int /*fd*/, const Vector<String16>& /*args*/)
+status_t BBinder::dump(int /*fd*/, const Vector<String16>& /*args*/)
 {
     return NO_ERROR;
 }
@@ -139,19 +157,16 @@
     const void* objectID, void* object, void* cleanupCookie,
     object_cleanup_func func)
 {
-    Extras* e = reinterpret_cast<Extras*>(
-                    atomic_load_explicit(&mExtras, memory_order_acquire));
+    Extras* e = mExtras.load(std::memory_order_acquire);
 
     if (!e) {
         e = new Extras;
-        uintptr_t expected = 0;
-        if (!atomic_compare_exchange_strong_explicit(
-                                        &mExtras, &expected,
-                                        reinterpret_cast<uintptr_t>(e),
-                                        memory_order_release,
-                                        memory_order_acquire)) {
+        Extras* expected = nullptr;
+        if (!mExtras.compare_exchange_strong(expected, e,
+                                             std::memory_order_release,
+                                             std::memory_order_acquire)) {
             delete e;
-            e = reinterpret_cast<Extras*>(expected);  // Filled in by CAS
+            e = expected;  // Filled in by CAS
         }
         if (e == 0) return; // out of memory
     }
@@ -160,18 +175,9 @@
     e->mObjects.attach(objectID, object, cleanupCookie, func);
 }
 
-// The C11 standard doesn't allow atomic loads from const fields,
-// though C++11 does.  Fudge it until standards get straightened out.
-static inline uintptr_t load_const_atomic(const atomic_uintptr_t* p,
-                                          memory_order mo) {
-    atomic_uintptr_t* non_const_p = const_cast<atomic_uintptr_t*>(p);
-    return atomic_load_explicit(non_const_p, mo);
-}
-
 void* BBinder::findObject(const void* objectID) const
 {
-    Extras* e = reinterpret_cast<Extras*>(
-                    load_const_atomic(&mExtras, memory_order_acquire));
+    Extras* e = mExtras.load(std::memory_order_acquire);
     if (!e) return NULL;
 
     AutoMutex _l(e->mLock);
@@ -180,8 +186,7 @@
 
 void BBinder::detachObject(const void* objectID)
 {
-    Extras* e = reinterpret_cast<Extras*>(
-                    atomic_load_explicit(&mExtras, memory_order_acquire));
+    Extras* e = mExtras.load(std::memory_order_acquire);
     if (!e) return;
 
     AutoMutex _l(e->mLock);
@@ -195,8 +200,7 @@
 
 BBinder::~BBinder()
 {
-    Extras* e = reinterpret_cast<Extras*>(
-                    atomic_load_explicit(&mExtras, memory_order_relaxed));
+    Extras* e = mExtras.load(std::memory_order_relaxed);
     if (e) delete e;
 }
 
@@ -219,6 +223,25 @@
             return dump(fd, args);
         }
 
+        case SHELL_COMMAND_TRANSACTION: {
+            int in = data.readFileDescriptor();
+            int out = data.readFileDescriptor();
+            int err = data.readFileDescriptor();
+            int argc = data.readInt32();
+            Vector<String16> args;
+            for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
+               args.add(data.readString16());
+            }
+            sp<IResultReceiver> resultReceiver = IResultReceiver::asInterface(
+                    data.readStrongBinder());
+
+            // XXX can't add virtuals until binaries are updated.
+            //return shellCommand(in, out, err, args, resultReceiver);
+            if (resultReceiver != NULL) {
+                resultReceiver->send(INVALID_OPERATION);
+            }
+        }
+
         case SYSPROPS_TRANSACTION: {
             report_sysprop_change();
             return NO_ERROR;
@@ -252,7 +275,7 @@
 BpRefBase::~BpRefBase()
 {
     if (mRemote) {
-        if (!(mState&kRemoteAcquired)) {
+        if (!(mState.load(std::memory_order_relaxed)&kRemoteAcquired)) {
             mRemote->decStrong(this);
         }
         mRefs->decWeak(this);
@@ -261,7 +284,7 @@
 
 void BpRefBase::onFirstRef()
 {
-    android_atomic_or(kRemoteAcquired, &mState);
+    mState.fetch_or(kRemoteAcquired, std::memory_order_relaxed);
 }
 
 void BpRefBase::onLastStrongRef(const void* /*id*/)
diff --git a/BpBinder.cpp b/BpBinder.cpp
index 345ba20..c0e0296 100644
--- a/BpBinder.cpp
+++ b/BpBinder.cpp
@@ -20,6 +20,7 @@
 #include <binder/BpBinder.h>
 
 #include <binder/IPCThreadState.h>
+#include <binder/IResultReceiver.h>
 #include <utils/Log.h>
 
 #include <stdio.h>
diff --git a/Debug.cpp b/Debug.cpp
index bdb7182..a8f2da5 100644
--- a/Debug.cpp
+++ b/Debug.cpp
@@ -138,7 +138,7 @@
         *pos = 0;
         return pos;
     }
-    
+
     if( fullContext ) {
         *pos++ = '0';
         *pos++ = 'x';
@@ -167,21 +167,21 @@
     if (func == NULL) func = defaultPrintFunc;
 
     size_t offset;
-    
+
     unsigned char *pos = (unsigned char *)buf;
-    
+
     if (pos == NULL) {
         if (singleLineBytesCutoff < 0) func(cookie, "\n");
         func(cookie, "(NULL)");
         return;
     }
-    
+
     if (length == 0) {
         if (singleLineBytesCutoff < 0) func(cookie, "\n");
         func(cookie, "(empty)");
         return;
     }
-    
+
     if ((int32_t)length < 0) {
         if (singleLineBytesCutoff < 0) func(cookie, "\n");
         char buf[64];
@@ -189,12 +189,12 @@
         func(cookie, buf);
         return;
     }
-    
+
     char buffer[256];
     static const size_t maxBytesPerLine = (sizeof(buffer)-1-11-4)/(3+1);
-    
+
     if (bytesPerLine > maxBytesPerLine) bytesPerLine = maxBytesPerLine;
-    
+
     const bool oneLine = (int32_t)length <= singleLineBytesCutoff;
     bool newLine = false;
     if (cStyle) {
@@ -205,7 +205,7 @@
         func(cookie, "\n");
         newLine = true;
     }
-    
+
     for (offset = 0; ; offset += bytesPerLine, pos += bytesPerLine) {
         long remain = length;
 
@@ -217,21 +217,20 @@
 
         size_t index;
         size_t word;
-        
+
         for (word = 0; word < bytesPerLine; ) {
 
             const size_t startIndex = word+(alignment-(alignment?1:0));
-            const ssize_t dir = -1;
 
             for (index = 0; index < alignment || (alignment == 0 && index < bytesPerLine); index++) {
-            
+
                 if (!cStyle) {
                     if (index == 0 && word > 0 && alignment > 0) {
                         *c++ = ' ';
                     }
-                
+
                     if (remain-- > 0) {
-                        const unsigned char val = *(pos+startIndex+(index*dir));
+                        const unsigned char val = *(pos+startIndex-index);
                         *c++ = makehexdigit(val>>4);
                         *c++ = makehexdigit(val);
                     } else if (!oneLine) {
@@ -248,14 +247,14 @@
                             *c++ = '0';
                             *c++ = 'x';
                         }
-                        const unsigned char val = *(pos+startIndex+(index*dir));
+                        const unsigned char val = *(pos+startIndex-index);
                         *c++ = makehexdigit(val>>4);
                         *c++ = makehexdigit(val);
                         remain--;
                     }
                 }
             }
-            
+
             word += index;
         }
 
@@ -272,7 +271,7 @@
                     *c++ = ' ';
                 }
             }
-            
+
             *c++ = '\'';
             if (length > bytesPerLine) *c++ = '\n';
         } else {
@@ -284,7 +283,7 @@
         *c = 0;
         func(cookie, buffer);
         newLine = true;
-        
+
         if (length <= bytesPerLine) break;
         length -= bytesPerLine;
     }
diff --git a/IMediaResourceMonitor.cpp b/IMediaResourceMonitor.cpp
new file mode 100644
index 0000000..e8deb4a
--- /dev/null
+++ b/IMediaResourceMonitor.cpp
@@ -0,0 +1,67 @@
+/*
+ * Copyright 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <binder/IMediaResourceMonitor.h>
+#include <binder/Parcel.h>
+#include <utils/Errors.h>
+#include <sys/types.h>
+
+namespace android {
+
+// ----------------------------------------------------------------------
+
+class BpMediaResourceMonitor : public BpInterface<IMediaResourceMonitor> {
+public:
+    BpMediaResourceMonitor(const sp<IBinder>& impl)
+        : BpInterface<IMediaResourceMonitor>(impl) {}
+
+    virtual void notifyResourceGranted(/*in*/ int32_t pid, /*in*/ const String16& type,
+            /*in*/ const String16& subType, /*in*/ int64_t value)
+    {
+        Parcel data, reply;
+        data.writeInterfaceToken(IMediaResourceMonitor::getInterfaceDescriptor());
+        data.writeInt32(pid);
+        data.writeString16(type);
+        data.writeString16(subType);
+        data.writeInt64(value);
+        remote()->transact(NOTIFY_RESOURCE_GRANTED, data, &reply, IBinder::FLAG_ONEWAY);
+    }
+};
+
+IMPLEMENT_META_INTERFACE(MediaResourceMonitor, "android.media.IMediaResourceMonitor");
+
+// ----------------------------------------------------------------------
+
+status_t BnMediaResourceMonitor::onTransact( uint32_t code, const Parcel& data, Parcel* reply,
+        uint32_t flags) {
+    switch(code) {
+        case NOTIFY_RESOURCE_GRANTED: {
+            CHECK_INTERFACE(IMediaResourceMonitor, data, reply);
+            int32_t pid = data.readInt32();
+            const String16 type = data.readString16();
+            const String16 subType = data.readString16();
+            int64_t value = data.readInt64();
+            notifyResourceGranted(/*in*/ pid, /*in*/ type, /*in*/ subType, /*in*/ value);
+            return NO_ERROR;
+        } break;
+        default:
+            return BBinder::onTransact(code, data, reply, flags);
+    }
+}
+
+// ----------------------------------------------------------------------
+
+}; // namespace android
diff --git a/IPCThreadState.cpp b/IPCThreadState.cpp
index ef88181..1f6bda2 100644
--- a/IPCThreadState.cpp
+++ b/IPCThreadState.cpp
@@ -287,12 +287,18 @@
         return new IPCThreadState;
     }
     
-    if (gShutdown) return NULL;
+    if (gShutdown) {
+        ALOGW("Calling IPCThreadState::self() during shutdown is dangerous, expect a crash.\n");
+        return NULL;
+    }
     
     pthread_mutex_lock(&gTLSMutex);
     if (!gHaveTLS) {
-        if (pthread_key_create(&gTLS, threadDestructor) != 0) {
+        int key_create_value = pthread_key_create(&gTLS, threadDestructor);
+        if (key_create_value != 0) {
             pthread_mutex_unlock(&gTLSMutex);
+            ALOGW("IPCThreadState::self() unable to create TLS key, expect a crash: %s\n",
+                    strerror(key_create_value));
             return NULL;
         }
         gHaveTLS = true;
@@ -852,7 +858,7 @@
         IF_LOG_COMMANDS() {
             alog << "About to read/write, write size = " << mOut.dataSize() << endl;
         }
-#if defined(HAVE_ANDROID_OS)
+#if defined(__ANDROID__)
         if (ioctl(mProcess->mDriverFD, BINDER_WRITE_READ, &bwr) >= 0)
             err = NO_ERROR;
         else
@@ -1158,7 +1164,7 @@
         IPCThreadState* const self = static_cast<IPCThreadState*>(st);
         if (self) {
                 self->flushCommands();
-#if defined(HAVE_ANDROID_OS)
+#if defined(__ANDROID__)
         if (self->mProcess->mDriverFD > 0) {
             ioctl(self->mProcess->mDriverFD, BINDER_THREAD_EXIT, 0);
         }
diff --git a/IProcessInfoService.cpp b/IProcessInfoService.cpp
index d86eb27..c37920d 100644
--- a/IProcessInfoService.cpp
+++ b/IProcessInfoService.cpp
@@ -49,6 +49,39 @@
         return reply.readInt32();
     }
 
+    virtual status_t getProcessStatesAndOomScoresFromPids(size_t length,
+            /*in*/ int32_t* pids, /*out*/ int32_t* states, /*out*/ int32_t* scores)
+    {
+        Parcel data, reply;
+        data.writeInterfaceToken(IProcessInfoService::getInterfaceDescriptor());
+        data.writeInt32Array(length, pids);
+        // write length of output arrays, used by java AIDL stubs
+        data.writeInt32(length);
+        data.writeInt32(length);
+        status_t err = remote()->transact(
+                GET_PROCESS_STATES_AND_OOM_SCORES_FROM_PIDS, data, &reply);
+        if (err != NO_ERROR
+                || ((err = reply.readExceptionCode()) != NO_ERROR)) {
+            return err;
+        }
+        int32_t replyLen = reply.readInt32();
+        if (static_cast<size_t>(replyLen) != length) {
+            return NOT_ENOUGH_DATA;
+        }
+        if (replyLen > 0 && (err = reply.read(
+                states, length * sizeof(*states))) != NO_ERROR) {
+            return err;
+        }
+        replyLen = reply.readInt32();
+        if (static_cast<size_t>(replyLen) != length) {
+            return NOT_ENOUGH_DATA;
+        }
+        if (replyLen > 0 && (err = reply.read(
+                scores, length * sizeof(*scores))) != NO_ERROR) {
+            return err;
+        }
+        return reply.readInt32();
+    }
 };
 
 IMPLEMENT_META_INTERFACE(ProcessInfoService, "android.os.IProcessInfoService");
@@ -84,6 +117,38 @@
             reply->writeInt32(res);
             return NO_ERROR;
         } break;
+        case GET_PROCESS_STATES_AND_OOM_SCORES_FROM_PIDS: {
+            CHECK_INTERFACE(IProcessInfoService, data, reply);
+            int32_t arrayLen = data.readInt32();
+            if (arrayLen <= 0) {
+                reply->writeNoException();
+                reply->writeInt32(0);
+                reply->writeInt32(NOT_ENOUGH_DATA);
+                return NO_ERROR;
+            }
+
+            size_t len = static_cast<size_t>(arrayLen);
+            int32_t pids[len];
+            status_t res = data.read(pids, len * sizeof(*pids));
+
+            // Ignore output array length returned in the parcel here, as the
+            // states array must always be the same length as the input PIDs array.
+            int32_t states[len];
+            int32_t scores[len];
+            for (size_t i = 0; i < len; i++) {
+                states[i] = -1;
+                scores[i] = -10000;
+            }
+            if (res == NO_ERROR) {
+                res = getProcessStatesAndOomScoresFromPids(
+                        len, /*in*/ pids, /*out*/ states, /*out*/ scores);
+            }
+            reply->writeNoException();
+            reply->writeInt32Array(len, states);
+            reply->writeInt32Array(len, scores);
+            reply->writeInt32(res);
+            return NO_ERROR;
+        } break;
         default:
             return BBinder::onTransact(code, data, reply, flags);
     }
diff --git a/IResultReceiver.cpp b/IResultReceiver.cpp
new file mode 100644
index 0000000..2a22b69
--- /dev/null
+++ b/IResultReceiver.cpp
@@ -0,0 +1,69 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define LOG_TAG "ResultReceiver"
+
+#include <binder/IResultReceiver.h>
+
+#include <utils/Log.h>
+#include <binder/Parcel.h>
+#include <utils/String8.h>
+
+#include <private/binder/Static.h>
+
+namespace android {
+
+// ----------------------------------------------------------------------
+
+class BpResultReceiver : public BpInterface<IResultReceiver>
+{
+public:
+    BpResultReceiver(const sp<IBinder>& impl)
+        : BpInterface<IResultReceiver>(impl)
+    {
+    }
+
+    virtual void send(int32_t resultCode) {
+        Parcel data;
+        data.writeInterfaceToken(IResultReceiver::getInterfaceDescriptor());
+        data.writeInt32(resultCode);
+        remote()->transact(OP_SEND, data, NULL, IBinder::FLAG_ONEWAY);
+    }
+};
+
+IMPLEMENT_META_INTERFACE(ResultReceiver, "com.android.internal.os.IResultReceiver");
+
+// ----------------------------------------------------------------------
+
+status_t BnResultReceiver::onTransact(
+    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
+{
+    switch(code) {
+        case OP_SEND: {
+            CHECK_INTERFACE(IResultReceiver, data, reply);
+            int32_t resultCode = data.readInt32();
+            send(resultCode);
+            if (reply != NULL) {
+                reply->writeNoException();
+            }
+            return NO_ERROR;
+        } break;
+        default:
+            return BBinder::onTransact(code, data, reply, flags);
+    }
+}
+
+}; // namespace android
diff --git a/IServiceManager.cpp b/IServiceManager.cpp
index 3c716df..61f24d6 100644
--- a/IServiceManager.cpp
+++ b/IServiceManager.cpp
@@ -33,7 +33,7 @@
 sp<IServiceManager> defaultServiceManager()
 {
     if (gDefaultServiceManager != NULL) return gDefaultServiceManager;
-    
+
     {
         AutoMutex _l(gDefaultServiceManagerLock);
         while (gDefaultServiceManager == NULL) {
@@ -43,7 +43,7 @@
                 sleep(1);
         }
     }
-    
+
     return gDefaultServiceManager;
 }
 
@@ -67,11 +67,16 @@
 
 bool checkPermission(const String16& permission, pid_t pid, uid_t uid)
 {
+#ifdef __BRILLO__
+    // Brillo doesn't currently run ActivityManager or support framework permissions.
+    return true;
+#endif
+
     sp<IPermissionController> pc;
     gDefaultServiceManagerLock.lock();
     pc = gPermissionController;
     gDefaultServiceManagerLock.unlock();
-    
+
     int64_t startTime = 0;
 
     while (true) {
@@ -85,14 +90,14 @@
                 }
                 return res;
             }
-            
+
             // Is this a permission failure, or did the controller go away?
             if (IInterface::asBinder(pc)->isBinderAlive()) {
                 ALOGW("Permission failure: %s from uid=%d pid=%d",
                         String8(permission).string(), uid, pid);
                 return false;
             }
-            
+
             // Object is dead!
             gDefaultServiceManagerLock.lock();
             if (gPermissionController == pc) {
@@ -100,7 +105,7 @@
             }
             gDefaultServiceManagerLock.unlock();
         }
-    
+
         // Need to retrieve the permission controller.
         sp<IBinder> binder = defaultServiceManager()->checkService(_permission);
         if (binder == NULL) {
@@ -113,7 +118,7 @@
             sleep(1);
         } else {
             pc = interface_cast<IPermissionController>(binder);
-            // Install the new permission controller, and try again.        
+            // Install the new permission controller, and try again.
             gDefaultServiceManagerLock.lock();
             gPermissionController = pc;
             gDefaultServiceManagerLock.unlock();
@@ -184,48 +189,4 @@
 
 IMPLEMENT_META_INTERFACE(ServiceManager, "android.os.IServiceManager");
 
-// ----------------------------------------------------------------------
-
-status_t BnServiceManager::onTransact(
-    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
-{
-    //printf("ServiceManager received: "); data.print();
-    switch(code) {
-        case GET_SERVICE_TRANSACTION: {
-            CHECK_INTERFACE(IServiceManager, data, reply);
-            String16 which = data.readString16();
-            sp<IBinder> b = const_cast<BnServiceManager*>(this)->getService(which);
-            reply->writeStrongBinder(b);
-            return NO_ERROR;
-        } break;
-        case CHECK_SERVICE_TRANSACTION: {
-            CHECK_INTERFACE(IServiceManager, data, reply);
-            String16 which = data.readString16();
-            sp<IBinder> b = const_cast<BnServiceManager*>(this)->checkService(which);
-            reply->writeStrongBinder(b);
-            return NO_ERROR;
-        } break;
-        case ADD_SERVICE_TRANSACTION: {
-            CHECK_INTERFACE(IServiceManager, data, reply);
-            String16 which = data.readString16();
-            sp<IBinder> b = data.readStrongBinder();
-            status_t err = addService(which, b);
-            reply->writeInt32(err);
-            return NO_ERROR;
-        } break;
-        case LIST_SERVICES_TRANSACTION: {
-            CHECK_INTERFACE(IServiceManager, data, reply);
-            Vector<String16> list = listServices();
-            const size_t N = list.size();
-            reply->writeInt32(N);
-            for (size_t i=0; i<N; i++) {
-                reply->writeString16(list[i]);
-            }
-            return NO_ERROR;
-        } break;
-        default:
-            return BBinder::onTransact(code, data, reply, flags);
-    }
-}
-
 }; // namespace android
diff --git a/Parcel.cpp b/Parcel.cpp
index 1429a5c..1008f02 100644
--- a/Parcel.cpp
+++ b/Parcel.cpp
@@ -18,7 +18,9 @@
 //#define LOG_NDEBUG 0
 
 #include <errno.h>
+#include <fcntl.h>
 #include <inttypes.h>
+#include <pthread.h>
 #include <stdint.h>
 #include <stdio.h>
 #include <stdlib.h>
@@ -32,6 +34,7 @@
 #include <binder/IPCThreadState.h>
 #include <binder/Parcel.h>
 #include <binder/ProcessState.h>
+#include <binder/Status.h>
 #include <binder/TextOutput.h>
 
 #include <cutils/ashmem.h>
@@ -71,9 +74,6 @@
 // Note: must be kept in sync with android/os/StrictMode.java's PENALTY_GATHER
 #define STRICT_MODE_PENALTY_GATHER (0x40 << 16)
 
-// Note: must be kept in sync with android/os/Parcel.java's EX_HAS_REPLY_HEADER
-#define EX_HAS_REPLY_HEADER -128
-
 // XXX This can be made public if we want to provide
 // support for typed data.
 struct small_flat_data
@@ -97,6 +97,32 @@
     BLOB_ASHMEM_MUTABLE = 2,
 };
 
+static dev_t ashmem_rdev()
+{
+    static dev_t __ashmem_rdev;
+    static pthread_mutex_t __ashmem_rdev_lock = PTHREAD_MUTEX_INITIALIZER;
+
+    pthread_mutex_lock(&__ashmem_rdev_lock);
+
+    dev_t rdev = __ashmem_rdev;
+    if (!rdev) {
+        int fd = TEMP_FAILURE_RETRY(open("/dev/ashmem", O_RDONLY));
+        if (fd >= 0) {
+            struct stat st;
+
+            int ret = TEMP_FAILURE_RETRY(fstat(fd, &st));
+            close(fd);
+            if ((ret >= 0) && S_ISCHR(st.st_mode)) {
+                rdev = __ashmem_rdev = st.st_rdev;
+            }
+        }
+    }
+
+    pthread_mutex_unlock(&__ashmem_rdev_lock);
+
+    return rdev;
+}
+
 void acquire_object(const sp<ProcessState>& proc,
     const flat_binder_object& obj, const void* who, size_t* outAshmemSize)
 {
@@ -128,7 +154,7 @@
             if ((obj.cookie != 0) && (outAshmemSize != NULL)) {
                 struct stat st;
                 int ret = fstat(obj.handle, &st);
-                if (!ret && S_ISCHR(st.st_mode)) {
+                if (!ret && S_ISCHR(st.st_mode) && (st.st_rdev == ashmem_rdev())) {
                     // If we own an ashmem fd, keep track of how much memory it refers to.
                     int size = ashmem_get_size_region(obj.handle);
                     if (size > 0) {
@@ -181,7 +207,7 @@
                 if (outAshmemSize != NULL) {
                     struct stat st;
                     int ret = fstat(obj.handle, &st);
-                    if (!ret && S_ISCHR(st.st_mode)) {
+                    if (!ret && S_ISCHR(st.st_mode) && (st.st_rdev == ashmem_rdev())) {
                         int size = ashmem_get_size_region(obj.handle);
                         if (size > 0) {
                             *outAshmemSize -= size;
@@ -386,13 +412,11 @@
 
 size_t Parcel::dataAvail() const
 {
-    // TODO: decide what to do about the possibility that this can
-    // report an available-data size that exceeds a Java int's max
-    // positive value, causing havoc.  Fortunately this will only
-    // happen if someone constructs a Parcel containing more than two
-    // gigabytes of data, which on typical phone hardware is simply
-    // not possible.
-    return dataSize() - dataPosition();
+    size_t result = dataSize() - dataPosition();
+    if (result > INT32_MAX) {
+        abort();
+    }
+    return result;
 }
 
 size_t Parcel::dataPosition() const
@@ -753,6 +777,149 @@
     return NULL;
 }
 
+status_t Parcel::writeUtf8AsUtf16(const std::string& str) {
+    const uint8_t* strData = (uint8_t*)str.data();
+    const size_t strLen= str.length();
+    const ssize_t utf16Len = utf8_to_utf16_length(strData, strLen);
+    if (utf16Len < 0 || utf16Len> std::numeric_limits<int32_t>::max()) {
+        return BAD_VALUE;
+    }
+
+    status_t err = writeInt32(utf16Len);
+    if (err) {
+        return err;
+    }
+
+    // Allocate enough bytes to hold our converted string and its terminating NULL.
+    void* dst = writeInplace((utf16Len + 1) * sizeof(char16_t));
+    if (!dst) {
+        return NO_MEMORY;
+    }
+
+    utf8_to_utf16(strData, strLen, (char16_t*)dst);
+
+    return NO_ERROR;
+}
+
+status_t Parcel::writeUtf8AsUtf16(const std::unique_ptr<std::string>& str) {
+  if (!str) {
+    return writeInt32(-1);
+  }
+  return writeUtf8AsUtf16(*str);
+}
+
+status_t Parcel::writeByteVector(const std::unique_ptr<std::vector<int8_t>>& val)
+{
+    if (!val) {
+        return writeInt32(-1);
+    }
+
+    return writeByteVector(*val);
+}
+
+status_t Parcel::writeByteVector(const std::vector<int8_t>& val)
+{
+    status_t status;
+    if (val.size() > std::numeric_limits<int32_t>::max()) {
+        status = BAD_VALUE;
+        return status;
+    }
+
+    status = writeInt32(val.size());
+    if (status != OK) {
+        return status;
+    }
+
+    void* data = writeInplace(val.size());
+    if (!data) {
+        status = BAD_VALUE;
+        return status;
+    }
+
+    memcpy(data, val.data(), val.size());
+    return status;
+}
+
+status_t Parcel::writeInt32Vector(const std::vector<int32_t>& val)
+{
+    return writeTypedVector(val, &Parcel::writeInt32);
+}
+
+status_t Parcel::writeInt32Vector(const std::unique_ptr<std::vector<int32_t>>& val)
+{
+    return writeNullableTypedVector(val, &Parcel::writeInt32);
+}
+
+status_t Parcel::writeInt64Vector(const std::vector<int64_t>& val)
+{
+    return writeTypedVector(val, &Parcel::writeInt64);
+}
+
+status_t Parcel::writeInt64Vector(const std::unique_ptr<std::vector<int64_t>>& val)
+{
+    return writeNullableTypedVector(val, &Parcel::writeInt64);
+}
+
+status_t Parcel::writeFloatVector(const std::vector<float>& val)
+{
+    return writeTypedVector(val, &Parcel::writeFloat);
+}
+
+status_t Parcel::writeFloatVector(const std::unique_ptr<std::vector<float>>& val)
+{
+    return writeNullableTypedVector(val, &Parcel::writeFloat);
+}
+
+status_t Parcel::writeDoubleVector(const std::vector<double>& val)
+{
+    return writeTypedVector(val, &Parcel::writeDouble);
+}
+
+status_t Parcel::writeDoubleVector(const std::unique_ptr<std::vector<double>>& val)
+{
+    return writeNullableTypedVector(val, &Parcel::writeDouble);
+}
+
+status_t Parcel::writeBoolVector(const std::vector<bool>& val)
+{
+    return writeTypedVector(val, &Parcel::writeBool);
+}
+
+status_t Parcel::writeBoolVector(const std::unique_ptr<std::vector<bool>>& val)
+{
+    return writeNullableTypedVector(val, &Parcel::writeBool);
+}
+
+status_t Parcel::writeCharVector(const std::vector<char16_t>& val)
+{
+    return writeTypedVector(val, &Parcel::writeChar);
+}
+
+status_t Parcel::writeCharVector(const std::unique_ptr<std::vector<char16_t>>& val)
+{
+    return writeNullableTypedVector(val, &Parcel::writeChar);
+}
+
+status_t Parcel::writeString16Vector(const std::vector<String16>& val)
+{
+    return writeTypedVector(val, &Parcel::writeString16);
+}
+
+status_t Parcel::writeString16Vector(
+        const std::unique_ptr<std::vector<std::unique_ptr<String16>>>& val)
+{
+    return writeNullableTypedVector(val, &Parcel::writeString16);
+}
+
+status_t Parcel::writeUtf8VectorAsUtf16Vector(
+                        const std::unique_ptr<std::vector<std::unique_ptr<std::string>>>& val) {
+    return writeNullableTypedVector(val, &Parcel::writeUtf8AsUtf16);
+}
+
+status_t Parcel::writeUtf8VectorAsUtf16Vector(const std::vector<std::string>& val) {
+    return writeTypedVector(val, &Parcel::writeUtf8AsUtf16);
+}
+
 status_t Parcel::writeInt32(int32_t val)
 {
     return writeAligned(val);
@@ -796,6 +963,21 @@
     return ret;
 }
 
+status_t Parcel::writeBool(bool val)
+{
+    return writeInt32(int32_t(val));
+}
+
+status_t Parcel::writeChar(char16_t val)
+{
+    return writeInt32(int32_t(val));
+}
+
+status_t Parcel::writeByte(int8_t val)
+{
+    return writeInt32(int32_t(val));
+}
+
 status_t Parcel::writeInt64(int64_t val)
 {
     return writeAligned(val);
@@ -854,6 +1036,15 @@
     return err;
 }
 
+status_t Parcel::writeString16(const std::unique_ptr<String16>& str)
+{
+    if (!str) {
+        return writeInt32(-1);
+    }
+
+    return writeString16(*str);
+}
+
 status_t Parcel::writeString16(const String16& str)
 {
     return writeString16(str.string(), str.size());
@@ -882,11 +1073,45 @@
     return flatten_binder(ProcessState::self(), val, this);
 }
 
+status_t Parcel::writeStrongBinderVector(const std::vector<sp<IBinder>>& val)
+{
+    return writeTypedVector(val, &Parcel::writeStrongBinder);
+}
+
+status_t Parcel::writeStrongBinderVector(const std::unique_ptr<std::vector<sp<IBinder>>>& val)
+{
+    return writeNullableTypedVector(val, &Parcel::writeStrongBinder);
+}
+
+status_t Parcel::readStrongBinderVector(std::unique_ptr<std::vector<sp<IBinder>>>* val) const {
+    return readNullableTypedVector(val, &Parcel::readStrongBinder);
+}
+
+status_t Parcel::readStrongBinderVector(std::vector<sp<IBinder>>* val) const {
+    return readTypedVector(val, &Parcel::readStrongBinder);
+}
+
 status_t Parcel::writeWeakBinder(const wp<IBinder>& val)
 {
     return flatten_binder(ProcessState::self(), val, this);
 }
 
+status_t Parcel::writeRawNullableParcelable(const Parcelable* parcelable) {
+    if (!parcelable) {
+        return writeInt32(0);
+    }
+
+    return writeParcelable(*parcelable);
+}
+
+status_t Parcel::writeParcelable(const Parcelable& parcelable) {
+    status_t status = writeInt32(1);  // parcelable is not null.
+    if (status != OK) {
+        return status;
+    }
+    return parcelable.writeToParcel(this);
+}
+
 status_t Parcel::writeNativeHandle(const native_handle* handle)
 {
     if (!handle || handle->version != sizeof(native_handle))
@@ -928,12 +1153,24 @@
         return -errno;
     }
     status_t err = writeFileDescriptor(dupFd, true /*takeOwnership*/);
-    if (err) {
+    if (err != OK) {
         close(dupFd);
     }
     return err;
 }
 
+status_t Parcel::writeUniqueFileDescriptor(const ScopedFd& fd) {
+    return writeDupFileDescriptor(fd.get());
+}
+
+status_t Parcel::writeUniqueFileDescriptorVector(const std::vector<ScopedFd>& val) {
+    return writeTypedVector(val, &Parcel::writeUniqueFileDescriptor);
+}
+
+status_t Parcel::writeUniqueFileDescriptorVector(const std::unique_ptr<std::vector<ScopedFd>>& val) {
+    return writeNullableTypedVector(val, &Parcel::writeUniqueFileDescriptor);
+}
+
 status_t Parcel::writeBlob(size_t len, bool mutableCopy, WritableBlob* outBlob)
 {
     if (len > INT32_MAX) {
@@ -1085,7 +1322,8 @@
 
 status_t Parcel::writeNoException()
 {
-    return writeInt32(0);
+    binder::Status status;
+    return status.writeToParcel(this);
 }
 
 void Parcel::remove(size_t /*start*/, size_t /*amt*/)
@@ -1168,6 +1406,168 @@
     return err;
 }
 
+status_t Parcel::readByteVector(std::vector<int8_t>* val) const {
+    val->clear();
+
+    int32_t size;
+    status_t status = readInt32(&size);
+
+    if (status != OK) {
+        return status;
+    }
+
+    if (size < 0) {
+        status = UNEXPECTED_NULL;
+        return status;
+    }
+    if (size_t(size) > dataAvail()) {
+        status = BAD_VALUE;
+        return status;
+    }
+
+    const void* data = readInplace(size);
+    if (!data) {
+        status = BAD_VALUE;
+        return status;
+    }
+    val->resize(size);
+    memcpy(val->data(), data, size);
+
+    return status;
+}
+
+status_t Parcel::readByteVector(std::unique_ptr<std::vector<int8_t>>* val) const {
+    const int32_t start = dataPosition();
+    int32_t size;
+    status_t status = readInt32(&size);
+    val->reset();
+
+    if (status != OK || size < 0) {
+        return status;
+    }
+
+    setDataPosition(start);
+    val->reset(new std::vector<int8_t>());
+
+    status = readByteVector(val->get());
+
+    if (status != OK) {
+        val->reset();
+    }
+
+    return status;
+}
+
+status_t Parcel::readInt32Vector(std::unique_ptr<std::vector<int32_t>>* val) const {
+    return readNullableTypedVector(val, &Parcel::readInt32);
+}
+
+status_t Parcel::readInt32Vector(std::vector<int32_t>* val) const {
+    return readTypedVector(val, &Parcel::readInt32);
+}
+
+status_t Parcel::readInt64Vector(std::unique_ptr<std::vector<int64_t>>* val) const {
+    return readNullableTypedVector(val, &Parcel::readInt64);
+}
+
+status_t Parcel::readInt64Vector(std::vector<int64_t>* val) const {
+    return readTypedVector(val, &Parcel::readInt64);
+}
+
+status_t Parcel::readFloatVector(std::unique_ptr<std::vector<float>>* val) const {
+    return readNullableTypedVector(val, &Parcel::readFloat);
+}
+
+status_t Parcel::readFloatVector(std::vector<float>* val) const {
+    return readTypedVector(val, &Parcel::readFloat);
+}
+
+status_t Parcel::readDoubleVector(std::unique_ptr<std::vector<double>>* val) const {
+    return readNullableTypedVector(val, &Parcel::readDouble);
+}
+
+status_t Parcel::readDoubleVector(std::vector<double>* val) const {
+    return readTypedVector(val, &Parcel::readDouble);
+}
+
+status_t Parcel::readBoolVector(std::unique_ptr<std::vector<bool>>* val) const {
+    const int32_t start = dataPosition();
+    int32_t size;
+    status_t status = readInt32(&size);
+    val->reset();
+
+    if (status != OK || size < 0) {
+        return status;
+    }
+
+    setDataPosition(start);
+    val->reset(new std::vector<bool>());
+
+    status = readBoolVector(val->get());
+
+    if (status != OK) {
+        val->reset();
+    }
+
+    return status;
+}
+
+status_t Parcel::readBoolVector(std::vector<bool>* val) const {
+    int32_t size;
+    status_t status = readInt32(&size);
+
+    if (status != OK) {
+        return status;
+    }
+
+    if (size < 0) {
+        return UNEXPECTED_NULL;
+    }
+
+    val->resize(size);
+
+    /* C++ bool handling means a vector of bools isn't necessarily addressable
+     * (we might use individual bits)
+     */
+    bool data;
+    for (int32_t i = 0; i < size; ++i) {
+        status = readBool(&data);
+        (*val)[i] = data;
+
+        if (status != OK) {
+            return status;
+        }
+    }
+
+    return OK;
+}
+
+status_t Parcel::readCharVector(std::unique_ptr<std::vector<char16_t>>* val) const {
+    return readNullableTypedVector(val, &Parcel::readChar);
+}
+
+status_t Parcel::readCharVector(std::vector<char16_t>* val) const {
+    return readTypedVector(val, &Parcel::readChar);
+}
+
+status_t Parcel::readString16Vector(
+        std::unique_ptr<std::vector<std::unique_ptr<String16>>>* val) const {
+    return readNullableTypedVector(val, &Parcel::readString16);
+}
+
+status_t Parcel::readString16Vector(std::vector<String16>* val) const {
+    return readTypedVector(val, &Parcel::readString16);
+}
+
+status_t Parcel::readUtf8VectorFromUtf16Vector(
+        std::unique_ptr<std::vector<std::unique_ptr<std::string>>>* val) const {
+    return readNullableTypedVector(val, &Parcel::readUtf8FromUtf16);
+}
+
+status_t Parcel::readUtf8VectorFromUtf16Vector(std::vector<std::string>* val) const {
+    return readTypedVector(val, &Parcel::readUtf8FromUtf16);
+}
+
 status_t Parcel::readInt32(int32_t *pArg) const
 {
     return readAligned(pArg);
@@ -1286,6 +1686,84 @@
     return readAligned<intptr_t>();
 }
 
+status_t Parcel::readBool(bool *pArg) const
+{
+    int32_t tmp;
+    status_t ret = readInt32(&tmp);
+    *pArg = (tmp != 0);
+    return ret;
+}
+
+bool Parcel::readBool() const
+{
+    return readInt32() != 0;
+}
+
+status_t Parcel::readChar(char16_t *pArg) const
+{
+    int32_t tmp;
+    status_t ret = readInt32(&tmp);
+    *pArg = char16_t(tmp);
+    return ret;
+}
+
+char16_t Parcel::readChar() const
+{
+    return char16_t(readInt32());
+}
+
+status_t Parcel::readByte(int8_t *pArg) const
+{
+    int32_t tmp;
+    status_t ret = readInt32(&tmp);
+    *pArg = int8_t(tmp);
+    return ret;
+}
+
+int8_t Parcel::readByte() const
+{
+    return int8_t(readInt32());
+}
+
+status_t Parcel::readUtf8FromUtf16(std::string* str) const {
+    size_t utf16Size = 0;
+    const char16_t* src = readString16Inplace(&utf16Size);
+    if (!src) {
+        return UNEXPECTED_NULL;
+    }
+
+    // Save ourselves the trouble, we're done.
+    if (utf16Size == 0u) {
+        str->clear();
+       return NO_ERROR;
+    }
+
+    ssize_t utf8Size = utf16_to_utf8_length(src, utf16Size);
+    if (utf8Size < 0) {
+        return BAD_VALUE;
+    }
+    // Note that while it is probably safe to assume string::resize keeps a
+    // spare byte around for the trailing null, we're going to be explicit.
+    str->resize(utf8Size + 1);
+    utf16_to_utf8(src, utf16Size, &((*str)[0]));
+    str->resize(utf8Size);
+    return NO_ERROR;
+}
+
+status_t Parcel::readUtf8FromUtf16(std::unique_ptr<std::string>* str) const {
+    const int32_t start = dataPosition();
+    int32_t size;
+    status_t status = readInt32(&size);
+    str->reset();
+
+    if (status != OK || size < 0) {
+        return status;
+    }
+
+    setDataPosition(start);
+    str->reset(new std::string());
+    return readUtf8FromUtf16(str->get());
+}
 
 const char* Parcel::readCString() const
 {
@@ -1324,6 +1802,42 @@
     return String16();
 }
 
+status_t Parcel::readString16(std::unique_ptr<String16>* pArg) const
+{
+    const int32_t start = dataPosition();
+    int32_t size;
+    status_t status = readInt32(&size);
+    pArg->reset();
+
+    if (status != OK || size < 0) {
+        return status;
+    }
+
+    setDataPosition(start);
+    pArg->reset(new String16());
+
+    status = readString16(pArg->get());
+
+    if (status != OK) {
+        pArg->reset();
+    }
+
+    return status;
+}
+
+status_t Parcel::readString16(String16* pArg) const
+{
+    size_t len;
+    const char16_t* str = readString16Inplace(&len);
+    if (str) {
+        pArg->setTo(str, len);
+        return 0;
+    } else {
+        *pArg = String16();
+        return UNEXPECTED_NULL;
+    }
+}
+
 const char16_t* Parcel::readString16Inplace(size_t* outLen) const
 {
     int32_t size = readInt32();
@@ -1339,10 +1853,15 @@
     return NULL;
 }
 
+status_t Parcel::readStrongBinder(sp<IBinder>* val) const
+{
+    return unflatten_binder(ProcessState::self(), *this, val);
+}
+
 sp<IBinder> Parcel::readStrongBinder() const
 {
     sp<IBinder> val;
-    unflatten_binder(ProcessState::self(), *this, &val);
+    readStrongBinder(&val);
     return val;
 }
 
@@ -1353,20 +1872,23 @@
     return val;
 }
 
+status_t Parcel::readParcelable(Parcelable* parcelable) const {
+    int32_t have_parcelable = 0;
+    status_t status = readInt32(&have_parcelable);
+    if (status != OK) {
+        return status;
+    }
+    if (!have_parcelable) {
+        return UNEXPECTED_NULL;
+    }
+    return parcelable->readFromParcel(this);
+}
+
 int32_t Parcel::readExceptionCode() const
 {
-  int32_t exception_code = readAligned<int32_t>();
-  if (exception_code == EX_HAS_REPLY_HEADER) {
-    int32_t header_start = dataPosition();
-    int32_t header_size = readAligned<int32_t>();
-    // Skip over fat responses headers.  Not used (or propagated) in
-    // native code
-    setDataPosition(header_start + header_size);
-    // And fat response headers are currently only used when there are no
-    // exceptions, so return no error:
-    return 0;
-  }
-  return exception_code;
+    binder::Status status;
+    status.readFromParcel(*this);
+    return status.exceptionCode();
 }
 
 native_handle* Parcel::readNativeHandle() const
@@ -1400,16 +1922,40 @@
 int Parcel::readFileDescriptor() const
 {
     const flat_binder_object* flat = readObject(true);
-    if (flat) {
-        switch (flat->type) {
-            case BINDER_TYPE_FD:
-                //ALOGI("Returning file descriptor %ld from parcel %p", flat->handle, this);
-                return flat->handle;
-        }
+
+    if (flat && flat->type == BINDER_TYPE_FD) {
+        return flat->handle;
     }
+
     return BAD_TYPE;
 }
 
+status_t Parcel::readUniqueFileDescriptor(ScopedFd* val) const
+{
+    int got = readFileDescriptor();
+
+    if (got == BAD_TYPE) {
+        return BAD_TYPE;
+    }
+
+    val->reset(dup(got));
+
+    if (val->get() < 0) {
+        return BAD_VALUE;
+    }
+
+    return OK;
+}
+
+
+status_t Parcel::readUniqueFileDescriptorVector(std::unique_ptr<std::vector<ScopedFd>>* val) const {
+    return readNullableTypedVector(val, &Parcel::readUniqueFileDescriptor);
+}
+
+status_t Parcel::readUniqueFileDescriptorVector(std::vector<ScopedFd>* val) const {
+    return readTypedVector(val, &Parcel::readUniqueFileDescriptor);
+}
+
 status_t Parcel::readBlob(size_t len, ReadableBlob* outBlob) const
 {
     int32_t blobType;
@@ -1679,8 +2225,14 @@
         if (mData) {
             LOG_ALLOC("Parcel %p: freeing with %zu capacity", this, mDataCapacity);
             pthread_mutex_lock(&gParcelGlobalAllocSizeLock);
-            gParcelGlobalAllocSize -= mDataCapacity;
-            gParcelGlobalAllocCount--;
+            if (mDataCapacity <= gParcelGlobalAllocSize) {
+              gParcelGlobalAllocSize = gParcelGlobalAllocSize - mDataCapacity;
+            } else {
+              gParcelGlobalAllocSize = 0;
+            }
+            if (gParcelGlobalAllocCount > 0) {
+              gParcelGlobalAllocCount--;
+            }
             pthread_mutex_unlock(&gParcelGlobalAllocSizeLock);
             free(mData);
         }
@@ -1728,6 +2280,9 @@
         pthread_mutex_lock(&gParcelGlobalAllocSizeLock);
         gParcelGlobalAllocSize += desired;
         gParcelGlobalAllocSize -= mDataCapacity;
+        if (!mData) {
+            gParcelGlobalAllocCount++;
+        }
         pthread_mutex_unlock(&gParcelGlobalAllocSizeLock);
         mData = data;
         mDataCapacity = desired;
diff --git a/PersistableBundle.cpp b/PersistableBundle.cpp
new file mode 100644
index 0000000..aef791c
--- /dev/null
+++ b/PersistableBundle.cpp
@@ -0,0 +1,434 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define LOG_TAG "PersistableBundle"
+
+#include <binder/PersistableBundle.h>
+
+#include <limits>
+
+#include <binder/IBinder.h>
+#include <binder/Parcel.h>
+#include <log/log.h>
+#include <utils/Errors.h>
+
+using android::BAD_TYPE;
+using android::BAD_VALUE;
+using android::NO_ERROR;
+using android::Parcel;
+using android::sp;
+using android::status_t;
+using android::UNEXPECTED_NULL;
+
+enum {
+    // Keep in sync with BUNDLE_MAGIC in frameworks/base/core/java/android/os/BaseBundle.java.
+    BUNDLE_MAGIC = 0x4C444E42,
+};
+
+enum {
+    // Keep in sync with frameworks/base/core/java/android/os/Parcel.java.
+    VAL_STRING = 0,
+    VAL_INTEGER = 1,
+    VAL_LONG = 6,
+    VAL_DOUBLE = 8,
+    VAL_BOOLEAN = 9,
+    VAL_STRINGARRAY = 14,
+    VAL_INTARRAY = 18,
+    VAL_LONGARRAY = 19,
+    VAL_BOOLEANARRAY = 23,
+    VAL_PERSISTABLEBUNDLE = 25,
+    VAL_DOUBLEARRAY = 28,
+};
+
+namespace {
+template <typename T>
+bool getValue(const android::String16& key, T* out, const std::map<android::String16, T>& map) {
+    const auto& it = map.find(key);
+    if (it == map.end()) return false;
+    *out = it->second;
+    return true;
+}
+}  // namespace
+
+namespace android {
+
+namespace os {
+
+#define RETURN_IF_FAILED(calledOnce)                                     \
+    {                                                                    \
+        status_t returnStatus = calledOnce;                              \
+        if (returnStatus) {                                              \
+            ALOGE("Failed at %s:%d (%s)", __FILE__, __LINE__, __func__); \
+            return returnStatus;                                         \
+         }                                                               \
+    }
+
+#define RETURN_IF_ENTRY_ERASED(map, key)                                 \
+    {                                                                    \
+        size_t num_erased = map.erase(key);                              \
+        if (num_erased) {                                                \
+            ALOGE("Failed at %s:%d (%s)", __FILE__, __LINE__, __func__); \
+            return num_erased;                                           \
+         }                                                               \
+    }
+
+status_t PersistableBundle::writeToParcel(Parcel* parcel) const {
+    /*
+     * Keep implementation in sync with writeToParcelInner() in
+     * frameworks/base/core/java/android/os/BaseBundle.java.
+     */
+
+    // Special case for empty bundles.
+    if (empty()) {
+        RETURN_IF_FAILED(parcel->writeInt32(0));
+        return NO_ERROR;
+    }
+
+    size_t length_pos = parcel->dataPosition();
+    RETURN_IF_FAILED(parcel->writeInt32(1));  // dummy, will hold length
+    RETURN_IF_FAILED(parcel->writeInt32(BUNDLE_MAGIC));
+
+    size_t start_pos = parcel->dataPosition();
+    RETURN_IF_FAILED(writeToParcelInner(parcel));
+    size_t end_pos = parcel->dataPosition();
+
+    // Backpatch length. This length value includes the length header.
+    parcel->setDataPosition(length_pos);
+    size_t length = end_pos - start_pos;
+    if (length > std::numeric_limits<int32_t>::max()) {
+        ALOGE("Parcel length (%zu) too large to store in 32-bit signed int", length);
+        return BAD_VALUE;
+    }
+    RETURN_IF_FAILED(parcel->writeInt32(static_cast<int32_t>(length)));
+    parcel->setDataPosition(end_pos);
+    return NO_ERROR;
+}
+
+status_t PersistableBundle::readFromParcel(const Parcel* parcel) {
+    /*
+     * Keep implementation in sync with readFromParcelInner() in
+     * frameworks/base/core/java/android/os/BaseBundle.java.
+     */
+    int32_t length = parcel->readInt32();
+    if (length < 0) {
+        ALOGE("Bad length in parcel: %d", length);
+        return UNEXPECTED_NULL;
+    }
+
+    return readFromParcelInner(parcel, static_cast<size_t>(length));
+}
+
+bool PersistableBundle::empty() const {
+    return size() == 0u;
+}
+
+size_t PersistableBundle::size() const {
+    return (mBoolMap.size() +
+            mIntMap.size() +
+            mLongMap.size() +
+            mDoubleMap.size() +
+            mStringMap.size() +
+            mBoolVectorMap.size() +
+            mIntVectorMap.size() +
+            mLongVectorMap.size() +
+            mDoubleVectorMap.size() +
+            mStringVectorMap.size() +
+            mPersistableBundleMap.size());
+}
+
+size_t PersistableBundle::erase(const String16& key) {
+    RETURN_IF_ENTRY_ERASED(mBoolMap, key);
+    RETURN_IF_ENTRY_ERASED(mIntMap, key);
+    RETURN_IF_ENTRY_ERASED(mLongMap, key);
+    RETURN_IF_ENTRY_ERASED(mDoubleMap, key);
+    RETURN_IF_ENTRY_ERASED(mStringMap, key);
+    RETURN_IF_ENTRY_ERASED(mBoolVectorMap, key);
+    RETURN_IF_ENTRY_ERASED(mIntVectorMap, key);
+    RETURN_IF_ENTRY_ERASED(mLongVectorMap, key);
+    RETURN_IF_ENTRY_ERASED(mDoubleVectorMap, key);
+    RETURN_IF_ENTRY_ERASED(mStringVectorMap, key);
+    return mPersistableBundleMap.erase(key);
+}
+
+void PersistableBundle::putBoolean(const String16& key, bool value) {
+    erase(key);
+    mBoolMap[key] = value;
+}
+
+void PersistableBundle::putInt(const String16& key, int32_t value) {
+    erase(key);
+    mIntMap[key] = value;
+}
+
+void PersistableBundle::putLong(const String16& key, int64_t value) {
+    erase(key);
+    mLongMap[key] = value;
+}
+
+void PersistableBundle::putDouble(const String16& key, double value) {
+    erase(key);
+    mDoubleMap[key] = value;
+}
+
+void PersistableBundle::putString(const String16& key, const String16& value) {
+    erase(key);
+    mStringMap[key] = value;
+}
+
+void PersistableBundle::putBooleanVector(const String16& key, const std::vector<bool>& value) {
+    erase(key);
+    mBoolVectorMap[key] = value;
+}
+
+void PersistableBundle::putIntVector(const String16& key, const std::vector<int32_t>& value) {
+    erase(key);
+    mIntVectorMap[key] = value;
+}
+
+void PersistableBundle::putLongVector(const String16& key, const std::vector<int64_t>& value) {
+    erase(key);
+    mLongVectorMap[key] = value;
+}
+
+void PersistableBundle::putDoubleVector(const String16& key, const std::vector<double>& value) {
+    erase(key);
+    mDoubleVectorMap[key] = value;
+}
+
+void PersistableBundle::putStringVector(const String16& key, const std::vector<String16>& value) {
+    erase(key);
+    mStringVectorMap[key] = value;
+}
+
+void PersistableBundle::putPersistableBundle(const String16& key, const PersistableBundle& value) {
+    erase(key);
+    mPersistableBundleMap[key] = value;
+}
+
+bool PersistableBundle::getBoolean(const String16& key, bool* out) const {
+    return getValue(key, out, mBoolMap);
+}
+
+bool PersistableBundle::getInt(const String16& key, int32_t* out) const {
+    return getValue(key, out, mIntMap);
+}
+
+bool PersistableBundle::getLong(const String16& key, int64_t* out) const {
+    return getValue(key, out, mLongMap);
+}
+
+bool PersistableBundle::getDouble(const String16& key, double* out) const {
+    return getValue(key, out, mDoubleMap);
+}
+
+bool PersistableBundle::getString(const String16& key, String16* out) const {
+    return getValue(key, out, mStringMap);
+}
+
+bool PersistableBundle::getBooleanVector(const String16& key, std::vector<bool>* out) const {
+    return getValue(key, out, mBoolVectorMap);
+}
+
+bool PersistableBundle::getIntVector(const String16& key, std::vector<int32_t>* out) const {
+    return getValue(key, out, mIntVectorMap);
+}
+
+bool PersistableBundle::getLongVector(const String16& key, std::vector<int64_t>* out) const {
+    return getValue(key, out, mLongVectorMap);
+}
+
+bool PersistableBundle::getDoubleVector(const String16& key, std::vector<double>* out) const {
+    return getValue(key, out, mDoubleVectorMap);
+}
+
+bool PersistableBundle::getStringVector(const String16& key, std::vector<String16>* out) const {
+    return getValue(key, out, mStringVectorMap);
+}
+
+bool PersistableBundle::getPersistableBundle(const String16& key, PersistableBundle* out) const {
+    return getValue(key, out, mPersistableBundleMap);
+}
+
+status_t PersistableBundle::writeToParcelInner(Parcel* parcel) const {
+    /*
+     * To keep this implementation in sync with writeArrayMapInternal() in
+     * frameworks/base/core/java/android/os/Parcel.java, the number of key
+     * value pairs must be written into the parcel before writing the key-value
+     * pairs themselves.
+     */
+    size_t num_entries = size();
+    if (num_entries > std::numeric_limits<int32_t>::max()) {
+        ALOGE("The size of this PersistableBundle (%zu) too large to store in 32-bit signed int",
+              num_entries);
+        return BAD_VALUE;
+    }
+    RETURN_IF_FAILED(parcel->writeInt32(static_cast<int32_t>(num_entries)));
+
+    for (const auto& key_val_pair : mBoolMap) {
+        RETURN_IF_FAILED(parcel->writeString16(key_val_pair.first));
+        RETURN_IF_FAILED(parcel->writeInt32(VAL_BOOLEAN));
+        RETURN_IF_FAILED(parcel->writeBool(key_val_pair.second));
+    }
+    for (const auto& key_val_pair : mIntMap) {
+        RETURN_IF_FAILED(parcel->writeString16(key_val_pair.first));
+        RETURN_IF_FAILED(parcel->writeInt32(VAL_INTEGER));
+        RETURN_IF_FAILED(parcel->writeInt32(key_val_pair.second));
+    }
+    for (const auto& key_val_pair : mLongMap) {
+        RETURN_IF_FAILED(parcel->writeString16(key_val_pair.first));
+        RETURN_IF_FAILED(parcel->writeInt32(VAL_LONG));
+        RETURN_IF_FAILED(parcel->writeInt64(key_val_pair.second));
+    }
+    for (const auto& key_val_pair : mDoubleMap) {
+        RETURN_IF_FAILED(parcel->writeString16(key_val_pair.first));
+        RETURN_IF_FAILED(parcel->writeInt32(VAL_DOUBLE));
+        RETURN_IF_FAILED(parcel->writeDouble(key_val_pair.second));
+    }
+    for (const auto& key_val_pair : mStringMap) {
+        RETURN_IF_FAILED(parcel->writeString16(key_val_pair.first));
+        RETURN_IF_FAILED(parcel->writeInt32(VAL_STRING));
+        RETURN_IF_FAILED(parcel->writeString16(key_val_pair.second));
+    }
+    for (const auto& key_val_pair : mBoolVectorMap) {
+        RETURN_IF_FAILED(parcel->writeString16(key_val_pair.first));
+        RETURN_IF_FAILED(parcel->writeInt32(VAL_BOOLEANARRAY));
+        RETURN_IF_FAILED(parcel->writeBoolVector(key_val_pair.second));
+    }
+    for (const auto& key_val_pair : mIntVectorMap) {
+        RETURN_IF_FAILED(parcel->writeString16(key_val_pair.first));
+        RETURN_IF_FAILED(parcel->writeInt32(VAL_INTARRAY));
+        RETURN_IF_FAILED(parcel->writeInt32Vector(key_val_pair.second));
+    }
+    for (const auto& key_val_pair : mLongVectorMap) {
+        RETURN_IF_FAILED(parcel->writeString16(key_val_pair.first));
+        RETURN_IF_FAILED(parcel->writeInt32(VAL_LONGARRAY));
+        RETURN_IF_FAILED(parcel->writeInt64Vector(key_val_pair.second));
+    }
+    for (const auto& key_val_pair : mDoubleVectorMap) {
+        RETURN_IF_FAILED(parcel->writeString16(key_val_pair.first));
+        RETURN_IF_FAILED(parcel->writeInt32(VAL_DOUBLEARRAY));
+        RETURN_IF_FAILED(parcel->writeDoubleVector(key_val_pair.second));
+    }
+    for (const auto& key_val_pair : mStringVectorMap) {
+        RETURN_IF_FAILED(parcel->writeString16(key_val_pair.first));
+        RETURN_IF_FAILED(parcel->writeInt32(VAL_STRINGARRAY));
+        RETURN_IF_FAILED(parcel->writeString16Vector(key_val_pair.second));
+    }
+    for (const auto& key_val_pair : mPersistableBundleMap) {
+        RETURN_IF_FAILED(parcel->writeString16(key_val_pair.first));
+        RETURN_IF_FAILED(parcel->writeInt32(VAL_PERSISTABLEBUNDLE));
+        RETURN_IF_FAILED(key_val_pair.second.writeToParcel(parcel));
+    }
+    return NO_ERROR;
+}
+
+status_t PersistableBundle::readFromParcelInner(const Parcel* parcel, size_t length) {
+    /*
+     * Note: we don't actually use length for anything other than an empty PersistableBundle
+     * check, since we do not actually need to copy in an entire Parcel, unlike in the Java
+     * implementation.
+     */
+    if (length == 0) {
+        // Empty PersistableBundle or end of data.
+        return NO_ERROR;
+    }
+
+    int32_t magic;
+    RETURN_IF_FAILED(parcel->readInt32(&magic));
+    if (magic != BUNDLE_MAGIC) {
+        ALOGE("Bad magic number for PersistableBundle: 0x%08x", magic);
+        return BAD_VALUE;
+    }
+
+    /*
+     * To keep this implementation in sync with unparcel() in
+     * frameworks/base/core/java/android/os/BaseBundle.java, the number of
+     * key-value pairs must be read from the parcel before reading the key-value
+     * pairs themselves.
+     */
+    int32_t num_entries;
+    RETURN_IF_FAILED(parcel->readInt32(&num_entries));
+
+    for (; num_entries > 0; --num_entries) {
+        size_t start_pos = parcel->dataPosition();
+        String16 key;
+        int32_t value_type;
+        RETURN_IF_FAILED(parcel->readString16(&key));
+        RETURN_IF_FAILED(parcel->readInt32(&value_type));
+
+        /*
+         * We assume that both the C++ and Java APIs ensure that all keys in a PersistableBundle
+         * are unique.
+         */
+        switch (value_type) {
+            case VAL_STRING: {
+                RETURN_IF_FAILED(parcel->readString16(&mStringMap[key]));
+                break;
+            }
+            case VAL_INTEGER: {
+                RETURN_IF_FAILED(parcel->readInt32(&mIntMap[key]));
+                break;
+            }
+            case VAL_LONG: {
+                RETURN_IF_FAILED(parcel->readInt64(&mLongMap[key]));
+                break;
+            }
+            case VAL_DOUBLE: {
+                RETURN_IF_FAILED(parcel->readDouble(&mDoubleMap[key]));
+                break;
+            }
+            case VAL_BOOLEAN: {
+                RETURN_IF_FAILED(parcel->readBool(&mBoolMap[key]));
+                break;
+            }
+            case VAL_STRINGARRAY: {
+                RETURN_IF_FAILED(parcel->readString16Vector(&mStringVectorMap[key]));
+                break;
+            }
+            case VAL_INTARRAY: {
+                RETURN_IF_FAILED(parcel->readInt32Vector(&mIntVectorMap[key]));
+                break;
+            }
+            case VAL_LONGARRAY: {
+                RETURN_IF_FAILED(parcel->readInt64Vector(&mLongVectorMap[key]));
+                break;
+            }
+            case VAL_BOOLEANARRAY: {
+                RETURN_IF_FAILED(parcel->readBoolVector(&mBoolVectorMap[key]));
+                break;
+            }
+            case VAL_PERSISTABLEBUNDLE: {
+                RETURN_IF_FAILED(mPersistableBundleMap[key].readFromParcel(parcel));
+                break;
+            }
+            case VAL_DOUBLEARRAY: {
+                RETURN_IF_FAILED(parcel->readDoubleVector(&mDoubleVectorMap[key]));
+                break;
+            }
+            default: {
+                ALOGE("Unrecognized type: %d", value_type);
+                return BAD_TYPE;
+                break;
+            }
+        }
+    }
+
+    return NO_ERROR;
+}
+
+}  // namespace os
+
+}  // namespace android
diff --git a/ProcessState.cpp b/ProcessState.cpp
index 016d3c5..33fe26c 100644
--- a/ProcessState.cpp
+++ b/ProcessState.cpp
@@ -310,9 +310,8 @@
 
 static int open_driver()
 {
-    int fd = open("/dev/binder", O_RDWR);
+    int fd = open("/dev/binder", O_RDWR | O_CLOEXEC);
     if (fd >= 0) {
-        fcntl(fd, F_SETFD, FD_CLOEXEC);
         int vers = 0;
         status_t result = ioctl(fd, BINDER_VERSION, &vers);
         if (result == -1) {
@@ -350,10 +349,6 @@
     , mThreadPoolSeq(1)
 {
     if (mDriverFD >= 0) {
-        // XXX Ideally, there should be a specific define for whether we
-        // have mmap (or whether we could possibly have the kernel module
-        // availabla).
-#if !defined(HAVE_WIN32_IPC)
         // mmap the binder, providing a chunk of virtual address space to receive transactions.
         mVMStart = mmap(0, BINDER_VM_SIZE, PROT_READ, MAP_PRIVATE | MAP_NORESERVE, mDriverFD, 0);
         if (mVMStart == MAP_FAILED) {
@@ -362,9 +357,6 @@
             close(mDriverFD);
             mDriverFD = -1;
         }
-#else
-        mDriverFD = -1;
-#endif
     }
 
     LOG_ALWAYS_FATAL_IF(mDriverFD < 0, "Binder driver could not be opened.  Terminating.");
diff --git a/Status.cpp b/Status.cpp
new file mode 100644
index 0000000..d3520d6
--- /dev/null
+++ b/Status.cpp
@@ -0,0 +1,162 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <binder/Status.h>
+
+namespace android {
+namespace binder {
+
+Status Status::ok() {
+    return Status();
+}
+
+Status Status::fromExceptionCode(int32_t exceptionCode) {
+    return Status(exceptionCode, OK);
+}
+
+Status Status::fromExceptionCode(int32_t exceptionCode,
+                                 const String8& message) {
+    return Status(exceptionCode, OK, message);
+}
+
+Status Status::fromServiceSpecificError(int32_t serviceSpecificErrorCode) {
+    return Status(EX_SERVICE_SPECIFIC, serviceSpecificErrorCode);
+}
+
+Status Status::fromServiceSpecificError(int32_t serviceSpecificErrorCode,
+                                        const String8& message) {
+    return Status(EX_SERVICE_SPECIFIC, serviceSpecificErrorCode, message);
+}
+
+Status Status::fromStatusT(status_t status) {
+    Status ret;
+    ret.setFromStatusT(status);
+    return ret;
+}
+
+Status::Status(int32_t exceptionCode, int32_t errorCode)
+    : mException(exceptionCode),
+      mErrorCode(errorCode) {}
+
+Status::Status(int32_t exceptionCode, int32_t errorCode, const String8& message)
+    : mException(exceptionCode),
+      mErrorCode(errorCode),
+      mMessage(message) {}
+
+status_t Status::readFromParcel(const Parcel& parcel) {
+    status_t status = parcel.readInt32(&mException);
+    if (status != OK) {
+        setFromStatusT(status);
+        return status;
+    }
+
+    // Skip over fat response headers.  Not used (or propagated) in native code.
+    if (mException == EX_HAS_REPLY_HEADER) {
+        // Note that the header size includes the 4 byte size field.
+        const int32_t header_start = parcel.dataPosition();
+        int32_t header_size;
+        status = parcel.readInt32(&header_size);
+        if (status != OK) {
+            setFromStatusT(status);
+            return status;
+        }
+        parcel.setDataPosition(header_start + header_size);
+        // And fat response headers are currently only used when there are no
+        // exceptions, so act like there was no error.
+        mException = EX_NONE;
+    }
+
+    if (mException == EX_NONE) {
+        return status;
+    }
+
+    // The remote threw an exception.  Get the message back.
+    String16 message;
+    status = parcel.readString16(&message);
+    if (status != OK) {
+        setFromStatusT(status);
+        return status;
+    }
+    mMessage = String8(message);
+
+    if (mException == EX_SERVICE_SPECIFIC) {
+        status = parcel.readInt32(&mErrorCode);
+    }
+    if (status != OK) {
+        setFromStatusT(status);
+        return status;
+    }
+
+    return status;
+}
+
+status_t Status::writeToParcel(Parcel* parcel) const {
+    // Something really bad has happened, and we're not going to even
+    // try returning rich error data.
+    if (mException == EX_TRANSACTION_FAILED) {
+        return mErrorCode;
+    }
+
+    status_t status = parcel->writeInt32(mException);
+    if (status != OK) { return status; }
+    if (mException == EX_NONE) {
+        // We have no more information to write.
+        return status;
+    }
+    status = parcel->writeString16(String16(mMessage));
+    if (mException != EX_SERVICE_SPECIFIC) {
+        // We have no more information to write.
+        return status;
+    }
+    status = parcel->writeInt32(mErrorCode);
+    return status;
+}
+
+void Status::setException(int32_t ex, const String8& message) {
+    mException = ex;
+    mErrorCode = NO_ERROR;  // an exception, not a transaction failure.
+    mMessage.setTo(message);
+}
+
+void Status::setServiceSpecificError(int32_t errorCode, const String8& message) {
+    setException(EX_SERVICE_SPECIFIC, message);
+    mErrorCode = errorCode;
+}
+
+void Status::setFromStatusT(status_t status) {
+    mException = (status == NO_ERROR) ? EX_NONE : EX_TRANSACTION_FAILED;
+    mErrorCode = status;
+    mMessage.clear();
+}
+
+String8 Status::toString8() const {
+    String8 ret;
+    if (mException == EX_NONE) {
+        ret.append("No error");
+    } else {
+        ret.appendFormat("Status(%d): '", mException);
+        if (mException == EX_SERVICE_SPECIFIC ||
+            mException == EX_TRANSACTION_FAILED) {
+            ret.appendFormat("%d: ", mErrorCode);
+        }
+        ret.append(String8(mMessage));
+        ret.append("'");
+    }
+    return ret;
+}
+
+}  // namespace binder
+}  // namespace android
diff --git a/include/hwbinder/Binder.h b/include/hwbinder/Binder.h
index 86628a0..f849fd4 100644
--- a/include/hwbinder/Binder.h
+++ b/include/hwbinder/Binder.h
@@ -17,7 +17,7 @@
 #ifndef ANDROID_BINDER_H
 #define ANDROID_BINDER_H
 
-#include <stdatomic.h>
+#include <atomic>
 #include <stdint.h>
 #include <binder/IBinder.h>
 
@@ -71,7 +71,7 @@
 
     class Extras;
 
-    atomic_uintptr_t    mExtras;  // should be atomic<Extras *>
+    std::atomic<Extras*> mExtras;
             void*       mReserved0;
 };
 
@@ -95,7 +95,7 @@
 
     IBinder* const          mRemote;
     RefBase::weakref_type*  mRefs;
-    volatile int32_t        mState;
+    std::atomic<int32_t>    mState;
 };
 
 }; // namespace android
diff --git a/include/hwbinder/IBinder.h b/include/hwbinder/IBinder.h
index 43b6543..5f1e87c 100644
--- a/include/hwbinder/IBinder.h
+++ b/include/hwbinder/IBinder.h
@@ -23,8 +23,12 @@
 #include <utils/Vector.h>
 
 
+// linux/binder.h already defines this, but we can't just include it from there
+// because there are host builds that include this file.
+#ifndef B_PACK_CHARS
 #define B_PACK_CHARS(c1, c2, c3, c4) \
     ((((c1)<<24)) | (((c2)<<16)) | (((c3)<<8)) | (c4))
+#endif  // B_PACK_CHARS
 
 // ---------------------------------------------------------------------------
 namespace android {
@@ -33,6 +37,7 @@
 class BpBinder;
 class IInterface;
 class Parcel;
+class IResultReceiver;
 
 /**
  * Base class and low-level protocol for a remotable object.
@@ -50,6 +55,7 @@
 
         PING_TRANSACTION        = B_PACK_CHARS('_','P','N','G'),
         DUMP_TRANSACTION        = B_PACK_CHARS('_','D','M','P'),
+        SHELL_COMMAND_TRANSACTION = B_PACK_CHARS('_','C','M','D'),
         INTERFACE_TRANSACTION   = B_PACK_CHARS('_', 'N', 'T', 'F'),
         SYSPROPS_TRANSACTION    = B_PACK_CHARS('_', 'S', 'P', 'R'),
 
@@ -75,6 +81,9 @@
     virtual bool            isBinderAlive() const = 0;
     virtual status_t        pingBinder() = 0;
     virtual status_t        dump(int fd, const Vector<String16>& args) = 0;
+    static  status_t        shellCommand(const sp<IBinder>& target, int in, int out, int err,
+                                         Vector<String16>& args,
+                                         const sp<IResultReceiver>& resultReceiver);
 
     virtual status_t        transact(   uint32_t code,
                                         const Parcel& data,
diff --git a/include/hwbinder/IMediaResourceMonitor.h b/include/hwbinder/IMediaResourceMonitor.h
new file mode 100644
index 0000000..b7b9c50
--- /dev/null
+++ b/include/hwbinder/IMediaResourceMonitor.h
@@ -0,0 +1,50 @@
+/*
+ * Copyright 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ANDROID_I_MEDIA_RESOURCE_MONITOR_H
+#define ANDROID_I_MEDIA_RESOURCE_MONITOR_H
+
+#include <binder/IInterface.h>
+
+namespace android {
+
+// ----------------------------------------------------------------------
+
+class IMediaResourceMonitor : public IInterface {
+public:
+    DECLARE_META_INTERFACE(MediaResourceMonitor);
+
+    virtual void notifyResourceGranted(/*in*/ int32_t pid, /*in*/ const String16& type,
+            /*in*/ const String16& subType, /*in*/ int64_t value) = 0;
+
+    enum {
+        NOTIFY_RESOURCE_GRANTED = IBinder::FIRST_CALL_TRANSACTION,
+    };
+};
+
+// ----------------------------------------------------------------------
+
+class BnMediaResourceMonitor : public BnInterface<IMediaResourceMonitor> {
+public:
+    virtual status_t onTransact(uint32_t code, const Parcel& data, Parcel* reply,
+            uint32_t flags = 0);
+};
+
+// ----------------------------------------------------------------------
+
+}; // namespace android
+
+#endif // ANDROID_I_MEDIA_RESOURCE_MONITOR_H
diff --git a/include/hwbinder/IProcessInfoService.h b/include/hwbinder/IProcessInfoService.h
index dc62f45..34ce0f0 100644
--- a/include/hwbinder/IProcessInfoService.h
+++ b/include/hwbinder/IProcessInfoService.h
@@ -31,8 +31,14 @@
                                                   /*in*/ int32_t* pids,
                                                   /*out*/ int32_t* states) = 0;
 
+    virtual status_t    getProcessStatesAndOomScoresFromPids( size_t length,
+                                                  /*in*/ int32_t* pids,
+                                                  /*out*/ int32_t* states,
+                                                  /*out*/ int32_t* scores) = 0;
+
     enum {
         GET_PROCESS_STATES_FROM_PIDS = IBinder::FIRST_CALL_TRANSACTION,
+        GET_PROCESS_STATES_AND_OOM_SCORES_FROM_PIDS,
     };
 };
 
diff --git a/include/hwbinder/IResultReceiver.h b/include/hwbinder/IResultReceiver.h
new file mode 100644
index 0000000..02dc6a6
--- /dev/null
+++ b/include/hwbinder/IResultReceiver.h
@@ -0,0 +1,55 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+//
+#ifndef ANDROID_IRESULT_RECEIVER_H
+#define ANDROID_IRESULT_RECEIVER_H
+
+#include <binder/IInterface.h>
+
+namespace android {
+
+// ----------------------------------------------------------------------
+
+class IResultReceiver : public IInterface
+{
+public:
+    DECLARE_META_INTERFACE(ResultReceiver);
+
+    virtual void send(int32_t resultCode) = 0;
+
+    enum {
+        OP_SEND = IBinder::FIRST_CALL_TRANSACTION
+    };
+};
+
+// ----------------------------------------------------------------------
+
+class BnResultReceiver : public BnInterface<IResultReceiver>
+{
+public:
+    virtual status_t    onTransact( uint32_t code,
+                                    const Parcel& data,
+                                    Parcel* reply,
+                                    uint32_t flags = 0);
+};
+
+// ----------------------------------------------------------------------
+
+}; // namespace android
+
+#endif // ANDROID_IRESULT_RECEIVER_H
+
diff --git a/include/hwbinder/IServiceManager.h b/include/hwbinder/IServiceManager.h
index 2c297d6..7ccd9fe 100644
--- a/include/hwbinder/IServiceManager.h
+++ b/include/hwbinder/IServiceManager.h
@@ -81,20 +81,6 @@
                             int32_t* outPid, int32_t* outUid);
 bool checkPermission(const String16& permission, pid_t pid, uid_t uid);
 
-
-// ----------------------------------------------------------------------
-
-class BnServiceManager : public BnInterface<IServiceManager>
-{
-public:
-    virtual status_t    onTransact( uint32_t code,
-                                    const Parcel& data,
-                                    Parcel* reply,
-                                    uint32_t flags = 0);
-};
-
-// ----------------------------------------------------------------------
-
 }; // namespace android
 
 #endif // ANDROID_ISERVICE_MANAGER_H
diff --git a/include/hwbinder/Parcel.h b/include/hwbinder/Parcel.h
index 16cd6cf..5956e13 100644
--- a/include/hwbinder/Parcel.h
+++ b/include/hwbinder/Parcel.h
@@ -17,7 +17,11 @@
 #ifndef ANDROID_PARCEL_H
 #define ANDROID_PARCEL_H
 
+#include <string>
+#include <vector>
+
 #include <cutils/native_handle.h>
+#include <nativehelper/ScopedFd.h>
 #include <utils/Errors.h>
 #include <utils/RefBase.h>
 #include <utils/String16.h>
@@ -25,6 +29,9 @@
 #include <utils/Flattenable.h>
 #include <linux/binder.h>
 
+#include <binder/IInterface.h>
+#include <binder/Parcelable.h>
+
 // ---------------------------------------------------------------------------
 namespace android {
 
@@ -103,11 +110,53 @@
     status_t            writeCString(const char* str);
     status_t            writeString8(const String8& str);
     status_t            writeString16(const String16& str);
+    status_t            writeString16(const std::unique_ptr<String16>& str);
     status_t            writeString16(const char16_t* str, size_t len);
     status_t            writeStrongBinder(const sp<IBinder>& val);
     status_t            writeWeakBinder(const wp<IBinder>& val);
     status_t            writeInt32Array(size_t len, const int32_t *val);
     status_t            writeByteArray(size_t len, const uint8_t *val);
+    status_t            writeBool(bool val);
+    status_t            writeChar(char16_t val);
+    status_t            writeByte(int8_t val);
+
+    // Take a UTF8 encoded string, convert to UTF16, write it to the parcel.
+    status_t            writeUtf8AsUtf16(const std::string& str);
+    status_t            writeUtf8AsUtf16(const std::unique_ptr<std::string>& str);
+
+    status_t            writeByteVector(const std::unique_ptr<std::vector<int8_t>>& val);
+    status_t            writeByteVector(const std::vector<int8_t>& val);
+    status_t            writeInt32Vector(const std::unique_ptr<std::vector<int32_t>>& val);
+    status_t            writeInt32Vector(const std::vector<int32_t>& val);
+    status_t            writeInt64Vector(const std::unique_ptr<std::vector<int64_t>>& val);
+    status_t            writeInt64Vector(const std::vector<int64_t>& val);
+    status_t            writeFloatVector(const std::unique_ptr<std::vector<float>>& val);
+    status_t            writeFloatVector(const std::vector<float>& val);
+    status_t            writeDoubleVector(const std::unique_ptr<std::vector<double>>& val);
+    status_t            writeDoubleVector(const std::vector<double>& val);
+    status_t            writeBoolVector(const std::unique_ptr<std::vector<bool>>& val);
+    status_t            writeBoolVector(const std::vector<bool>& val);
+    status_t            writeCharVector(const std::unique_ptr<std::vector<char16_t>>& val);
+    status_t            writeCharVector(const std::vector<char16_t>& val);
+    status_t            writeString16Vector(
+                            const std::unique_ptr<std::vector<std::unique_ptr<String16>>>& val);
+    status_t            writeString16Vector(const std::vector<String16>& val);
+    status_t            writeUtf8VectorAsUtf16Vector(
+                            const std::unique_ptr<std::vector<std::unique_ptr<std::string>>>& val);
+    status_t            writeUtf8VectorAsUtf16Vector(const std::vector<std::string>& val);
+
+    status_t            writeStrongBinderVector(const std::unique_ptr<std::vector<sp<IBinder>>>& val);
+    status_t            writeStrongBinderVector(const std::vector<sp<IBinder>>& val);
+
+    template<typename T>
+    status_t            writeParcelableVector(const std::unique_ptr<std::vector<std::unique_ptr<T>>>& val);
+    template<typename T>
+    status_t            writeParcelableVector(const std::vector<T>& val);
+
+    template<typename T>
+    status_t            writeNullableParcelable(const std::unique_ptr<T>& parcelable);
+
+    status_t            writeParcelable(const Parcelable& parcelable);
 
     template<typename T>
     status_t            write(const Flattenable<T>& val);
@@ -118,7 +167,7 @@
 
     // Place a native_handle into the parcel (the native_handle's file-
     // descriptors are dup'ed, so it is safe to delete the native_handle
-    // when this function returns). 
+    // when this function returns).
     // Doesn't take ownership of the native_handle.
     status_t            writeNativeHandle(const native_handle* handle);
     
@@ -131,6 +180,19 @@
     // will be closed once the parcel is destroyed.
     status_t            writeDupFileDescriptor(int fd);
 
+    // Place a file descriptor into the parcel.  This will not affect the
+    // semantics of the smart file descriptor. A new descriptor will be
+    // created, and will be closed when the parcel is destroyed.
+    status_t            writeUniqueFileDescriptor(
+                            const ScopedFd& fd);
+
+    // Place a vector of file desciptors into the parcel. Each descriptor is
+    // dup'd as in writeDupFileDescriptor
+    status_t            writeUniqueFileDescriptorVector(
+                            const std::unique_ptr<std::vector<ScopedFd>>& val);
+    status_t            writeUniqueFileDescriptorVector(
+                            const std::vector<ScopedFd>& val);
+
     // Writes a blob to the parcel.
     // If the blob is small, then it is stored in-place, otherwise it is
     // transferred by way of an anonymous shared memory region.  Prefer sending
@@ -169,15 +231,66 @@
     status_t            readDouble(double *pArg) const;
     intptr_t            readIntPtr() const;
     status_t            readIntPtr(intptr_t *pArg) const;
+    bool                readBool() const;
+    status_t            readBool(bool *pArg) const;
+    char16_t            readChar() const;
+    status_t            readChar(char16_t *pArg) const;
+    int8_t              readByte() const;
+    status_t            readByte(int8_t *pArg) const;
+
+    // Read a UTF16 encoded string, convert to UTF8
+    status_t            readUtf8FromUtf16(std::string* str) const;
+    status_t            readUtf8FromUtf16(std::unique_ptr<std::string>* str) const;
 
     const char*         readCString() const;
     String8             readString8() const;
     String16            readString16() const;
+    status_t            readString16(String16* pArg) const;
+    status_t            readString16(std::unique_ptr<String16>* pArg) const;
     const char16_t*     readString16Inplace(size_t* outLen) const;
     sp<IBinder>         readStrongBinder() const;
+    status_t            readStrongBinder(sp<IBinder>* val) const;
     wp<IBinder>         readWeakBinder() const;
 
     template<typename T>
+    status_t            readParcelableVector(
+                            std::unique_ptr<std::vector<std::unique_ptr<T>>>* val) const;
+    template<typename T>
+    status_t            readParcelableVector(std::vector<T>* val) const;
+
+    status_t            readParcelable(Parcelable* parcelable) const;
+
+    template<typename T>
+    status_t            readParcelable(std::unique_ptr<T>* parcelable) const;
+
+    template<typename T>
+    status_t            readStrongBinder(sp<T>* val) const;
+
+    status_t            readStrongBinderVector(std::unique_ptr<std::vector<sp<IBinder>>>* val) const;
+    status_t            readStrongBinderVector(std::vector<sp<IBinder>>* val) const;
+
+    status_t            readByteVector(std::unique_ptr<std::vector<int8_t>>* val) const;
+    status_t            readByteVector(std::vector<int8_t>* val) const;
+    status_t            readInt32Vector(std::unique_ptr<std::vector<int32_t>>* val) const;
+    status_t            readInt32Vector(std::vector<int32_t>* val) const;
+    status_t            readInt64Vector(std::unique_ptr<std::vector<int64_t>>* val) const;
+    status_t            readInt64Vector(std::vector<int64_t>* val) const;
+    status_t            readFloatVector(std::unique_ptr<std::vector<float>>* val) const;
+    status_t            readFloatVector(std::vector<float>* val) const;
+    status_t            readDoubleVector(std::unique_ptr<std::vector<double>>* val) const;
+    status_t            readDoubleVector(std::vector<double>* val) const;
+    status_t            readBoolVector(std::unique_ptr<std::vector<bool>>* val) const;
+    status_t            readBoolVector(std::vector<bool>* val) const;
+    status_t            readCharVector(std::unique_ptr<std::vector<char16_t>>* val) const;
+    status_t            readCharVector(std::vector<char16_t>* val) const;
+    status_t            readString16Vector(
+                            std::unique_ptr<std::vector<std::unique_ptr<String16>>>* val) const;
+    status_t            readString16Vector(std::vector<String16>* val) const;
+    status_t            readUtf8VectorFromUtf16Vector(
+                            std::unique_ptr<std::vector<std::unique_ptr<std::string>>>* val) const;
+    status_t            readUtf8VectorFromUtf16Vector(std::vector<std::string>* val) const;
+
+    template<typename T>
     status_t            read(Flattenable<T>& val) const;
 
     template<typename T>
@@ -201,6 +314,17 @@
     // in the parcel, which you do not own -- use dup() to get your own copy.
     int                 readFileDescriptor() const;
 
+    // Retrieve a smart file descriptor from the parcel.
+    status_t            readUniqueFileDescriptor(
+                            ScopedFd* val) const;
+
+
+    // Retrieve a vector of smart file descriptors from the parcel.
+    status_t            readUniqueFileDescriptorVector(
+                            std::unique_ptr<std::vector<ScopedFd>>* val) const;
+    status_t            readUniqueFileDescriptorVector(
+                            std::vector<ScopedFd>* val) const;
+
     // Reads a blob from the parcel.
     // The caller should call release() on the blob after reading its contents.
     status_t            readBlob(size_t len, ReadableBlob* outBlob) const;
@@ -256,6 +380,34 @@
     template<class T>
     status_t            writeAligned(T val);
 
+    status_t            writeRawNullableParcelable(const Parcelable*
+                                                   parcelable);
+
+    template<typename T, typename U>
+    status_t            unsafeReadTypedVector(std::vector<T>* val,
+                                              status_t(Parcel::*read_func)(U*) const) const;
+    template<typename T>
+    status_t            readNullableTypedVector(std::unique_ptr<std::vector<T>>* val,
+                                                status_t(Parcel::*read_func)(T*) const) const;
+    template<typename T>
+    status_t            readTypedVector(std::vector<T>* val,
+                                        status_t(Parcel::*read_func)(T*) const) const;
+    template<typename T, typename U>
+    status_t            unsafeWriteTypedVector(const std::vector<T>& val,
+                                               status_t(Parcel::*write_func)(U));
+    template<typename T>
+    status_t            writeNullableTypedVector(const std::unique_ptr<std::vector<T>>& val,
+                                                 status_t(Parcel::*write_func)(const T&));
+    template<typename T>
+    status_t            writeNullableTypedVector(const std::unique_ptr<std::vector<T>>& val,
+                                                 status_t(Parcel::*write_func)(T));
+    template<typename T>
+    status_t            writeTypedVector(const std::vector<T>& val,
+                                         status_t(Parcel::*write_func)(const T&));
+    template<typename T>
+    status_t            writeTypedVector(const std::vector<T>& val,
+                                         status_t(Parcel::*write_func)(T));
+
     status_t            mError;
     uint8_t*            mData;
     size_t              mDataSize;
@@ -402,6 +554,206 @@
     return NO_ERROR;
 }
 
+template<typename T>
+status_t Parcel::readStrongBinder(sp<T>* val) const {
+    sp<IBinder> tmp;
+    status_t ret = readStrongBinder(&tmp);
+
+    if (ret == OK) {
+        *val = interface_cast<T>(tmp);
+
+        if (val->get() == nullptr) {
+            return UNKNOWN_ERROR;
+        }
+    }
+
+    return ret;
+}
+
+template<typename T, typename U>
+status_t Parcel::unsafeReadTypedVector(
+        std::vector<T>* val,
+        status_t(Parcel::*read_func)(U*) const) const {
+    int32_t size;
+    status_t status = this->readInt32(&size);
+
+    if (status != OK) {
+        return status;
+    }
+
+    if (size < 0) {
+        return UNEXPECTED_NULL;
+    }
+
+    val->resize(size);
+
+    for (auto& v: *val) {
+        status = (this->*read_func)(&v);
+
+        if (status != OK) {
+            return status;
+        }
+    }
+
+    return OK;
+}
+
+template<typename T>
+status_t Parcel::readTypedVector(std::vector<T>* val,
+                                 status_t(Parcel::*read_func)(T*) const) const {
+    return unsafeReadTypedVector(val, read_func);
+}
+
+template<typename T>
+status_t Parcel::readNullableTypedVector(std::unique_ptr<std::vector<T>>* val,
+                                         status_t(Parcel::*read_func)(T*) const) const {
+    const int32_t start = dataPosition();
+    int32_t size;
+    status_t status = readInt32(&size);
+    val->reset();
+
+    if (status != OK || size < 0) {
+        return status;
+    }
+
+    setDataPosition(start);
+    val->reset(new std::vector<T>());
+
+    status = unsafeReadTypedVector(val->get(), read_func);
+
+    if (status != OK) {
+        val->reset();
+    }
+
+    return status;
+}
+
+template<typename T, typename U>
+status_t Parcel::unsafeWriteTypedVector(const std::vector<T>& val,
+                                        status_t(Parcel::*write_func)(U)) {
+    if (val.size() > std::numeric_limits<int32_t>::max()) {
+        return BAD_VALUE;
+    }
+
+    status_t status = this->writeInt32(val.size());
+
+    if (status != OK) {
+        return status;
+    }
+
+    for (const auto& item : val) {
+        status = (this->*write_func)(item);
+
+        if (status != OK) {
+            return status;
+        }
+    }
+
+    return OK;
+}
+
+template<typename T>
+status_t Parcel::writeTypedVector(const std::vector<T>& val,
+                                  status_t(Parcel::*write_func)(const T&)) {
+    return unsafeWriteTypedVector(val, write_func);
+}
+
+template<typename T>
+status_t Parcel::writeTypedVector(const std::vector<T>& val,
+                                  status_t(Parcel::*write_func)(T)) {
+    return unsafeWriteTypedVector(val, write_func);
+}
+
+template<typename T>
+status_t Parcel::writeNullableTypedVector(const std::unique_ptr<std::vector<T>>& val,
+                                          status_t(Parcel::*write_func)(const T&)) {
+    if (val.get() == nullptr) {
+        return this->writeInt32(-1);
+    }
+
+    return unsafeWriteTypedVector(*val, write_func);
+}
+
+template<typename T>
+status_t Parcel::writeNullableTypedVector(const std::unique_ptr<std::vector<T>>& val,
+                                          status_t(Parcel::*write_func)(T)) {
+    if (val.get() == nullptr) {
+        return this->writeInt32(-1);
+    }
+
+    return unsafeWriteTypedVector(*val, write_func);
+}
+
+template<typename T>
+status_t Parcel::readParcelableVector(std::vector<T>* val) const {
+    return unsafeReadTypedVector<T, Parcelable>(val, &Parcel::readParcelable);
+}
+
+template<typename T>
+status_t Parcel::readParcelableVector(std::unique_ptr<std::vector<std::unique_ptr<T>>>* val) const {
+    const int32_t start = dataPosition();
+    int32_t size;
+    status_t status = readInt32(&size);
+    val->reset();
+
+    if (status != OK || size < 0) {
+        return status;
+    }
+
+    setDataPosition(start);
+    val->reset(new std::vector<T>());
+
+    status = unsafeReadTypedVector(val->get(), &Parcel::readParcelable);
+
+    if (status != OK) {
+        val->reset();
+    }
+
+    return status;
+}
+
+template<typename T>
+status_t Parcel::readParcelable(std::unique_ptr<T>* parcelable) const {
+    const int32_t start = dataPosition();
+    int32_t present;
+    status_t status = readInt32(&present);
+    parcelable->reset();
+
+    if (status != OK || !present) {
+        return status;
+    }
+
+    setDataPosition(start);
+    parcelable->reset(new T());
+
+    status = readParcelable(parcelable->get());
+
+    if (status != OK) {
+        parcelable->reset();
+    }
+
+    return status;
+}
+
+template<typename T>
+status_t Parcel::writeNullableParcelable(const std::unique_ptr<T>& parcelable) {
+    return writeRawNullableParcelable(parcelable.get());
+}
+
+template<typename T>
+status_t Parcel::writeParcelableVector(const std::vector<T>& val) {
+    return unsafeWriteTypedVector<T,const Parcelable&>(val, &Parcel::writeParcelable);
+}
+
+template<typename T>
+status_t Parcel::writeParcelableVector(const std::unique_ptr<std::vector<std::unique_ptr<T>>>& val) {
+    if (val.get() == nullptr) {
+        return this->writeInt32(-1);
+    }
+
+    return unsafeWriteTypedVector(*val, &Parcel::writeParcelable);
+}
+
 // ---------------------------------------------------------------------------
 
 inline TextOutput& operator<<(TextOutput& to, const Parcel& parcel)
diff --git a/include/hwbinder/Parcelable.h b/include/hwbinder/Parcelable.h
new file mode 100644
index 0000000..faf0d34
--- /dev/null
+++ b/include/hwbinder/Parcelable.h
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ANDROID_PARCELABLE_H
+#define ANDROID_PARCELABLE_H
+
+#include <vector>
+
+#include <utils/Errors.h>
+#include <utils/String16.h>
+
+namespace android {
+
+class Parcel;
+
+// Abstract interface of all parcelables.
+class Parcelable {
+public:
+    virtual ~Parcelable() = default;
+
+    // Write |this| parcelable to the given |parcel|.  Keep in mind that
+    // implementations of writeToParcel must be manually kept in sync
+    // with readFromParcel and the Java equivalent versions of these methods.
+    //
+    // Returns android::OK on success and an appropriate error otherwise.
+    virtual status_t writeToParcel(Parcel* parcel) const = 0;
+
+    // Read data from the given |parcel| into |this|.  After readFromParcel
+    // completes, |this| should have equivalent state to the object that
+    // wrote itself to the parcel.
+    //
+    // Returns android::OK on success and an appropriate error otherwise.
+    virtual status_t readFromParcel(const Parcel* parcel) = 0;
+};  // class Parcelable
+
+}  // namespace android
+
+#endif // ANDROID_PARCELABLE_H
diff --git a/include/hwbinder/PersistableBundle.h b/include/hwbinder/PersistableBundle.h
new file mode 100644
index 0000000..fe5619f
--- /dev/null
+++ b/include/hwbinder/PersistableBundle.h
@@ -0,0 +1,118 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ANDROID_PERSISTABLE_BUNDLE_H
+#define ANDROID_PERSISTABLE_BUNDLE_H
+
+#include <map>
+#include <vector>
+
+#include <binder/Parcelable.h>
+#include <utils/String16.h>
+#include <utils/StrongPointer.h>
+
+namespace android {
+
+namespace os {
+
+/*
+ * C++ implementation of PersistableBundle, a mapping from String values to
+ * various types that can be saved to persistent and later restored.
+ */
+class PersistableBundle : public Parcelable {
+public:
+    PersistableBundle() = default;
+    virtual ~PersistableBundle() = default;
+    PersistableBundle(const PersistableBundle& bundle) = default;
+
+    status_t writeToParcel(Parcel* parcel) const override;
+    status_t readFromParcel(const Parcel* parcel) override;
+
+    bool empty() const;
+    size_t size() const;
+    size_t erase(const String16& key);
+
+    /*
+     * Setters for PersistableBundle. Adds a a key-value pair instantiated with
+     * |key| and |value| into the member map appropriate for the type of |value|.
+     * If there is already an existing value for |key|, |value| will replace it.
+     */
+    void putBoolean(const String16& key, bool value);
+    void putInt(const String16& key, int32_t value);
+    void putLong(const String16& key, int64_t value);
+    void putDouble(const String16& key, double value);
+    void putString(const String16& key, const String16& value);
+    void putBooleanVector(const String16& key, const std::vector<bool>& value);
+    void putIntVector(const String16& key, const std::vector<int32_t>& value);
+    void putLongVector(const String16& key, const std::vector<int64_t>& value);
+    void putDoubleVector(const String16& key, const std::vector<double>& value);
+    void putStringVector(const String16& key, const std::vector<String16>& value);
+    void putPersistableBundle(const String16& key, const PersistableBundle& value);
+
+    /*
+     * Getters for PersistableBundle. If |key| exists, these methods write the
+     * value associated with |key| into |out|, and return true. Otherwise, these
+     * methods return false.
+     */
+    bool getBoolean(const String16& key, bool* out) const;
+    bool getInt(const String16& key, int32_t* out) const;
+    bool getLong(const String16& key, int64_t* out) const;
+    bool getDouble(const String16& key, double* out) const;
+    bool getString(const String16& key, String16* out) const;
+    bool getBooleanVector(const String16& key, std::vector<bool>* out) const;
+    bool getIntVector(const String16& key, std::vector<int32_t>* out) const;
+    bool getLongVector(const String16& key, std::vector<int64_t>* out) const;
+    bool getDoubleVector(const String16& key, std::vector<double>* out) const;
+    bool getStringVector(const String16& key, std::vector<String16>* out) const;
+    bool getPersistableBundle(const String16& key, PersistableBundle* out) const;
+
+    friend bool operator==(const PersistableBundle& lhs, const PersistableBundle& rhs) {
+        return (lhs.mBoolMap == rhs.mBoolMap && lhs.mIntMap == rhs.mIntMap &&
+                lhs.mLongMap == rhs.mLongMap && lhs.mDoubleMap == rhs.mDoubleMap &&
+                lhs.mStringMap == rhs.mStringMap && lhs.mBoolVectorMap == rhs.mBoolVectorMap &&
+                lhs.mIntVectorMap == rhs.mIntVectorMap &&
+                lhs.mLongVectorMap == rhs.mLongVectorMap &&
+                lhs.mDoubleVectorMap == rhs.mDoubleVectorMap &&
+                lhs.mStringVectorMap == rhs.mStringVectorMap &&
+                lhs.mPersistableBundleMap == rhs.mPersistableBundleMap);
+    }
+
+    friend bool operator!=(const PersistableBundle& lhs, const PersistableBundle& rhs) {
+        return !(lhs == rhs);
+    }
+
+private:
+    status_t writeToParcelInner(Parcel* parcel) const;
+    status_t readFromParcelInner(const Parcel* parcel, size_t length);
+
+    std::map<String16, bool> mBoolMap;
+    std::map<String16, int32_t> mIntMap;
+    std::map<String16, int64_t> mLongMap;
+    std::map<String16, double> mDoubleMap;
+    std::map<String16, String16> mStringMap;
+    std::map<String16, std::vector<bool>> mBoolVectorMap;
+    std::map<String16, std::vector<int32_t>> mIntVectorMap;
+    std::map<String16, std::vector<int64_t>> mLongVectorMap;
+    std::map<String16, std::vector<double>> mDoubleVectorMap;
+    std::map<String16, std::vector<String16>> mStringVectorMap;
+    std::map<String16, PersistableBundle> mPersistableBundleMap;
+};
+
+}  // namespace os
+
+}  // namespace android
+
+#endif  // ANDROID_PERSISTABLE_BUNDLE_H
diff --git a/include/hwbinder/Status.h b/include/hwbinder/Status.h
new file mode 100644
index 0000000..ce947fa
--- /dev/null
+++ b/include/hwbinder/Status.h
@@ -0,0 +1,154 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ANDROID_BINDER_STATUS_H
+#define ANDROID_BINDER_STATUS_H
+
+#include <cstdint>
+
+#include <binder/Parcel.h>
+#include <utils/String8.h>
+
+namespace android {
+namespace binder {
+
+// An object similar in function to a status_t except that it understands
+// how exceptions are encoded in the prefix of a Parcel. Used like:
+//
+//     Parcel data;
+//     Parcel reply;
+//     status_t status;
+//     binder::Status remote_exception;
+//     if ((status = data.writeInterfaceToken(interface_descriptor)) != OK ||
+//         (status = data.writeInt32(function_input)) != OK) {
+//         // We failed to write into the memory of our local parcel?
+//     }
+//     if ((status = remote()->transact(transaction, data, &reply)) != OK) {
+//        // Something has gone wrong in the binder driver or libbinder.
+//     }
+//     if ((status = remote_exception.readFromParcel(reply)) != OK) {
+//         // The remote didn't correctly write the exception header to the
+//         // reply.
+//     }
+//     if (!remote_exception.isOk()) {
+//         // The transaction went through correctly, but the remote reported an
+//         // exception during handling.
+//     }
+//
+class Status final {
+public:
+    // Keep the exception codes in sync with android/os/Parcel.java.
+    enum Exception {
+        EX_NONE = 0,
+        EX_SECURITY = -1,
+        EX_BAD_PARCELABLE = -2,
+        EX_ILLEGAL_ARGUMENT = -3,
+        EX_NULL_POINTER = -4,
+        EX_ILLEGAL_STATE = -5,
+        EX_NETWORK_MAIN_THREAD = -6,
+        EX_UNSUPPORTED_OPERATION = -7,
+        EX_SERVICE_SPECIFIC = -8,
+
+        // This is special and Java specific; see Parcel.java.
+        EX_HAS_REPLY_HEADER = -128,
+        // This is special, and indicates to C++ binder proxies that the
+        // transaction has failed at a low level.
+        EX_TRANSACTION_FAILED = -129,
+    };
+
+    // A more readable alias for the default constructor.
+    static Status ok();
+    // Authors should explicitly pick whether their integer is:
+    //  - an exception code (EX_* above)
+    //  - service specific error code
+    //  - status_t
+    //
+    //  Prefer a generic exception code when possible, then a service specific
+    //  code, and finally a status_t for low level failures or legacy support.
+    //  Exception codes and service specific errors map to nicer exceptions for
+    //  Java clients.
+    static Status fromExceptionCode(int32_t exceptionCode);
+    static Status fromExceptionCode(int32_t exceptionCode,
+                                    const String8& message);
+    static Status fromServiceSpecificError(int32_t serviceSpecificErrorCode);
+    static Status fromServiceSpecificError(int32_t serviceSpecificErrorCode,
+                                           const String8& message);
+    static Status fromStatusT(status_t status);
+
+    Status() = default;
+    ~Status() = default;
+
+    // Status objects are copyable and contain just simple data.
+    Status(const Status& status) = default;
+    Status(Status&& status) = default;
+    Status& operator=(const Status& status) = default;
+
+    // Bear in mind that if the client or service is a Java endpoint, this
+    // is not the logic which will provide/interpret the data here.
+    status_t readFromParcel(const Parcel& parcel);
+    status_t writeToParcel(Parcel* parcel) const;
+
+    // Set one of the pre-defined exception types defined above.
+    void setException(int32_t ex, const String8& message);
+    // Set a service specific exception with error code.
+    void setServiceSpecificError(int32_t errorCode, const String8& message);
+    // Setting a |status| != OK causes generated code to return |status|
+    // from Binder transactions, rather than writing an exception into the
+    // reply Parcel.  This is the least preferable way of reporting errors.
+    void setFromStatusT(status_t status);
+
+    // Get information about an exception.
+    int32_t exceptionCode() const  { return mException; }
+    const String8& exceptionMessage() const { return mMessage; }
+    status_t transactionError() const {
+        return mException == EX_TRANSACTION_FAILED ? mErrorCode : OK;
+    }
+    int32_t serviceSpecificErrorCode() const {
+        return mException == EX_SERVICE_SPECIFIC ? mErrorCode : 0;
+    }
+
+    bool isOk() const { return mException == EX_NONE; }
+
+    // For logging.
+    String8 toString8() const;
+
+private:
+    Status(int32_t exceptionCode, int32_t errorCode);
+    Status(int32_t exceptionCode, int32_t errorCode, const String8& message);
+
+    // If |mException| == EX_TRANSACTION_FAILED, generated code will return
+    // |mErrorCode| as the result of the transaction rather than write an
+    // exception to the reply parcel.
+    //
+    // Otherwise, we always write |mException| to the parcel.
+    // If |mException| !=  EX_NONE, we write |mMessage| as well.
+    // If |mException| == EX_SERVICE_SPECIFIC we write |mErrorCode| as well.
+    int32_t mException = EX_NONE;
+    int32_t mErrorCode = 0;
+    String8 mMessage;
+};  // class Status
+
+// For gtest output logging
+template<typename T>
+T& operator<< (T& stream, const Status& s) {
+    stream << s.toString8().string();
+    return stream;
+}
+
+}  // namespace binder
+}  // namespace android
+
+#endif // ANDROID_BINDER_STATUS_H
diff --git a/tests/Android.mk b/tests/Android.mk
index 3668729..a40523d 100644
--- a/tests/Android.mk
+++ b/tests/Android.mk
@@ -32,3 +32,11 @@
 LOCAL_SRC_FILES := binderLibTest.cpp
 LOCAL_SHARED_LIBRARIES := libbinder libutils
 include $(BUILD_NATIVE_TEST)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := binderThroughputTest
+LOCAL_SRC_FILES := binderThroughputTest.cpp
+LOCAL_SHARED_LIBRARIES := libbinder libutils
+LOCAL_CLANG := true
+LOCAL_CFLAGS += -g -Wall -Werror -std=c++11 -Wno-missing-field-initializers -Wno-sign-compare -O3
+include $(BUILD_NATIVE_TEST)
diff --git a/tests/binderDriverInterfaceTest.cpp b/tests/binderDriverInterfaceTest.cpp
index 315f349..0277550 100644
--- a/tests/binderDriverInterfaceTest.cpp
+++ b/tests/binderDriverInterfaceTest.cpp
@@ -34,7 +34,7 @@
             int ret;
             uint32_t max_threads = 0;
 
-            m_binderFd = open(BINDER_DEV_NAME, O_RDWR | O_NONBLOCK);
+            m_binderFd = open(BINDER_DEV_NAME, O_RDWR | O_NONBLOCK | O_CLOEXEC);
             ASSERT_GE(m_binderFd, 0);
             m_buffer = mmap(NULL, 64*1024, PROT_READ, MAP_SHARED, m_binderFd, 0);
             ASSERT_NE(m_buffer, (void *)NULL);
diff --git a/tests/binderThroughputTest.cpp b/tests/binderThroughputTest.cpp
new file mode 100644
index 0000000..71b96d4
--- /dev/null
+++ b/tests/binderThroughputTest.cpp
@@ -0,0 +1,317 @@
+#include <binder/Binder.h>
+#include <binder/IBinder.h>
+#include <binder/IPCThreadState.h>
+#include <binder/IServiceManager.h>
+#include <string>
+#include <cstring>
+#include <cstdlib>
+#include <cstdio>
+
+#include <iostream>
+#include <vector>
+#include <tuple>
+
+#include <unistd.h>
+#include <sys/wait.h>
+
+using namespace std;
+using namespace android;
+
+enum BinderWorkerServiceCode {
+    BINDER_NOP = IBinder::FIRST_CALL_TRANSACTION,
+};
+
+#define ASSERT_TRUE(cond) \
+do { \
+    if (!(cond)) {\
+       cerr << __func__ << ":" << __LINE__ << " condition:" << #cond << " failed\n" << endl; \
+       exit(EXIT_FAILURE); \
+    } \
+} while (0)
+
+class BinderWorkerService : public BBinder
+{
+public:
+    BinderWorkerService() {}
+    ~BinderWorkerService() {}
+    virtual status_t onTransact(uint32_t code,
+                                const Parcel& data, Parcel* reply,
+                                uint32_t flags = 0) {
+        (void)flags;
+        (void)data;
+        (void)reply;
+        switch (code) {
+        case BINDER_NOP:
+            return NO_ERROR;
+        default:
+            return UNKNOWN_TRANSACTION;
+        };
+    }
+};
+
+class Pipe {
+    int m_readFd;
+    int m_writeFd;
+    Pipe(int readFd, int writeFd) : m_readFd{readFd}, m_writeFd{writeFd} {}
+    Pipe(const Pipe &) = delete;
+    Pipe& operator=(const Pipe &) = delete;
+    Pipe& operator=(const Pipe &&) = delete;
+public:
+    Pipe(Pipe&& rval) noexcept {
+        m_readFd = rval.m_readFd;
+        m_writeFd = rval.m_writeFd;
+        rval.m_readFd = 0;
+        rval.m_writeFd = 0;
+    }
+    ~Pipe() {
+        if (m_readFd)
+            close(m_readFd);
+        if (m_writeFd)
+            close(m_writeFd);
+    }
+    void signal() {
+        bool val = true;
+        int error = write(m_writeFd, &val, sizeof(val));
+        ASSERT_TRUE(error >= 0);
+    };
+    void wait() {
+        bool val = false;
+        int error = read(m_readFd, &val, sizeof(val));
+        ASSERT_TRUE(error >= 0);
+    }
+    template <typename T> void send(const T& v) {
+        int error = write(m_writeFd, &v, sizeof(T));
+        ASSERT_TRUE(error >= 0);
+    }
+    template <typename T> void recv(T& v) {
+        int error = read(m_readFd, &v, sizeof(T));
+        ASSERT_TRUE(error >= 0);
+    }
+    static tuple<Pipe, Pipe> createPipePair() {
+        int a[2];
+        int b[2];
+
+        int error1 = pipe(a);
+        int error2 = pipe(b);
+        ASSERT_TRUE(error1 >= 0);
+        ASSERT_TRUE(error2 >= 0);
+
+        return make_tuple(Pipe(a[0], b[1]), Pipe(b[0], a[1]));
+    }
+};
+
+static const uint32_t num_buckets = 128;
+static const uint64_t max_time_bucket = 50ull * 1000000;
+static const uint64_t time_per_bucket = max_time_bucket / num_buckets;
+static constexpr float time_per_bucket_ms = time_per_bucket / 1.0E6;
+
+struct ProcResults {
+    uint64_t m_best = max_time_bucket;
+    uint64_t m_worst = 0;
+    uint32_t m_buckets[num_buckets] = {0};
+    uint64_t m_transactions = 0;
+    uint64_t m_total_time = 0;
+
+    void add_time(uint64_t time) {
+        m_buckets[min(time, max_time_bucket-1) / time_per_bucket] += 1;
+        m_best = min(time, m_best);
+        m_worst = max(time, m_worst);
+        m_transactions += 1;
+        m_total_time += time;
+    }
+    static ProcResults combine(const ProcResults& a, const ProcResults& b) {
+        ProcResults ret;
+        for (int i = 0; i < num_buckets; i++) {
+            ret.m_buckets[i] = a.m_buckets[i] + b.m_buckets[i];
+        }
+        ret.m_worst = max(a.m_worst, b.m_worst);
+        ret.m_best = min(a.m_best, b.m_best);
+        ret.m_transactions = a.m_transactions + b.m_transactions;
+        ret.m_total_time = a.m_total_time + b.m_total_time;
+        return ret;
+    }
+    void dump() {
+        double best = (double)m_best / 1.0E6;
+        double worst = (double)m_worst / 1.0E6;
+        double average = (double)m_total_time / m_transactions / 1.0E6;
+        cout << "average:" << average << "ms worst:" << worst << "ms best:" << best << "ms" << endl;
+
+        uint64_t cur_total = 0;
+        for (int i = 0; i < num_buckets; i++) {
+            float cur_time = time_per_bucket_ms * i + 0.5f * time_per_bucket_ms;
+            if ((cur_total < 0.5f * m_transactions) && (cur_total + m_buckets[i] >= 0.5f * m_transactions)) {
+                cout << "50%: " << cur_time << " ";
+            }
+            if ((cur_total < 0.9f * m_transactions) && (cur_total + m_buckets[i] >= 0.9f * m_transactions)) {
+                cout << "90%: " << cur_time << " ";
+            }
+            if ((cur_total < 0.95f * m_transactions) && (cur_total + m_buckets[i] >= 0.95f * m_transactions)) {
+                cout << "95%: " << cur_time << " ";
+            }
+            if ((cur_total < 0.99f * m_transactions) && (cur_total + m_buckets[i] >= 0.99f * m_transactions)) {
+                cout << "99%: " << cur_time << " ";
+            }
+            cur_total += m_buckets[i];
+        }
+        cout << endl;
+
+    }
+};
+
+String16 generateServiceName(int num)
+{
+    char num_str[32];
+    snprintf(num_str, sizeof(num_str), "%d", num);
+    String16 serviceName = String16("binderWorker") + String16(num_str);
+    return serviceName;
+}
+
+void worker_fx(
+    int num,
+    int worker_count,
+    int iterations,
+    Pipe p)
+{
+    // Create BinderWorkerService and for go.
+    ProcessState::self()->startThreadPool();
+    sp<IServiceManager> serviceMgr = defaultServiceManager();
+    sp<BinderWorkerService> service = new BinderWorkerService;
+    serviceMgr->addService(generateServiceName(num), service);
+
+    srand(num);
+    p.signal();
+    p.wait();
+
+    // Get references to other binder services.
+    cout << "Created BinderWorker" << num << endl;
+    (void)worker_count;
+    vector<sp<IBinder> > workers;
+    for (int i = 0; i < worker_count; i++) {
+        if (num == i)
+            continue;
+        workers.push_back(serviceMgr->getService(generateServiceName(i)));
+    }
+
+    // Run the benchmark.
+    ProcResults results;
+    chrono::time_point<chrono::high_resolution_clock> start, end;
+    for (int i = 0; i < iterations; i++) {
+        int target = rand() % workers.size();
+        Parcel data, reply;
+        start = chrono::high_resolution_clock::now();
+        status_t ret = workers[target]->transact(BINDER_NOP, data, &reply);
+        end = chrono::high_resolution_clock::now();
+
+        uint64_t cur_time = uint64_t(chrono::duration_cast<chrono::nanoseconds>(end - start).count());
+        results.add_time(cur_time);
+
+        if (ret != NO_ERROR) {
+           cout << "thread " << num << " failed " << ret << "i : " << i << endl;
+           exit(EXIT_FAILURE);
+        }
+    }
+    // Signal completion to master and wait.
+    p.signal();
+    p.wait();
+
+    // Send results to master and wait for go to exit.
+    p.send(results);
+    p.wait();
+
+    exit(EXIT_SUCCESS);
+}
+
+Pipe make_worker(int num, int iterations, int worker_count)
+{
+    auto pipe_pair = Pipe::createPipePair();
+    pid_t pid = fork();
+    if (pid) {
+        /* parent */
+        return move(get<0>(pipe_pair));
+    } else {
+        /* child */
+        worker_fx(num, worker_count, iterations, move(get<1>(pipe_pair)));
+        /* never get here */
+        return move(get<0>(pipe_pair));
+    }
+
+}
+
+void wait_all(vector<Pipe>& v)
+{
+    for (int i = 0; i < v.size(); i++) {
+        v[i].wait();
+    }
+}
+
+void signal_all(vector<Pipe>& v)
+{
+    for (int i = 0; i < v.size(); i++) {
+        v[i].signal();
+    }
+}
+
+int main(int argc, char *argv[])
+{
+    int workers = 2;
+    int iterations = 10000;
+    (void)argc;
+    (void)argv;
+    vector<Pipe> pipes;
+
+    // Parse arguments.
+    for (int i = 1; i < argc; i++) {
+        if (string(argv[i]) == "-w") {
+            workers = atoi(argv[i+1]);
+            i++;
+            continue;
+        }
+        if (string(argv[i]) == "-i") {
+            iterations = atoi(argv[i+1]);
+            i++;
+            continue;
+        }
+    }
+
+    // Create all the workers and wait for them to spawn.
+    for (int i = 0; i < workers; i++) {
+        pipes.push_back(make_worker(i, iterations, workers));
+    }
+    wait_all(pipes);
+
+
+    // Run the workers and wait for completion.
+    chrono::time_point<chrono::high_resolution_clock> start, end;
+    cout << "waiting for workers to complete" << endl;
+    start = chrono::high_resolution_clock::now();
+    signal_all(pipes);
+    wait_all(pipes);
+    end = chrono::high_resolution_clock::now();
+
+    // Calculate overall throughput.
+    double iterations_per_sec = double(iterations * workers) / (chrono::duration_cast<chrono::nanoseconds>(end - start).count() / 1.0E9);
+    cout << "iterations per sec: " << iterations_per_sec << endl;
+
+    // Collect all results from the workers.
+    cout << "collecting results" << endl;
+    signal_all(pipes);
+    ProcResults tot_results;
+    for (int i = 0; i < workers; i++) {
+        ProcResults tmp_results;
+        pipes[i].recv(tmp_results);
+        tot_results = ProcResults::combine(tot_results, tmp_results);
+    }
+    tot_results.dump();
+
+    // Kill all the workers.
+    cout << "killing workers" << endl;
+    signal_all(pipes);
+    for (int i = 0; i < workers; i++) {
+        int status;
+        wait(&status);
+        if (status != 0) {
+            cout << "nonzero child status" << status << endl;
+        }
+    }
+    return 0;
+}