verify embedded buffer matches address in parent am: fcd86bd0d1 am: 68b6a9027e am: 2e1f5e023c am: 41202fc9c6

Original change: https://googleplex-android-review.googlesource.com/c/platform/system/libhwbinder/+/14314385

Change-Id: I30396472b8ca4399d1c17d8921b24f96faa0b95e
diff --git a/Android.bp b/Android.bp
index a5901e0..ae84ebb 100644
--- a/Android.bp
+++ b/Android.bp
@@ -12,15 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
-subdirs = [
-    "vts/performance",
-]
-
 cc_defaults {
     name: "libhwbinder_defaults",
 
     export_include_dirs: ["include"],
-    include_dirs: ["frameworks/native/include"],
 
     sanitize: {
         misc_undefined: ["integer"],
@@ -52,14 +47,6 @@
 
 cc_defaults {
     name: "libhwbinder-impl-shared-libs",
-    defaults: ["libhwbinder-impl-shared-libs-no-vndk-private"],
-    shared_libs: [
-        "libbinderthreadstate",
-    ],
-}
-
-cc_defaults {
-    name: "libhwbinder-impl-shared-libs-no-vndk-private",
     shared_libs: [
         "libbase",
         "liblog",
@@ -75,49 +62,43 @@
 // WARNING: this should no longer be used
 cc_library {
     name: "libhwbinder",
-    recovery_available: true,
     vendor_available: true,
-    vndk: {
-        enabled: true,
-        support_system_process: true,
-    },
 
     export_include_dirs: ["include"],
+
+    visibility: [":__subpackages__"],
 }
 
 // Combined into libhidlbase for efficiency.
 // Used as shared library to provide headers for libhidltransport-impl-internal.
 cc_library_static {
     name: "libhwbinder-impl-internal",
-    // TODO(b/135299443): allow this library to link against vndk-private libs
-    // and instead rely on the fact that users of this static library must be
-    // vndk (since they must use libbinderthreadstate).
-    include_dirs: ["frameworks/native/libs/binderthreadstate/include/"],
-    defaults: [
-        "libhwbinder_defaults",
-        "libhwbinder-impl-shared-libs-no-vndk-private",
-        "hwbinder_pgo",
-        "hwbinder_lto",
+    include_dirs: [
+        // TODO(b/31559095): get headers from bionic on host
+        "bionic/libc/kernel/android/uapi/",
+        "bionic/libc/kernel/uapi/",
     ],
-    recovery_available: true,
-    vendor_available: true,
-}
 
-// Explicitly provide a no lto, no PGO variant, to workaround the issue that we
-// can't detect non-lto users of the module in Android.mk.
-// TODO(b/135558503): remove
-cc_library {
-    name: "libhwbinder_noltopgo",
     defaults: [
         "libhwbinder_defaults",
         "libhwbinder-impl-shared-libs",
+        "hwbinder_pgo",
+        "hwbinder_lto",
     ],
+    host_supported: true,
     recovery_available: true,
     vendor_available: true,
-    vndk: {
-        enabled: true,
-        support_system_process: true,
-    },
+    // TODO(b/153609531): remove when no longer needed.
+    native_bridge_supported: true,
+    apex_available: [
+        "//apex_available:platform",
+        "com.android.neuralnetworks",
+        "com.android.bluetooth.updatable",
+        "com.android.media",
+        "com.android.media.swcodec",
+        "com.android.tethering",
+    ],
+    min_sdk_version: "29",
 }
 
 // Only libhwbinder_benchmark needs to have pgo enabled. When all places
diff --git a/Binder.cpp b/Binder.cpp
index 87bc143..9edd27b 100644
--- a/Binder.cpp
+++ b/Binder.cpp
@@ -22,7 +22,7 @@
 #include <hwbinder/IInterface.h>
 #include <hwbinder/Parcel.h>
 
-#include <sched.h>
+#include <linux/sched.h>
 #include <stdio.h>
 
 namespace android {
@@ -252,5 +252,5 @@
 
 // ---------------------------------------------------------------------------
 
-}; // namespace hardware
-}; // namespace android
+} // namespace hardware
+} // namespace android
diff --git a/BpHwBinder.cpp b/BpHwBinder.cpp
index aacbc8d..81ce7cc 100644
--- a/BpHwBinder.cpp
+++ b/BpHwBinder.cpp
@@ -100,12 +100,17 @@
 }
 
 status_t BpHwBinder::transact(
-    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags, TransactCallback /*callback*/)
+    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags, TransactCallback callback)
 {
     // Once a binder has died, it will never come back to life.
     if (mAlive) {
         status_t status = IPCThreadState::self()->transact(
             mHandle, code, data, reply, flags);
+
+        if (status == ::android::OK && callback != nullptr) {
+            callback(*reply);
+        }
+
         if (status == DEAD_OBJECT) mAlive = 0;
         return status;
     }
@@ -264,21 +269,6 @@
 
     IPCThreadState* ipc = IPCThreadState::self();
 
-    mLock.lock();
-    Vector<Obituary>* obits = mObituaries;
-    if(obits != nullptr) {
-        if (ipc) ipc->clearDeathNotification(mHandle, this);
-        mObituaries = nullptr;
-    }
-    mLock.unlock();
-
-    if (obits != nullptr) {
-        // XXX Should we tell any remaining DeathRecipient
-        // objects that the last strong ref has gone away, so they
-        // are no longer linked?
-        delete obits;
-    }
-
     if (ipc) {
         ipc->expungeHandle(mHandle, this);
         ipc->decWeakHandle(mHandle);
@@ -303,6 +293,26 @@
         ipc->decStrongHandle(mHandle);
         ipc->flushCommands();
     }
+
+    mLock.lock();
+    Vector<Obituary>* obits = mObituaries;
+    if(obits != nullptr) {
+        if (!obits->isEmpty()) {
+            ALOGI("onLastStrongRef automatically unlinking death recipients");
+        }
+
+        if (ipc) ipc->clearDeathNotification(mHandle, this);
+        mObituaries = nullptr;
+    }
+    mLock.unlock();
+
+    if (obits != nullptr) {
+        // XXX Should we tell any remaining DeathRecipient
+        // objects that the last strong ref has gone away, so they
+        // are no longer linked?
+        delete obits;
+        obits = nullptr;
+    }
 }
 
 bool BpHwBinder::onIncStrongAttempted(uint32_t /*flags*/, const void* /*id*/)
@@ -314,5 +324,5 @@
 
 // ---------------------------------------------------------------------------
 
-}; // namespace hardware
-}; // namespace android
+} // namespace hardware
+} // namespace android
diff --git a/BufferedTextOutput.cpp b/BufferedTextOutput.cpp
index 1b340a3..5addba4 100644
--- a/BufferedTextOutput.cpp
+++ b/BufferedTextOutput.cpp
@@ -279,5 +279,5 @@
     return mGlobalState;
 }
 
-}; // namespace hardware
-}; // namespace android
+} // namespace hardware
+} // namespace android
diff --git a/Debug.cpp b/Debug.cpp
index 38e3a3f..4464032 100644
--- a/Debug.cpp
+++ b/Debug.cpp
@@ -309,6 +309,6 @@
     return proc->getKernelReferences(count, buf);
 }
 
-}; // namespace hardware
-}; // namespace android
+} // namespace hardware
+} // namespace android
 
