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