1 /*
2  * Copyright (c) 2024 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 "dh_modem_context_ext.h"
17 
18 #include <dlfcn.h>
19 #include <string>
20 
21 #include "distributed_hardware_errno.h"
22 #include "distributed_hardware_log.h"
23 namespace OHOS {
24 namespace DistributedHardware {
25 IMPLEMENT_SINGLE_INSTANCE(DHModemContextExt);
26 
27 constexpr const char* LIB_DISTRIBUTEDMODEM_EXT_NAME = "libdistributedmodem_ext.z.so";
28 
DHModemContextExt()29 DHModemContextExt::DHModemContextExt()
30 {
31     DHLOGI("Ctor DHModemContextExt");
32 }
33 
~DHModemContextExt()34 DHModemContextExt::~DHModemContextExt()
35 {
36     DHLOGI("Dtor DHModemContextExt");
37 }
38 
GetHandler()39 int32_t DHModemContextExt::GetHandler()
40 {
41     soHandle_ = dlopen(LIB_DISTRIBUTEDMODEM_EXT_NAME, RTLD_LAZY | RTLD_NODELETE);
42     if (soHandle_ == nullptr) {
43         DHLOGE("load so failed, failed reason: %{public}s", dlerror());
44         return ERR_DH_FWK_POINTER_IS_NULL;
45     }
46     return DH_FWK_SUCCESS;
47 }
48 
GetModemExtInstance()49 std::shared_ptr<IDistributedModemExt> DHModemContextExt::GetModemExtInstance()
50 {
51     if (soHandle_ == nullptr && GetHandler() != DH_FWK_SUCCESS) {
52         DHLOGE("load modem_ext so failed.");
53         return distributedModemExt_;
54     }
55     auto func = (CreateDistributedModemExtImplFuncPtr)dlsym(soHandle_, "CreateDistributedModemExtImplObject");
56     if (dlerror() != nullptr || func == nullptr) {
57         dlclose(soHandle_);
58         DHLOGE("Create object function is not exist.");
59         return distributedModemExt_;
60     }
61     distributedModemExt_ = std::shared_ptr<IDistributedModemExt>(func());
62     return distributedModemExt_;
63 }
64 
UnInit()65 int32_t DHModemContextExt::UnInit()
66 {
67     DHLOGI("dlclose modem_ext so.");
68     if (soHandle_ == nullptr) {
69         DHLOGE("handler is null.");
70         return ERR_DH_FWK_LOADER_HANDLER_IS_NULL;
71     }
72 
73     if (dlclose(soHandle_) != 0) {
74         DHLOGE("dlclose modem_ext so failed.");
75         soHandle_ = nullptr;
76         return ERR_DH_FWK_LOADER_DLCLOSE_FAIL;
77     }
78     soHandle_ = nullptr;
79     return DH_FWK_SUCCESS;
80 }
81 } // namespace DistributedHardware
82 } // namespace OHOS
83