libhidl: : update from upstream

Followed instructions from go/nnapi-dep-instructions.

No manual changes / interventions have been made.

$ git merge cros/upstream/master --no-ff
$ repo upload --cbr . --no-verify

BUG=b:197814725
TEST=FEATURES=test emerge-amd64-generic nnapi aosp-frameworks-ml-nn

Change-Id: I1b0760a90f83ad0a1f40c87b3ba653237d4cb6a0
diff --git a/Android.bp b/Android.bp
index 034919e..33ba0e9 100644
--- a/Android.bp
+++ b/Android.bp
@@ -12,6 +12,23 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["system_libhidl_license"],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "system_libhidl_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
 cc_defaults {
     name: "libhidl-defaults",
     cflags: [
diff --git a/adapter/Android.bp b/adapter/Android.bp
index 3dc382e..83609ff 100644
--- a/adapter/Android.bp
+++ b/adapter/Android.bp
@@ -12,6 +12,15 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "system_libhidl_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["system_libhidl_license"],
+}
+
 cc_library {
     name: "libhidladapter",
     defaults: ["libhidl-defaults"],
@@ -34,4 +43,3 @@
         "libutils",
     ],
 }
-
diff --git a/base/HidlSupport.cpp b/base/HidlSupport.cpp
index af805b9..78faa2f 100644
--- a/base/HidlSupport.cpp
+++ b/base/HidlSupport.cpp
@@ -217,6 +217,14 @@
     if (size >= UINT32_MAX) {
         LOG(FATAL) << "string size can't exceed 2^32 bytes: " << size;
     }
+
+    if (size == 0) {
+        mBuffer = kEmptyString;
+        mSize = 0;
+        mOwnsBuffer = false;
+        return;
+    }
+
     char *buf = (char *)malloc(size + 1);
     memcpy(buf, data, size);
     buf[size] = '\0';
diff --git a/base/include/hidl/HidlInternal.h b/base/include/hidl/HidlInternal.h
index 3cd246a..3d1a444 100644
--- a/base/include/hidl/HidlInternal.h
+++ b/base/include/hidl/HidlInternal.h
@@ -201,7 +201,10 @@
     // A list of registered instrumentation callbacks.
     std::vector<InstrumentationCallback> mInstrumentationCallbacks;
     // Flag whether to enable instrumentation.
-    bool mEnableInstrumentation;
+    union {
+        bool mEnableInstrumentation;
+        void* mReserved0;
+    };
     // Prefix to lookup the instrumentation libraries.
     std::string mInstrumentationLibPackage;
     // Used for dlsym to load the profiling method for given interface.
@@ -209,6 +212,12 @@
 
 };
 
+#ifdef __LP64__
+static_assert(sizeof(HidlInstrumentor) == 88, "HidlInstrumentor size frozen by prebuilts");
+#else
+static_assert(sizeof(HidlInstrumentor) == 44, "HidlInstrumentor size frozen by prebuilts");
+#endif
+
 }  // namespace details
 }  // namespace hardware
 }  // namespace android
diff --git a/libhidlmemory/Android.bp b/libhidlmemory/Android.bp
index 547be11..fc5770c 100644
--- a/libhidlmemory/Android.bp
+++ b/libhidlmemory/Android.bp
@@ -12,6 +12,15 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "system_libhidl_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["system_libhidl_license"],
+}
+
 cc_library {
     name: "libhidlmemory",
     vendor_available: true,
diff --git a/minijail/Android.bp b/minijail/Android.bp
index 83db2d9..ad12dad 100644
--- a/minijail/Android.bp
+++ b/minijail/Android.bp
@@ -1,6 +1,15 @@
 // TODO(b/110363419): remove or make failures harder
 // Deprecated: most minijail users should either use libavservices_minijail
 // or reinstitute this (w/ fatal checks).
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "system_libhidl_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["system_libhidl_license"],
+}
+
 cc_library_shared {
     name: "libhwminijail",
     defaults: ["hidl_defaults"],
diff --git a/test_main.cpp b/test_main.cpp
index 0a1e97b..5c6c78e 100644
--- a/test_main.cpp
+++ b/test_main.cpp
@@ -17,7 +17,7 @@
 #define LOG_TAG "LibHidlTest"
 
 #pragma clang diagnostic push
-#pragma clang diagnostic fatal "-Wpadded"
+#pragma clang diagnostic error "-Wpadded"
 #include <hidl/HidlInternal.h>
 #include <hidl/HidlSupport.h>
 #pragma clang diagnostic pop
@@ -175,6 +175,20 @@
     EXPECT_FALSE(hs2 <= hs1);
 }
 
