Statically load passthrough HALs for tests.

During tests, we should statically load passthrough HALs
for stability and portability of test binaries.

Test: hidl_test
Bug: 67500459
Change-Id: I21cd31ffb531df9fee74f30c28001daba6127bdf
diff --git a/transport/ServiceManagement.cpp b/transport/ServiceManagement.cpp
index 3f0ebc6..c6c43a7 100644
--- a/transport/ServiceManagement.cpp
+++ b/transport/ServiceManagement.cpp
@@ -273,25 +273,37 @@
         const std::string prefix = packageAndVersion + "-impl";
         const std::string sym = "HIDL_FETCH_" + ifaceName;
 
-        const int dlMode = RTLD_LAZY;
-        void *handle = nullptr;
+        constexpr int dlMode = RTLD_LAZY;
+        void* handle = nullptr;
 
         dlerror(); // clear
 
         std::vector<std::string> paths = {HAL_LIBRARY_PATH_ODM, HAL_LIBRARY_PATH_VENDOR,
                                           HAL_LIBRARY_PATH_VNDK_SP, HAL_LIBRARY_PATH_SYSTEM};
+
 #ifdef LIBHIDL_TARGET_DEBUGGABLE
         const char* env = std::getenv("TREBLE_TESTING_OVERRIDE");
         const bool trebleTestingOverride = env && !strcmp(env, "true");
         if (trebleTestingOverride) {
+            // Load HAL implementations that are statically linked
+            handle = dlopen(nullptr, dlMode);
+            if (handle == nullptr) {
+                const char* error = dlerror();
+                LOG(ERROR) << "Failed to dlopen self: "
+                           << (error == nullptr ? "unknown error" : error);
+            } else if (!eachLib(handle, "SELF", sym)) {
+                return;
+            }
+
             const char* vtsRootPath = std::getenv("VTS_ROOT_PATH");
             if (vtsRootPath && strlen(vtsRootPath) > 0) {
                 const std::string halLibraryPathVtsOverride =
                     std::string(vtsRootPath) + HAL_LIBRARY_PATH_SYSTEM;
-                paths.push_back(halLibraryPathVtsOverride);
+                paths.insert(paths.begin(), halLibraryPathVtsOverride);
             }
         }
 #endif
+
         for (const std::string& path : paths) {
             std::vector<std::string> libs = search(path, prefix, ".so");