diff --git a/IInterface.cpp b/IInterface.cpp
index 3545325..ca8ad93 100644
--- a/IInterface.cpp
+++ b/IInterface.cpp
@@ -47,5 +47,5 @@
 
 // ---------------------------------------------------------------------------
 
-}; // namespace hardware
-}; // namespace android
+} // namespace hardware
+} // namespace android
diff --git a/IPCThreadState.cpp b/IPCThreadState.cpp
index 13ae0cd..2f4464d 100644
--- a/IPCThreadState.cpp
+++ b/IPCThreadState.cpp
@@ -17,12 +17,10 @@
 #define LOG_TAG "hw-IPCThreadState"
 
 #include <hwbinder/IPCThreadState.h>
-#include <binderthreadstate/IPCThreadStateBase.h>
 
 #include <hwbinder/Binder.h>
 #include <hwbinder/BpHwBinder.h>
 #include <hwbinder/TextOutput.h>
-#include <hwbinder/binder_kernel.h>
 
 #include <android-base/macros.h>
 #include <utils/CallStack.h>
@@ -30,13 +28,14 @@
 #include <utils/SystemClock.h>
 #include <utils/threads.h>
 
-#include <private/binder/binder_module.h>
+#include "binder_kernel.h"
 #include <hwbinder/Static.h>
 
+#include <atomic>
 #include <errno.h>
 #include <inttypes.h>
+#include <linux/sched.h>
 #include <pthread.h>
-#include <sched.h>
 #include <signal.h>
 #include <stdio.h>
 #include <sys/ioctl.h>
@@ -112,8 +111,9 @@
     "BC_DEAD_BINDER_DONE"
 };
 
-static const char* getReturnString(size_t idx)
+static const char* getReturnString(uint32_t cmd)
 {
+    size_t idx = cmd & _IOC_NRMASK;
     if (idx < sizeof(kReturnStrings) / sizeof(kReturnStrings[0]))
         return kReturnStrings[idx];
     else
@@ -275,13 +275,13 @@
 }
 
 static pthread_mutex_t gTLSMutex = PTHREAD_MUTEX_INITIALIZER;
-static bool gHaveTLS = false;
+static std::atomic<bool> gHaveTLS = false;
 static pthread_key_t gTLS = 0;
