Avoid internal APEX stubs in libnative{bridge,loader} and clean up
exported symbols.

The APEX stubs don't have any practical effect on the lazy loading
library wrappers. Add notes about that and update the function wrappers
to keep them in sync.

Also add tests for the lazy libraries. That necessitated some
reshuffling in libnativeloader tests to reuse the mocks.

Test: art/libnativebridge/tests/runtests.sh
Test: atest libnativebridge-lazy-tests
Test: atest libnativeloader_test libnativeloader_lazy_test
Bug: 122710865
Change-Id: I7e291f2e84d8e35731dfb1114c9b19978ff87969
diff --git a/libnativebridge/libnativebridge.map.txt b/libnativebridge/libnativebridge.map.txt
index 158363b..8b51ab8 100644
--- a/libnativebridge/libnativebridge.map.txt
+++ b/libnativebridge/libnativebridge.map.txt
@@ -14,33 +14,18 @@
 # limitations under the License.
 #
 
-# TODO(b/122710865): Most of these uses come from libnativeloader, which should be bundled
-# together with libnativebridge in the APEX. Once this happens, prune this list.
+# Platform dependencies go through libnativebridge_lazy, which accesses
+# libnativebridge symbols through dlopen/dlsym. That means this list doesn't
+# have much effect, rather it's the function wrappers in native_bridge_lazy.cpp
+# that defines the exported interface. Please keep in sync with this list.
 LIBNATIVEBRIDGE_1 {
   global:
-    NativeBridgeIsSupported;
-    NativeBridgeLoadLibrary;
-    NativeBridgeUnloadLibrary;
     NativeBridgeGetError;
-    NativeBridgeIsPathSupported;
-    NativeBridgeCreateNamespace;
-    NativeBridgeGetExportedNamespace;
-    NativeBridgeLinkNamespaces;
-    NativeBridgeLoadLibraryExt;
-    NativeBridgeInitAnonymousNamespace;
     NativeBridgeInitialized;
     NativeBridgeGetTrampoline;
-    LoadNativeBridge;
     PreInitializeNativeBridge;
-    PreZygoteForkNativeBridge;
-    InitializeNativeBridge;
-    NativeBridgeGetVersion;
-    NativeBridgeGetSignalHandler;
-    UnloadNativeBridge;
     NativeBridgeAvailable;
     NeedsNativeBridge;
-    NativeBridgeError;
-    NativeBridgeNameAcceptable;
   local:
     *;
 };
diff --git a/libnativebridge/native_bridge_lazy.cc b/libnativebridge/native_bridge_lazy.cc
index b3f4ada..dd8a806 100644
--- a/libnativebridge/native_bridge_lazy.cc
+++ b/libnativebridge/native_bridge_lazy.cc
@@ -44,12 +44,6 @@
 
 }  // namespace
 
-bool LoadNativeBridge(const char* native_bridge_library_filename,
-                      const struct NativeBridgeRuntimeCallbacks* runtime_callbacks) {
-  static auto f = GET_FUNC_PTR(LoadNativeBridge);
-  return f(native_bridge_library_filename, runtime_callbacks);
-}
-
 bool NeedsNativeBridge(const char* instruction_set) {
   static auto f = GET_FUNC_PTR(NeedsNativeBridge);
   return f(instruction_set);
@@ -60,21 +54,6 @@
   return f(app_data_dir, instruction_set);
 }
 
-void PreZygoteForkNativeBridge() {
-  static auto f = GET_FUNC_PTR(PreZygoteForkNativeBridge);
-  return f();
-}
-
-bool InitializeNativeBridge(JNIEnv* env, const char* instruction_set) {
-  static auto f = GET_FUNC_PTR(InitializeNativeBridge);
-  return f(env, instruction_set);
-}
-
-void UnloadNativeBridge() {
-  static auto f = GET_FUNC_PTR(UnloadNativeBridge);
-  return f();
-}
-
 bool NativeBridgeAvailable() {
   static auto f = GET_FUNC_PTR(NativeBridgeAvailable);
   return f();
@@ -85,88 +64,16 @@
   return f();
 }
 
-void* NativeBridgeLoadLibrary(const char* libpath, int flag) {
-  static auto f = GET_FUNC_PTR(NativeBridgeLoadLibrary);
-  return f(libpath, flag);
-}
-
 void* NativeBridgeGetTrampoline(void* handle, const char* name, const char* shorty, uint32_t len) {
   static auto f = GET_FUNC_PTR(NativeBridgeGetTrampoline);
   return f(handle, name, shorty, len);
 }
 
-bool NativeBridgeIsSupported(const char* libpath) {
-  static auto f = GET_FUNC_PTR(NativeBridgeIsSupported);
-  return f(libpath);
-}
-
-uint32_t NativeBridgeGetVersion() {
-  static auto f = GET_FUNC_PTR(NativeBridgeGetVersion);
-  return f();
-}
-
-NativeBridgeSignalHandlerFn NativeBridgeGetSignalHandler(int signal) {
-  static auto f = GET_FUNC_PTR(NativeBridgeGetSignalHandler);
-  return f(signal);
-}
-
-bool NativeBridgeError() {
-  static auto f = GET_FUNC_PTR(NativeBridgeError);
-  return f();
-}
-
-bool NativeBridgeNameAcceptable(const char* native_bridge_library_filename) {
-  static auto f = GET_FUNC_PTR(NativeBridgeNameAcceptable);
-  return f(native_bridge_library_filename);
-}
-
-int NativeBridgeUnloadLibrary(void* handle) {
-  static auto f = GET_FUNC_PTR(NativeBridgeUnloadLibrary);
-  return f(handle);
-}
-
 const char* NativeBridgeGetError() {
   static auto f = GET_FUNC_PTR(NativeBridgeGetError);
   return f();
 }
 
