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