-static bool gShutdown = false;
+static std::atomic<bool> gShutdown = false;
 
 IPCThreadState* IPCThreadState::self()
 {
-    if (gHaveTLS) {
+    if (gHaveTLS.load(std::memory_order_acquire)) {
 restart:
         const pthread_key_t k = gTLS;
         IPCThreadState* st = (IPCThreadState*)pthread_getspecific(k);
@@ -289,13 +289,14 @@
         return new IPCThreadState;
     }
 
-    if (gShutdown) {
+    // Racey, heuristic test for simultaneous shutdown.
+    if (gShutdown.load(std::memory_order_relaxed)) {
         ALOGW("Calling IPCThreadState::self() during shutdown is dangerous, expect a crash.\n");
         return nullptr;
     }
 
     pthread_mutex_lock(&gTLSMutex);
-    if (!gHaveTLS) {
+    if (!gHaveTLS.load(std::memory_order_relaxed)) {
         int key_create_value = pthread_key_create(&gTLS, threadDestructor);
         if (key_create_value != 0) {
             pthread_mutex_unlock(&gTLSMutex);
@@ -303,7 +304,7 @@
                     strerror(key_create_value));
             return nullptr;
         }
-        gHaveTLS = true;
+        gHaveTLS.store(true, std::memory_order_release);
     }
     pthread_mutex_unlock(&gTLSMutex);
     goto restart;
@@ -311,7 +312,7 @@
 
 IPCThreadState* IPCThreadState::selfOrNull()
 {
-    if (gHaveTLS) {
+    if (gHaveTLS.load(std::memory_order_acquire)) {
         const pthread_key_t k = gTLS;
         IPCThreadState* st = (IPCThreadState*)pthread_getspecific(k);
         return st;
@@ -321,9 +322,9 @@
 
 void IPCThreadState::shutdown()
 {
-    gShutdown = true;
+    gShutdown.store(true, std::memory_order_relaxed);
 
-    if (gHaveTLS) {
+    if (gHaveTLS.load(std::memory_order_acquire)) {
         // XXX Need to wait for all thread pool threads to exit!
         IPCThreadState* st = (IPCThreadState*)pthread_getspecific(gTLS);
         if (st) {
@@ -331,13 +332,10 @@
             pthread_setspecific(gTLS, nullptr);
         }
         pthread_key_delete(gTLS);
-        gHaveTLS = false;
+        gHaveTLS.store(false, std::memory_order_release);
     }
 }
 
-// TODO(b/66905301): remove symbol
-void IPCThreadState::disableBackgroundScheduling(bool /* disable */) {}
-
 sp<ProcessState> IPCThreadState::process()
 {
     return mProcess;
@@ -561,9 +559,8 @@
         result = getAndExecuteCommand();
 
         if (result < NO_ERROR && result != TIMED_OUT && result != -ECONNREFUSED && result != -EBADF) {
-            ALOGE("getAndExecuteCommand(fd=%d) returned unexpected error %d, aborting",
+            LOG_ALWAYS_FATAL("getAndExecuteCommand(fd=%d) returned unexpected error %d, aborting",
                   mProcess->mDriverFD, result);
-            abort();
         }
 
         // Let this thread exit the thread pool if it is no longer
@@ -647,11 +644,11 @@
     if ((flags & TF_ONE_WAY) == 0) {
         if (UNLIKELY(mCallRestriction != ProcessState::CallRestriction::NONE)) {
             if (mCallRestriction == ProcessState::CallRestriction::ERROR_IF_NOT_ONEWAY) {
-                ALOGE("Process making non-oneway call but is restricted.");
+                ALOGE("Process making non-oneway call (code: %u) but is restricted.", code);
                 CallStack::logStack("non-oneway call", CallStack::getCurrent(10).get(),
                     ANDROID_LOG_ERROR);
             } else /* FATAL_IF_NOT_ONEWAY */ {
-                LOG_ALWAYS_FATAL("Process may not make oneway calls.");
+                LOG_ALWAYS_FATAL("Process may not make oneway calls (code: %u).", code);
             }
         }
 
@@ -735,7 +732,7 @@
     waitForResponse(nullptr, &result);
 
 #if LOG_REFCOUNTS
-    printf("IPCThreadState::attemptIncStrongHandle(%ld) = %s\n",
+    ALOGV("IPCThreadState::attemptIncStrongHandle(%ld) = %s\n",
         handle, result == NO_ERROR ? "SUCCESS" : "FAILURE");
 #endif
 
@@ -750,7 +747,7 @@
 void IPCThreadState::expungeHandle(int32_t handle, IBinder* binder)
 {
 #if LOG_REFCOUNTS
-    printf("IPCThreadState::expungeHandle(%ld)\n", handle);
+    ALOGV("IPCThreadState::expungeHandle(%ld)\n", handle);
 #endif
     self()->mProcess->expungeHandle(handle, binder);  // NOLINT
 }
@@ -773,6 +770,7 @@
 
 IPCThreadState::IPCThreadState()
     : mProcess(ProcessState::self()),
+      mServingStackPointer(nullptr),
       mStrictModePolicy(0),
       mLastTransactionBinderFlags(0),
       mIsLooper(false),
@@ -782,8 +780,6 @@
     clearCaller();
     mIn.setDataCapacity(256);
     mOut.setDataCapacity(256);
-
-    mIPCThreadStateBase = IPCThreadStateBase::self();
 }
 
 IPCThreadState::~IPCThreadState()
@@ -967,7 +963,11 @@
     if (err >= NO_ERROR) {
         if (bwr.write_consumed > 0) {
             if (bwr.write_consumed < mOut.dataSize())
-                mOut.remove(0, bwr.write_consumed);
+                LOG_ALWAYS_FATAL("Driver did not consume write buffer. "
+                                 "err: %s consumed: %zu of %zu",
+                                 statusToString(err).c_str(),
+                                 (size_t)bwr.write_consumed,
+                                 mOut.dataSize());
             else {
                 mOut.setDataSize(0);
                 processPostWriteDerefs();
@@ -1030,9 +1030,11 @@
     return NO_ERROR;
 }
 
+sp<BHwBinder> the_context_object;
+
 void IPCThreadState::setTheContextObject(sp<BHwBinder> obj)
 {
-    mContextObject = obj;
+    the_context_object = obj;
 }
 
 bool IPCThreadState::isLooperThread()
@@ -1143,9 +1145,6 @@
                 "Not enough command data for brTRANSACTION");
             if (result != NO_ERROR) break;
 
-            // Record the fact that we're in a hwbinder call
-            mIPCThreadStateBase->pushCurrentState(
-                IPCThreadStateBase::CallState::HWBINDER);
             Parcel buffer;
             buffer.ipcSetDataReference(
                 reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
@@ -1153,6 +1152,9 @@
                 reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
                 tr.offsets_size/sizeof(binder_size_t), freeBuffer, this);
 
+            const void* origServingStackPointer = mServingStackPointer;
+            mServingStackPointer = &origServingStackPointer; // anything on the stack
+
             const pid_t origPid = mCallingPid;
             const char* origSid = mCallingSid;
             const uid_t origUid = mCallingUid;
@@ -1209,10 +1211,9 @@
                 }
 
             } else {
-                error = mContextObject->transact(tr.code, buffer, &reply, tr.flags, reply_callback);
+                error = the_context_object->transact(tr.code, buffer, &reply, tr.flags, reply_callback);
             }
 
-            mIPCThreadStateBase->popCurrentState();
             if ((tr.flags & TF_ONE_WAY) == 0) {
                 if (!reply_sent) {
                     // Should have been a reply but there wasn't, so there
@@ -1233,6 +1234,7 @@
             //ALOGI("<<<< TRANSACT from pid %d restore pid %d sid %s uid %d\n",
             //     mCallingPid, origPid, (origSid ? origSid : "<N/A>"), origUid);
 
+            mServingStackPointer = origServingStackPointer;
             mCallingPid = origPid;
             mCallingSid = origSid;
             mCallingUid = origUid;
@@ -1273,7 +1275,7 @@
         break;
 
     default:
-        printf("*** BAD COMMAND %d received from Binder driver\n", cmd);
+        ALOGE("*** BAD COMMAND %d received from Binder driver\n", cmd);
         result = UNKNOWN_ERROR;
         break;
     }
@@ -1285,9 +1287,8 @@
     return result;
 }
 
-bool IPCThreadState::isServingCall() const
-{
-    return mIPCThreadStateBase->getCurrentBinderCallState() == IPCThreadStateBase::CallState::HWBINDER;
+const void* IPCThreadState::getServingStackPointer() const {
+    return mServingStackPointer;
 }
 
 void IPCThreadState::threadDestructor(void *st)
@@ -1321,5 +1322,5 @@
     state->mOut.writePointer((uintptr_t)data);
 }
 
-}; // namespace hardware
-}; // namespace android
+} // namespace hardware
+} // namespace android
diff --git a/Parcel.cpp b/Parcel.cpp
index f794923..2c6bf5d 100644
--- a/Parcel.cpp
+++ b/Parcel.cpp
@@ -36,7 +36,6 @@
 #include <hwbinder/Parcel.h>
 #include <hwbinder/ProcessState.h>
 #include <hwbinder/TextOutput.h>
-#include <hwbinder/binder_kernel.h>
 
 #include <cutils/ashmem.h>
 #include <utils/Debug.h>
@@ -45,13 +44,9 @@
 #include <utils/String8.h>
 #include <utils/String16.h>
 
-#include <private/binder/binder_module.h>
+#include "binder_kernel.h"
 #include <hwbinder/Static.h>
 
-#ifndef INT32_MAX
-#define INT32_MAX ((int32_t)(2147483647))
-#endif
-
 #define LOG_REFS(...)
 //#define LOG_REFS(...) ALOG(LOG_DEBUG, LOG_TAG, __VA_ARGS__)
 #define LOG_ALLOC(...)
@@ -67,8 +62,8 @@
 #define PAD_SIZE_UNSAFE(s) (((s)+3)&~3)
 
 static size_t pad_size(size_t s) {
-    if (s > (SIZE_T_MAX - 3)) {
-        abort();
+    if (s > (std::numeric_limits<size_t>::max() - 3)) {
+        LOG_ALWAYS_FATAL("pad size too big %zu", s);
     }
     return PAD_SIZE_UNSAFE(s);
 }
@@ -85,8 +80,6 @@
 
 static size_t gMaxFds = 0;
 
-static const size_t PARCEL_REF_CAP = 1024;
-
 void acquire_binder_object(const sp<ProcessState>& proc,
     const flat_binder_object& obj, const void* who)
 {
@@ -210,7 +203,7 @@
 
             obj.flags = priority & FLAT_BINDER_FLAG_PRIORITY_MASK;
             obj.flags |= FLAT_BINDER_FLAG_ACCEPTS_FDS | FLAT_BINDER_FLAG_INHERIT_RT;
-            obj.flags |= (policy & 3) << FLAT_BINDER_FLAG_SCHEDPOLICY_SHIFT;
+            obj.flags |= (policy & 3) << FLAT_BINDER_FLAG_SCHED_POLICY_SHIFT;
             if (local->isRequestingSid()) {
                 obj.flags |= FLAT_BINDER_FLAG_TXN_SECURITY_CTX;
             }
@@ -227,55 +220,6 @@
     return finish_flatten_binder(binder, obj, out);
 }
 
-status_t flatten_binder(const sp<ProcessState>& /*proc*/,
-    const wp<IBinder>& binder, Parcel* out)
-{
-    flat_binder_object obj = {};
-
-    obj.flags = 0x7f | FLAT_BINDER_FLAG_ACCEPTS_FDS;
-    if (binder != nullptr) {
-        sp<IBinder> real = binder.promote();
-        if (real != nullptr) {
-            IBinder *local = real->localBinder();
-            if (!local) {
-                BpHwBinder *proxy = real->remoteBinder();
-                if (proxy == nullptr) {
-                    ALOGE("null proxy");
-                }
-                const int32_t handle = proxy ? proxy->handle() : 0;
-                obj.hdr.type = BINDER_TYPE_WEAK_HANDLE;
-                obj.binder = 0; /* Don't pass uninitialized stack data to a remote process */
-                obj.handle = handle;
-                obj.cookie = 0;
-            } else {
-                obj.hdr.type = BINDER_TYPE_WEAK_BINDER;
-                obj.binder = reinterpret_cast<uintptr_t>(binder.get_refs());
-                obj.cookie = reinterpret_cast<uintptr_t>(binder.unsafe_get());
-            }
-            return finish_flatten_binder(real, obj, out);
-        }
-
-        // XXX How to deal?  In order to flatten the given binder,
-        // we need to probe it for information, which requires a primary
-        // reference...  but we don't have one.
-        //
-        // The OpenBinder implementation uses a dynamic_cast<> here,
-        // but we can't do that with the different reference counting
-        // implementation we are using.
-        ALOGE("Unable to unflatten Binder weak reference!");
-        obj.hdr.type = BINDER_TYPE_BINDER;
-        obj.binder = 0;
-        obj.cookie = 0;
-        return finish_flatten_binder(nullptr, obj, out);
-
-    } else {
-        obj.hdr.type = BINDER_TYPE_BINDER;
-        obj.binder = 0;
-        obj.cookie = 0;
-        return finish_flatten_binder(nullptr, obj, out);
-    }
-}
-
 inline static status_t finish_unflatten_binder(
     BpHwBinder* /*proxy*/, const flat_binder_object& /*flat*/,
     const Parcel& /*in*/)
@@ -302,46 +246,6 @@
     return BAD_TYPE;
 }
 
-status_t unflatten_binder(const sp<ProcessState>& proc,
-    const Parcel& in, wp<IBinder>* out)
-{
-    const flat_binder_object* flat = in.readObject<flat_binder_object>();
-
-    if (flat) {
-        switch (flat->hdr.type) {
-            case BINDER_TYPE_BINDER:
-                *out = reinterpret_cast<IBinder*>(flat->cookie);
-                return finish_unflatten_binder(nullptr, *flat, in);
-            case BINDER_TYPE_WEAK_BINDER:
-                if (flat->binder != 0) {
-                    out->set_object_and_refs(
-                        reinterpret_cast<IBinder*>(flat->cookie),
-                        reinterpret_cast<RefBase::weakref_type*>(flat->binder));
-                } else {
-                    *out = nullptr;
-                }
-                return finish_unflatten_binder(nullptr, *flat, in);
-            case BINDER_TYPE_HANDLE:
-            case BINDER_TYPE_WEAK_HANDLE:
-                *out = proc->getWeakProxyForHandle(flat->handle);
-                return finish_unflatten_binder(
-                    static_cast<BpHwBinder*>(out->unsafe_get()), *flat, in);
-        }
-    }
-    return BAD_TYPE;
-}
-
-/*
- * Return true iff:
- * 1. obj is indeed a binder_buffer_object (type is BINDER_TYPE_PTR), and
- * 2. obj does NOT have the flag BINDER_BUFFER_FLAG_REF (it is not a reference, but
- *    an actual buffer.)
- */
-static inline bool isBuffer(const binder_buffer_object& obj) {
-    return obj.hdr.type == BINDER_TYPE_PTR
-        && (obj.flags & BINDER_BUFFER_FLAG_REF) == 0;
-}
-
 // ---------------------------------------------------------------------------
 
 Parcel::Parcel()
@@ -384,7 +288,7 @@
 {
     size_t result = dataSize() - dataPosition();
     if (result > INT32_MAX) {
-        abort();
+        LOG_ALWAYS_FATAL("result too big: %zu", result);
     }
     return result;
 }
@@ -421,7 +325,7 @@
     if (pos > INT32_MAX) {
         // don't accept size_t values which may have come from an
         // inadvertent conversion from a negative int.
-        abort();
+        LOG_ALWAYS_FATAL("pos too big: %zu", pos);
     }
 
     mDataPos = pos;
@@ -717,11 +621,6 @@
     return flatten_binder(ProcessState::self(), val, this);
 }
 
-status_t Parcel::writeWeakBinder(const wp<IBinder>& val)
-{
-    return flatten_binder(ProcessState::self(), val, this);
-}
-
 template <typename T>
 status_t Parcel::writeObject(const T& val)
 {
@@ -796,19 +695,15 @@
 template status_t Parcel::writeObject<binder_buffer_object>(const binder_buffer_object& val);
 template status_t Parcel::writeObject<binder_fd_array_object>(const binder_fd_array_object& val);
 
-
-// TODO merge duplicated code in writeEmbeddedBuffer, writeEmbeddedReference, and writeEmbeddedNullReference
-// TODO merge duplicated code in writeBuffer, writeReference, and writeNullReference
-
 bool Parcel::validateBufferChild(size_t child_buffer_handle,
                                  size_t child_offset) const {
     if (child_buffer_handle >= mObjectsSize)
         return false;
     binder_buffer_object *child = reinterpret_cast<binder_buffer_object*>
             (mData + mObjects[child_buffer_handle]);
-    if (!isBuffer(*child) || child_offset > child->length) {
+    if (child->hdr.type != BINDER_TYPE_PTR || child_offset > child->length) {
         // Parent object not a buffer, or not large enough
-        LOG_BUFFER("writeEmbeddedReference found wierd child. "
+        LOG_BUFFER("writeEmbeddedReference found weird child. "
                    "child_offset = %zu, child->length = %zu",
                    child_offset, (size_t)child->length);
         return false;
@@ -822,7 +717,7 @@
         return false;
     binder_buffer_object *parent = reinterpret_cast<binder_buffer_object*>
             (mData + mObjects[parent_buffer_handle]);
-    if (!isBuffer(*parent) ||
+    if (parent->hdr.type != BINDER_TYPE_PTR ||
             sizeof(binder_uintptr_t) > parent->length ||
             parent_offset > parent->length - sizeof(binder_uintptr_t)) {
         // Parent object not a buffer, or not large enough
@@ -840,9 +735,9 @@
         return BAD_VALUE;
     binder_buffer_object obj = {
         .hdr = { .type = BINDER_TYPE_PTR },
+        .flags = BINDER_BUFFER_FLAG_HAS_PARENT,
         .buffer = reinterpret_cast<binder_uintptr_t>(buffer),
         .length = length,
-        .flags = BINDER_BUFFER_FLAG_HAS_PARENT,
         .parent = parent_buffer_handle,
         .parent_offset = parent_offset,
     };
@@ -859,113 +754,9 @@
         buffer, length, mObjectsSize);
     binder_buffer_object obj {
         .hdr = { .type = BINDER_TYPE_PTR },
+        .flags = 0,
         .buffer = reinterpret_cast<binder_uintptr_t>(buffer),
         .length = length,
-        .flags = 0,
-    };
-    if (handle != nullptr) {
-        // We use an index into mObjects as a handle
-        *handle = mObjectsSize;
-    }
-    return writeObject(obj);
-}
-
-status_t Parcel::incrementNumReferences() {
-    ++mNumRef;
-    LOG_BUFFER("incrementNumReferences: %zu", mNumRef);
-    return mNumRef <= PARCEL_REF_CAP ? OK : NO_MEMORY;
-}
-
-status_t Parcel::writeReference(size_t *handle,
-        size_t child_buffer_handle, size_t child_offset) {
-    LOG_BUFFER("writeReference(child = (%zu, %zu)) -> %zu",
-        child_buffer_handle, child_offset,
-        mObjectsSize);
-    status_t status = incrementNumReferences();
-    if (status != OK)
-        return status;
-    if (!validateBufferChild(child_buffer_handle, child_offset))
-        return BAD_VALUE;
-    binder_buffer_object obj {
-        .hdr = { .type = BINDER_TYPE_PTR },
-        .flags = BINDER_BUFFER_FLAG_REF,
-        // The current binder.h does not have child and child_offset names yet.
-        // Use the buffer and length parameters.
-        .buffer = child_buffer_handle,
-        .length = child_offset,
-    };
-    if (handle != nullptr)
-        // We use an index into mObjects as a handle
-        *handle = mObjectsSize;
-    return writeObject(obj);
-}
-
-/* Write an object that describes a pointer from parent to child.
- * Output the handle of that object in the size_t *handle variable. */
-status_t Parcel::writeEmbeddedReference(size_t *handle,
-    size_t child_buffer_handle, size_t child_offset,
-    size_t parent_buffer_handle, size_t parent_offset) {
-    LOG_BUFFER("writeEmbeddedReference(child = (%zu, %zu), parent = (%zu, %zu)) -> %zu",
-        child_buffer_handle, child_offset,
-        parent_buffer_handle, parent_offset,
-        mObjectsSize);
-    status_t status = incrementNumReferences();
-    if (status != OK)
-        return status;
-    // The current binder.h does not have child and child_offset names yet.
-    // Use the buffer and length parameters.
-    if (!validateBufferChild(child_buffer_handle, child_offset))
-        return BAD_VALUE;
-    if(!validateBufferParent(parent_buffer_handle, parent_offset))
-        return BAD_VALUE;
-    binder_buffer_object obj {
-        .hdr = { .type = BINDER_TYPE_PTR },
-        .flags = BINDER_BUFFER_FLAG_REF | BINDER_BUFFER_FLAG_HAS_PARENT,
-        .buffer = child_buffer_handle,
-        .length = child_offset,
-        .parent = parent_buffer_handle,
-        .parent_offset = parent_offset,
-    };
-    if (handle != nullptr) {
-        // We use an index into mObjects as a handle
-        *handle = mObjectsSize;
-    }
-    return writeObject(obj);
-}
-
-status_t Parcel::writeNullReference(size_t * handle) {
-    LOG_BUFFER("writeNullReference -> %zu", mObjectsSize);
-    status_t status = incrementNumReferences();
-    if (status != OK)
-        return status;
-
-    binder_buffer_object obj {
-        .hdr = { .type = BINDER_TYPE_PTR },
-        .flags = BINDER_BUFFER_FLAG_REF,
-    };
-
-    if (handle != nullptr)
-        // We use an index into mObjects as a handle
-        *handle = mObjectsSize;
-    return writeObject(obj);
-}
-
-status_t Parcel::writeEmbeddedNullReference(size_t * handle,
-        size_t parent_buffer_handle, size_t parent_offset) {
-    LOG_BUFFER("writeEmbeddedNullReference(parent = (%zu, %zu)) -> %zu",
-        parent_buffer_handle,
-        parent_offset,
-        mObjectsSize);
-    status_t status = incrementNumReferences();
-    if (status != OK)
-        return status;
-    if(!validateBufferParent(parent_buffer_handle, parent_offset))
-        return BAD_VALUE;
-    binder_buffer_object obj {
-        .hdr = { .type = BINDER_TYPE_PTR, },
-        .flags = BINDER_BUFFER_FLAG_REF | BINDER_BUFFER_FLAG_HAS_PARENT,
-        .parent = parent_buffer_handle,
-        .parent_offset = parent_offset,
     };
     if (handle != nullptr) {
         // We use an index into mObjects as a handle
@@ -988,7 +779,7 @@
         binder_size_t dataPos = mObjects[i];
         binder_buffer_object *obj =
             reinterpret_cast<binder_buffer_object*>(mData+dataPos);
-        if(!isBuffer(*obj))
+        if(obj->hdr.type != BINDER_TYPE_PTR)
             continue;
         BufferInfo ifo;
         ifo.index = i;
@@ -1423,13 +1214,6 @@
     return val;
 }
 
-wp<IBinder> Parcel::readWeakBinder() const
-{
-    wp<IBinder> val;
-    unflatten_binder(ProcessState::self(), *this, &val);
-    return val;
-}
-
 template<typename T>
 const T* Parcel::readObject(size_t *objects_offset) const
 {
@@ -1582,7 +1366,7 @@
 
     const binder_buffer_object* buffer_obj = readObject<binder_buffer_object>(buffer_handle);
 
-    if (buffer_obj == nullptr || !isBuffer(*buffer_obj)) {
+    if (buffer_obj == nullptr || buffer_obj->hdr.type != BINDER_TYPE_PTR) {
         return BAD_VALUE;
     }
 
@@ -1640,48 +1424,6 @@
                       parent_buffer_handle, parent_offset, buffer_out);
 }
 
-// isRef if corresponds to a writeReference call, else corresponds to a writeBuffer call.
-// see ::android::hardware::writeReferenceToParcel for details.
-status_t Parcel::readReference(void const* *bufptr,
-                               size_t *buffer_handle, bool *isRef) const
-{
-    LOG_BUFFER("readReference");
-    const binder_buffer_object* buffer_obj = readObject<binder_buffer_object>();
-    LOG_BUFFER("    readReference: buf = %p, len = %zu, flags = %x",
-        (void*)buffer_obj->buffer, (size_t)buffer_obj->length,
-        (int)buffer_obj->flags);
-    // TODO need verification here
-    if (buffer_obj && buffer_obj->hdr.type == BINDER_TYPE_PTR) {
-        if (buffer_handle != nullptr) {
-            *buffer_handle = 0; // TODO fix this, as readBuffer would do
-        }
-        if(isRef != nullptr) {
-            *isRef = (buffer_obj->flags & BINDER_BUFFER_FLAG_REF) != 0;
-            LOG_BUFFER("    readReference: isRef = %d", *isRef);
-        }
-        // in read side, always use .buffer and .length.
-        if(bufptr != nullptr) {
-            *bufptr = (void*)buffer_obj->buffer;
-        }
-        return OK;
-    }
-
-    return BAD_VALUE;
-}
-
-// isRef if corresponds to a writeEmbeddedReference call, else corresponds to a writeEmbeddedBuffer call.
-// see ::android::hardware::writeEmbeddedReferenceToParcel for details.
-status_t Parcel::readEmbeddedReference(void const* *bufptr,
-                                       size_t *buffer_handle,
-                                       size_t /* parent_buffer_handle */,
-                                       size_t /* parent_offset */,
-                                       bool *isRef) const
-{
-    // TODO verify parent and offset
-    LOG_BUFFER("readEmbeddedReference");
-    return (readReference(bufptr, buffer_handle, isRef));
-}
-
 status_t Parcel::readEmbeddedNativeHandle(size_t parent_buffer_handle,
                                           size_t parent_offset,
                                           const native_handle_t **handle) const
@@ -1746,6 +1488,12 @@
         return status;
     }
 
+    if (*handle == nullptr) {
+        // null handle already read above
+        ALOGE("Expecting non-null handle buffer");
+        return BAD_VALUE;
+    }
+
     int numFds = (*handle)->numFds;
     int numInts = (*handle)->numInts;
 
@@ -1858,7 +1606,7 @@
         i--;
         const binder_buffer_object* buffer
             = reinterpret_cast<binder_buffer_object*>(mData+mObjects[i]);
-        if (isBuffer(*buffer)) {
+        if (buffer->hdr.type == BINDER_TYPE_PTR) {
             /* The binder kernel driver requires each buffer to be 8-byte
              * aligned */
             size_t alignedSize = (buffer->length + (BUFFER_ALIGNMENT_BYTES - 1))
@@ -1888,7 +1636,6 @@
     mObjectsSize = mObjectsCapacity = objectsCount;
     mNextObjectHint = 0;
     clearCache();
-    mNumRef = 0;
     mOwner = relFunc;
     mOwnerCookie = relCookie;
     for (size_t i = 0; i < mObjectsSize; i++) {
@@ -1922,14 +1669,10 @@
             if (flat->hdr.type == BINDER_TYPE_PTR) {
                 const binder_buffer_object* buffer
                     = reinterpret_cast<const binder_buffer_object*>(DATA+OBJS[i]);
-                if(isBuffer(*buffer)) {
-                    HexDump bufferDump((const uint8_t*)buffer->buffer, (size_t)buffer->length);
-                    bufferDump.setSingleLineCutoff(0);
-                    to << endl << "Object #" << i << " @ " << (void*)OBJS[i] << " (buffer size " << buffer->length << "):";
-                    to << indent << bufferDump << dedent;
-                } else {
-                    to << endl << "Object #" << i << " @ " << (void*)OBJS[i];
-                }
+                HexDump bufferDump((const uint8_t*)buffer->buffer, (size_t)buffer->length);
+                bufferDump.setSingleLineCutoff(0);
+                to << endl << "Object #" << i << " @ " << (void*)OBJS[i] << " (buffer size " << buffer->length << "):";
+                to << indent << bufferDump << dedent;
             } else {
                 to << endl << "Object #" << i << " @ " << (void*)OBJS[i] << ": "
                     << TypeCode(flat->hdr.type & 0x7f7f7f00)
@@ -2061,7 +1804,6 @@
     mNextObjectHint = 0;
     mHasFds = false;
     clearCache();
-    mNumRef = 0;
     mFdsKnown = true;
     mAllowFds = true;
 
@@ -2162,10 +1904,16 @@
                 }
                 release_object(proc, *flat, this);
             }
-            binder_size_t* objects =
-                (binder_size_t*)realloc(mObjects, objectsSize*sizeof(binder_size_t));
-            if (objects) {
-                mObjects = objects;
+
+            if (objectsSize == 0) {
+                free(mObjects);
+                mObjects = nullptr;
+            } else {
+                binder_size_t* objects =
+                    (binder_size_t*)realloc(mObjects, objectsSize*sizeof(binder_size_t));
+                if (objects) {
+                    mObjects = objects;
+                }
             }
             mObjectsSize = objectsSize;
             mNextObjectHint = 0;
@@ -2248,7 +1996,6 @@
     mAllowFds = true;
     mOwner = nullptr;
     clearCache();
-    mNumRef = 0;
 
     // racing multiple init leads only to multiple identical write
     if (gMaxFds == 0) {
@@ -2278,5 +2025,5 @@
     mFdsKnown = true;
 }
 
-}; // namespace hardware
-}; // namespace android
+} // namespace hardware
+} // namespace android
diff --git a/ProcessState.cpp b/ProcessState.cpp
index 8a8b7cc..694efd1 100644
--- a/ProcessState.cpp
+++ b/ProcessState.cpp
@@ -21,12 +21,11 @@
 #include <cutils/atomic.h>
 #include <hwbinder/BpHwBinder.h>
 #include <hwbinder/IPCThreadState.h>
-#include <hwbinder/binder_kernel.h>
 #include <utils/Log.h>
 #include <utils/String8.h>
 #include <utils/threads.h>
 
-#include <private/binder/binder_module.h>
+#include "binder_kernel.h"
 #include <hwbinder/Static.h>
 
 #include <errno.h>
@@ -233,6 +232,11 @@
     status_t result = ioctl(mDriverFD, BINDER_GET_NODE_INFO_FOR_REF, &info);
 
     if (result != OK) {
+        static bool logged = false;
+        if (!logged) {
+          ALOGW("Kernel does not support BINDER_GET_NODE_INFO_FOR_REF.");
+          logged = true;
+        }
         return -1;
     }
 
@@ -244,7 +248,8 @@
 }
 
 void ProcessState::setCallRestriction(CallRestriction restriction) {
-    LOG_ALWAYS_FATAL_IF(IPCThreadState::selfOrNull(), "Call restrictions must be set before the threadpool is started.");
+    LOG_ALWAYS_FATAL_IF(IPCThreadState::selfOrNull() != nullptr,
+        "Call restrictions must be set before the threadpool is started.");
 
     mCallRestriction = restriction;
 }
@@ -449,9 +454,10 @@
             mDriverFD = -1;
         }
     }
-    else {
-        ALOGE("Binder driver could not be opened.  Terminating.");
-    }
+
+#ifdef __ANDROID__
+    LOG_ALWAYS_FATAL_IF(mDriverFD < 0, "Binder driver could not be opened. Terminating.");
+#endif
 }
 
 ProcessState::~ProcessState()
@@ -465,5 +471,5 @@
     mDriverFD = -1;
 }
 
-}; // namespace hardware
-}; // namespace android
+} // namespace hardware
+} // namespace android
diff --git a/Static.cpp b/Static.cpp
index 87f632c..2fb12e6 100644
--- a/Static.cpp
+++ b/Static.cpp
@@ -46,30 +46,8 @@
     }
 };
 
