1 /*
2 * Copyright (C) 2023 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "library_ohos.h"
17
18 #include <dlfcn.h>
19
20 #include <base/containers/string.h>
21 #include <core/log.h>
22 #include <core/namespace.h>
23
24 CORE_BEGIN_NAMESPACE()
25 using BASE_NS::string;
26 using BASE_NS::string_view;
27
LibraryOHOS(const string_view filename)28 LibraryOHOS::LibraryOHOS(const string_view filename)
29 {
30 string tmp(filename);
31 libraryHandle_ = dlopen(tmp.c_str(), RTLD_NOW | RTLD_LOCAL);
32 if (!libraryHandle_) {
33 const char* errorMessage = dlerror();
34 if (errorMessage != NULL) {
35 CORE_LOG_E("Loading dynamic library '%s' failed: %s", filename.data(), errorMessage);
36 }
37 }
38 }
39
~LibraryOHOS()40 LibraryOHOS::~LibraryOHOS()
41 {
42 if (libraryHandle_) {
43 dlclose(libraryHandle_);
44 libraryHandle_ = nullptr;
45 }
46 }
47
GetPlugin() const48 IPlugin* LibraryOHOS::GetPlugin() const
49 {
50 if (!libraryHandle_) {
51 return nullptr;
52 }
53
54 return reinterpret_cast<IPlugin*>(dlsym(libraryHandle_, "gPluginData"));
55 }
56
Destroy()57 void LibraryOHOS::Destroy()
58 {
59 delete this;
60 }
61
Load(const string_view filePath)62 ILibrary::Ptr ILibrary::Load(const string_view filePath)
63 {
64 #define TO_STRING(name) #name
65 #define LIB_NAME(name) TO_STRING(name)
66
67 if (filePath.find(LIB_NAME(LIB_ENGINE_CORE)) == string_view::npos &&
68 filePath.find(LIB_NAME(LIB_RENDER)) == string_view::npos &&
69 filePath.find(LIB_NAME(LIB_CORE3D)) == string_view::npos) {
70 return ILibrary::Ptr {};
71 }
72
73 CORE_LOG_E("load filePath %s", filePath.data());
74 return ILibrary::Ptr { new LibraryOHOS(filePath) };
75 }
76
GetFileExtension()77 string_view ILibrary::GetFileExtension()
78 {
79 return ".so";
80 }
81 CORE_END_NAMESPACE()
82
83