-bool NativeBridgeIsPathSupported(const char* path) {
-  static auto f = GET_FUNC_PTR(NativeBridgeIsPathSupported);
-  return f(path);
-}
-
-bool NativeBridgeInitAnonymousNamespace(const char* public_ns_sonames,
-                                        const char* anon_ns_library_path) {
-  static auto f = GET_FUNC_PTR(NativeBridgeInitAnonymousNamespace);
-  return f(public_ns_sonames, anon_ns_library_path);
-}
-
-struct native_bridge_namespace_t* NativeBridgeCreateNamespace(
-    const char* name, const char* ld_library_path, const char* default_library_path, uint64_t type,
-    const char* permitted_when_isolated_path, struct native_bridge_namespace_t* parent_ns) {
-  static auto f = GET_FUNC_PTR(NativeBridgeCreateNamespace);
-  return f(name, ld_library_path, default_library_path, type, permitted_when_isolated_path,
-           parent_ns);
-}
-
-bool NativeBridgeLinkNamespaces(struct native_bridge_namespace_t* from,
-                                struct native_bridge_namespace_t* to,
-                                const char* shared_libs_sonames) {
-  static auto f = GET_FUNC_PTR(NativeBridgeLinkNamespaces);
-  return f(from, to, shared_libs_sonames);
-}
-
-void* NativeBridgeLoadLibraryExt(const char* libpath, int flag,
-                                 struct native_bridge_namespace_t* ns) {
-  static auto f = GET_FUNC_PTR(NativeBridgeLoadLibraryExt);
-  return f(libpath, flag, ns);
-}
-
-struct native_bridge_namespace_t* NativeBridgeGetVendorNamespace() {
-  static auto f = GET_FUNC_PTR(NativeBridgeGetVendorNamespace);
-  return f();
-}
-
 #undef GET_FUNC_PTR
 
 }  // namespace android
diff --git a/libnativebridge/tests/Android.bp b/libnativebridge/tests/Android.bp
index fa98f5e..b789a2e 100644
--- a/libnativebridge/tests/Android.bp
+++ b/libnativebridge/tests/Android.bp
@@ -82,7 +82,6 @@
     defaults: ["libnativebridge-test-case-defaults"],
 }
 
-// Build the unit tests.
 cc_defaults {
     name: "libnativebridge-tests-defaults",
     defaults: [
@@ -101,6 +100,11 @@
             ],
         },
     },