-class FdTextOutput : public BufferedTextOutput
-{
-public:
-    explicit FdTextOutput(int fd) : BufferedTextOutput(MULTITHREADED), mFD(fd) { }
-    virtual ~FdTextOutput() { };
-
-protected:
-    virtual status_t writeLines(const struct iovec& vec, size_t N)
-    {
-        writev(mFD, &vec, N);
-        return NO_ERROR;
-    }
-
-private:
-    int mFD;
-};
-
 static LogTextOutput gLogTextOutput;
-static FdTextOutput gStdoutTextOutput(STDOUT_FILENO);
-static FdTextOutput gStderrTextOutput(STDERR_FILENO);
-
 TextOutput& alog(gLogTextOutput);
-TextOutput& aout(gStdoutTextOutput);
-TextOutput& aerr(gStderrTextOutput);
 
 // ------------ ProcessState.cpp
 
diff --git a/TEST_MAPPING b/TEST_MAPPING
new file mode 100644
index 0000000..2bd0463
--- /dev/null
+++ b/TEST_MAPPING
@@ -0,0 +1,7 @@
+{
+  "presubmit": [
+    {
+      "name": "libbinderthreadstateutils_test"
+    }
+  ]
+}
diff --git a/TextOutput.cpp b/TextOutput.cpp
index 7bd85ad..e6e8cb7 100644
--- a/TextOutput.cpp
+++ b/TextOutput.cpp
@@ -70,5 +70,5 @@
     return to;
 }
 