+// empty string optimization should apply for any constructor
+TEST_F(LibHidlTest, HidlStringEmptyLiteralAllocation) {
+    using android::hardware::hidl_string;
+
+    hidl_string empty1;
+    hidl_string empty2("");
+    hidl_string empty3("foo", 0);
+    hidl_string empty4((std::string()));
+
+    EXPECT_EQ(empty1.c_str(), empty2.c_str());
+    EXPECT_EQ(empty1.c_str(), empty3.c_str());
+    EXPECT_EQ(empty1.c_str(), empty4.c_str());
+}
+
 TEST_F(LibHidlTest, MemoryTest) {
     using android::hardware::hidl_memory;
 
diff --git a/transport/Android.bp b/transport/Android.bp
index 86603ee..10f31a7 100644
--- a/transport/Android.bp
+++ b/transport/Android.bp
@@ -12,6 +12,15 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "system_libhidl_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["system_libhidl_license"],
+}
+
 hidl_package_root {
     name: "android.hidl",
 }
diff --git a/transport/HidlLazyUtils.cpp b/transport/HidlLazyUtils.cpp
index d00b461..c5f8c74 100644
--- a/transport/HidlLazyUtils.cpp
+++ b/transport/HidlLazyUtils.cpp
@@ -36,6 +36,12 @@
 
     bool addRegisteredService(const sp<IBase>& service, const std::string& name);
 
+    bool tryUnregisterLocked();
+
+    void reRegisterLocked();
+
+    void setActiveServicesCallback(const std::function<bool(bool)>& activeServicesCallback);
+
   protected:
     Return<void> onClients(const sp<IBase>& service, bool clients) override;
 
@@ -44,29 +50,46 @@
         sp<IBase> service;
         std::string name;
         bool clients = false;
+        // Used to keep track of unregistered services to allow re-registry
+        bool registered = true;
     };
 
     /**
      * Looks up service that is guaranteed to be registered (service from
      * onClients).
      */
-    Service& assertRegisteredService(const sp<IBase>& service);
+    Service& assertRegisteredServiceLocked(const sp<IBase>& service);
 
     /**
      * Registers or re-registers services. Returns whether successful.
      */
-    bool registerService(const sp<IBase>& service, const std::string& name);
+    bool registerServiceLocked(const sp<IBase>& service, const std::string& name);
 
     /**
      * Unregisters all services that we can. If we can't unregister all, re-register other
      * services.
      */
-    void tryShutdown();
+    void tryShutdownLocked();
+
+    /**
+     * For below.
+     */
+    std::mutex mMutex;
 
     /**
      * Number of services that have been registered.
      */
     std::vector<Service> mRegisteredServices;