+}
+
+cc_test {
+    name: "libnativebridge-tests",
+    defaults: ["libnativebridge-tests-defaults"],
 
     // native_bridge.cc doesn't support reloading the native bridge after
     // unloading, so each test needs to be its own process.
@@ -132,6 +136,7 @@
 
     shared_libs: [
         "liblog",
+        "libnativebridge",
         "libnativebridge-test-case",
         "libnativebridge2-test-case",
         "libnativebridge3-test-case",
@@ -142,14 +147,13 @@
 }
 
 cc_test {
-    name: "libnativebridge-tests",
-    defaults: ["libnativebridge-tests-defaults"],
-    shared_libs: ["libnativebridge"],
-}
-
-cc_test {
     name: "libnativebridge-lazy-tests",
     defaults: ["libnativebridge-tests-defaults"],
     host_supported: false,
-    shared_libs: ["libnativebridge_lazy"],
+    test_suites: ["device-tests"],
+    static_libs: [
+        "libbase",
+        "libnativebridge_lazy",
+    ],
+    srcs: ["libnativebridge_lazy_test.cpp"],
 }
diff --git a/libnativebridge/tests/libnativebridge_lazy_test.cpp b/libnativebridge/tests/libnativebridge_lazy_test.cpp
new file mode 100644
index 0000000..e1d66f5
--- /dev/null
+++ b/libnativebridge/tests/libnativebridge_lazy_test.cpp
@@ -0,0 +1,54 @@
+/*
+ * Copyright (C) 2021 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <android-base/macros.h>
+#include <gtest/gtest.h>
+
+#include "nativebridge/native_bridge.h"
+
+namespace android {
+
+class NativeBridgeLazyTest : public ::testing::Test {};
+
+// The testing we can do here is limited since there's no exported API to
+// actually load the native bridge, but we only need to test the trivial
+// wrappers.
+
+TEST_F(NativeBridgeLazyTest, NeedsNativeBridge) {
+  EXPECT_FALSE(NeedsNativeBridge(ABI_STRING));
+}
+
+TEST_F(NativeBridgeLazyTest, PreInitializeNativeBridge) {
+  EXPECT_FALSE(PreInitializeNativeBridge(nullptr, ""));
+}
+
+TEST_F(NativeBridgeLazyTest, NativeBridgeAvailable) {
+  EXPECT_FALSE(NativeBridgeAvailable());
+}
+
+TEST_F(NativeBridgeLazyTest, NativeBridgeInitialized) {
+  EXPECT_FALSE(NativeBridgeInitialized());
+}
+
+TEST_F(NativeBridgeLazyTest, NativeBridgeGetTrampoline) {
+  EXPECT_EQ(nullptr, NativeBridgeGetTrampoline(nullptr, nullptr, nullptr, 0));
+}
+
+TEST_F(NativeBridgeLazyTest, NativeBridgeGetError) {
+  EXPECT_STREQ("native bridge is not initialized", NativeBridgeGetError());
+}
+
+};  // namespace android
diff --git a/libnativeloader/Android.bp b/libnativeloader/Android.bp
index 6e87620..3f13506 100644
--- a/libnativeloader/Android.bp
+++ b/libnativeloader/Android.bp
@@ -116,21 +116,17 @@
     export_header_lib_headers: ["jni_headers"],
 }
 
-art_cc_test {
-    name: "libnativeloader_test",
+cc_defaults {
+    name: "libnativeloader-test-defaults",
     defaults: [
         "art_module_source_build_defaults",
         "art_test_defaults",
     ],
     host_supported: false,
 
-    srcs: [
-        "native_loader_api_test.c",
-        "native_loader_test.cpp",
-    ],
     cflags: ["-DANDROID"],
 
-    // The test mocks libdl_android and libnativebridge symbols, so export them
+    // The tests mock libdl_android and libnativebridge symbols, so export them
     // to override the ones loaded from their libs.
     ldflags: [
         "-Wl,--export-dynamic-symbol=android_*",
@@ -146,8 +142,30 @@
     ],
     shared_libs: [
         "libbase",
-        "libnativeloader",
     ],
 
     test_suites: ["device-tests"],
 }
+
+art_cc_test {
+    name: "libnativeloader_test",
+    defaults: ["libnativeloader-test-defaults"],
+    srcs: [
+        "native_loader_api_test.c",
+        "native_loader_test.cpp",
+    ],
+    shared_libs: [
+        "libnativeloader",
+    ],
+}
+
+art_cc_test {
+    name: "libnativeloader_lazy_test",
+    defaults: ["libnativeloader-test-defaults"],
+    srcs: [
+        "native_loader_lazy_test.cpp",
+    ],
+    static_libs: [
+        "libnativeloader_lazy",
+    ],
+}
diff --git a/libnativeloader/libnativeloader.map.txt b/libnativeloader/libnativeloader.map.txt
index 40c30bd..59f457c 100644
--- a/libnativeloader/libnativeloader.map.txt
+++ b/libnativeloader/libnativeloader.map.txt
@@ -14,12 +14,13 @@
 # limitations under the License.
 #
 
-# TODO(b/122710865): Prune these uses once the runtime APEX is complete.
+# Platform dependencies go through libnativeloader_lazy, which accesses
+# libnativeloader symbols through dlopen/dlsym. That means this list doesn't
+# have much effect, rather it's the function wrappers in native_loader_lazy.cpp
+# that defines the exported interface. Please keep in sync with this list.
 LIBNATIVELOADER_1 {
   global:
     OpenNativeLibrary;
-    InitializeNativeLoader;
-    ResetNativeLoader;
     CloseNativeLibrary;
     OpenNativeLibraryInNamespace;
     FindNamespaceByClassLoader;
diff --git a/libnativeloader/native_loader_lazy.cpp b/libnativeloader/native_loader_lazy.cpp
index 49b22ea..5b82d00 100644
--- a/libnativeloader/native_loader_lazy.cpp
+++ b/libnativeloader/native_loader_lazy.cpp
@@ -44,11 +44,6 @@
 
 }  // namespace
 
-void InitializeNativeLoader() {
-  static auto f = GET_FUNC_PTR(InitializeNativeLoader);
-  return f();
-}
-
 jstring CreateClassLoaderNamespace(JNIEnv* env, int32_t target_sdk_version, jobject class_loader,
                                    bool is_shared, jstring dex_path, jstring library_path,
                                    jstring permitted_path, jstring uses_library_list) {
@@ -92,11 +87,6 @@
   return f(ns, path, needs_native_bridge, error_msg);
 }
 
-void ResetNativeLoader() {
-  static auto f = GET_FUNC_PTR(ResetNativeLoader);
-  return f();
-}
-
 #undef GET_FUNC_PTR
 
 }  // namespace android
diff --git a/libnativeloader/native_loader_lazy_test.cpp b/libnativeloader/native_loader_lazy_test.cpp
new file mode 100644
index 0000000..b863c85
--- /dev/null
+++ b/libnativeloader/native_loader_lazy_test.cpp
@@ -0,0 +1,127 @@
+/*
+ * Copyright (C) 2021 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#if defined(ART_TARGET_ANDROID)
+
+#include <gtest/gtest.h>
+
+#include "native_loader_test.h"
+#include "nativehelper/scoped_utf_chars.h"
+#include "nativeloader/native_loader.h"
+
+namespace android {
+namespace nativeloader {
+
+using ::testing::StrEq;
+
+// Only need to test that the trivial lazy lib wrappers call through to the real
+// functions, but still have to mock things well enough to avoid null pointer
+// dereferences.
+
+class NativeLoaderLazyTest : public ::testing::Test {
+ protected:
+  void SetUp() override {
+    mock = std::make_unique<testing::NiceMock<MockPlatform>>(false);
+    env = std::make_unique<JNIEnv>();
+    env->functions = CreateJNINativeInterface();
+  }
+
+  void TearDown() override {
+    // ResetNativeLoader isn't accessible through the lazy library, so we cannot
+    // reset libnativeloader internal state. Hence be sure to not reuse the same
+    // class loader/namespace names.
+    delete env->functions;
+    mock.reset();
+  }
+
+  void CallCreateClassLoaderNamespace(const char* class_loader) {
+    ON_CALL(*mock, JniObject_getParent(StrEq(class_loader))).WillByDefault(Return(nullptr));
+    EXPECT_CALL(*mock, mock_create_namespace)
+        .WillOnce(Return(TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE(class_loader))));
+    ON_CALL(*mock, mock_link_namespaces).WillByDefault(Return(true));
+
+    jstring err = CreateClassLoaderNamespace(env.get(),
+                                             17,
+                                             env.get()->NewStringUTF(class_loader),
+                                             false,
+                                             env.get()->NewStringUTF("/data/app/foo/classes.dex"),
+                                             env.get()->NewStringUTF("/data/app/foo"),
+                                             /*permitted_path=*/nullptr,
+                                             /*uses_library_list=*/nullptr);
+    EXPECT_EQ(err, nullptr) << "Error is: " << std::string(ScopedUtfChars(env.get(), err).c_str());
+  }
+
+  std::unique_ptr<JNIEnv> env;
+};
+
+TEST_F(NativeLoaderLazyTest, CreateClassLoaderNamespace) {
+  CallCreateClassLoaderNamespace("my_classloader_1");
+}
+
+TEST_F(NativeLoaderLazyTest, OpenNativeLibrary) {
+  bool needs_native_bridge;
+  char* errmsg = nullptr;
+  EXPECT_EQ(nullptr,
+            OpenNativeLibrary(env.get(),
+                              17,
+                              "libnotfound.so",
+                              env.get()->NewStringUTF("my_classloader"),
+                              /*caller_location=*/nullptr,
+                              /*library_path=*/nullptr,
+                              &needs_native_bridge,
+                              &errmsg));
+  EXPECT_NE(nullptr, errmsg);
+  NativeLoaderFreeErrorMessage(errmsg);
+}
+
+TEST_F(NativeLoaderLazyTest, CloseNativeLibrary) {
+  char* errmsg = nullptr;
+  EXPECT_FALSE(CloseNativeLibrary(nullptr, false, &errmsg));
+  EXPECT_NE(nullptr, errmsg);
+  NativeLoaderFreeErrorMessage(errmsg);
+}
+
+TEST_F(NativeLoaderLazyTest, OpenNativeLibraryInNamespace) {
+  CallCreateClassLoaderNamespace("my_classloader_2");
+  struct NativeLoaderNamespace* ns = FindNativeLoaderNamespaceByClassLoader(
+      env.get(), env.get()->NewStringUTF("my_classloader_2"));
+  ASSERT_NE(nullptr, ns);
+
+  bool needs_native_bridge;
+  char* errmsg = nullptr;
+  EXPECT_FALSE(OpenNativeLibraryInNamespace(ns, "libnotfound.so", &needs_native_bridge, &errmsg));
+  EXPECT_NE(nullptr, errmsg);
+  NativeLoaderFreeErrorMessage(errmsg);
+}
+
+TEST_F(NativeLoaderLazyTest, FindNamespaceByClassLoader) {
+  EXPECT_EQ(nullptr, FindNamespaceByClassLoader(env.get(), env.get()->NewStringUTF("namespace")));
+}
+
+TEST_F(NativeLoaderLazyTest, FindNativeLoaderNamespaceByClassLoader) {
+  EXPECT_EQ(
+      nullptr,
+      FindNativeLoaderNamespaceByClassLoader(env.get(), env.get()->NewStringUTF("namespace")));
+}
+
+TEST_F(NativeLoaderLazyTest, NativeLoaderFreeErrorMessage) {
+  NativeLoaderFreeErrorMessage(nullptr);
+}
+
+}  // namespace nativeloader
+}  // namespace android
+
+#endif  // defined(ART_TARGET_ANDROID)
diff --git a/libnativeloader/native_loader_test.cpp b/libnativeloader/native_loader_test.cpp
index e754414..79e5070 100644
--- a/libnativeloader/native_loader_test.cpp
+++ b/libnativeloader/native_loader_test.cpp
@@ -16,19 +16,14 @@
 
 #if defined(ART_TARGET_ANDROID)
 