-}; // namespace hardware
-}; // namespace android
+} // namespace hardware
+} // namespace android
diff --git a/include/hwbinder/binder_kernel.h b/binder_kernel.h
similarity index 62%
rename from include/hwbinder/binder_kernel.h
rename to binder_kernel.h
index 8a28f5b..fdf5b1e 100644
--- a/include/hwbinder/binder_kernel.h
+++ b/binder_kernel.h
@@ -17,24 +17,15 @@
 #ifndef ANDROID_HARDWARE_BINDER_KERNEL_H
 #define ANDROID_HARDWARE_BINDER_KERNEL_H
 
-#include <linux/android/binder.h>
-
 /**
- * This file exists because the uapi kernel headers in bionic are built
- * from upstream kernel headers only, and not all of the hwbinder kernel changes
- * have made it upstream yet. Therefore, the modifications to the
- * binder header are added locally in this file.
+ * Only need this file to fix the __packed__ keyword.
  */
 
-enum {
-	BINDER_BUFFER_FLAG_REF          = 1U << 1,
-};
+// TODO(b/31559095): bionic on host
+#ifndef __ANDROID__
+#define __packed __attribute__((__packed__))
+#endif
 
-enum {
-        FLAT_BINDER_FLAG_SCHEDPOLICY_MASK = 0x600,
-        FLAT_BINDER_FLAG_SCHEDPOLICY_SHIFT = 9,
-        FLAT_BINDER_FLAG_INHERIT_RT = 0x800,
-};
-
+#include <linux/android/binder.h>
 
 #endif // ANDROID_HARDWARE_BINDER_KERNEL_H
