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