1 /*
2 * Copyright (C) 2021 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 #include "SupportLibrary.h"
18
19 #include <android-base/logging.h>
20
21 #include <dlfcn.h>
22
23 #include <cstring>
24 #include <memory>
25 #include <string>
26
loadNnApiSupportLibrary(const std::string & libName)27 std::unique_ptr<const NnApiSupportLibrary> loadNnApiSupportLibrary(const std::string& libName) {
28 void* libHandle = dlopen(libName.c_str(), RTLD_LAZY | RTLD_LOCAL | RTLD_NODELETE);
29 if (libHandle == nullptr) {
30 LOG(ERROR) << "nnapi error: unable to open library " << libName.c_str() << " " << dlerror();
31 return nullptr;
32 }
33
34 auto result = loadNnApiSupportLibrary(libHandle);
35 if (!result) {
36 dlclose(libHandle);
37 }
38 return result;
39 }
40
loadNnApiSupportLibrary(void * libHandle)41 std::unique_ptr<const NnApiSupportLibrary> loadNnApiSupportLibrary(void* libHandle) {
42 NnApiSLDriverImpl* (*getSlDriverImpl)();
43 getSlDriverImpl = reinterpret_cast<decltype(getSlDriverImpl)>(
44 dlsym(libHandle, "ANeuralNetworks_getSLDriverImpl"));
45 if (getSlDriverImpl == nullptr) {
46 LOG(ERROR) << "Failed to find ANeuralNetworks_getSLDriverImpl symbol";
47 return nullptr;
48 }
49
50 NnApiSLDriverImpl* impl = getSlDriverImpl();
51 if (impl == nullptr) {
52 LOG(ERROR) << "ANeuralNetworks_getSLDriverImpl returned nullptr";
53 return nullptr;
54 }
55
56 if (impl->implFeatureLevel < ANEURALNETWORKS_FEATURE_LEVEL_5) {
57 LOG(ERROR) << "Unsupported NnApiSLDriverImpl->implFeatureLevel: " << impl->implFeatureLevel;
58 return nullptr;
59 }
60
61 if (impl->implFeatureLevel == ANEURALNETWORKS_FEATURE_LEVEL_5) {
62 return std::make_unique<NnApiSupportLibrary>(*reinterpret_cast<NnApiSLDriverImplFL5*>(impl),
63 libHandle);
64 }
65 if (impl->implFeatureLevel == ANEURALNETWORKS_FEATURE_LEVEL_6) {
66 return std::make_unique<NnApiSupportLibrary>(*reinterpret_cast<NnApiSLDriverImplFL6*>(impl),
67 libHandle);
68 }
69 if (impl->implFeatureLevel == ANEURALNETWORKS_FEATURE_LEVEL_7) {
70 return std::make_unique<NnApiSupportLibrary>(*reinterpret_cast<NnApiSLDriverImplFL7*>(impl),
71 libHandle);
72 }
73 if (impl->implFeatureLevel >= ANEURALNETWORKS_FEATURE_LEVEL_8) {
74 return std::make_unique<NnApiSupportLibrary>(*reinterpret_cast<NnApiSLDriverImplFL8*>(impl),
75 libHandle);
76 }
77
78 return nullptr;
79 }
80