diff --git a/include/hwbinder/Binder.h b/include/hwbinder/Binder.h
index 960ea80..88c155f 100644
--- a/include/hwbinder/Binder.h
+++ b/include/hwbinder/Binder.h
@@ -109,8 +109,8 @@
     std::atomic<int32_t>    mState;
 };
 
-}; // namespace hardware
-}; // namespace android
+} // namespace hardware
+} // namespace android
 
 // ---------------------------------------------------------------------------
 
diff --git a/include/hwbinder/BpHwBinder.h b/include/hwbinder/BpHwBinder.h
index 73d2dd0..a5b2245 100644
--- a/include/hwbinder/BpHwBinder.h
+++ b/include/hwbinder/BpHwBinder.h
@@ -55,7 +55,6 @@
 
     virtual BpHwBinder*   remoteBinder();
 
-            status_t    setConstantData(const void* data, size_t size);
             void        sendObituary();
                         // This refcount includes:
                         // 1. Strong references to the node by this and other processes
@@ -119,8 +118,8 @@
     mutable String16            mDescriptorCache;
 };
 
-}; // namespace hardware
-}; // namespace android
+} // namespace hardware
+} // namespace android
 
 // ---------------------------------------------------------------------------
 
diff --git a/include/hwbinder/BufferedTextOutput.h b/include/hwbinder/BufferedTextOutput.h
index 401331a..3541659 100644
--- a/include/hwbinder/BufferedTextOutput.h
+++ b/include/hwbinder/BufferedTextOutput.h
@@ -63,7 +63,7 @@
 };
 
 // ---------------------------------------------------------------------------
