Line data Source code
1 : /**
2 : * Copyright (c) 2025 Huawei Technologies Co., Ltd.
3 : * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4 : * CANN Open Software License Agreement Version 2.0 (the "License").
5 : * Please refer to the License for details. You may not use this file except in compliance with the License.
6 : * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7 : * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8 : * See LICENSE in the root of the software repository for the full text of the License.
9 : */
10 :
11 : #ifndef DLRTS_FUNCTION_V2_H
12 : #define DLRTS_FUNCTION_V2_H
13 :
14 : #include <mutex>
15 : #include <dlfcn.h>
16 : #include "log.h"
17 : namespace Hccl {
18 : template <const char* soName>
19 : class DlRtsFunctionV2 {
20 : public:
21 : explicit DlRtsFunctionV2() = default;
22 1 : virtual ~DlRtsFunctionV2()
23 : {
24 1 : if (handle_ != nullptr) {
25 0 : dlclose(handle_);
26 0 : handle_ = nullptr;
27 : }
28 1 : }
29 :
30 : template <const char* funcName>
31 1 : void* Handle()
32 : {
33 1 : Init();
34 1 : if (handle_ == nullptr) {
35 1 : return nullptr;
36 : }
37 0 : return dlsym(handle_, funcName);
38 : }
39 :
40 : private:
41 1 : void Init()
42 : {
43 1 : std::lock_guard<std::mutex> lock(handleMutex_);
44 1 : if (isInit_) {
45 0 : return;
46 : }
47 3 : HCCL_INFO("DlRtsFunctionInit start, open so: %s", soName);
48 1 : handle_ = dlopen(soName, RTLD_NOW);
49 1 : const char* errMsg = dlerror();
50 1 : if (handle_ == nullptr) {
51 3 : HCCL_ERROR(
52 : "dlopen [%s] failed, %s", soName,
53 : (errMsg == nullptr) ? "check the file exist or permission denied." : errMsg);
54 1 : return;
55 : }
56 0 : isInit_ = true;
57 1 : }
58 : void* handle_ = nullptr;
59 : std::mutex handleMutex_;
60 : bool isInit_ = false;
61 : };
62 : } // namespace Hccl
63 : #endif // DLRTS_FUNCTION_V2_H
|