+#include "native_loader_test.h"
+
 #include <dlfcn.h>
-#include <memory>
-#include <unordered_map>
 
-#include <android-base/stringprintf.h>
 #include <android-base/strings.h>
-#include <gmock/gmock.h>
 #include <gtest/gtest.h>
-#include <jni.h>
 
-#include "native_loader_namespace.h"
 #include "nativehelper/scoped_utf_chars.h"
-#include "nativeloader/dlext_namespaces.h"
 #include "nativeloader/native_loader.h"
 #include "public_libraries.h"
 
@@ -37,9 +32,7 @@
 
 using ::testing::Eq;
 using ::testing::NotNull;
-using ::testing::Return;
 using ::testing::StrEq;
-using ::testing::_;
 using internal::ConfigEntry;
 using internal::ParseApexLibrariesConfig;
 using internal::ParseConfig;
@@ -50,228 +43,6 @@
 #define LIB_DIR "lib"
 #endif
 
-// gmock interface that represents interested platform APIs on libdl_android and libnativebridge
-class Platform {
- public:
-  virtual ~Platform() {}
-
-  // These mock_* are the APIs semantically the same across libdl_android and libnativebridge.
-  // Instead of having two set of mock APIs for the two, define only one set with an additional
-  // argument 'bool bridged' to identify the context (i.e., called for libdl_android or
-  // libnativebridge).
-  typedef char* mock_namespace_handle;
-  virtual bool mock_init_anonymous_namespace(bool bridged, const char* sonames,
-                                             const char* search_paths) = 0;
-  virtual mock_namespace_handle mock_create_namespace(
-      bool bridged, const char* name, const char* ld_library_path, const char* default_library_path,
-      uint64_t type, const char* permitted_when_isolated_path, mock_namespace_handle parent) = 0;
-  virtual bool mock_link_namespaces(bool bridged, mock_namespace_handle from,
-                                    mock_namespace_handle to, const char* sonames) = 0;
-  virtual mock_namespace_handle mock_get_exported_namespace(bool bridged, const char* name) = 0;
-  virtual void* mock_dlopen_ext(bool bridged, const char* filename, int flags,
-                                mock_namespace_handle ns) = 0;
-
-  // libnativebridge APIs for which libdl_android has no corresponding APIs
-  virtual bool NativeBridgeInitialized() = 0;
-  virtual const char* NativeBridgeGetError() = 0;
-  virtual bool NativeBridgeIsPathSupported(const char*) = 0;
-  virtual bool NativeBridgeIsSupported(const char*) = 0;
-
-  // To mock "ClassLoader Object.getParent()"
-  virtual const char* JniObject_getParent(const char*) = 0;
-};
-
-// The mock does not actually create a namespace object. But simply casts the pointer to the
-// string for the namespace name as the handle to the namespace object.
-#define TO_ANDROID_NAMESPACE(str) \
-  reinterpret_cast<struct android_namespace_t*>(const_cast<char*>(str))
-
-#define TO_BRIDGED_NAMESPACE(str) \
-  reinterpret_cast<struct native_bridge_namespace_t*>(const_cast<char*>(str))
-
-#define TO_MOCK_NAMESPACE(ns) reinterpret_cast<Platform::mock_namespace_handle>(ns)
-
-// These represents built-in namespaces created by the linker according to ld.config.txt
-static std::unordered_map<std::string, Platform::mock_namespace_handle> namespaces = {
-#define NAMESPACE_ENTRY(ns) {ns, TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE(ns))}
-  NAMESPACE_ENTRY("com_android_i18n"),
-  NAMESPACE_ENTRY("com_android_neuralnetworks"),
-  NAMESPACE_ENTRY("com_android_art"),
-  NAMESPACE_ENTRY("default"),
-  NAMESPACE_ENTRY("sphal"),
-  NAMESPACE_ENTRY("system"),
-  NAMESPACE_ENTRY("vndk"),
-  NAMESPACE_ENTRY("vndk_product"),
-#undef NAMESPACE_ENTRY
-};
-
-// The actual gmock object
-class MockPlatform : public Platform {
- public:
-  explicit MockPlatform(bool is_bridged) : is_bridged_(is_bridged) {
-    ON_CALL(*this, NativeBridgeIsSupported(_)).WillByDefault(Return(is_bridged_));
-    ON_CALL(*this, NativeBridgeIsPathSupported(_)).WillByDefault(Return(is_bridged_));
-    ON_CALL(*this, mock_get_exported_namespace(_, _))
-        .WillByDefault(testing::Invoke([](bool, const char* name) -> mock_namespace_handle {
-          if (namespaces.find(name) != namespaces.end()) {
-            return namespaces[name];
-          }
-          std::string msg = android::base::StringPrintf("(namespace %s not found)", name);
-          // The strdup'ed string will leak, but the test is already failing if we get here.
-          return TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE(strdup(msg.c_str())));
-        }));
-  }
-
-  // Mocking the common APIs
-  MOCK_METHOD3(mock_init_anonymous_namespace, bool(bool, const char*, const char*));
-  MOCK_METHOD7(mock_create_namespace,
-               mock_namespace_handle(bool, const char*, const char*, const char*, uint64_t,
-                                     const char*, mock_namespace_handle));
-  MOCK_METHOD4(mock_link_namespaces,
-               bool(bool, mock_namespace_handle, mock_namespace_handle, const char*));
-  MOCK_METHOD2(mock_get_exported_namespace, mock_namespace_handle(bool, const char*));
-  MOCK_METHOD4(mock_dlopen_ext, void*(bool, const char*, int, mock_namespace_handle));
-
-  // Mocking libnativebridge APIs
-  MOCK_METHOD0(NativeBridgeInitialized, bool());
-  MOCK_METHOD0(NativeBridgeGetError, const char*());
-  MOCK_METHOD1(NativeBridgeIsPathSupported, bool(const char*));
-  MOCK_METHOD1(NativeBridgeIsSupported, bool(const char*));
-
-  // Mocking "ClassLoader Object.getParent()"
-  MOCK_METHOD1(JniObject_getParent, const char*(const char*));
-
- private:
-  bool is_bridged_;
-};
-
-static std::unique_ptr<MockPlatform> mock;
-
-// Provide C wrappers for the mock object. These symbols must be exported by ld
-// to be able to override the real symbols in the shared libs.
-extern "C" {
-
-// libdl_android APIs
-
-bool android_init_anonymous_namespace(const char* sonames, const char* search_path) {
-  return mock->mock_init_anonymous_namespace(false, sonames, search_path);
-}
-
-struct android_namespace_t* android_create_namespace(const char* name, const char* ld_library_path,
-                                                     const char* default_library_path,
-                                                     uint64_t type,
-                                                     const char* permitted_when_isolated_path,
-                                                     struct android_namespace_t* parent) {
-  return TO_ANDROID_NAMESPACE(
-      mock->mock_create_namespace(false, name, ld_library_path, default_library_path, type,
-                                  permitted_when_isolated_path, TO_MOCK_NAMESPACE(parent)));
-}
-
-bool android_link_namespaces(struct android_namespace_t* from, struct android_namespace_t* to,
-                             const char* sonames) {
-  return mock->mock_link_namespaces(false, TO_MOCK_NAMESPACE(from), TO_MOCK_NAMESPACE(to), sonames);
-}
-
-struct android_namespace_t* android_get_exported_namespace(const char* name) {
-  return TO_ANDROID_NAMESPACE(mock->mock_get_exported_namespace(false, name));
-}
-
-void* android_dlopen_ext(const char* filename, int flags, const android_dlextinfo* info) {
-  return mock->mock_dlopen_ext(false, filename, flags, TO_MOCK_NAMESPACE(info->library_namespace));
-}
-
-// libnativebridge APIs
-
-bool NativeBridgeIsSupported(const char* libpath) {
-  return mock->NativeBridgeIsSupported(libpath);
-}
-
-struct native_bridge_namespace_t* NativeBridgeGetExportedNamespace(const char* name) {
-  return TO_BRIDGED_NAMESPACE(mock->mock_get_exported_namespace(true, name));
-}
-
-struct native_bridge_namespace_t* NativeBridgeCreateNamespace(
-    const char* name, const char* ld_library_path, const char* default_library_path, uint64_t type,
-    const char* permitted_when_isolated_path, struct native_bridge_namespace_t* parent) {
-  return TO_BRIDGED_NAMESPACE(
-      mock->mock_create_namespace(true, name, ld_library_path, default_library_path, type,
-                                  permitted_when_isolated_path, TO_MOCK_NAMESPACE(parent)));
-}
-
-bool NativeBridgeLinkNamespaces(struct native_bridge_namespace_t* from,
-                                struct native_bridge_namespace_t* to, const char* sonames) {
-  return mock->mock_link_namespaces(true, TO_MOCK_NAMESPACE(from), TO_MOCK_NAMESPACE(to), sonames);
-}
-
-void* NativeBridgeLoadLibraryExt(const char* libpath, int flag,
-                                 struct native_bridge_namespace_t* ns) {
-  return mock->mock_dlopen_ext(true, libpath, flag, TO_MOCK_NAMESPACE(ns));
-}
-
-bool NativeBridgeInitialized() {
-  return mock->NativeBridgeInitialized();
-}
-
-bool NativeBridgeInitAnonymousNamespace(const char* public_ns_sonames,
-                                        const char* anon_ns_library_path) {
-  return mock->mock_init_anonymous_namespace(true, public_ns_sonames, anon_ns_library_path);
-}
-
-const char* NativeBridgeGetError() {
-  return mock->NativeBridgeGetError();
-}
-
-bool NativeBridgeIsPathSupported(const char* path) {
-  return mock->NativeBridgeIsPathSupported(path);
-}
-
-}  // extern "C"
-
-// A very simple JNI mock.
-// jstring is a pointer to utf8 char array. We don't need utf16 char here.
-// jobject, jclass, and jmethodID are also a pointer to utf8 char array
-// Only a few JNI methods that are actually used in libnativeloader are mocked.
-JNINativeInterface* CreateJNINativeInterface() {
-  JNINativeInterface* inf = new JNINativeInterface();
-  memset(inf, 0, sizeof(JNINativeInterface));
-
-  inf->GetStringUTFChars = [](JNIEnv*, jstring s, jboolean*) -> const char* {
-    return reinterpret_cast<const char*>(s);
-  };
-
-  inf->ReleaseStringUTFChars = [](JNIEnv*, jstring, const char*) -> void { return; };
-
-  inf->NewStringUTF = [](JNIEnv*, const char* bytes) -> jstring {
-    return reinterpret_cast<jstring>(const_cast<char*>(bytes));
-  };
-
-  inf->FindClass = [](JNIEnv*, const char* name) -> jclass {
-    return reinterpret_cast<jclass>(const_cast<char*>(name));
-  };
-
-  inf->CallObjectMethodV = [](JNIEnv*, jobject obj, jmethodID mid, va_list) -> jobject {
-    if (strcmp("getParent", reinterpret_cast<const char*>(mid)) == 0) {
-      // JniObject_getParent can be a valid jobject or nullptr if there is
-      // no parent classloader.
-      const char* ret = mock->JniObject_getParent(reinterpret_cast<const char*>(obj));
-      return reinterpret_cast<jobject>(const_cast<char*>(ret));
-    }
-    return nullptr;
-  };
-
-  inf->GetMethodID = [](JNIEnv*, jclass, const char* name, const char*) -> jmethodID {
-    return reinterpret_cast<jmethodID>(const_cast<char*>(name));
-  };
-
-  inf->NewWeakGlobalRef = [](JNIEnv*, jobject obj) -> jobject { return obj; };
-
-  inf->IsSameObject = [](JNIEnv*, jobject a, jobject b) -> jboolean {
-    return strcmp(reinterpret_cast<const char*>(a), reinterpret_cast<const char*>(b)) == 0;
-  };
-
-  return inf;
-}
-
 static void* const any_nonnull = reinterpret_cast<void*>(0x12345678);
 
 // Custom matcher for comparing namespace handles
