blob: c1e22bfb2d934dbda5d07a2e49e135c503fc2fec [file] [log] [blame]
Andy Hungd4265822022-04-01 18:54:32 -07001/*
2 * Copyright (C) 2022 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "Library"
18#include <utils/Log.h>
19#include <mediautils/Library.h>
20
21namespace {
22
23std::string dlerrorIfPresent() {
24 const char *dlerr = dlerror();
25 if (dlerr == nullptr) return "dlerror: none";
26 return std::string("dlerror: '").append(dlerr).append("'");
27}
28
29}
30namespace android::mediautils {
31
32std::shared_ptr<void> loadLibrary(const char *libraryName, int flags) {
33 std::shared_ptr<void> library{
34 dlopen(libraryName, flags),
35 [](void *lib) {
36 if (lib != nullptr) {
37 const int ret = dlclose(lib);
38 ALOGW_IF(ret !=0, "%s: dlclose(%p) == %d, %s",
39 __func__, lib, ret, dlerrorIfPresent().c_str());
40 }
41 }
42 };
43
44 if (!library) {
45 ALOGW("%s: cannot load libraryName %s, %s",
46 __func__, libraryName, dlerrorIfPresent().c_str());
47 return {};
48 }
49 return library;
50}
51
52std::shared_ptr<void> getUntypedObjectFromLibrary(
53 const char *objectName, const std::shared_ptr<void>& library) {
54 if (!library) {
55 ALOGW("%s: null library, cannot load objectName %s", __func__, objectName);
56 return {};
57 }
58 void *ptr = dlsym(library.get(), objectName);
59 if (ptr == nullptr) {
60 ALOGW("%s: cannot load objectName %s, %s",
61 __func__, objectName, dlerrorIfPresent().c_str());
62 return {};
63 }
64
65 // Note: we use the "aliasing" constructor of the std:shared_ptr.
66 //
67 // https://en.cppreference.com/w/cpp/memory/shared_ptr/shared_ptr
68 //
69 return { library, ptr }; // returns shared_ptr to ptr, but ref counted on library.
70}
71
72} // namespace android::mediautils