1 /*
2  * Copyright (C) 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 <dlfcn.h>
16 
17 #include "base/log/log_wrapper.h"
18 #include "core/common/ai/data_detector_loader.h"
19 namespace OHOS::Ace {
20 namespace {
21 #ifdef __aarch64__
22 constexpr char AI_ADAPTER_SO_PATH[] = "system/lib64/libai_text_analyzer_innerapi.z.so";
23 #else
24 constexpr char AI_ADAPTER_SO_PATH[] = "system/lib/libai_text_analyzer_innerapi.z.so";
25 #endif
26 } // namespace
27 
28 // static
Load()29 std::shared_ptr<DataDetectorLoader> DataDetectorLoader::Load()
30 {
31     auto engLib(std::make_shared<DataDetectorLoader>());
32     return engLib->Init() ? engLib : nullptr;
33 }
34 
~DataDetectorLoader()35 DataDetectorLoader::~DataDetectorLoader()
36 {
37     Close();
38 }
39 
Init()40 bool DataDetectorLoader::Init()
41 {
42     mLibraryHandle_ = dlopen(AI_ADAPTER_SO_PATH, RTLD_LAZY);
43     if (mLibraryHandle_ == nullptr) {
44         return false;
45     }
46     mCreateDataDetectorInstance_ = (DataDetectorInterface* (*)())dlsym(mLibraryHandle_,
47         "OHOS_ACE_createDataDetectorInstance");
48     mDestoryDataDetectorInstance_ = (void (*)(DataDetectorInterface*))dlsym(
49         mLibraryHandle_, "OHOS_ACE_destroyDataDetectorInstance");
50     if (mCreateDataDetectorInstance_ == nullptr || mDestoryDataDetectorInstance_ == nullptr) {
51         LOGE("Could not find engine interface function in %s", AI_ADAPTER_SO_PATH);
52         Close();
53         return false;
54     }
55     return true;
56 }
57 
CreateDataDetector()58 DataDetectorInstance DataDetectorLoader::CreateDataDetector()
59 {
60     if (mCreateDataDetectorInstance_ == nullptr || mDestoryDataDetectorInstance_ == nullptr) {
61         return DataDetectorInstance();
62     }
63     return DataDetectorInstance(mCreateDataDetectorInstance_(), [lib = shared_from_this(),
64         destroy = mDestoryDataDetectorInstance_](DataDetectorInterface* e) {
65             destroy(e);
66         });
67 }
68 
Close()69 void DataDetectorLoader::Close()
70 {
71     if (mLibraryHandle_ != nullptr) {
72         dlclose(mLibraryHandle_);
73     }
74     mLibraryHandle_ = nullptr;
75     mCreateDataDetectorInstance_ = nullptr;
76     mDestoryDataDetectorInstance_ = nullptr;
77 }
78 } // namespace OHOS::Ace
79