@@ -808,7 +579,6 @@
   ASSERT_EQ("Invalid library_list \"jni com_android_foo lib64/libfoo.so\"", result.error().message());
 }
 
-
 }  // namespace nativeloader
 }  // namespace android
 
diff --git a/libnativeloader/native_loader_test.h b/libnativeloader/native_loader_test.h
new file mode 100644
index 0000000..cab18da
--- /dev/null
+++ b/libnativeloader/native_loader_test.h
@@ -0,0 +1,261 @@
+/*
+ * Copyright (C) 2021 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ART_LIBNATIVELOADER_NATIVE_LOADER_TEST_H_
+#define ART_LIBNATIVELOADER_NATIVE_LOADER_TEST_H_
+
+#include <string>
+#include <unordered_map>
+
+#include <android-base/stringprintf.h>
+#include <gmock/gmock.h>
+#include <jni.h>
+
+#include "native_loader_namespace.h"
+#include "nativeloader/dlext_namespaces.h"
+
+namespace android {
+namespace nativeloader {
+
+using ::testing::Return;
+using ::testing::_;
+
+// gmock interface that represents interested platform APIs on libdl_android and libnativebridge
+class Platform {
+ public:
+  virtual ~Platform() {}
+
+  // These mock_* are the APIs semantically the same across libdl_android and libnativebridge.
+  // Instead of having two set of mock APIs for the two, define only one set with an additional
+  // argument 'bool bridged' to identify the context (i.e., called for libdl_android or
+  // libnativebridge).
+  typedef char* mock_namespace_handle;
+  virtual bool mock_init_anonymous_namespace(bool bridged, const char* sonames,
+                                             const char* search_paths) = 0;
+  virtual mock_namespace_handle mock_create_namespace(
+      bool bridged, const char* name, const char* ld_library_path, const char* default_library_path,
+      uint64_t type, const char* permitted_when_isolated_path, mock_namespace_handle parent) = 0;
+  virtual bool mock_link_namespaces(bool bridged, mock_namespace_handle from,
+                                    mock_namespace_handle to, const char* sonames) = 0;
+  virtual mock_namespace_handle mock_get_exported_namespace(bool bridged, const char* name) = 0;
+  virtual void* mock_dlopen_ext(bool bridged, const char* filename, int flags,
+                                mock_namespace_handle ns) = 0;
+
+  // libnativebridge APIs for which libdl_android has no corresponding APIs
+  virtual bool NativeBridgeInitialized() = 0;
+  virtual const char* NativeBridgeGetError() = 0;
+  virtual bool NativeBridgeIsPathSupported(const char*) = 0;
+  virtual bool NativeBridgeIsSupported(const char*) = 0;
+
+  // To mock "ClassLoader Object.getParent()"
+  virtual const char* JniObject_getParent(const char*) = 0;
+};
+
+// The mock does not actually create a namespace object. But simply casts the pointer to the
+// string for the namespace name as the handle to the namespace object.
+#define TO_ANDROID_NAMESPACE(str) \
+  reinterpret_cast<struct android_namespace_t*>(const_cast<char*>(str))
+
+#define TO_BRIDGED_NAMESPACE(str) \
+  reinterpret_cast<struct native_bridge_namespace_t*>(const_cast<char*>(str))
+
+#define TO_MOCK_NAMESPACE(ns) reinterpret_cast<Platform::mock_namespace_handle>(ns)
+
+// These represents built-in namespaces created by the linker according to ld.config.txt
+static std::unordered_map<std::string, Platform::mock_namespace_handle> namespaces = {
+#define NAMESPACE_ENTRY(ns) {ns, TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE(ns))}
+  NAMESPACE_ENTRY("com_android_i18n"),
+  NAMESPACE_ENTRY("com_android_neuralnetworks"),
+  NAMESPACE_ENTRY("com_android_art"),
+  NAMESPACE_ENTRY("default"),
+  NAMESPACE_ENTRY("sphal"),
+  NAMESPACE_ENTRY("system"),
+  NAMESPACE_ENTRY("vndk"),
+  NAMESPACE_ENTRY("vndk_product"),
+#undef NAMESPACE_ENTRY
+};
+
+// The actual gmock object
+class MockPlatform : public Platform {
+ public:
+  explicit MockPlatform(bool is_bridged) : is_bridged_(is_bridged) {
+    ON_CALL(*this, NativeBridgeIsSupported(_)).WillByDefault(Return(is_bridged_));
+    ON_CALL(*this, NativeBridgeIsPathSupported(_)).WillByDefault(Return(is_bridged_));
+    ON_CALL(*this, mock_get_exported_namespace(_, _))
+        .WillByDefault(testing::Invoke([](bool, const char* name) -> mock_namespace_handle {
+          if (namespaces.find(name) != namespaces.end()) {
+            return namespaces[name];
+          }
+          std::string msg = android::base::StringPrintf("(namespace %s not found)", name);
+          // The strdup'ed string will leak, but the test is already failing if we get here.
+          return TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE(strdup(msg.c_str())));
+        }));
+  }
+
+  // Mocking the common APIs
+  MOCK_METHOD3(mock_init_anonymous_namespace, bool(bool, const char*, const char*));
+  MOCK_METHOD7(mock_create_namespace,
+               mock_namespace_handle(bool, const char*, const char*, const char*, uint64_t,
+                                     const char*, mock_namespace_handle));
+  MOCK_METHOD4(mock_link_namespaces,
+               bool(bool, mock_namespace_handle, mock_namespace_handle, const char*));
+  MOCK_METHOD2(mock_get_exported_namespace, mock_namespace_handle(bool, const char*));
+  MOCK_METHOD4(mock_dlopen_ext, void*(bool, const char*, int, mock_namespace_handle));
+
+  // Mocking libnativebridge APIs
+  MOCK_METHOD0(NativeBridgeInitialized, bool());
+  MOCK_METHOD0(NativeBridgeGetError, const char*());
+  MOCK_METHOD1(NativeBridgeIsPathSupported, bool(const char*));
+  MOCK_METHOD1(NativeBridgeIsSupported, bool(const char*));
+
+  // Mocking "ClassLoader Object.getParent()"
+  MOCK_METHOD1(JniObject_getParent, const char*(const char*));
+
+ private:
+  bool is_bridged_;
+};
+
+static std::unique_ptr<MockPlatform> mock;
+
+// Provide C wrappers for the mock object. These symbols must be exported by ld
+// to be able to override the real symbols in the shared libs.
+extern "C" {
+
+// libdl_android APIs
+
+bool android_init_anonymous_namespace(const char* sonames, const char* search_path) {
+  return mock->mock_init_anonymous_namespace(false, sonames, search_path);
+}
+
+struct android_namespace_t* android_create_namespace(const char* name, const char* ld_library_path,
+                                                     const char* default_library_path,
+                                                     uint64_t type,
+                                                     const char* permitted_when_isolated_path,
+                                                     struct android_namespace_t* parent) {
+  return TO_ANDROID_NAMESPACE(
+      mock->mock_create_namespace(false, name, ld_library_path, default_library_path, type,
+                                  permitted_when_isolated_path, TO_MOCK_NAMESPACE(parent)));
+}
+
+bool android_link_namespaces(struct android_namespace_t* from, struct android_namespace_t* to,
+                             const char* sonames) {
+  return mock->mock_link_namespaces(false, TO_MOCK_NAMESPACE(from), TO_MOCK_NAMESPACE(to), sonames);
+}
+
+struct android_namespace_t* android_get_exported_namespace(const char* name) {
+  return TO_ANDROID_NAMESPACE(mock->mock_get_exported_namespace(false, name));
+}
+
+void* android_dlopen_ext(const char* filename, int flags, const android_dlextinfo* info) {
+  return mock->mock_dlopen_ext(false, filename, flags, TO_MOCK_NAMESPACE(info->library_namespace));
+}
+
+// libnativebridge APIs
+
+bool NativeBridgeIsSupported(const char* libpath) {
+  return mock->NativeBridgeIsSupported(libpath);
+}
+
+struct native_bridge_namespace_t* NativeBridgeGetExportedNamespace(const char* name) {
+  return TO_BRIDGED_NAMESPACE(mock->mock_get_exported_namespace(true, name));
+}
+
+struct native_bridge_namespace_t* NativeBridgeCreateNamespace(
+    const char* name, const char* ld_library_path, const char* default_library_path, uint64_t type,
+    const char* permitted_when_isolated_path, struct native_bridge_namespace_t* parent) {
+  return TO_BRIDGED_NAMESPACE(
+      mock->mock_create_namespace(true, name, ld_library_path, default_library_path, type,
+                                  permitted_when_isolated_path, TO_MOCK_NAMESPACE(parent)));
+}
+
+bool NativeBridgeLinkNamespaces(struct native_bridge_namespace_t* from,
+                                struct native_bridge_namespace_t* to, const char* sonames) {
+  return mock->mock_link_namespaces(true, TO_MOCK_NAMESPACE(from), TO_MOCK_NAMESPACE(to), sonames);
+}
+
+void* NativeBridgeLoadLibraryExt(const char* libpath, int flag,
+                                 struct native_bridge_namespace_t* ns) {
+  return mock->mock_dlopen_ext(true, libpath, flag, TO_MOCK_NAMESPACE(ns));
+}
+
+bool NativeBridgeInitialized() {
+  return mock->NativeBridgeInitialized();
+}
+
+bool NativeBridgeInitAnonymousNamespace(const char* public_ns_sonames,
+                                        const char* anon_ns_library_path) {
+  return mock->mock_init_anonymous_namespace(true, public_ns_sonames, anon_ns_library_path);
+}
+
+const char* NativeBridgeGetError() {
+  return mock->NativeBridgeGetError();
+}
+
+bool NativeBridgeIsPathSupported(const char* path) {
+  return mock->NativeBridgeIsPathSupported(path);
+}
+
+}  // extern "C"
+
+// A very simple JNI mock.
+// jstring is a pointer to utf8 char array. We don't need utf16 char here.
+// jobject, jclass, and jmethodID are also a pointer to utf8 char array
+// Only a few JNI methods that are actually used in libnativeloader are mocked.
+JNINativeInterface* CreateJNINativeInterface() {
+  JNINativeInterface* inf = new JNINativeInterface();
+  memset(inf, 0, sizeof(JNINativeInterface));
+
+  inf->GetStringUTFChars = [](JNIEnv*, jstring s, jboolean*) -> const char* {
+    return reinterpret_cast<const char*>(s);
+  };
+
+  inf->ReleaseStringUTFChars = [](JNIEnv*, jstring, const char*) -> void { return; };
+
+  inf->NewStringUTF = [](JNIEnv*, const char* bytes) -> jstring {
+    return reinterpret_cast<jstring>(const_cast<char*>(bytes));
+  };
+
+  inf->FindClass = [](JNIEnv*, const char* name) -> jclass {
+    return reinterpret_cast<jclass>(const_cast<char*>(name));
+  };
+
+  inf->CallObjectMethodV = [](JNIEnv*, jobject obj, jmethodID mid, va_list) -> jobject {
+    if (strcmp("getParent", reinterpret_cast<const char*>(mid)) == 0) {
+      // JniObject_getParent can be a valid jobject or nullptr if there is
+      // no parent classloader.
+      const char* ret = mock->JniObject_getParent(reinterpret_cast<const char*>(obj));
+      return reinterpret_cast<jobject>(const_cast<char*>(ret));
+    }
+    return nullptr;
+  };
+
+  inf->GetMethodID = [](JNIEnv*, jclass, const char* name, const char*) -> jmethodID {
+    return reinterpret_cast<jmethodID>(const_cast<char*>(name));
+  };
+
+  inf->NewWeakGlobalRef = [](JNIEnv*, jobject obj) -> jobject { return obj; };
+
+  inf->IsSameObject = [](JNIEnv*, jobject a, jobject b) -> jboolean {
+    return strcmp(reinterpret_cast<const char*>(a), reinterpret_cast<const char*>(b)) == 0;
+  };
+
+  return inf;
+}
+
+}  // namespace nativeloader
+}  // namespace android
+
+#endif  // ART_LIBNATIVELOADER_NATIVE_LOADER_TEST_H_