MediaUtils: Use delayed / lazy library loading

Postpone loading libutilscallstack until needed
to save memory.

Test: atest library_tests
Test: adb shell 'showmap $(pgrep mediametrics)'
Bug: 227536784
Change-Id: I3d4c9e9b6d854b013185e18fc20d4bec320df14e
diff --git a/media/utils/tests/Android.bp b/media/utils/tests/Android.bp
index 5498ac5..30c10b7 100644
--- a/media/utils/tests/Android.bp
+++ b/media/utils/tests/Android.bp
@@ -7,6 +7,62 @@
     default_applicable_licenses: ["frameworks_av_license"],
 }
 
+cc_test_library {
+    name: "libsharedtest",
+    cflags: [
+        "-Wall",
+        "-Werror",
+        "-Wextra",
+    ],
+
+    sanitize:{
+       address: true,
+       cfi: true,
+       integer_overflow: true,
+       memtag_heap: true,
+    },
+
+    shared_libs: [
+        "liblog",
+    ],
+
+    srcs: [
+        "sharedtest.cpp",
+    ]
+}
+
+cc_test {
+    name: "library_tests",
+
+    cflags: [
+        "-Wall",
+        "-Werror",
+        "-Wextra",
+    ],
+
+    sanitize:{
+       address: true,
+       cfi: true,
+       integer_overflow: true,
+       memtag_heap: true,
+    },
+
+    shared_libs: [
+        "libbase",
+        "liblog",
+        "libmediautils",
+        "libutils",
+    ],
+
+    data_libs: [
+        "libsharedtest",
+    ],
+
+    srcs: [
+        "library_tests.cpp",
+    ],
+}
+
 cc_test {
     name: "media_synchronization_tests",
 
diff --git a/media/utils/tests/library_tests.cpp b/media/utils/tests/library_tests.cpp
new file mode 100644
index 0000000..c5c500c
--- /dev/null
+++ b/media/utils/tests/library_tests.cpp
@@ -0,0 +1,78 @@
+/*
+ * Copyright (C) 2022 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.
+ */
+
+#define LOG_TAG "library_tests"
+#include <utils/Log.h>
+
+#include <mediautils/Library.h>
+
+#include <android-base/file.h>
+#include <gtest/gtest.h>
+
+using namespace android::mediautils;
+
+namespace {
+
+static int32_t here = 0;  // accessed on same thread.
+
+TEST(library_tests, basic) {
+    std::string path = android::base::GetExecutableDirectory() + "/libsharedtest.so";
+    // The flags to loadLibrary should not include  RTLD_GLOBAL or RTLD_NODELETE
+    // which prevent unloading.
+    std::shared_ptr<void> library = loadLibrary(path.c_str(), RTLD_LAZY);
+    ASSERT_TRUE(library);
+    ASSERT_EQ(1, library.use_count());
+
+    std::shared_ptr<int32_t*> ptr = getObjectFromLibrary<int32_t*>("gPtr", library);
+    ASSERT_TRUE(ptr);
+    ASSERT_EQ(2, library.use_count());
+
+    ASSERT_EQ(nullptr, *ptr); // original contents are nullptr.
+
+    // There is a static object destructor in libsharedtest.so that will set the
+    // contents of the integer pointer (if non-null) to 1 when called.
+    // This is used to detect that the library is unloaded.
+    *ptr = &here;
+
+    ptr.reset();  // Note: this shared pointer uses library's refcount.
+    ASSERT_EQ(1, library.use_count());  // Verify library's refcount goes down by 1.
+    ASSERT_EQ(0, here);  // the shared library's object destructor hasn't been called.
+
+    // use weak_ptr to investigate whether the library is gone.
+    std::weak_ptr<void> wlibrary = library;
+    ASSERT_EQ(1, wlibrary.use_count());
+    library.reset();
+
+    // we should have released the last reference.
+    ASSERT_EQ(0, wlibrary.use_count());
+
+    // The library should unload and the global object destroyed.
+    // Note on Android, specifying RTLD_GLOBAL or RTLD_NODELETE in the flags
+    // will prevent unloading libraries.
+    ASSERT_EQ(1, here);
+}
+
+TEST(library_tests, sad_library) {
+    std::string path = android::base::GetExecutableDirectory()
+            + "/something_random_library_that_doesn't_exit.so";
+
+    std::shared_ptr<void> library = loadLibrary(path.c_str(), RTLD_LAZY);
+    // We shouldn't crash on an invalid library path, just return an empty shared pointer.
+    // Check the logcat for any error details.
+    ASSERT_FALSE(library);
+}
+
+} // namespace
diff --git a/media/utils/tests/sharedtest.cpp b/media/utils/tests/sharedtest.cpp
new file mode 100644
index 0000000..3888874
--- /dev/null
+++ b/media/utils/tests/sharedtest.cpp
@@ -0,0 +1,57 @@
+/*
+ * Copyright (C) 2022 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 <cstdint>
+#define LOG_TAG "sharedtest"
+#include <utils/Log.h>
+
+// Test library which is dynamicly loaded by library_tests.
+
+// Static variable construction.
+// Calls A constructor on library load, A destructor on library unload.
+
+int32_t *gPtr = nullptr;  // this pointer is filled with the location to set memory
+                          // when ~A() is called.
+                          // we cannot use anything internal to this file as the
+                          // data segment may no longer exist after unloading the library.
+struct A {
+    A() {
+        ALOGD("%s: gPtr:%p", __func__, gPtr);
+    }
+
+    ~A() {
+        ALOGD("%s: gPtr:%p", __func__, gPtr);
+        if (gPtr != nullptr) {
+            *gPtr = 1;
+        }
+    }
+} gA;
+
+//  __attribute__((constructor)) methods occur before any static variable construction.
+// Libraries that use __attribute__((constructor)) should not rely on global constructors
+// before method call because they will not be initialized before use.
+// See heapprofd_client_api.
+// NOTE: is this right? Shouldn't it occur after construction?
+ __attribute__((constructor))
+void onConstruction() {
+    ALOGD("%s: in progress", __func__);  // for logcat analysis
+}
+
+// __attribute__((destructor)) methods occur before any static variable destruction.
+ __attribute__((destructor))
+void onDestruction() {
+    ALOGD("%s: in progress", __func__);  // for logcat analysis
+}