+
+    /**
+     * Callback for reporting the number of services with clients.
+     */
+    std::function<bool(bool)> mActiveServicesCallback;
+
+    /**
+     * Previous value passed to the active services callback.
+     */
+    std::optional<bool> mPreviousHasClients;
 };
 
 class LazyServiceRegistrarImpl {
@@ -75,6 +98,9 @@
 
     status_t registerService(const sp<::android::hidl::base::V1_0::IBase>& service,
                              const std::string& name);
+    bool tryUnregister();
+    void reRegister();
+    void setActiveServicesCallback(const std::function<bool(bool)>& activeServicesCallback);
 
   private:
     sp<ClientCounterCallback> mClientCallback;
@@ -82,7 +108,8 @@
 
 bool ClientCounterCallback::addRegisteredService(const sp<IBase>& service,
                                                  const std::string& name) {
-    bool success = registerService(service, name);
+    std::lock_guard<std::mutex> lock(mMutex);
+    bool success = registerServiceLocked(service, name);
 
     if (success) {
         mRegisteredServices.push_back({service, name});
@@ -91,7 +118,7 @@
     return success;
 }
 
-ClientCounterCallback::Service& ClientCounterCallback::assertRegisteredService(
+ClientCounterCallback::Service& ClientCounterCallback::assertRegisteredServiceLocked(
         const sp<IBase>& service) {
     for (Service& registered : mRegisteredServices) {
         if (registered.service != service) continue;
@@ -102,7 +129,8 @@
     __builtin_unreachable();
 }
 
-bool ClientCounterCallback::registerService(const sp<IBase>& service, const std::string& name) {
+bool ClientCounterCallback::registerServiceLocked(const sp<IBase>& service,
+                                                  const std::string& name) {
     auto manager = hardware::defaultServiceManager1_2();
 
     const std::string descriptor = getDescriptor(service.get());
@@ -124,13 +152,10 @@
     return true;
 }
 
-/**
- * onClients is oneway, so no need to worry about multi-threading. Note that this means multiple
- * invocations could occur on different threads however.
- */
 Return<void> ClientCounterCallback::onClients(const sp<::android::hidl::base::V1_0::IBase>& service,
                                               bool clients) {
-    Service& registered = assertRegisteredService(service);
+    std::lock_guard<std::mutex> lock(mMutex);
+    Service& registered = assertRegisteredServiceLocked(service);
     if (registered.clients == clients) {
         LOG(FATAL) << "Process already thought " << getDescriptor(service.get()) << "/"
                    << registered.name << " had clients: " << registered.clients
@@ -147,46 +172,79 @@
               << " available) client(s) in use after notification " << getDescriptor(service.get())
               << "/" << registered.name << " has clients: " << clients;
 
-    if (numWithClients == 0) {
-        tryShutdown();
+    bool handledInCallback = false;
+    if (mActiveServicesCallback != nullptr) {
+        bool hasClients = numWithClients != 0;
+        if (hasClients != mPreviousHasClients) {
+            handledInCallback = mActiveServicesCallback(hasClients);
+            mPreviousHasClients = hasClients;
+        }
+    }
+
+    // If there is no callback defined or the callback did not handle this
+    // client count change event, try to shutdown the process if its services
+    // have no clients.
+    if (!handledInCallback && numWithClients == 0) {
+        tryShutdownLocked();
     }
 
     return Status::ok();
 }
 
-void ClientCounterCallback::tryShutdown() {
-    LOG(INFO) << "Trying to exit HAL. No clients in use for any service in process.";
-
+bool ClientCounterCallback::tryUnregisterLocked() {
     auto manager = hardware::defaultServiceManager1_2();
 
-    auto unRegisterIt = mRegisteredServices.begin();
-    for (; unRegisterIt != mRegisteredServices.end(); ++unRegisterIt) {
-        auto& entry = (*unRegisterIt);
-
+    for (Service& entry : mRegisteredServices) {
         const std::string descriptor = getDescriptor(entry.service.get());
         bool success = manager->tryUnregister(descriptor, entry.name, entry.service);
 
         if (!success) {
             LOG(INFO) << "Failed to unregister HAL " << descriptor << "/" << entry.name;
-            break;
+            return false;
         }
+
+        // Mark the entry unregistered, but do not remove it (may still be re-registered)
+        entry.registered = false;
     }
 
-    if (unRegisterIt == mRegisteredServices.end()) {
+    return true;
+}
+
+void ClientCounterCallback::reRegisterLocked() {
+    for (Service& entry : mRegisteredServices) {
+        // re-register entry if not already registered
+        if (entry.registered) {
+            continue;
+        }
+
+        if (!registerServiceLocked(entry.service, entry.name)) {
+            // Must restart. Otherwise, clients will never be able to get ahold of this service.
+            LOG(FATAL) << "Bad state: could not re-register " << getDescriptor(entry.service.get());
+        }
+
+        entry.registered = true;
+    }
+}
+
+void ClientCounterCallback::tryShutdownLocked() {
+    LOG(INFO) << "Trying to exit HAL. No clients in use for any service in process.";
+
+    if (tryUnregisterLocked()) {
         LOG(INFO) << "Unregistered all clients and exiting";
         exit(EXIT_SUCCESS);
     }
 
-    for (auto reRegisterIt = mRegisteredServices.begin(); reRegisterIt != unRegisterIt;
-         reRegisterIt++) {
-        auto& entry = (*reRegisterIt);
+    // At this point, we failed to unregister some of the services, leaving the
+    // server in an inconsistent state. Re-register all services that were
+    // unregistered by tryUnregisterLocked().
+    reRegisterLocked();
+}
 
-        // re-register entry
-        if (!registerService(entry.service, entry.name)) {
-            // Must restart. Otherwise, clients will never be able to get ahold of this service.
-            LOG(FATAL) << "Bad state: could not re-register " << getDescriptor(entry.service.get());
-        }
-    }
+void ClientCounterCallback::setActiveServicesCallback(
+        const std::function<bool(bool)>& activeServicesCallback) {
+    std::lock_guard<std::mutex> lock(mMutex);
+
+    mActiveServicesCallback = activeServicesCallback;
 }
 
 status_t LazyServiceRegistrarImpl::registerService(
@@ -198,6 +256,23 @@
     return ::android::OK;
 }
 
+bool LazyServiceRegistrarImpl::tryUnregister() {
+    // see comments in header, this should only be called from the active
+    // services callback, see also b/191781736
+    return mClientCallback->tryUnregisterLocked();
+}
+
+void LazyServiceRegistrarImpl::reRegister() {
+    // see comments in header, this should only be called from the active
+    // services callback, see also b/191781736
+    mClientCallback->reRegisterLocked();
+}
+
+void LazyServiceRegistrarImpl::setActiveServicesCallback(
+        const std::function<bool(bool)>& activeServicesCallback) {
+    mClientCallback->setActiveServicesCallback(activeServicesCallback);
+}
+
 }  // namespace details
 
 LazyServiceRegistrar::LazyServiceRegistrar() {
@@ -214,5 +289,18 @@
     return mImpl->registerService(service, name);
 }
 
+bool LazyServiceRegistrar::tryUnregister() {
+    return mImpl->tryUnregister();
+}
+
+void LazyServiceRegistrar::reRegister() {
+    mImpl->reRegister();
+}
+
+void LazyServiceRegistrar::setActiveServicesCallback(
+        const std::function<bool(bool)>& activeServicesCallback) {
+    mImpl->setActiveServicesCallback(activeServicesCallback);
+}
+
 }  // namespace hardware
 }  // namespace android
diff --git a/transport/HidlTransportSupport.cpp b/transport/HidlTransportSupport.cpp
index e645cd0..d0ac243 100644
--- a/transport/HidlTransportSupport.cpp
+++ b/transport/HidlTransportSupport.cpp
@@ -128,12 +128,7 @@
 
 namespace details {
 int32_t getPidIfSharable() {
-#if LIBHIDL_TARGET_DEBUGGABLE
     return getpid();
-#else
-    using android::hidl::manager::V1_0::IServiceManager;
-    return static_cast<int32_t>(IServiceManager::PidConstant::NO_PID);
-#endif
 }
 }  // namespace details
 
diff --git a/transport/ServiceManagement.cpp b/transport/ServiceManagement.cpp
index 8122324..c638279 100644
--- a/transport/ServiceManagement.cpp
+++ b/transport/ServiceManagement.cpp
@@ -159,12 +159,6 @@
 static constexpr bool kEnforceVintfManifest = false;
 #endif
 
-#ifdef LIBHIDL_TARGET_DEBUGGABLE
-static constexpr bool kDebuggable = true;
-#else
-static constexpr bool kDebuggable = false;
-#endif
-
 static bool* getTrebleTestingOverridePtr() {
     static bool gTrebleTestingOverride = false;
     return &gTrebleTestingOverride;
@@ -174,8 +168,13 @@
     *getTrebleTestingOverridePtr() = testingOverride;
 }
 
+static bool isDebuggable() {
+    static bool debuggable = base::GetBoolProperty("ro.debuggable", false);
+    return debuggable;
+}
+
 static inline bool isTrebleTestingOverride() {
-    if (kEnforceVintfManifest && !kDebuggable) {
+    if (kEnforceVintfManifest && !isDebuggable()) {
         // don't allow testing override in production
         return false;
     }
@@ -183,70 +182,8 @@
     return *getTrebleTestingOverridePtr();
 }
 
-/*
- * Returns the age of the current process by reading /proc/self/stat and comparing starttime to the
- * current time. This is useful for measuring how long it took a HAL to register itself.
- */
-__attribute__((noinline)) static long getProcessAgeMs() {
-    constexpr const int PROCFS_STAT_STARTTIME_INDEX = 21;
-    std::string content;
-    if (!android::base::ReadFileToString("/proc/self/stat", &content, false)) {
-        LOG(ERROR) << "Process age: Could not read /proc/self/stat";
-        return -1;
-    }
-
-    std::vector<std::string> stats = android::base::Split(content, " ");
-    if (PROCFS_STAT_STARTTIME_INDEX >= stats.size()) {
-        LOG(ERROR) << "Process age: Could not read starttime from /proc/self/stat";
-        return -1;
-    }
-
-    const std::string& startTimeString = stats.at(PROCFS_STAT_STARTTIME_INDEX);
-    unsigned long long startTimeInClockTicks = 0;
-    if (!android::base::ParseUint(startTimeString, &startTimeInClockTicks)) {
-        LOG(ERROR) << "Process age: Could not parse start time: " << startTimeString;
-        return -1;
-    }
-
-    const int64_t ticksPerSecond = sysconf(_SC_CLK_TCK);
-    if (ticksPerSecond <= 0) {
-        LOG(ERROR) << "Process age: Invalid _SC_CLK_TCK: " << ticksPerSecond;
-        return -1;
-    }
-
-    const int64_t uptime = android::uptimeMillis();
-    if (uptime < 0) {
-        LOG(ERROR) << "Process age: Invalid uptime: " << uptime;
-        return -1;
-    }
-
-    unsigned long long startTimeTicks;
-    if (__builtin_umulll_overflow(1000ULL, startTimeInClockTicks, &startTimeTicks)) {
-        LOG(ERROR) << "Process age: Too many ticks, overflow: " << startTimeInClockTicks;
-        return -1;
-    }
-
-    long startTimeMs = startTimeTicks / ticksPerSecond;
-    if (startTimeMs >= uptime) {
-        LOG(ERROR) << "Process age: process started in future: " << startTimeMs << " after "
-                   << uptime;
-        return -1;
-    }
-
-    return uptime - startTimeMs;
-}
-
 static void onRegistrationImpl(const std::string& descriptor, const std::string& instanceName) {
-    long halStartDelay = getProcessAgeMs();
-    if (halStartDelay >= 0) {
-        // The "start delay" printed here is an estimate of how long it took the HAL to go from
-        // process creation to registering itself as a HAL.  Actual start time could be longer
-        // because the process might not have joined the threadpool yet, so it might not be ready to
-        // process transactions.
-        LOG(INFO) << "Registered " << descriptor << "/" << instanceName << " (start delay of "
-                  << halStartDelay << "ms)";
-    }
-
+    LOG(INFO) << "Registered " << descriptor << "/" << instanceName;
     tryShortenProcessName(descriptor);
 }
 
@@ -479,18 +416,27 @@
             *(void **)(&generator) = dlsym(handle, sym.c_str());
             if(!generator) {
                 const char* error = dlerror();
-                LOG(ERROR) << "Passthrough lookup opened " << lib
-                           << " but could not find symbol " << sym << ": "
-                           << (error == nullptr ? "unknown error" : error);
-                dlclose(handle);
-                return true;
+                LOG(ERROR) << "Passthrough lookup opened " << lib << " but could not find symbol "
+                           << sym << ": " << (error == nullptr ? "unknown error" : error)
+                           << ". Keeping library open.";
+
+                // dlclose too problematic in multi-threaded environment
+                // dlclose(handle);
+
+                return true;  // continue
             }
 
             ret = (*generator)(name.c_str());
 
             if (ret == nullptr) {
-                dlclose(handle);
-                return true; // this module doesn't provide this instance name
+                LOG(ERROR) << "Could not find instance '" << name.c_str() << "' in library " << lib
+                           << ". Keeping library open.";
+
+                // dlclose too problematic in multi-threaded environment
+                // dlclose(handle);
+
+                // this module doesn't provide this particular instance
+                return true;  // continue
             }
 
             // Actual fqname might be a subclass.
@@ -819,7 +765,7 @@
     const bool vintfHwbinder = (transport == Transport::HWBINDER);
     const bool vintfPassthru = (transport == Transport::PASSTHROUGH);
     const bool trebleTestingOverride = isTrebleTestingOverride();
-    const bool allowLegacy = !kEnforceVintfManifest || (trebleTestingOverride && kDebuggable);
+    const bool allowLegacy = !kEnforceVintfManifest || (trebleTestingOverride && isDebuggable());
     const bool vintfLegacy = (transport == Transport::EMPTY) && allowLegacy;
 
     if (!kEnforceVintfManifest) {
@@ -901,7 +847,13 @@
 
     if (kEnforceVintfManifest && !isTrebleTestingOverride()) {
         using Transport = IServiceManager1_0::Transport;
-        Transport transport = sm->getTransport(descriptor, name);
+        Return<Transport> transport = sm->getTransport(descriptor, name);
+
+        if (!transport.isOk()) {
+            LOG(ERROR) << "Could not get transport for " << descriptor << "/" << name << ": "
+                       << transport.description();
+            return UNKNOWN_ERROR;
+        }
 
         if (transport != Transport::HWBINDER) {
             LOG(ERROR) << "Service " << descriptor << "/" << name
diff --git a/transport/allocator/1.0/Android.bp b/transport/allocator/1.0/Android.bp
index 2e93a6f..0cc3b62 100644
--- a/transport/allocator/1.0/Android.bp
+++ b/transport/allocator/1.0/Android.bp
@@ -1,5 +1,14 @@
 // This file is autogenerated by hidl-gen -Landroidbp.
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "system_libhidl_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["system_libhidl_license"],
+}
+
 hidl_interface {
     name: "android.hidl.allocator@1.0",
     root: "android.hidl",
diff --git a/transport/allocator/1.0/default/Android.bp b/transport/allocator/1.0/default/Android.bp
index 1116f1d..42abe9c 100644
--- a/transport/allocator/1.0/default/Android.bp
+++ b/transport/allocator/1.0/default/Android.bp
@@ -12,6 +12,15 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "system_libhidl_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["system_libhidl_license"],
+}
+
 cc_binary {
     name: "android.hidl.allocator@1.0-service",
     relative_install_path: "hw",
diff --git a/transport/allocator/1.0/utils/Android.bp b/transport/allocator/1.0/utils/Android.bp
index b324ef1..f21047d 100644
--- a/transport/allocator/1.0/utils/Android.bp
+++ b/transport/allocator/1.0/utils/Android.bp
@@ -12,6 +12,15 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "system_libhidl_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["system_libhidl_license"],
+}
+
 cc_library {
     name: "libhidlallocatorutils",
     vendor_available: true,
diff --git a/transport/allocator/1.0/vts/functional/Android.bp b/transport/allocator/1.0/vts/functional/Android.bp
index e170ce0..f53fc4f 100644
--- a/transport/allocator/1.0/vts/functional/Android.bp
+++ b/transport/allocator/1.0/vts/functional/Android.bp
@@ -14,6 +14,15 @@
 // limitations under the License.
 //
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "system_libhidl_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["system_libhidl_license"],
+}
+
 cc_test {
     name: "VtsHidlAllocatorV1_0TargetTest",
     defaults: ["VtsHalTargetTestDefaults"],
diff --git a/transport/base/1.0/Android.bp b/transport/base/1.0/Android.bp
index 61e5eda..461f7e7 100644
--- a/transport/base/1.0/Android.bp
+++ b/transport/base/1.0/Android.bp
@@ -1,5 +1,14 @@
 // This file is autogenerated by hidl-gen -Landroidbp.
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "system_libhidl_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["system_libhidl_license"],
+}
+
 hidl_interface {
     name: "android.hidl.base@1.0",
     root: "android.hidl",
diff --git a/transport/base/1.0/vts/functional/Android.bp b/transport/base/1.0/vts/functional/Android.bp
index 0c814ae..f25aaaa 100644
--- a/transport/base/1.0/vts/functional/Android.bp
+++ b/transport/base/1.0/vts/functional/Android.bp
@@ -12,6 +12,15 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "system_libhidl_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["system_libhidl_license"],
+}
+
 cc_test {
     name: "vts_ibase_test",
     defaults: ["libinit_test_utils_libraries_defaults"],
diff --git a/transport/include/hidl/HidlLazyUtils.h b/transport/include/hidl/HidlLazyUtils.h
index 97fe20e..376b6ab 100644
--- a/transport/include/hidl/HidlLazyUtils.h
+++ b/transport/include/hidl/HidlLazyUtils.h
@@ -16,6 +16,8 @@
 
 #pragma once
 
+#include <functional>
+
 #include <android/hidl/base/1.0/IBase.h>
 #include <utils/RefBase.h>
 #include <utils/StrongPointer.h>
@@ -41,6 +43,39 @@
      static LazyServiceRegistrar& getInstance();
      status_t registerService(const sp<::android::hidl::base::V1_0::IBase>& service,
                               const std::string& name = "default");
+     /**
+      * Set a callback that is invoked when the active HAL count (i.e. HALs with clients)
+      * registered with this process drops to zero (or becomes nonzero).
+      * The callback takes a boolean argument, which is 'true' if there is
+      * at least one HAL with clients.
+      *
+      * Callback return value:
+      * - false: Default behavior for lazy HALs (shut down the process if there
+      *          are no clients).
+      * - true:  Don't shut down the process even if there are no clients.
+      *
+      * This callback gives a chance to:
+      * 1 - Perform some additional operations before exiting;
+      * 2 - Prevent the process from exiting by returning "true" from the
+      *     callback.
+      *
+      * This method should be called before 'registerService' to avoid races.
+      */
+     void setActiveServicesCallback(const std::function<bool(bool)>& activeServicesCallback);
+
+     /**
+      * Try to unregister all services previously registered with 'registerService'.
+      * Returns 'true' if successful. This should only be called within
+      * the callback registered by setActiveServicesCallback.
+      */
+     bool tryUnregister();
+
+     /**
+      * Re-register services that were unregistered by 'tryUnregister'.
+      * This method should be called in the case 'tryUnregister' fails
+      * (and should be called on the same thread).
+      */
+     void reRegister();
 
    private:
      std::shared_ptr<details::LazyServiceRegistrarImpl> mImpl;
diff --git a/transport/include/hidl/ServiceManagement.h b/transport/include/hidl/ServiceManagement.h
index c8e8f6c..886e816 100644
--- a/transport/include/hidl/ServiceManagement.h
+++ b/transport/include/hidl/ServiceManagement.h
@@ -54,7 +54,10 @@
 void preloadPassthroughService(const std::string &descriptor);
 
 // Returns a service with the following constraints:
-// - retry => service is waited for and returned if available in this process
+// - retry => service is waited for and returned if it is declared in the
+//     manifest AND it is available in this process (if errors indicate an
+//     sepolicy denial, then this will return - TODO(b/28321379) more precise
+//     errors to handle more cases)
 // - getStub => internal only. Forces to get the unwrapped (no BsFoo) if available.
 // TODO(b/65843592)
 // If the service is a remote service, this function returns BpBase. If the service is
diff --git a/transport/manager/1.0/Android.bp b/transport/manager/1.0/Android.bp
index b0d2eee..4a84b86 100644
--- a/transport/manager/1.0/Android.bp
+++ b/transport/manager/1.0/Android.bp
@@ -1,5 +1,14 @@
 // This file is autogenerated by hidl-gen -Landroidbp.
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "system_libhidl_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["system_libhidl_license"],
+}
+
 hidl_interface {
     name: "android.hidl.manager@1.0",
     root: "android.hidl",
diff --git a/transport/manager/1.1/Android.bp b/transport/manager/1.1/Android.bp
index d3fbe7f..c9e22c9 100644
--- a/transport/manager/1.1/Android.bp
+++ b/transport/manager/1.1/Android.bp
@@ -1,5 +1,14 @@
 // This file is autogenerated by hidl-gen -Landroidbp.
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "system_libhidl_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["system_libhidl_license"],
+}
+
 hidl_interface {
     name: "android.hidl.manager@1.1",
     root: "android.hidl",
diff --git a/transport/manager/1.2/Android.bp b/transport/manager/1.2/Android.bp
index 75d7a07..a58c12e 100644
--- a/transport/manager/1.2/Android.bp
+++ b/transport/manager/1.2/Android.bp
@@ -1,5 +1,14 @@
 // This file is autogenerated by hidl-gen -Landroidbp.
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "system_libhidl_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["system_libhidl_license"],
+}
+
 hidl_interface {
     name: "android.hidl.manager@1.2",
     root: "android.hidl",
diff --git a/transport/memory/1.0/Android.bp b/transport/memory/1.0/Android.bp
index 4fd00c0..8e066a9 100644
--- a/transport/memory/1.0/Android.bp
+++ b/transport/memory/1.0/Android.bp
@@ -1,5 +1,14 @@
 // This file is autogenerated by hidl-gen -Landroidbp.
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "system_libhidl_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["system_libhidl_license"],
+}
+
 hidl_interface {
     name: "android.hidl.memory@1.0",
     root: "android.hidl",
diff --git a/transport/memory/1.0/default/Android.bp b/transport/memory/1.0/default/Android.bp
index f56ee95..a44a0db 100644
--- a/transport/memory/1.0/default/Android.bp
+++ b/transport/memory/1.0/default/Android.bp
@@ -12,6 +12,15 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "system_libhidl_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["system_libhidl_license"],
+}
+
 cc_library_shared {
     name: "android.hidl.memory@1.0-impl",
     vendor_available: true,
diff --git a/transport/memory/block/1.0/Android.bp b/transport/memory/block/1.0/Android.bp
index 86c29bc..bfaf139 100644
--- a/transport/memory/block/1.0/Android.bp
+++ b/transport/memory/block/1.0/Android.bp
@@ -1,5 +1,14 @@
 // This file is autogenerated by hidl-gen -Landroidbp.
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "system_libhidl_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["system_libhidl_license"],
+}
+
 hidl_interface {
     name: "android.hidl.memory.block@1.0",
     root: "android.hidl",
diff --git a/transport/memory/token/1.0/Android.bp b/transport/memory/token/1.0/Android.bp
index a42f786..c304284 100644
--- a/transport/memory/token/1.0/Android.bp
+++ b/transport/memory/token/1.0/Android.bp
@@ -1,5 +1,14 @@
 // This file is autogenerated by hidl-gen -Landroidbp.
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "system_libhidl_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["system_libhidl_license"],
+}
+
 hidl_interface {
     name: "android.hidl.memory.token@1.0",
     root: "android.hidl",
diff --git a/transport/safe_union/1.0/Android.bp b/transport/safe_union/1.0/Android.bp
index d0aa348..cae92dd 100644
--- a/transport/safe_union/1.0/Android.bp
+++ b/transport/safe_union/1.0/Android.bp
@@ -1,5 +1,14 @@
 // This file is autogenerated by hidl-gen -Landroidbp.
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "system_libhidl_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["system_libhidl_license"],
+}
+
 hidl_interface {
     name: "android.hidl.safe_union@1.0",
     root: "android.hidl",
diff --git a/transport/token/1.0/Android.bp b/transport/token/1.0/Android.bp
index 0a7d3c2..8bda482 100644
--- a/transport/token/1.0/Android.bp
+++ b/transport/token/1.0/Android.bp
@@ -1,5 +1,14 @@
 // This file is autogenerated by hidl-gen -Landroidbp.
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "system_libhidl_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["system_libhidl_license"],
+}
+
 hidl_interface {
     name: "android.hidl.token@1.0",
     root: "android.hidl",
diff --git a/transport/token/1.0/utils/Android.bp b/transport/token/1.0/utils/Android.bp
index f9a4623..84f6f0f 100644
--- a/transport/token/1.0/utils/Android.bp
+++ b/transport/token/1.0/utils/Android.bp
@@ -12,6 +12,15 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "system_libhidl_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["system_libhidl_license"],
+}
+
 cc_library {
     name: "android.hidl.token@1.0-utils",
     defaults: ["libhidl-defaults"],
diff --git a/vintfdata/Android.mk b/vintfdata/Android.mk
index a7721c2..4c5cca5 100644
--- a/vintfdata/Android.mk
+++ b/vintfdata/Android.mk
@@ -48,6 +48,9 @@
 
 include $(CLEAR_VARS)
 LOCAL_MODULE        := vendor_compatibility_matrix.xml
+LOCAL_LICENSE_KINDS := SPDX-license-identifier-Apache-2.0
+LOCAL_LICENSE_CONDITIONS := notice
+LOCAL_NOTICE_FILE   := $(LOCAL_PATH)/../NOTICE
 LOCAL_MODULE_STEM   := compatibility_matrix.xml
 LOCAL_MODULE_CLASS  := ETC
 LOCAL_MODULE_PATH   := $(TARGET_OUT_VENDOR)/etc/vintf
@@ -69,6 +72,9 @@
 # System Manifest
 include $(CLEAR_VARS)
 LOCAL_MODULE        := system_manifest.xml
+LOCAL_LICENSE_KINDS := SPDX-license-identifier-Apache-2.0
+LOCAL_LICENSE_CONDITIONS := notice
+LOCAL_NOTICE_FILE   := $(LOCAL_PATH)/../NOTICE
 LOCAL_MODULE_STEM   := manifest.xml
 LOCAL_MODULE_CLASS  := ETC
 LOCAL_MODULE_PATH   := $(TARGET_OUT)/etc/vintf
@@ -89,6 +95,9 @@
 ifneq ($(PRODUCT_MANIFEST_FILES),)
 include $(CLEAR_VARS)
 LOCAL_MODULE := product_manifest.xml
+LOCAL_LICENSE_KINDS := SPDX-license-identifier-Apache-2.0
+LOCAL_LICENSE_CONDITIONS := notice
+LOCAL_NOTICE_FILE := $(LOCAL_PATH)/../NOTICE
 LOCAL_MODULE_STEM := manifest.xml
 LOCAL_MODULE_CLASS := ETC
 LOCAL_PRODUCT_MODULE := true
@@ -107,6 +116,9 @@
 # System_ext Manifest
 include $(CLEAR_VARS)
 LOCAL_MODULE := system_ext_manifest.xml
+LOCAL_LICENSE_KINDS := SPDX-license-identifier-Apache-2.0
+LOCAL_LICENSE_CONDITIONS := notice
+LOCAL_NOTICE_FILE := $(LOCAL_PATH)/../NOTICE
 LOCAL_MODULE_STEM := manifest.xml
 LOCAL_MODULE_CLASS := ETC
 LOCAL_SYSTEM_EXT_MODULE := true