Merge "SurfaceFlinger: define LOG_NDEBUG for debug." into main
diff --git a/cmds/servicemanager/NameUtil.h b/cmds/servicemanager/NameUtil.h
index b080939..4b10c2b 100644
--- a/cmds/servicemanager/NameUtil.h
+++ b/cmds/servicemanager/NameUtil.h
@@ -19,8 +19,6 @@
 #include <string>
 #include <string_view>
 
-#include <android-base/strings.h>
-
 namespace android {
 
 #ifndef VENDORSERVICEMANAGER
diff --git a/data/etc/Android.bp b/data/etc/Android.bp
index b63d14b..ab09de1 100644
--- a/data/etc/Android.bp
+++ b/data/etc/Android.bp
@@ -370,6 +370,14 @@
     defaults: ["frameworks_native_data_etc_defaults"],
 }
 
+// installed in system for GSI
+prebuilt_etc {
+    name: "android.software.credentials.prebuilt.xml",
+    relative_install_path: "permissions",
+    src: "android.software.credentials.xml",
+    filename_from_src: true,
+}
+
 prebuilt_etc {
     name: "android.software.device_id_attestation.prebuilt.xml",
     src: "android.software.device_id_attestation.xml",
diff --git a/libs/binder/ActivityManager.cpp b/libs/binder/ActivityManager.cpp
index 5264276..98349c6 100644
--- a/libs/binder/ActivityManager.cpp
+++ b/libs/binder/ActivityManager.cpp
@@ -23,10 +23,10 @@
 #include <binder/IServiceManager.h>
 #include <binder/ProcessState.h>
 
-#include <utils/SystemClock.h>
-
 namespace android {
 
+using namespace std::chrono_literals;
+
 ActivityManager::ActivityManager()
 {
 }
@@ -43,15 +43,16 @@
         }
     } else {
         ALOGI("Thread pool not started. Polling for activity service.");
-        int64_t startTime = 0;
+        auto startTime = std::chrono::steady_clock::now().min();
         while (service == nullptr || !IInterface::asBinder(service)->isBinderAlive()) {
             sp<IBinder> binder = defaultServiceManager()->checkService(String16("activity"));
             if (binder == nullptr) {
                 // Wait for the activity service to come back...
-                if (startTime == 0) {
-                    startTime = uptimeMillis();
+                if (startTime == startTime.min()) {
+                    startTime = std::chrono::steady_clock::now();
                     ALOGI("Waiting for activity service");
-                } else if ((uptimeMillis() - startTime) > 1000000) {
+                } else if (std::chrono::steady_clock::now() - startTime > 1000s) {
+                    // TODO(b/342453147): timeout of 1000s = 16min and 40s doesn't seem intended
                     ALOGW("Waiting too long for activity service, giving up");
                     service = nullptr;
                     break;
diff --git a/libs/binder/Android.bp b/libs/binder/Android.bp
index 1c8aa37..cdc7166 100644
--- a/libs/binder/Android.bp
+++ b/libs/binder/Android.bp
@@ -87,7 +87,7 @@
 
 cc_cmake_snapshot {
     name: "binder_sdk",
-    modules: [
+    modules_host: [
         "libbinder_sdk",
         "libbinder_sdk_single_threaded",
         "libbinder_ndk_sdk",
@@ -100,7 +100,6 @@
     prebuilts: [
         // to enable arm64 host support, build with musl - e.g. on aosp_cf_arm64_phone
         "aidl",
-        "libc++",
     ],
     include_sources: true,
     cflags: [
@@ -267,20 +266,18 @@
         "-Wunused-const-variable",
         "-DANDROID_BASE_UNIQUE_FD_DISABLE_IMPLICIT_CONVERSION",
         "-DANDROID_UTILS_REF_BASE_DISABLE_IMPLICIT_CONSTRUCTION",
+        // Hide symbols by default and set the BUILDING_LIBBINDER macro so that
+        // the code knows to export them.
+        "-fvisibility=hidden",
+        "-DBUILDING_LIBBINDER",
     ],
 
     target: {
-        bionic: {
-            // Hide symbols by default and set the BUILDING_LIBBINDER macro so that
-            // the code knows to export them.
-            //
-            // Only enabled on bionic builds, where RTTI is disabled, because
-            // it is failing to export required typeinfo symbols.
-            // TODO: b/341341056 - Find a solution for non-bionic builds.
-            cflags: [
-                "-fvisibility=hidden",
-                "-DBUILDING_LIBBINDER",
-            ],
+        vendor: {
+            // Trimming the exported symbols reveals a bug in vendor code, so
+            // disable it for the vendor variant for now. http://b/349657329
+            // TODO: Fix the issue and remove this override.
+            cflags: ["-fvisibility=default"],
         },
     },
 }
diff --git a/libs/binder/BackendUnifiedServiceManager.cpp b/libs/binder/BackendUnifiedServiceManager.cpp
index 496c5ef..b0d3048 100644
--- a/libs/binder/BackendUnifiedServiceManager.cpp
+++ b/libs/binder/BackendUnifiedServiceManager.cpp
@@ -15,6 +15,10 @@
  */
 #include "BackendUnifiedServiceManager.h"
 
+#if defined(__BIONIC__) && !defined(__ANDROID_VNDK__)
+#include <android-base/properties.h>
+#endif
+
 namespace android {
 
 using AidlServiceManager = android::os::IServiceManager;
diff --git a/libs/binder/BackendUnifiedServiceManager.h b/libs/binder/BackendUnifiedServiceManager.h
index a67d5ba..d72b5bb 100644
--- a/libs/binder/BackendUnifiedServiceManager.h
+++ b/libs/binder/BackendUnifiedServiceManager.h
@@ -15,7 +15,6 @@
  */
 #pragma once
 
-#include <android-base/properties.h>
 #include <android/os/BnServiceManager.h>
 #include <android/os/IServiceManager.h>
 #include <binder/IPCThreadState.h>
diff --git a/libs/binder/IPCThreadState.cpp b/libs/binder/IPCThreadState.cpp
index c3bbdba..984c93d 100644
--- a/libs/binder/IPCThreadState.cpp
+++ b/libs/binder/IPCThreadState.cpp
@@ -22,10 +22,7 @@
 #include <binder/BpBinder.h>
 #include <binder/TextOutput.h>
 
-#include <cutils/sched_policy.h>
 #include <utils/CallStack.h>
-#include <utils/Log.h>
-#include <utils/SystemClock.h>
 
 #include <atomic>
 #include <errno.h>
@@ -38,6 +35,7 @@
 #include <sys/resource.h>
 #include <unistd.h>
 
+#include "Utils.h"
 #include "binder_module.h"
 
 #if LOG_NDEBUG
@@ -65,6 +63,8 @@
 
 namespace android {
 
+using namespace std::chrono_literals;
+
 // Static const and functions will be optimized out if not used,
 // when LOG_NDEBUG and references in IF_LOG_COMMANDS() are optimized out.
 static const char* kReturnStrings[] = {
@@ -285,7 +285,9 @@
     return cmd;
 }
 
+LIBBINDER_IGNORE("-Wzero-as-null-pointer-constant")
 static pthread_mutex_t gTLSMutex = PTHREAD_MUTEX_INITIALIZER;
+LIBBINDER_IGNORE_END()
 static std::atomic<bool> gHaveTLS(false);
 static pthread_key_t gTLS = 0;
 static std::atomic<bool> gShutdown = false;
@@ -647,8 +649,9 @@
 
         size_t newThreadsCount = mProcess->mExecutingThreadsCount.fetch_add(1) + 1;
         if (newThreadsCount >= mProcess->mMaxThreads) {
-            int64_t expected = 0;
-            mProcess->mStarvationStartTimeMs.compare_exchange_strong(expected, uptimeMillis());
+            auto expected = ProcessState::never();
+            mProcess->mStarvationStartTime
+                    .compare_exchange_strong(expected, std::chrono::steady_clock::now());
         }
 
         result = executeCommand(cmd);
@@ -656,12 +659,13 @@
         size_t maxThreads = mProcess->mMaxThreads;
         newThreadsCount = mProcess->mExecutingThreadsCount.fetch_sub(1) - 1;
         if (newThreadsCount < maxThreads) {
-            size_t starvationStartTimeMs = mProcess->mStarvationStartTimeMs.exchange(0);
-            if (starvationStartTimeMs != 0) {
-                int64_t starvationTimeMs = uptimeMillis() - starvationStartTimeMs;
-                if (starvationTimeMs > 100) {
+            auto starvationStartTime =
+                    mProcess->mStarvationStartTime.exchange(ProcessState::never());
+            if (starvationStartTime != ProcessState::never()) {
+                auto starvationTime = std::chrono::steady_clock::now() - starvationStartTime;
+                if (starvationTime > 100ms) {
                     ALOGE("binder thread pool (%zu threads) starved for %" PRId64 " ms", maxThreads,
-                          starvationTimeMs);
+                          to_ms(starvationTime));
                 }
             }
         }
diff --git a/libs/binder/IServiceManager.cpp b/libs/binder/IServiceManager.cpp
index 5844c85..17e522d 100644
--- a/libs/binder/IServiceManager.cpp
+++ b/libs/binder/IServiceManager.cpp
@@ -16,11 +16,12 @@
 
 #define LOG_TAG "ServiceManagerCppClient"
 
-#include <BackendUnifiedServiceManager.h>
 #include <binder/IServiceManager.h>
+#include "BackendUnifiedServiceManager.h"
 
 #include <inttypes.h>
 #include <unistd.h>
+#include <chrono>
 #include <condition_variable>
 
 #include <android-base/properties.h>
@@ -28,9 +29,7 @@
 #include <android/os/IServiceManager.h>
 #include <binder/IPCThreadState.h>
 #include <binder/Parcel.h>
-#include <utils/Log.h>
 #include <utils/String8.h>
-#include <utils/SystemClock.h>
 
 #ifndef __ANDROID_VNDK__
 #include <binder/IPermissionController.h>
@@ -48,9 +47,12 @@
 #endif
 
 #include "Static.h"
+#include "Utils.h"
 
 namespace android {
 
+using namespace std::chrono_literals;
+
 using AidlRegistrationCallback = IServiceManager::LocalRegistrationCallback;
 
 using AidlServiceManager = android::os::IServiceManager;
@@ -194,16 +196,16 @@
     pc = gPermissionController;
     gPermissionControllerLock.unlock();
 
-    int64_t startTime = 0;
+    auto startTime = std::chrono::steady_clock::now().min();
 
     while (true) {
         if (pc != nullptr) {
             bool res = pc->checkPermission(permission, pid, uid);
             if (res) {
-                if (startTime != 0) {
-                    ALOGI("Check passed after %d seconds for %s from uid=%d pid=%d",
-                          (int)((uptimeMillis() - startTime) / 1000), String8(permission).c_str(),
-                          uid, pid);
+                if (startTime != startTime.min()) {
+                    const auto waitTime = std::chrono::steady_clock::now() - startTime;
+                    ALOGI("Check passed after %" PRIu64 "ms for %s from uid=%d pid=%d",
+                          to_ms(waitTime), String8(permission).c_str(), uid, pid);
                 }
                 return res;
             }
@@ -229,8 +231,8 @@
         sp<IBinder> binder = defaultServiceManager()->checkService(_permission);
         if (binder == nullptr) {
             // Wait for the permission controller to come back...
-            if (startTime == 0) {
-                startTime = uptimeMillis();
+            if (startTime == startTime.min()) {
+                startTime = std::chrono::steady_clock::now();
                 ALOGI("Waiting to check permission %s from uid=%d pid=%d",
                       String8(permission).c_str(), uid, pid);
             }
@@ -287,8 +289,8 @@
 
     const bool isVendorService =
         strcmp(ProcessState::self()->getDriverName().c_str(), "/dev/vndbinder") == 0;
-    constexpr int64_t timeout = 5000;
-    int64_t startTime = uptimeMillis();
+    constexpr auto timeout = 5s;
+    const auto startTime = std::chrono::steady_clock::now();
     // Vendor code can't access system properties
     if (!gSystemBootCompleted && !isVendorService) {
 #ifdef __ANDROID__
@@ -306,15 +308,16 @@
           ProcessState::self()->getDriverName().c_str());
 
     int n = 0;
-    while (uptimeMillis() - startTime < timeout) {
+    while (std::chrono::steady_clock::now() - startTime < timeout) {
         n++;
         usleep(1000*sleepTime);
 
         sp<IBinder> svc = checkService(name);
         if (svc != nullptr) {
-            ALOGI("Waiting for service '%s' on '%s' successful after waiting %" PRIi64 "ms",
+            const auto waitTime = std::chrono::steady_clock::now() - startTime;
+            ALOGI("Waiting for service '%s' on '%s' successful after waiting %" PRIu64 "ms",
                   String8(name).c_str(), ProcessState::self()->getDriverName().c_str(),
-                  uptimeMillis() - startTime);
+                  to_ms(waitTime));
             return svc;
         }
     }
@@ -416,7 +419,6 @@
             // that another thread serves the callback, and we never get a
             // command, so we hang indefinitely.
             std::unique_lock<std::mutex> lock(waiter->mMutex);
-            using std::literals::chrono_literals::operator""s;
             waiter->mCv.wait_for(lock, 1s, [&] {
                 return waiter->mBinder != nullptr;
             });
diff --git a/libs/binder/IShellCallback.cpp b/libs/binder/IShellCallback.cpp
index 86dd5c4..1d6852a 100644
--- a/libs/binder/IShellCallback.cpp
+++ b/libs/binder/IShellCallback.cpp
@@ -21,7 +21,6 @@
 
 #include <binder/IShellCallback.h>
 
-#include <utils/Log.h>
 #include <binder/Parcel.h>
 #include <utils/String8.h>
 
diff --git a/libs/binder/LazyServiceRegistrar.cpp b/libs/binder/LazyServiceRegistrar.cpp
index 7644806..0f0af0b 100644
--- a/libs/binder/LazyServiceRegistrar.cpp
+++ b/libs/binder/LazyServiceRegistrar.cpp
@@ -14,15 +14,13 @@
  * limitations under the License.
  */
 
-#include "log/log_main.h"
 #define LOG_TAG "AidlLazyServiceRegistrar"
 
-#include <binder/LazyServiceRegistrar.h>
-#include <binder/IPCThreadState.h>
-#include <binder/IServiceManager.h>
 #include <android/os/BnClientCallback.h>
 #include <android/os/IServiceManager.h>
-#include <utils/Log.h>
+#include <binder/IPCThreadState.h>
+#include <binder/IServiceManager.h>
+#include <binder/LazyServiceRegistrar.h>
 
 namespace android {
 namespace binder {
diff --git a/libs/binder/PermissionController.cpp b/libs/binder/PermissionController.cpp
index 0c89245..c11eb7d 100644
--- a/libs/binder/PermissionController.cpp
+++ b/libs/binder/PermissionController.cpp
@@ -19,10 +19,10 @@
 #include <binder/Binder.h>
 #include <binder/IServiceManager.h>
 
-#include <utils/SystemClock.h>
-
 namespace android {
 
+using namespace std::chrono_literals;
+
 PermissionController::PermissionController()
 {
 }
@@ -30,16 +30,16 @@
 sp<IPermissionController> PermissionController::getService()
 {
     std::lock_guard<Mutex> scoped_lock(mLock);
-    int64_t startTime = 0;
+    auto startTime = std::chrono::steady_clock::now().min();
     sp<IPermissionController> service = mService;
     while (service == nullptr || !IInterface::asBinder(service)->isBinderAlive()) {
         sp<IBinder> binder = defaultServiceManager()->checkService(String16("permission"));
         if (binder == nullptr) {
             // Wait for the activity service to come back...
-            if (startTime == 0) {
-                startTime = uptimeMillis();
+            if (startTime == startTime.min()) {
+                startTime = std::chrono::steady_clock::now();
                 ALOGI("Waiting for permission service");
-            } else if ((uptimeMillis() - startTime) > 10000) {
+            } else if (std::chrono::steady_clock::now() - startTime > 10s) {
                 ALOGW("Waiting too long for permission service, giving up");
                 service = nullptr;
                 break;
diff --git a/libs/binder/PersistableBundle.cpp b/libs/binder/PersistableBundle.cpp
index 5b157cc..abb6612 100644
--- a/libs/binder/PersistableBundle.cpp
+++ b/libs/binder/PersistableBundle.cpp
@@ -113,7 +113,7 @@
     // 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()) {
+    if (length > static_cast<size_t>(std::numeric_limits<int32_t>::max())) {
         ALOGE("Parcel length (%zu) too large to store in 32-bit signed int", length);
         return BAD_VALUE;
     }
@@ -319,7 +319,7 @@
      * pairs themselves.
      */
     size_t num_entries = size();
-    if (num_entries > std::numeric_limits<int32_t>::max()) {
+    if (num_entries > static_cast<size_t>(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;
diff --git a/libs/binder/ProcessState.cpp b/libs/binder/ProcessState.cpp
index ad5a6b3..a42ede2 100644
--- a/libs/binder/ProcessState.cpp
+++ b/libs/binder/ProcessState.cpp
@@ -26,7 +26,6 @@
 #include <binder/Stability.h>
 #include <cutils/atomic.h>
 #include <utils/AndroidThreads.h>
-#include <utils/Log.h>
 #include <utils/String8.h>
 #include <utils/Thread.h>
 
@@ -555,7 +554,7 @@
         mMaxThreads(DEFAULT_MAX_BINDER_THREADS),
         mCurrentThreads(0),
         mKernelStartedThreads(0),
-        mStarvationStartTimeMs(0),
+        mStarvationStartTime(never()),
         mForked(false),
         mThreadPoolStarted(false),
         mThreadPoolSeq(1),
diff --git a/libs/binder/RpcServer.cpp b/libs/binder/RpcServer.cpp
index d9e926a..b8742af 100644
--- a/libs/binder/RpcServer.cpp
+++ b/libs/binder/RpcServer.cpp
@@ -71,8 +71,23 @@
     return setupSocketServer(UnixSocketAddress(path));
 }
 
-status_t RpcServer::setupVsockServer(unsigned int bindCid, unsigned int port) {
-    return setupSocketServer(VsockSocketAddress(bindCid, port));
+status_t RpcServer::setupVsockServer(unsigned bindCid, unsigned port, unsigned* assignedPort) {
+    auto status = setupSocketServer(VsockSocketAddress(bindCid, port));
+    if (status != OK) return status;
+
+    if (assignedPort == nullptr) return OK;
+    sockaddr_vm addr;
+    socklen_t len = sizeof(addr);
+    if (0 != getsockname(mServer.fd.get(), reinterpret_cast<sockaddr*>(&addr), &len)) {
+        status = -errno;
+        ALOGE("setupVsockServer: Failed to getsockname: %s", strerror(-status));
+        return status;
+    }
+
+    LOG_ALWAYS_FATAL_IF(len != sizeof(addr), "Wrong socket type: len %zu vs len %zu",
+                        static_cast<size_t>(len), sizeof(addr));
+    *assignedPort = addr.svm_port;
+    return OK;
 }
 
 status_t RpcServer::setupInetServer(const char* address, unsigned int port,
diff --git a/libs/binder/TEST_MAPPING b/libs/binder/TEST_MAPPING
index 2b3ff44..1256173 100644
--- a/libs/binder/TEST_MAPPING
+++ b/libs/binder/TEST_MAPPING
@@ -129,6 +129,12 @@
       "name": "memunreachable_binder_test"
     }
   ],
+  "postsubmit": [
+    {
+      "name": "binder_sdk_test",
+      "host": true
+    }
+  ],
   "imports": [
     {
       "path": "packages/modules/Virtualization"
diff --git a/libs/binder/Utils.h b/libs/binder/Utils.h
index df8a4ce..881cdf3 100644
--- a/libs/binder/Utils.h
+++ b/libs/binder/Utils.h
@@ -18,6 +18,7 @@
 
 #include <stddef.h>
 #include <sys/uio.h>
+#include <chrono>
 #include <cstdint>
 #include <optional>
 
@@ -57,6 +58,19 @@
         }                                       \
     } while (0)
 
+#define LIBBINDER_PRAGMA(arg) _Pragma(#arg)
+#if defined(__clang__)
+#define LIBBINDER_PRAGMA_FOR_COMPILER(arg) LIBBINDER_PRAGMA(clang arg)
+#elif defined(__GNUC__)
+#define LIBBINDER_PRAGMA_FOR_COMPILER(arg) LIBBINDER_PRAGMA(GCC arg)
+#else
+#define LIBBINDER_PRAGMA_FOR_COMPILER(arg)
+#endif
+#define LIBBINDER_IGNORE(warning_flag)             \
+    LIBBINDER_PRAGMA_FOR_COMPILER(diagnostic push) \
+    LIBBINDER_PRAGMA_FOR_COMPILER(diagnostic ignored warning_flag)
+#define LIBBINDER_IGNORE_END() LIBBINDER_PRAGMA_FOR_COMPILER(diagnostic pop)
+
 namespace android {
 
 /**
@@ -114,4 +128,10 @@
 // Android is little-endian.
 LIBBINDER_INTERNAL_EXPORTED std::string HexString(const void* bytes, size_t len);
 
+// Converts any std::chrono duration to the number of milliseconds
+template <class Rep, class Period>
+uint64_t to_ms(std::chrono::duration<Rep, Period> duration) {
+    return std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
+}
+
 }   // namespace android
diff --git a/libs/binder/include/binder/BpBinder.h b/libs/binder/include/binder/BpBinder.h
index 8ac30ba..d7f74c4 100644
--- a/libs/binder/include/binder/BpBinder.h
+++ b/libs/binder/include/binder/BpBinder.h
@@ -176,10 +176,10 @@
     BpBinder(BinderHandle&& handle, int32_t trackedUid);
     explicit BpBinder(RpcHandle&& handle);
 
-    virtual             ~BpBinder();
-    virtual void        onFirstRef();
-    virtual void        onLastStrongRef(const void* id);
-    virtual bool        onIncStrongAttempted(uint32_t flags, const void* id);
+    virtual ~BpBinder();
+    virtual void onFirstRef();
+    virtual void onLastStrongRef(const void* id);
+    virtual bool onIncStrongAttempted(uint32_t flags, const void* id);
 
     friend ::android::internal::Stability;
 
@@ -192,30 +192,30 @@
         uint32_t flags;
     };
 
-            void                reportOneDeath(const Obituary& obit);
-            bool                isDescriptorCached() const;
+    void reportOneDeath(const Obituary& obit);
+    bool isDescriptorCached() const;
 
-    mutable RpcMutex            mLock;
-            volatile int32_t    mAlive;
-            volatile int32_t    mObitsSent;
-            Vector<Obituary>*   mObituaries;
-            ObjectManager       mObjects;
-    mutable String16            mDescriptorCache;
-            int32_t             mTrackedUid;
+    mutable RpcMutex mLock;
+    volatile int32_t mAlive;
+    volatile int32_t mObitsSent;
+    Vector<Obituary>* mObituaries;
+    ObjectManager mObjects;
+    mutable String16 mDescriptorCache;
+    int32_t mTrackedUid;
 
-    static RpcMutex                             sTrackingLock;
-    static std::unordered_map<int32_t,uint32_t> sTrackingMap;
-    static int                                  sNumTrackedUids;
-    static std::atomic_bool                     sCountByUidEnabled;
-    static binder_proxy_limit_callback          sLimitCallback;
-    static uint32_t                             sBinderProxyCountHighWatermark;
-    static uint32_t                             sBinderProxyCountLowWatermark;
-    static bool                                 sBinderProxyThrottleCreate;
-    static std::unordered_map<int32_t,uint32_t> sLastLimitCallbackMap;
-    static std::atomic<uint32_t>                sBinderProxyCount;
-    static std::atomic<uint32_t>                sBinderProxyCountWarned;
-    static binder_proxy_warning_callback        sWarningCallback;
-    static uint32_t                             sBinderProxyCountWarningWatermark;
+    static RpcMutex sTrackingLock;
+    static std::unordered_map<int32_t, uint32_t> sTrackingMap;
+    static int sNumTrackedUids;
+    static std::atomic_bool sCountByUidEnabled;
+    static binder_proxy_limit_callback sLimitCallback;
+    static uint32_t sBinderProxyCountHighWatermark;
+    static uint32_t sBinderProxyCountLowWatermark;
+    static bool sBinderProxyThrottleCreate;
+    static std::unordered_map<int32_t, uint32_t> sLastLimitCallbackMap;
+    static std::atomic<uint32_t> sBinderProxyCount;
+    static std::atomic<uint32_t> sBinderProxyCountWarned;
+    static binder_proxy_warning_callback sWarningCallback;
+    static uint32_t sBinderProxyCountWarningWatermark;
 };
 
 } // namespace android
diff --git a/libs/binder/include/binder/Functional.h b/libs/binder/include/binder/Functional.h
index bb0e5f4..e153969 100644
--- a/libs/binder/include/binder/Functional.h
+++ b/libs/binder/include/binder/Functional.h
@@ -36,7 +36,7 @@
     inline void release() { f_.reset(); }
 
 private:
-    friend scope_guard<F> android::binder::impl::make_scope_guard(F);
+    friend scope_guard<F> android::binder::impl::make_scope_guard<>(F);
 
     inline scope_guard(F&& f) : f_(std::move(f)) {}
 
diff --git a/libs/binder/include/binder/ProcessState.h b/libs/binder/include/binder/ProcessState.h
index 11898a0..021bd58 100644
--- a/libs/binder/include/binder/ProcessState.h
+++ b/libs/binder/include/binder/ProcessState.h
@@ -24,6 +24,8 @@
 #include <pthread.h>
 
 #include <atomic>
+#include <chrono>
+#include <condition_variable>
 #include <mutex>
 
 // ---------------------------------------------------------------------------
@@ -177,7 +179,9 @@
     // Current number of pooled threads inside the thread pool.
     std::atomic_size_t mKernelStartedThreads;
     // Time when thread pool was emptied
-    std::atomic_int64_t mStarvationStartTimeMs;
+    std::atomic<std::chrono::steady_clock::time_point> mStarvationStartTime;
+
+    static constexpr auto never = &std::chrono::steady_clock::time_point::min;
 
     mutable std::mutex mLock; // protects everything below.
 
diff --git a/libs/binder/include/binder/RpcServer.h b/libs/binder/include/binder/RpcServer.h
index abea0fb..c241d31 100644
--- a/libs/binder/include/binder/RpcServer.h
+++ b/libs/binder/include/binder/RpcServer.h
@@ -85,9 +85,12 @@
 
     /**
      * Creates an RPC server binding to the given CID at the given port.
+     *
+     * Set |port| to VMADDR_PORT_ANY to pick an ephemeral port. In this case, |assignedPort|
+     * will be set to the picked port number, if it is not null.
      */
-    [[nodiscard]] LIBBINDER_EXPORTED status_t setupVsockServer(unsigned int bindCid,
-                                                               unsigned int port);
+    [[nodiscard]] LIBBINDER_EXPORTED status_t setupVsockServer(unsigned bindCid, unsigned port,
+                                                               unsigned* assignedPort = nullptr);
 
     /**
      * Creates an RPC server at the current port using IPv4.
diff --git a/libs/binder/ndk/include_ndk/android/persistable_bundle.h b/libs/binder/ndk/include_ndk/android/persistable_bundle.h
index 42ae15a..5e0d4da 100644
--- a/libs/binder/ndk/include_ndk/android/persistable_bundle.h
+++ b/libs/binder/ndk/include_ndk/android/persistable_bundle.h
@@ -29,6 +29,11 @@
 #include <sys/cdefs.h>
 #include <sys/types.h>
 
+#ifndef __clang__
+#define _Nullable
+#define _Nonnull
+#endif
+
 __BEGIN_DECLS
 
 /*
diff --git a/libs/binder/ndk/persistable_bundle.cpp b/libs/binder/ndk/persistable_bundle.cpp
index 9b6877d..afa032e 100644
--- a/libs/binder/ndk/persistable_bundle.cpp
+++ b/libs/binder/ndk/persistable_bundle.cpp
@@ -17,11 +17,12 @@
 #include <android/persistable_bundle.h>
 #include <binder/PersistableBundle.h>
 #include <log/log.h>
-#include <persistable_bundle_internal.h>
 #include <string.h>
 
 #include <set>
 
+#include "persistable_bundle_internal.h"
+
 __BEGIN_DECLS
 
 struct APersistableBundle {
diff --git a/libs/binder/ndk/service_manager.cpp b/libs/binder/ndk/service_manager.cpp
index 5529455..259cced 100644
--- a/libs/binder/ndk/service_manager.cpp
+++ b/libs/binder/ndk/service_manager.cpp
@@ -18,6 +18,7 @@
 #include <binder/IServiceManager.h>
 #include <binder/LazyServiceRegistrar.h>
 
+#include "../Utils.h"
 #include "ibinder_internal.h"
 #include "status_internal.h"
 
@@ -71,7 +72,9 @@
     }
 
     sp<IServiceManager> sm = defaultServiceManager();
+    LIBBINDER_IGNORE("-Wdeprecated-declarations")
     sp<IBinder> binder = sm->getService(String16(instance));
+    LIBBINDER_IGNORE_END()
 
     sp<AIBinder> ret = ABpBinder::lookupOrCreateFromBinder(binder);
     AIBinder_incStrong(ret.get());
diff --git a/libs/binder/ndk/tests/Android.bp b/libs/binder/ndk/tests/Android.bp
index 8fb755c..c61a164 100644
--- a/libs/binder/ndk/tests/Android.bp
+++ b/libs/binder/ndk/tests/Android.bp
@@ -34,6 +34,11 @@
     cflags: [
         "-O0",
         "-g",
+        "-Wall",
+        "-Wextra",
+        "-Wextra-semi",
+        "-Werror",
+        "-Winconsistent-missing-override",
     ],
 }
 
diff --git a/libs/binder/ndk/tests/binderVendorDoubleLoadTest.cpp b/libs/binder/ndk/tests/binderVendorDoubleLoadTest.cpp
index 43b2cb8..66be94f 100644
--- a/libs/binder/ndk/tests/binderVendorDoubleLoadTest.cpp
+++ b/libs/binder/ndk/tests/binderVendorDoubleLoadTest.cpp
@@ -18,8 +18,6 @@
 #include <aidl/BnBinderVendorDoubleLoadTest.h>
 #include <aidl/android/os/IServiceManager.h>
 #include <android-base/logging.h>
-#include <android-base/properties.h>
-#include <android-base/strings.h>
 #include <android/binder_ibinder.h>
 #include <android/binder_manager.h>
 #include <android/binder_process.h>
@@ -30,13 +28,9 @@
 #include <binder/Stability.h>
 #include <binder/Status.h>
 #include <gtest/gtest.h>
-
 #include <sys/prctl.h>
 
 using namespace android;
-using ::android::base::EndsWith;
-using ::android::base::GetProperty;
-using ::android::base::Split;
 using ::android::binder::Status;
 using ::android::internal::Stability;
 using ::ndk::ScopedAStatus;
diff --git a/libs/binder/ndk/tests/iface.cpp b/libs/binder/ndk/tests/iface.cpp
index 3ee36cd..a532ae1 100644
--- a/libs/binder/ndk/tests/iface.cpp
+++ b/libs/binder/ndk/tests/iface.cpp
@@ -20,6 +20,8 @@
 
 #include <android/binder_auto_utils.h>
 
+#include "../../Utils.h"
+
 using ::android::sp;
 using ::android::wp;
 
@@ -156,10 +158,9 @@
 }
 
 sp<IFoo> IFoo::getService(const char* instance, AIBinder** outBinder) {
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+    LIBBINDER_IGNORE("-Wdeprecated-declarations")
     AIBinder* binder = AServiceManager_getService(instance);  // maybe nullptr
-#pragma clang diagnostic pop
+    LIBBINDER_IGNORE_END()
     if (binder == nullptr) {
         return nullptr;
     }
diff --git a/libs/binder/ndk/tests/libbinder_ndk_unit_test.cpp b/libs/binder/ndk/tests/libbinder_ndk_unit_test.cpp
index 966ec95..2bc1422 100644
--- a/libs/binder/ndk/tests/libbinder_ndk_unit_test.cpp
+++ b/libs/binder/ndk/tests/libbinder_ndk_unit_test.cpp
@@ -34,6 +34,7 @@
 #include <binder/IServiceManager.h>
 #include <binder/IShellCallback.h>
 #include <sys/prctl.h>
+#include <sys/socket.h>
 
 #include <chrono>
 #include <condition_variable>
@@ -41,6 +42,7 @@
 #include <mutex>
 #include <thread>
 
+#include "../Utils.h"
 #include "android/binder_ibinder.h"
 
 using namespace android;
@@ -68,21 +70,21 @@
 };
 
 class MyBinderNdkUnitTest : public aidl::BnBinderNdkUnitTest {
-    ndk::ScopedAStatus repeatInt(int32_t in, int32_t* out) {
+    ndk::ScopedAStatus repeatInt(int32_t in, int32_t* out) override {
         *out = in;
         return ndk::ScopedAStatus::ok();
     }
-    ndk::ScopedAStatus takeInterface(const std::shared_ptr<aidl::IEmpty>& empty) {
+    ndk::ScopedAStatus takeInterface(const std::shared_ptr<aidl::IEmpty>& empty) override {
         (void)empty;
         return ndk::ScopedAStatus::ok();
     }
-    ndk::ScopedAStatus forceFlushCommands() {
+    ndk::ScopedAStatus forceFlushCommands() override {
         // warning: this is assuming that libbinder_ndk is using the same copy
         // of libbinder that we are.
         android::IPCThreadState::self()->flushCommands();
         return ndk::ScopedAStatus::ok();
     }
-    ndk::ScopedAStatus getsRequestedSid(bool* out) {
+    ndk::ScopedAStatus getsRequestedSid(bool* out) override {
         const char* sid = AIBinder_getCallingSid();
         std::cout << "Got security context: " << (sid ?: "null") << std::endl;
         *out = sid != nullptr;
@@ -96,11 +98,11 @@
         fsync(out);
         return STATUS_OK;
     }
-    ndk::ScopedAStatus forcePersist(bool persist) {
+    ndk::ScopedAStatus forcePersist(bool persist) override {
         AServiceManager_forceLazyServicesPersist(persist);
         return ndk::ScopedAStatus::ok();
     }
-    ndk::ScopedAStatus setCustomActiveServicesCallback() {
+    ndk::ScopedAStatus setCustomActiveServicesCallback() override {
         AServiceManager_setActiveServicesCallback(activeServicesCallback, this);
         return ndk::ScopedAStatus::ok();
     }
@@ -341,10 +343,9 @@
     // libbinder across processes to the NDK service which doesn't implement
     // shell
     static const sp<android::IServiceManager> sm(android::defaultServiceManager());
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+    LIBBINDER_IGNORE("-Wdeprecated-declarations")
     sp<IBinder> testService = sm->getService(String16(IFoo::kSomeInstanceName));
-#pragma clang diagnostic pop
+    LIBBINDER_IGNORE_END()
 
     Vector<String16> argsVec;
     EXPECT_EQ(OK, IBinder::shellCommand(testService, STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO,
@@ -387,10 +388,9 @@
     // checkService on it, since the other process serving it might not be started yet.
     {
         // getService, not waitForService, to take advantage of timeout
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+        LIBBINDER_IGNORE("-Wdeprecated-declarations")
         auto binder = ndk::SpAIBinder(AServiceManager_getService(IFoo::kSomeInstanceName));
-#pragma clang diagnostic pop
+        LIBBINDER_IGNORE_END()
         ASSERT_NE(nullptr, binder.get());
     }
 
@@ -424,7 +424,7 @@
     // At the time of writing this test, there is no good interface guaranteed
     // to be on all devices. Cuttlefish has light, so this will generally test
     // things.
-    EXPECT_EQ(count, hasLight ? 1 : 0);
+    EXPECT_EQ(count, hasLight ? 1u : 0u);
 }
 
 TEST(NdkBinder, GetLazyService) {
@@ -514,7 +514,7 @@
     // may reference other cookie members
 
     (*funcs->onDeath)();
-};
+}
 void LambdaOnUnlink(void* cookie) {
     auto funcs = static_cast<DeathRecipientCookie*>(cookie);
     (*funcs->onUnlink)();
@@ -522,7 +522,7 @@
     // may reference other cookie members
 
     delete funcs;
-};
+}
 TEST(NdkBinder, DeathRecipient) {
     using namespace std::chrono_literals;
 
@@ -580,10 +580,9 @@
 }
 
 TEST(NdkBinder, RetrieveNonNdkService) {
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+    LIBBINDER_IGNORE("-Wdeprecated-declarations")
     AIBinder* binder = AServiceManager_getService(kExistingNonNdkService);
-#pragma clang diagnostic pop
+    LIBBINDER_IGNORE_END()
     ASSERT_NE(nullptr, binder);
     EXPECT_TRUE(AIBinder_isRemote(binder));
     EXPECT_TRUE(AIBinder_isAlive(binder));
@@ -597,10 +596,9 @@
 }
 
 TEST(NdkBinder, LinkToDeath) {
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+    LIBBINDER_IGNORE("-Wdeprecated-declarations")
     AIBinder* binder = AServiceManager_getService(kExistingNonNdkService);
-#pragma clang diagnostic pop
+    LIBBINDER_IGNORE_END()
     ASSERT_NE(nullptr, binder);
 
     AIBinder_DeathRecipient* recipient = AIBinder_DeathRecipient_new(OnBinderDeath);
@@ -630,10 +628,9 @@
 }
 
 TEST(NdkBinder, SetInheritRtNonLocal) {
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+    LIBBINDER_IGNORE("-Wdeprecated-declarations")
     AIBinder* binder = AServiceManager_getService(kExistingNonNdkService);
-#pragma clang diagnostic pop
+    LIBBINDER_IGNORE_END()
     ASSERT_NE(binder, nullptr);
 
     ASSERT_TRUE(AIBinder_isRemote(binder));
@@ -669,14 +666,13 @@
 }
 
 TEST(NdkBinder, EqualityOfRemoteBinderPointer) {
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+    LIBBINDER_IGNORE("-Wdeprecated-declarations")
     AIBinder* binderA = AServiceManager_getService(kExistingNonNdkService);
     ASSERT_NE(nullptr, binderA);
 
     AIBinder* binderB = AServiceManager_getService(kExistingNonNdkService);
     ASSERT_NE(nullptr, binderB);
-#pragma clang diagnostic pop
+    LIBBINDER_IGNORE_END()
 
     EXPECT_EQ(binderA, binderB);
 
@@ -690,10 +686,9 @@
 }
 
 TEST(NdkBinder, ABpBinderRefCount) {
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+    LIBBINDER_IGNORE("-Wdeprecated-declarations")
     AIBinder* binder = AServiceManager_getService(kExistingNonNdkService);
-#pragma clang diagnostic pop
+    LIBBINDER_IGNORE_END()
     AIBinder_Weak* wBinder = AIBinder_Weak_new(binder);
 
     ASSERT_NE(nullptr, binder);
@@ -716,10 +711,9 @@
 }
 
 TEST(NdkBinder, RequestedSidWorks) {
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+    LIBBINDER_IGNORE("-Wdeprecated-declarations")
     ndk::SpAIBinder binder(AServiceManager_getService(kBinderNdkUnitTestService));
-#pragma clang diagnostic pop
+    LIBBINDER_IGNORE_END()
     std::shared_ptr<aidl::IBinderNdkUnitTest> service =
             aidl::IBinderNdkUnitTest::fromBinder(binder);
 
@@ -742,10 +736,9 @@
 
     std::shared_ptr<MyEmpty> empty = ndk::SharedRefBase::make<MyEmpty>();
 
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+    LIBBINDER_IGNORE("-Wdeprecated-declarations")
     ndk::SpAIBinder binder(AServiceManager_getService(kBinderNdkUnitTestService));
-#pragma clang diagnostic pop
+    LIBBINDER_IGNORE_END()
     std::shared_ptr<aidl::IBinderNdkUnitTest> service =
             aidl::IBinderNdkUnitTest::fromBinder(binder);
 
@@ -766,14 +759,11 @@
 }
 
 TEST(NdkBinder, ConvertToPlatformBinder) {
-    for (const ndk::SpAIBinder& binder :
-         {// remote
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wdeprecated-declarations"
-          ndk::SpAIBinder(AServiceManager_getService(kBinderNdkUnitTestService)),
-#pragma clang diagnostic pop
-          // local
-          ndk::SharedRefBase::make<MyBinderNdkUnitTest>()->asBinder()}) {
+    LIBBINDER_IGNORE("-Wdeprecated-declarations")
+    ndk::SpAIBinder remoteBinder(AServiceManager_getService(kBinderNdkUnitTestService));
+    LIBBINDER_IGNORE_END()
+    auto localBinder = ndk::SharedRefBase::make<MyBinderNdkUnitTest>()->asBinder();
+    for (const ndk::SpAIBinder& binder : {remoteBinder, localBinder}) {
         // convert to platform binder
         EXPECT_NE(binder, nullptr);
         sp<IBinder> platformBinder = AIBinder_toPlatformBinder(binder.get());
@@ -802,14 +792,11 @@
 }
 
 TEST(NdkBinder, GetAndVerifyScopedAIBinder_Weak) {
-    for (const ndk::SpAIBinder& binder :
-         {// remote
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wdeprecated-declarations"
-          ndk::SpAIBinder(AServiceManager_getService(kBinderNdkUnitTestService)),
-#pragma clang diagnostic pop
-          // local
-          ndk::SharedRefBase::make<MyBinderNdkUnitTest>()->asBinder()}) {
+    LIBBINDER_IGNORE("-Wdeprecated-declarations")
+    ndk::SpAIBinder remoteBinder(AServiceManager_getService(kBinderNdkUnitTestService));
+    LIBBINDER_IGNORE_END()
+    auto localBinder = ndk::SharedRefBase::make<MyBinderNdkUnitTest>()->asBinder();
+    for (const ndk::SpAIBinder& binder : {remoteBinder, localBinder}) {
         // get a const ScopedAIBinder_Weak and verify promote
         EXPECT_NE(binder.get(), nullptr);
         const ndk::ScopedAIBinder_Weak wkAIBinder =
@@ -826,22 +813,22 @@
 
 class MyResultReceiver : public BnResultReceiver {
    public:
-    Mutex mMutex;
-    Condition mCondition;
+    std::mutex mMutex;
+    std::condition_variable mCondition;
     bool mHaveResult = false;
     int32_t mResult = 0;
 
     virtual void send(int32_t resultCode) {
-        AutoMutex _l(mMutex);
+        std::unique_lock<std::mutex> _l(mMutex);
         mResult = resultCode;
         mHaveResult = true;
-        mCondition.signal();
+        mCondition.notify_one();
     }
 
     int32_t waitForResult() {
-        AutoMutex _l(mMutex);
+        std::unique_lock<std::mutex> _l(mMutex);
         while (!mHaveResult) {
-            mCondition.wait(mMutex);
+            mCondition.wait(_l);
         }
         return mResult;
     }
@@ -878,7 +865,7 @@
     sp<MyResultReceiver> resultReceiver = new MyResultReceiver();
 
     Vector<String16> argsVec;
-    for (int i = 0; i < args.size(); i++) {
+    for (size_t i = 0; i < args.size(); i++) {
         argsVec.add(String16(args[i]));
     }
     status_t error = IBinder::shellCommand(unitTestService, inFd[0], outFd[0], errFd[0], argsVec,
@@ -902,10 +889,9 @@
 
 TEST(NdkBinder, UseHandleShellCommand) {
     static const sp<android::IServiceManager> sm(android::defaultServiceManager());
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+    LIBBINDER_IGNORE("-Wdeprecated-declarations")
     sp<IBinder> testService = sm->getService(String16(kBinderNdkUnitTestService));
-#pragma clang diagnostic pop
+    LIBBINDER_IGNORE_END()
 
     EXPECT_EQ("", shellCmdToString(testService, {}));
     EXPECT_EQ("", shellCmdToString(testService, {"", ""}));
@@ -915,10 +901,9 @@
 
 TEST(NdkBinder, FlaggedServiceAccessible) {
     static const sp<android::IServiceManager> sm(android::defaultServiceManager());
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+    LIBBINDER_IGNORE("-Wdeprecated-declarations")
     sp<IBinder> testService = sm->getService(String16(kBinderNdkUnitTestServiceFlagged));
-#pragma clang diagnostic pop
+    LIBBINDER_IGNORE_END()
     ASSERT_NE(nullptr, testService);
 }
 
diff --git a/libs/binder/rust/src/binder.rs b/libs/binder/rust/src/binder.rs
index e34d31e..9a252b8 100644
--- a/libs/binder/rust/src/binder.rs
+++ b/libs/binder/rust/src/binder.rs
@@ -768,14 +768,14 @@
         $interface:path[$descriptor:expr] {
             native: $native:ident($on_transact:path),
             proxy: $proxy:ident,
-            $(async: $async_interface:ident,)?
+            $(async: $async_interface:ident $(($try_into_local_async:ident))?,)?
         }
     } => {
         $crate::declare_binder_interface! {
             $interface[$descriptor] {
                 native: $native($on_transact),
                 proxy: $proxy {},
-                $(async: $async_interface,)?
+                $(async: $async_interface $(($try_into_local_async))?,)?
                 stability: $crate::binder_impl::Stability::default(),
             }
         }
@@ -785,7 +785,7 @@
         $interface:path[$descriptor:expr] {
             native: $native:ident($on_transact:path),
             proxy: $proxy:ident,
-            $(async: $async_interface:ident,)?
+            $(async: $async_interface:ident $(($try_into_local_async:ident))?,)?
             stability: $stability:expr,
         }
     } => {
@@ -793,7 +793,7 @@
             $interface[$descriptor] {
                 native: $native($on_transact),
                 proxy: $proxy {},
-                $(async: $async_interface,)?
+                $(async: $async_interface $(($try_into_local_async))?,)?
                 stability: $stability,
             }
         }
@@ -805,7 +805,7 @@
             proxy: $proxy:ident {
                 $($fname:ident: $fty:ty = $finit:expr),*
             },
-            $(async: $async_interface:ident,)?
+            $(async: $async_interface:ident $(($try_into_local_async:ident))?,)?
         }
     } => {
         $crate::declare_binder_interface! {
@@ -814,7 +814,7 @@
                 proxy: $proxy {
                     $($fname: $fty = $finit),*
                 },
-                $(async: $async_interface,)?
+                $(async: $async_interface $(($try_into_local_async))?,)?
                 stability: $crate::binder_impl::Stability::default(),
             }
         }
@@ -826,7 +826,7 @@
             proxy: $proxy:ident {
                 $($fname:ident: $fty:ty = $finit:expr),*
             },
-            $(async: $async_interface:ident,)?
+            $(async: $async_interface:ident $(($try_into_local_async:ident))?,)?
             stability: $stability:expr,
         }
     } => {
@@ -838,7 +838,7 @@
                 proxy: $proxy {
                     $($fname: $fty = $finit),*
                 },
-                $(async: $async_interface,)?
+                $(async: $async_interface $(($try_into_local_async))?,)?
                 stability: $stability,
             }
         }
@@ -854,7 +854,7 @@
                 $($fname:ident: $fty:ty = $finit:expr),*
             },
 
-            $( async: $async_interface:ident, )?
+            $(async: $async_interface:ident $(($try_into_local_async:ident))?,)?
 
             stability: $stability:expr,
         }
@@ -1043,6 +1043,24 @@
                 }
 
                 if ibinder.associate_class(<$native as $crate::binder_impl::Remotable>::get_class()) {
+                    let service: std::result::Result<$crate::binder_impl::Binder<$native>, $crate::StatusCode> =
+                        std::convert::TryFrom::try_from(ibinder.clone());
+                    $(
+                    // This part is only generated if the user of the macro specifies that the
+                    // trait has an `try_into_local_async` implementation.
+                    if let Ok(service) = service {
+                        if let Some(async_service) = $native::$try_into_local_async(service) {
+                            // We were able to associate with our expected class,
+                            // the service is local, and the local service is async.
+                            return Ok(async_service);
+                        }
+                        // The service is local but not async. Fall back to treating it as a
+                        // remote service. This means that calls to this local service have an
+                        // extra performance cost due to serialization, but async handle to
+                        // non-async server is considered a rare case, so this is okay.
+                    }
+                    )?
+                    // Treat service as remote.
                     return Ok($crate::Strong::new(Box::new(<$proxy as $crate::binder_impl::Proxy>::from_binder(ibinder)?)));
                 }
 
diff --git a/libs/binder/rust/tests/integration.rs b/libs/binder/rust/tests/integration.rs
index 15ae56f..5359832 100644
--- a/libs/binder/rust/tests/integration.rs
+++ b/libs/binder/rust/tests/integration.rs
@@ -182,7 +182,7 @@
         proxy: BpTest {
             x: i32 = 100
         },
-        async: IATest,
+        async: IATest(try_into_local_async),
     }
 }
 
@@ -323,6 +323,14 @@
     }
 }
 
+impl BnTest {
+    fn try_into_local_async<P: binder::BinderAsyncPool + 'static>(
+        me: Binder<BnTest>,
+    ) -> Option<binder::Strong<dyn IATest<P>>> {
+        Some(binder::Strong::new(Box::new(me) as _))
+    }
+}
+
 /// Trivial testing binder interface
 pub trait ITestSameDescriptor: Interface {}
 
@@ -900,6 +908,19 @@
         assert_eq!(service.test().unwrap(), service_name);
     }
 
+    #[tokio::test]
+    async fn reassociate_rust_binder_async() {
+        let service_name = "testing_service";
+        let service_ibinder =
+            BnTest::new_binder(TestService::new(service_name), BinderFeatures::default())
+                .as_binder();
+
+        let service: Strong<dyn IATest<Tokio>> =
+            service_ibinder.into_interface().expect("Could not reassociate the generic ibinder");
+
+        assert_eq!(service.test().await.unwrap(), service_name);
+    }
+
     #[test]
     fn weak_binder_upgrade() {
         let service_name = "testing_service";
diff --git a/libs/binder/tests/BinderRpcTestServerConfig.aidl b/libs/binder/tests/BinderRpcTestServerConfig.aidl
index b2e0ef2..96550bc 100644
--- a/libs/binder/tests/BinderRpcTestServerConfig.aidl
+++ b/libs/binder/tests/BinderRpcTestServerConfig.aidl
@@ -20,7 +20,6 @@
     int socketType;
     int rpcSecurity;
     int serverVersion;
-    int vsockPort;
     int socketFd; // Inherited from the parent process.
     @utf8InCpp String addr;
 }
diff --git a/libs/binder/tests/binderClearBufTest.cpp b/libs/binder/tests/binderClearBufTest.cpp
index 3230a3f..63254cd 100644
--- a/libs/binder/tests/binderClearBufTest.cpp
+++ b/libs/binder/tests/binderClearBufTest.cpp
@@ -75,10 +75,9 @@
 };
 
 TEST(BinderClearBuf, ClearKernelBuffer) {
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+    LIBBINDER_IGNORE("-Wdeprecated-declarations")
     sp<IBinder> binder = defaultServiceManager()->getService(kServerName);
-#pragma clang diagnostic pop
+    LIBBINDER_IGNORE_END()
     ASSERT_NE(nullptr, binder);
 
     std::string replyBuffer;
diff --git a/libs/binder/tests/binderDriverInterfaceTest.cpp b/libs/binder/tests/binderDriverInterfaceTest.cpp
index cf23a46..7be4f21 100644
--- a/libs/binder/tests/binderDriverInterfaceTest.cpp
+++ b/libs/binder/tests/binderDriverInterfaceTest.cpp
@@ -19,11 +19,12 @@
 #include <stdio.h>
 #include <stdlib.h>
 
+#include <binder/IBinder.h>
 #include <gtest/gtest.h>
 #include <linux/android/binder.h>
-#include <binder/IBinder.h>
-#include <sys/mman.h>
 #include <poll.h>
+#include <sys/ioctl.h>
+#include <sys/mman.h>
 
 #define BINDER_DEV_NAME "/dev/binder"
 
@@ -93,8 +94,9 @@
             ret = ioctl(m_binderFd, cmd, arg);
             EXPECT_EQ(expect_ret, ret);
             if (ret < 0) {
-                if (errno != accept_errno)
+                if (errno != accept_errno) {
                     EXPECT_EQ(expect_errno, errno);
+                }
             }
         }
         void binderTestIoctlErr2(int cmd, void *arg, int expect_errno, int accept_errno) {
@@ -274,12 +276,15 @@
         binderTestIoctl(BINDER_WRITE_READ, &bwr);
     }
     EXPECT_EQ(offsetof(typeof(br), pad), bwr.read_consumed);
-    if (bwr.read_consumed > offsetof(typeof(br), cmd0))
+    if (bwr.read_consumed > offsetof(typeof(br), cmd0)) {
         EXPECT_EQ(BR_NOOP, br.cmd0);
-    if (bwr.read_consumed > offsetof(typeof(br), cmd1))
+    }
+    if (bwr.read_consumed > offsetof(typeof(br), cmd1)) {
         EXPECT_EQ(BR_TRANSACTION_COMPLETE, br.cmd1);
-    if (bwr.read_consumed > offsetof(typeof(br), cmd2))
+    }
+    if (bwr.read_consumed > offsetof(typeof(br), cmd2)) {
         EXPECT_EQ(BR_REPLY, br.cmd2);
+    }
     if (bwr.read_consumed >= offsetof(typeof(br), pad)) {
         EXPECT_EQ(0u, br.arg2.target.ptr);
         EXPECT_EQ(0u, br.arg2.cookie);
diff --git a/libs/binder/tests/binderLibTest.cpp b/libs/binder/tests/binderLibTest.cpp
index 00406ed..9b1ba01 100644
--- a/libs/binder/tests/binderLibTest.cpp
+++ b/libs/binder/tests/binderLibTest.cpp
@@ -29,7 +29,6 @@
 
 #include <android-base/properties.h>
 #include <android-base/result-gmock.h>
-#include <android-base/strings.h>
 #include <binder/Binder.h>
 #include <binder/BpBinder.h>
 #include <binder/Functional.h>
@@ -48,16 +47,14 @@
 #include <sys/socket.h>
 #include <sys/un.h>
 
+#include "../Utils.h"
 #include "../binder_module.h"
 
-#define ARRAY_SIZE(array) (sizeof array / sizeof array[0])
-
 using namespace android;
 using namespace android::binder::impl;
 using namespace std::string_literals;
 using namespace std::chrono_literals;
 using android::base::testing::HasValue;
-using android::base::testing::Ok;
 using android::binder::Status;
 using android::binder::unique_fd;
 using testing::ExplainMatchResult;
@@ -218,10 +215,9 @@
 
             sp<IServiceManager> sm = defaultServiceManager();
             //printf("%s: pid %d, get service\n", __func__, m_pid);
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+            LIBBINDER_IGNORE("-Wdeprecated-declarations")
             m_server = sm->getService(binderLibTestServiceName);
-#pragma clang diagnostic pop
+            LIBBINDER_IGNORE_END()
             ASSERT_TRUE(m_server != nullptr);
             //printf("%s: pid %d, get service done\n", __func__, m_pid);
         }
@@ -568,7 +564,7 @@
 
 TEST_F(BinderLibTest, SetError) {
     int32_t testValue[] = { 0, -123, 123 };
-    for (size_t i = 0; i < ARRAY_SIZE(testValue); i++) {
+    for (size_t i = 0; i < countof(testValue); i++) {
         Parcel data, reply;
         data.writeInt32(testValue[i]);
         EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_SET_ERROR_TRANSACTION, data, &reply),
@@ -599,8 +595,8 @@
     Parcel data, reply;
     int32_t serverId[3];
 
-    data.writeInt32(ARRAY_SIZE(serverId));
-    for (size_t i = 0; i < ARRAY_SIZE(serverId); i++) {
+    data.writeInt32(countof(serverId));
+    for (size_t i = 0; i < countof(serverId); i++) {
         sp<IBinder> server;
         BinderLibTestBundle datai;
 
@@ -618,7 +614,7 @@
     EXPECT_EQ(0, id);
 
     ASSERT_THAT(reply.readInt32(&count), StatusEq(NO_ERROR));
-    EXPECT_EQ(ARRAY_SIZE(serverId), (size_t)count);
+    EXPECT_EQ(countof(serverId), (size_t)count);
 
     for (size_t i = 0; i < (size_t)count; i++) {
         BinderLibTestBundle replyi(&reply);
@@ -638,8 +634,8 @@
     Parcel data, reply;
     int32_t serverId[3];
 
-    data.writeInt32(ARRAY_SIZE(serverId));
-    for (size_t i = 0; i < ARRAY_SIZE(serverId); i++) {
+    data.writeInt32(countof(serverId));
+    for (size_t i = 0; i < countof(serverId); i++) {
         sp<IBinder> server;
         BinderLibTestBundle datai;
         BinderLibTestBundle datai2;
@@ -664,7 +660,7 @@
     EXPECT_EQ(0, id);
 
     ASSERT_THAT(reply.readInt32(&count), StatusEq(NO_ERROR));
-    EXPECT_EQ(ARRAY_SIZE(serverId), (size_t)count);
+    EXPECT_EQ(countof(serverId), (size_t)count);
 
     for (size_t i = 0; i < (size_t)count; i++) {
         int32_t counti;
@@ -2114,10 +2110,9 @@
         if (index == 0) {
             ret = sm->addService(binderLibTestServiceName, testService);
         } else {
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+            LIBBINDER_IGNORE("-Wdeprecated-declarations")
             sp<IBinder> server = sm->getService(binderLibTestServiceName);
-#pragma clang diagnostic pop
+            LIBBINDER_IGNORE_END()
             Parcel data, reply;
             data.writeInt32(index);
             data.writeStrongBinder(testService);
diff --git a/libs/binder/tests/binderRpcTest.cpp b/libs/binder/tests/binderRpcTest.cpp
index 19882ea..9b1b64a 100644
--- a/libs/binder/tests/binderRpcTest.cpp
+++ b/libs/binder/tests/binderRpcTest.cpp
@@ -141,11 +141,6 @@
     return ret;
 };
 
-static unsigned int allocateVsockPort() {
-    static unsigned int vsockPort = 34567;
-    return vsockPort++;
-}
-
 static unique_fd initUnixSocket(std::string addr) {
     auto socket_addr = UnixSocketAddress(addr.c_str());
     unique_fd fd(TEMP_FAILURE_RETRY(socket(socket_addr.addr()->sa_family, SOCK_STREAM, AF_UNIX)));
@@ -300,7 +295,6 @@
     serverConfig.socketType = static_cast<int32_t>(socketType);
     serverConfig.rpcSecurity = static_cast<int32_t>(rpcSecurity);
     serverConfig.serverVersion = serverVersion;
-    serverConfig.vsockPort = allocateVsockPort();
     serverConfig.addr = addr;
     serverConfig.socketFd = socketFd.get();
     for (auto mode : options.serverSupportedFileDescriptorTransportModes) {
@@ -379,7 +373,7 @@
                         unique_fd(dup(bootstrapClientFd.get())));
                 break;
             case SocketType::VSOCK:
-                status = session->setupVsockClient(VMADDR_CID_LOCAL, serverConfig.vsockPort);
+                status = session->setupVsockClient(VMADDR_CID_LOCAL, serverInfo.port);
                 break;
             case SocketType::INET:
                 status = session->setupInetClient("127.0.0.1", serverInfo.port);
@@ -1152,8 +1146,6 @@
 #else // BINDER_RPC_TO_TRUSTY_TEST
 bool testSupportVsockLoopback() {
     // We don't need to enable TLS to know if vsock is supported.
-    unsigned int vsockPort = allocateVsockPort();
-
     unique_fd serverFd(
             TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
 
@@ -1165,16 +1157,21 @@
 
     sockaddr_vm serverAddr{
             .svm_family = AF_VSOCK,
-            .svm_port = vsockPort,
+            .svm_port = VMADDR_PORT_ANY,
             .svm_cid = VMADDR_CID_ANY,
     };
     int ret = TEMP_FAILURE_RETRY(
             bind(serverFd.get(), reinterpret_cast<sockaddr*>(&serverAddr), sizeof(serverAddr)));
-    LOG_ALWAYS_FATAL_IF(0 != ret, "Could not bind socket to port %u: %s", vsockPort,
+    LOG_ALWAYS_FATAL_IF(0 != ret, "Could not bind socket to port VMADDR_PORT_ANY: %s",
                         strerror(errno));
 
+    socklen_t len = sizeof(serverAddr);
+    ret = getsockname(serverFd.get(), reinterpret_cast<sockaddr*>(&serverAddr), &len);
+    LOG_ALWAYS_FATAL_IF(0 != ret, "Failed to getsockname: %s", strerror(errno));
+    LOG_ALWAYS_FATAL_IF(len < sizeof(serverAddr), "getsockname didn't read the full addr struct");
+
     ret = TEMP_FAILURE_RETRY(listen(serverFd.get(), 1 /*backlog*/));
-    LOG_ALWAYS_FATAL_IF(0 != ret, "Could not listen socket on port %u: %s", vsockPort,
+    LOG_ALWAYS_FATAL_IF(0 != ret, "Could not listen socket on port %u: %s", serverAddr.svm_port,
                         strerror(errno));
 
     // Try to connect to the server using the VMADDR_CID_LOCAL cid
@@ -1183,13 +1180,13 @@
     // and they return ETIMEDOUT after that.
     unique_fd connectFd(
             TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
-    LOG_ALWAYS_FATAL_IF(!connectFd.ok(), "Could not create socket for port %u: %s", vsockPort,
-                        strerror(errno));
+    LOG_ALWAYS_FATAL_IF(!connectFd.ok(), "Could not create socket for port %u: %s",
+                        serverAddr.svm_port, strerror(errno));
 
     bool success = false;
     sockaddr_vm connectAddr{
             .svm_family = AF_VSOCK,
-            .svm_port = vsockPort,
+            .svm_port = serverAddr.svm_port,
             .svm_cid = VMADDR_CID_LOCAL,
     };
     ret = TEMP_FAILURE_RETRY(connect(connectFd.get(), reinterpret_cast<sockaddr*>(&connectAddr),
@@ -1538,8 +1535,9 @@
                     };
                 } break;
                 case SocketType::VSOCK: {
-                    auto port = allocateVsockPort();
-                    auto status = rpcServer->setupVsockServer(VMADDR_CID_LOCAL, port);
+                    unsigned port;
+                    auto status =
+                            rpcServer->setupVsockServer(VMADDR_CID_LOCAL, VMADDR_PORT_ANY, &port);
                     if (status != OK) {
                         return AssertionFailure() << "setupVsockServer: " << statusToString(status);
                     }
diff --git a/libs/binder/tests/binderRpcTestService.cpp b/libs/binder/tests/binderRpcTestService.cpp
index 28125f1..aef9464 100644
--- a/libs/binder/tests/binderRpcTestService.cpp
+++ b/libs/binder/tests/binderRpcTestService.cpp
@@ -143,8 +143,8 @@
             break;
         case SocketType::VSOCK:
             LOG_ALWAYS_FATAL_IF(OK !=
-                                        server->setupVsockServer(VMADDR_CID_LOCAL,
-                                                                 serverConfig.vsockPort),
+                                        server->setupVsockServer(VMADDR_CID_LOCAL, VMADDR_PORT_ANY,
+                                                                 &outPort),
                                 "Need `sudo modprobe vsock_loopback`?");
             break;
         case SocketType::INET: {
diff --git a/libs/binder/tests/binderStabilityTest.cpp b/libs/binder/tests/binderStabilityTest.cpp
index 3d99358..7a8f48e 100644
--- a/libs/binder/tests/binderStabilityTest.cpp
+++ b/libs/binder/tests/binderStabilityTest.cpp
@@ -27,8 +27,9 @@
 
 #include <sys/prctl.h>
 
-#include "aidl/BnBinderStabilityTest.h"
+#include "../Utils.h"
 #include "BnBinderStabilityTest.h"
+#include "aidl/BnBinderStabilityTest.h"
 
 using namespace android;
 using namespace ndk;
@@ -155,10 +156,9 @@
 }
 
 TEST(BinderStability, ForceDowngradeToVendorStability) {
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+    LIBBINDER_IGNORE("-Wdeprecated-declarations")
     sp<IBinder> serverBinder = android::defaultServiceManager()->getService(kSystemStabilityServer);
-#pragma clang diagnostic pop
+    LIBBINDER_IGNORE_END()
     auto server = interface_cast<IBinderStabilityTest>(serverBinder);
 
     ASSERT_NE(nullptr, server.get());
@@ -209,10 +209,9 @@
     EXPECT_EQ(connectionInfo, std::nullopt);
 }
 TEST(BinderStability, CantCallVendorBinderInSystemContext) {
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+    LIBBINDER_IGNORE("-Wdeprecated-declarations")
     sp<IBinder> serverBinder = android::defaultServiceManager()->getService(kSystemStabilityServer);
-#pragma clang diagnostic pop
+    LIBBINDER_IGNORE_END()
     auto server = interface_cast<IBinderStabilityTest>(serverBinder);
 
     ASSERT_NE(nullptr, server.get());
@@ -316,11 +315,10 @@
 extern "C" void AIBinder_markVendorStability(AIBinder* binder); // <- BAD DO NOT COPY
 
 TEST(BinderStability, NdkCantCallVendorBinderInSystemContext) {
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+    LIBBINDER_IGNORE("-Wdeprecated-declarations")
     SpAIBinder binder = SpAIBinder(AServiceManager_getService(
         String8(kSystemStabilityServer).c_str()));
-#pragma clang diagnostic pop
+    LIBBINDER_IGNORE_END()
 
     std::shared_ptr<aidl::IBinderStabilityTest> remoteServer =
         aidl::IBinderStabilityTest::fromBinder(binder);
diff --git a/libs/binder/tests/binder_sdk/binder_sdk_docker_test.sh b/libs/binder/tests/binder_sdk/binder_sdk_docker_test.sh
index 0eca846..9ea8cb3 100755
--- a/libs/binder/tests/binder_sdk/binder_sdk_docker_test.sh
+++ b/libs/binder/tests/binder_sdk/binder_sdk_docker_test.sh
@@ -57,7 +57,7 @@
         exit 1
     fi
     ${ANDROID_BUILD_TOP}/build/soong/soong_ui.bash --make-mode binder_sdk
-    BINDER_SDK_ZIP="${ANDROID_BUILD_TOP}/out/soong/.intermediates/frameworks/native/libs/binder/binder_sdk/linux_glibc_x86_64/*/binder_sdk.zip"
+    BINDER_SDK_ZIP="${ANDROID_BUILD_TOP}/out/soong/.intermediates/frameworks/native/libs/binder/binder_sdk/linux_glibc_x86_64/binder_sdk.zip"
     DOCKER_PATH="$(dirname $(ls -1 ${BINDER_SDK_ZIP} | head --lines=1))"
 fi
 
diff --git a/libs/binder/tests/unit_fuzzers/BpBinderFuzz.cpp b/libs/binder/tests/unit_fuzzers/BpBinderFuzz.cpp
index a6fd487..bc0d5af 100644
--- a/libs/binder/tests/unit_fuzzers/BpBinderFuzz.cpp
+++ b/libs/binder/tests/unit_fuzzers/BpBinderFuzz.cpp
@@ -36,7 +36,9 @@
     FuzzedDataProvider fdp(data, size);
 
     std::string addr = std::string(getenv("TMPDIR") ?: "/tmp") + "/binderRpcBenchmark";
-    (void)unlink(addr.c_str());
+    if (0 != unlink(addr.c_str()) && errno != ENOENT) {
+        LOG(WARNING) << "Could not unlink: " << strerror(errno);
+    }
 
     sp<RpcServer> server = RpcServer::make();
 
diff --git a/opengl/libs/EGL/egl_display.cpp b/opengl/libs/EGL/egl_display.cpp
index 5b5afd3..b1a287f 100644
--- a/opengl/libs/EGL/egl_display.cpp
+++ b/opengl/libs/EGL/egl_display.cpp
@@ -383,6 +383,14 @@
         // before using cnx->major & cnx->minor
         if (major != nullptr) *major = cnx->major;
         if (minor != nullptr) *minor = cnx->minor;
+        auto mergeExtensionStrings = [](const std::vector<std::string>& strings) {
+            std::ostringstream combinedStringStream;
+            std::copy(strings.begin(), strings.end(),
+                      std::ostream_iterator<std::string>(combinedStringStream, " "));
+            // gBuiltinExtensionString already has a trailing space so is added here
+            return gBuiltinExtensionString + combinedStringStream.str();
+        };
+        mExtensionString = mergeExtensionStrings(extensionStrings);
     }
 
     { // scope for refLock
@@ -391,14 +399,6 @@
         refCond.notify_all();
     }
 
-    auto mergeExtensionStrings = [](const std::vector<std::string>& strings) {
-        std::ostringstream combinedStringStream;
-        std::copy(strings.begin(), strings.end(),
-                  std::ostream_iterator<std::string>(combinedStringStream, " "));
-        // gBuiltinExtensionString already has a trailing space so is added here
-        return gBuiltinExtensionString + combinedStringStream.str();
-    };
-    mExtensionString = mergeExtensionStrings(extensionStrings);
     return EGL_TRUE;
 }