-}; // namespace hardware
-}; // namespace android
+} // namespace hardware
+} // namespace android
 
 #endif // ANDROID_HARDWARE_BUFFEREDTEXTOUTPUT_H
diff --git a/include/hwbinder/Debug.h b/include/hwbinder/Debug.h
index 0c173a4..c23618c 100644
--- a/include/hwbinder/Debug.h
+++ b/include/hwbinder/Debug.h
@@ -44,7 +44,7 @@
 __END_DECLS
 
 // ---------------------------------------------------------------------------
-}; // namespace hardware
-}; // namespace android
+} // namespace hardware
+} // namespace android
 
 #endif // ANDROID_HARDWARE_BINDER_DEBUG_H
diff --git a/include/hwbinder/IBinder.h b/include/hwbinder/IBinder.h
index b8f3b0e..bc1f733 100644
--- a/include/hwbinder/IBinder.h
+++ b/include/hwbinder/IBinder.h
@@ -141,8 +141,8 @@
 private:
 };
 
-}; // namespace hardware
-}; // namespace android
+} // namespace hardware
+} // namespace android
 
 // ---------------------------------------------------------------------------
 
diff --git a/include/hwbinder/IInterface.h b/include/hwbinder/IInterface.h
index 96189ab..7e13957 100644
--- a/include/hwbinder/IInterface.h
+++ b/include/hwbinder/IInterface.h
@@ -65,7 +65,7 @@
 
 // ----------------------------------------------------------------------
 
-}; // namespace hardware
-}; // namespace android
+} // namespace hardware
+} // namespace android
 
 #endif // ANDROID_HARDWARE_IINTERFACE_H
diff --git a/include/hwbinder/IPCThreadState.h b/include/hwbinder/IPCThreadState.h
index deba2e8..ca99591 100644
--- a/include/hwbinder/IPCThreadState.h
+++ b/include/hwbinder/IPCThreadState.h
@@ -31,8 +31,6 @@
 // ---------------------------------------------------------------------------
 namespace android {
 
-class IPCThreadStateBase;
-
 namespace hardware {
 
 class IPCThreadState
@@ -89,11 +87,6 @@
 
     static  void                shutdown();
 
-            // TODO(b/66905301): remove symbol
-private:
-    static  void                disableBackgroundScheduling(bool disable);
-public:
-
             // Call blocks until the number of executing binder threads is less than
             // the maximum number of binder threads threads allowed for this process.
             void                blockUntilThreadAvailable();
@@ -104,31 +97,12 @@
             bool                isLooperThread();
             bool                isOnlyBinderThread();
 
-            // Is this thread currently serving a hwbinder call. This method
-            // returns true if while traversing backwards from the function call
-            // stack for this thread, we encounter a function serving a hwbinder
-            // call before encountering a binder call / hitting the end of the
-            // call stack.
-            // Eg: If thread T1 went through the following call pattern
-            //     1) T1 receives and executes binder call B1.
-            //     2) While handling B1, T1 makes hwbinder call H1.
-            //     3) The handler of H1, calls into T1 with a callback H2.
-            // If isServingCall() is called during B1 before 3), this method
-            // will return false, else true.
+            // WARNING: DO NOT USE THIS API
             //
-            //  ----
-            // | H2 | ---> While callback H2 is being handled during 3).
-            //  ----
-            // | B1 | ---> While B1 is being handled, hwbinder call H1 made.
-            //  ----
-            // Fig: Thread Call stack while handling H2.
-            //
-            // This is since after 3), while traversing the thread call stack,
-            // we hit a hwbinder call before a binder call / end of stack.
-            // This method may be typically used to determine whether to use
-            // hardware::IPCThreadState methods or IPCThreadState methods to
-            // infer information about thread state.
-            bool isServingCall() const;
+            // Returns a pointer to the stack from the last time a transaction
+            // was initiated by the kernel. Used to compare when making nested
+            // calls between multiple different transports.
+            const void*         getServingStackPointer() const;
 
             // Tasks which are done on the binder thread after the thread returns to the
             // threadpool.
@@ -169,23 +143,22 @@
             Parcel              mIn;
             Parcel              mOut;
             status_t            mLastError;
+            const void*         mServingStackPointer;
             pid_t               mCallingPid;
             const char*         mCallingSid;
             uid_t               mCallingUid;
             int32_t             mStrictModePolicy;
             int32_t             mLastTransactionBinderFlags;
-            sp<BHwBinder>         mContextObject;
             bool                mIsLooper;
             bool mIsPollingThread;
 
             std::vector<std::function<void(void)>> mPostCommandTasks;
-            IPCThreadStateBase *mIPCThreadStateBase;
 
             ProcessState::CallRestriction mCallRestriction;
 };
 
-}; // namespace hardware
-}; // namespace android
+} // namespace hardware
+} // namespace android
 
 // ---------------------------------------------------------------------------
 
