1 /*
2  * Copyright (c) 2022-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 "hdc_register.h"
17 
18 #include <dlfcn.h>
19 #include <unistd.h>
20 
21 #include "hilog_tag_wrapper.h"
22 
23 namespace OHOS::AbilityRuntime {
24 using StartRegister = void (*)(const std::string& processName, const std::string& pkgName, bool isDebug,
25     const HdcRegisterCallback& callback);
26 using StopRegister = void (*)();
27 
~HdcRegister()28 HdcRegister::~HdcRegister()
29 {
30     StopHdcRegister();
31 }
32 
Get()33 HdcRegister& HdcRegister::Get()
34 {
35     static HdcRegister hdcRegister;
36     return hdcRegister;
37 }
38 
StartHdcRegister(const std::string & bundleName,const std::string & processName,bool debugApp,HdcRegisterCallback callback)39 void HdcRegister::StartHdcRegister(const std::string& bundleName, const std::string& processName, bool debugApp,
40     HdcRegisterCallback callback)
41 {
42     TAG_LOGD(AAFwkTag::JSRUNTIME, "called");
43 
44     registerHandler_ = dlopen("libhdc_register.z.so", RTLD_LAZY);
45     if (registerHandler_ == nullptr) {
46         TAG_LOGE(AAFwkTag::JSRUNTIME, "null registerHandler_");
47         return;
48     }
49     auto startRegister = reinterpret_cast<StartRegister>(dlsym(registerHandler_, "StartConnect"));
50     if (startRegister == nullptr) {
51         TAG_LOGE(AAFwkTag::JSRUNTIME, "null StartConnect");
52         return;
53     }
54     startRegister(processName, bundleName, debugApp, callback);
55 }
56 
StopHdcRegister()57 void HdcRegister::StopHdcRegister()
58 {
59     TAG_LOGD(AAFwkTag::JSRUNTIME, "called");
60     if (registerHandler_ == nullptr) {
61         TAG_LOGE(AAFwkTag::JSRUNTIME, "null registerHandler_");
62         return;
63     }
64     auto stopRegister = reinterpret_cast<StopRegister>(dlsym(registerHandler_, "StopConnect"));
65     if (stopRegister != nullptr) {
66         stopRegister();
67     } else {
68         TAG_LOGE(AAFwkTag::JSRUNTIME, "null StopConnect");
69     }
70     dlclose(registerHandler_);
71     registerHandler_ = nullptr;
72 }
73 } // namespace OHOS::AbilityRuntime
74