1 /*
2  * Copyright 2019 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 "APM_EngineLoader"
18 
19 #include <dlfcn.h>
20 #include <utils/Log.h>
21 
22 #include "EngineLibrary.h"
23 
24 namespace android {
25 
26 // static
load(std::string libraryPath)27 std::shared_ptr<EngineLibrary> EngineLibrary::load(std::string libraryPath)
28 {
29     std::shared_ptr<EngineLibrary> engLib(new EngineLibrary());
30     return engLib->init(std::move(libraryPath)) ? engLib : nullptr;
31 }
32 
~EngineLibrary()33 EngineLibrary::~EngineLibrary()
34 {
35     close();
36 }
37 
init(std::string libraryPath)38 bool EngineLibrary::init(std::string libraryPath)
39 {
40     mLibraryHandle = dlopen(libraryPath.c_str(), 0);
41     if (mLibraryHandle == nullptr) {
42         ALOGE("Could not dlopen %s: %s", libraryPath.c_str(), dlerror());
43         return false;
44     }
45     mCreateEngineInstance = (EngineInterface* (*)())dlsym(mLibraryHandle, "createEngineInstance");
46     mDestroyEngineInstance = (void (*)(EngineInterface*))dlsym(
47             mLibraryHandle, "destroyEngineInstance");
48     if (mCreateEngineInstance == nullptr || mDestroyEngineInstance == nullptr) {
49         ALOGE("Could not find engine interface functions in %s", libraryPath.c_str());
50         close();
51         return false;
52     }
53     ALOGD("Loaded engine from %s", libraryPath.c_str());
54     return true;
55 }
56 
createEngine()57 EngineInstance EngineLibrary::createEngine()
58 {
59     if (mCreateEngineInstance == nullptr || mDestroyEngineInstance == nullptr) {
60         return EngineInstance();
61     }
62     return EngineInstance(mCreateEngineInstance(),
63             [lib = shared_from_this(), destroy = mDestroyEngineInstance] (EngineInterface* e) {
64                 destroy(e);
65             });
66 }
67 
close()68 void EngineLibrary::close()
69 {
70     if (mLibraryHandle != nullptr) {
71         dlclose(mLibraryHandle);
72     }
73     mLibraryHandle = nullptr;
74     mCreateEngineInstance = nullptr;
75     mDestroyEngineInstance = nullptr;
76 }
77 
78 }  // namespace android
79