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 : #include "file_utils.h"
12 : #include "mmpa/mmpa_api.h"
13 : #include "common/log_inner.h"
14 :
15 : namespace acl {
16 : namespace file_utils {
17 10 : aclError GetSoRealPath(std::string& path)
18 : {
19 : mmDlInfo dlInfo;
20 10 : if ((mmDladdr(reinterpret_cast<void*>(&GetSoRealPath), &dlInfo) != EN_OK) || (dlInfo.dli_fname == nullptr)) {
21 2 : ACL_LOG_WARN("Failed to get shared library path! errmsg:%s", mmDlerror());
22 2 : return ACL_ERROR_INTERNAL_ERROR;
23 : }
24 :
25 8 : if (strlen(dlInfo.dli_fname) >= MMPA_MAX_PATH) {
26 0 : ACL_LOG_WARN("The shared library path is too long!");
27 0 : return ACL_ERROR_INTERNAL_ERROR;
28 : }
29 :
30 8 : char_t realPath[MMPA_MAX_PATH] = {};
31 8 : if (mmRealPath(dlInfo.dli_fname, &realPath[0], MMPA_MAX_PATH) != EN_OK) {
32 2 : constexpr size_t maxErrorStrLen = 128U;
33 2 : char_t errBuf[maxErrorStrLen + 1U] = {};
34 2 : const auto errMsg = mmGetErrorFormatMessage(mmGetErrorCode(), &errBuf[0], maxErrorStrLen);
35 2 : ACL_LOG_WARN("Failed to get realpath of %s, errmsg:%s", dlInfo.dli_fname, errMsg);
36 2 : return ACL_ERROR_INTERNAL_ERROR;
37 : }
38 :
39 6 : path = realPath;
40 6 : path = path.substr(0U, path.rfind('/') + 1U);
41 6 : return ACL_SUCCESS;
42 : }
43 :
44 16 : std::string GetLocalRealPath(const std::string& path)
45 : {
46 16 : if (path.empty()) {
47 2 : return "";
48 : }
49 :
50 15 : char resolvedPath[PATH_MAX] = {0};
51 :
52 15 : if (realpath(path.c_str(), resolvedPath) == nullptr) {
53 1 : ACL_LOG_WARN("Failed to get real path for [%s], errno:%d", path.c_str(), errno);
54 2 : return "";
55 : }
56 :
57 28 : return std::string(resolvedPath);
58 : }
59 : } // namespace file_utils
60 : } // namespace acl
|