1 /*
2 * Copyright (c) 2022-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 #include "loader.h"
16
17 #include <dlfcn.h>
18 #include <fstream>
19
20 #include "pasteboard_hilog.h"
21 namespace OHOS::MiscServices {
Loader()22 Loader::Loader() {}
23
~Loader()24 Loader::~Loader() {}
25
LoadComponents()26 void Loader::LoadComponents()
27 {
28 Config config = LoadConfig();
29 for (auto &component : config.components) {
30 if (component.lib.empty()) {
31 continue;
32 }
33 if (Loader::ComponentIsExist(component.lib)) {
34 continue;
35 }
36 // no need to close the component, so we don't keep the handles
37 auto handle = dlopen(component.lib.c_str(), RTLD_LAZY);
38 if (handle == nullptr) {
39 PASTEBOARD_HILOGE(
40 PASTEBOARD_MODULE_SERVICE, "dlopen(%{public}s) failed(%{public}d)!", component.lib.c_str(), errno);
41 continue;
42 }
43 Loader::handleMap.insert(std::pair(component.lib, handle));
44
45 if (component.constructor.empty()) {
46 continue;
47 }
48
49 auto ctor = reinterpret_cast<Constructor>(dlsym(handle, component.constructor.c_str()));
50 if (ctor == nullptr) {
51 continue;
52 }
53 ctor(component.params.c_str());
54 }
55 }
56
LoadUid()57 int32_t Loader::LoadUid()
58 {
59 Config config = LoadConfig();
60 return config.uid;
61 }
62
LoadConfig()63 Config Loader::LoadConfig()
64 {
65 Config config;
66 std::string context;
67 std::ifstream fin(CONF_FILE);
68 while (fin.good()) {
69 std::string line;
70 std::getline(fin, line);
71 context += line;
72 }
73 config.Unmarshall(context);
74 return config;
75 }
76
ComponentIsExist(const std::string & lib)77 bool Loader::ComponentIsExist(const std::string &lib)
78 {
79 return Loader::handleMap.find(lib) != Loader::handleMap.end();
80 }
81 } // namespace OHOS::MiscServices