diff --git a/include/hwbinder/Parcel.h b/include/hwbinder/Parcel.h
index f6e45d5..d3bdfe6 100644
--- a/include/hwbinder/Parcel.h
+++ b/include/hwbinder/Parcel.h
@@ -25,16 +25,23 @@
 #include <utils/RefBase.h>
 #include <utils/String16.h>
 
-#include <linux/android/binder.h>
-
 #include <hwbinder/IInterface.h>
 
 struct binder_buffer_object;
+struct flat_binder_object;
 
 // ---------------------------------------------------------------------------
 namespace android {
 namespace hardware {
 
+#ifdef BINDER_IPC_32BIT
+typedef unsigned int binder_size_t;
+typedef unsigned int binder_uintptr_t;
+#else
+typedef unsigned long long binder_size_t;
+typedef unsigned long long binder_uintptr_t;
+#endif
+
 class IBinder;
 class IPCThreadState;
 class ProcessState;
@@ -65,7 +72,6 @@
     // Parses the RPC header, returning true if the interface name
     // in the header matches the expected interface from the caller.
     bool                enforceInterface(const char* interface) const;
-    bool                checkInterface(IBinder*) const;
 
     void                freeData();
 
@@ -96,7 +102,6 @@
     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            writeBool(bool val);
 
     template<typename T>
@@ -106,16 +111,6 @@
     status_t            writeEmbeddedBuffer(const void *buffer, size_t length, size_t *handle,
                             size_t parent_buffer_handle, size_t parent_offset);
 public:
-    status_t            writeReference(size_t *handle,
-                                       size_t child_buffer_handle, size_t child_offset);
-    status_t            writeEmbeddedReference(size_t *handle,
-                                               size_t child_buffer_handle, size_t child_offset,
-                                               size_t parent_buffer_handle, size_t parent_offset);
-    status_t            writeNullReference(size_t *handle);
-    status_t            writeEmbeddedNullReference(size_t *handle,
-                                                   size_t parent_buffer_handle, size_t parent_offset);
-
-
     status_t            writeEmbeddedNativeHandle(const native_handle_t *handle,
                             size_t parent_buffer_handle, size_t parent_offset);
     status_t            writeNativeHandleNoDup(const native_handle* handle, bool embedded,
@@ -154,7 +149,6 @@
     sp<IBinder>         readStrongBinder() const;
     status_t            readStrongBinder(sp<IBinder>* val) const;
     status_t            readNullableStrongBinder(sp<IBinder>* val) const;
-    wp<IBinder>         readWeakBinder() const;
 
     template<typename T>
     const T*            readObject(size_t *objects_offset = nullptr) const;
@@ -172,11 +166,6 @@
                                                    size_t parent_offset,
                                                    const void **buffer_out) const;
 
-    status_t            readReference(void const* *bufptr,
-                                      size_t *buffer_handle, bool *isRef) const;
-    status_t            readEmbeddedReference(void const* *bufptr, size_t *buffer_handle,
-                                              size_t parent_buffer_handle, size_t parent_offset,
-                                              bool *isRef) const;
     status_t            readEmbeddedNativeHandle(size_t parent_buffer_handle,
                            size_t parent_offset, const native_handle_t **handle) const;
     status_t            readNullableEmbeddedNativeHandle(size_t parent_buffer_handle,
@@ -241,7 +230,6 @@
                                        ) const;
 
 private:
-    status_t            incrementNumReferences();
     bool                validateBufferChild(size_t child_buffer_handle,
                                             size_t child_offset) const;
     bool                validateBufferParent(size_t parent_buffer_handle,
@@ -299,7 +287,8 @@
     size_t              mObjectsSize;
     size_t              mObjectsCapacity;
     mutable size_t      mNextObjectHint;
-    size_t              mNumRef;
+
+    [[deprecated]] size_t mNumRef;
 
     mutable bool        mFdsKnown;
     mutable bool        mHasFds;
@@ -333,8 +322,8 @@
 status_t unflatten_binder(const sp<ProcessState>& proc,
                           const flat_binder_object& flat, wp<IBinder>* out);
 
-}; // namespace hardware
-}; // namespace android
+} // namespace hardware
+} // namespace android
 
 // ---------------------------------------------------------------------------
 
diff --git a/include/hwbinder/ProcessState.h b/include/hwbinder/ProcessState.h
index 6490a8d..91337d8 100644
--- a/include/hwbinder/ProcessState.h
+++ b/include/hwbinder/ProcessState.h
@@ -140,8 +140,8 @@
             CallRestriction     mCallRestriction;
 };
 
-}; // namespace hardware
-}; // namespace android
+} // namespace hardware
+} // namespace android
 
 // ---------------------------------------------------------------------------
 
diff --git a/include/hwbinder/TextOutput.h b/include/hwbinder/TextOutput.h
index cdc60e9..9611ddb 100644
--- a/include/hwbinder/TextOutput.h
+++ b/include/hwbinder/TextOutput.h
@@ -54,12 +54,6 @@
 // Text output stream for printing to the log (via utils/Log.h).
 extern TextOutput& alog;
 
-// Text output stream for printing to stdout.
-extern TextOutput& aout;
-
-// Text output stream for printing to stderr.
-extern TextOutput& aerr;
-
 typedef TextOutput& (*TextOutputManipFunc)(TextOutput&);
 
 TextOutput& endl(TextOutput& to);
@@ -200,7 +194,7 @@
 inline bool HexDump::carrayStyle() const { return mCArrayStyle; }
 
 // ---------------------------------------------------------------------------
-}; // namespace hardware
-}; // namespace android
+} // namespace hardware
+} // namespace android
 
 #endif // ANDROID_HARDWARE_TEXTOUTPUT_H
diff --git a/vts/performance/Android.bp b/vts/performance/Android.bp
index 38edce5..35f61d5 100644
--- a/vts/performance/Android.bp
+++ b/vts/performance/Android.bp
@@ -16,19 +16,24 @@
 
 cc_defaults {
     name: "libhwbinder_test_defaults",
+    defaults: ["hwbinder_benchmark_pgo",],
 
     cflags: [
         "-Wall",
         "-Werror",
     ],
     shared_libs: [
-        "libhidlbase_pgo",
+        "libbase",
         "liblog",
         "libutils",
         "libcutils",
+        "libvndksupport",
     ],
 
-    static_libs: ["android.hardware.tests.libhwbinder@1.0"],
+    static_libs: [
+        "android.hardware.tests.libhwbinder@1.0",
+        "libhidlbase_pgo",
+    ],
 
     // Allow dlsym'ing self for statically linked passthrough implementations
     ldflags: ["-rdynamic"],
@@ -37,8 +42,10 @@
     // and test portability since this test pairs with specific hal
     // implementations
     whole_static_libs: [
-        "android.hardware.tests.libhwbinder@1.0-impl",
+        "android.hardware.tests.libhwbinder@1.0-impl.test",
     ],
+
+    require_root: true,
 }
 
 cc_benchmark {
@@ -59,8 +66,11 @@
     shared_libs: [
         "libbinder",
         "libutils",
+    ],
+    static_libs: [
         "android.hardware.tests.libbinder",
     ],
+    require_root: true,
 }
 
 // build for throughput benchmark test for hwbinder.