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 <cstdarg>
12 : #include <securec.h>
13 : #include "acl_rt_impl.h"
14 : #include "common/log_inner.h"
15 :
16 : namespace {
17 : constexpr const char_t* const TRUNCATED_MARK = "...[truncated]";
18 : constexpr size_t TRUNCATED_MARK_LEN = 14U; // strlen("...[truncated]")
19 :
20 : // 在缓冲区尾部覆盖写入截断标记,标记连同结尾 '\0' 仍落在 MAX_LOG_STRING 预算内,避免被下游二次截断。
21 5 : void AppendTruncatedMark(char_t* const buf)
22 : {
23 5 : (void)strcpy_s(&buf[acl::MAX_LOG_STRING - 1U - TRUNCATED_MARK_LEN], TRUNCATED_MARK_LEN + 1U, TRUNCATED_MARK);
24 5 : }
25 : } // namespace
26 :
27 : #ifdef __cplusplus
28 : extern "C" {
29 : #endif
30 :
31 10 : void aclAppLogImpl(
32 : aclLogLevel logLevel, const char* func, const char* file, uint32_t line, const char* fmt, va_list args)
33 : {
34 10 : if ((fmt == nullptr) || (func == nullptr) || (file == nullptr)) {
35 0 : return;
36 : }
37 10 : if (!acl::AclLog::IsLogOutputEnable(logLevel)) {
38 0 : return;
39 : }
40 : // 使用 vsnprintf_truncated_s / snprintf_truncated_s 而非 vsnprintf_s / sprintf_s:
41 : // 后者在内容超长时返回 -1 并丢弃整条日志,前者会截断保留内容(截断时返回 MAX_LOG_STRING - 1)。
42 10 : char_t str[acl::MAX_LOG_STRING] = {};
43 10 : const int32_t bodyRet = vsnprintf_truncated_s(str, static_cast<size_t>(acl::MAX_LOG_STRING), fmt, args);
44 10 : if (bodyRet == -1) {
45 : // 仅在格式化字符串非法(如包含 %n)时进入此分支,给出准确提示。
46 1 : acl::AclLog::ACLSaveLog(ACL_ERROR, "aclAppLog format string is invalid");
47 1 : return;
48 : }
49 :
50 9 : char_t strLog[acl::MAX_LOG_STRING] = {};
51 9 : const int32_t headRet = snprintf_truncated_s(
52 : strLog, static_cast<size_t>(acl::MAX_LOG_STRING), "%d %s:%s:%u: \"%s\"", acl::AclLog::GetTid(), func, file,
53 : line, str);
54 :
55 : // 正文或头部拼接发生截断时,在最终串尾部补写截断标记,提示用户内容不完整。
56 9 : if ((bodyRet >= static_cast<int32_t>(acl::MAX_LOG_STRING - 1U)) ||
57 : (headRet >= static_cast<int32_t>(acl::MAX_LOG_STRING - 1U))) {
58 5 : AppendTruncatedMark(strLog);
59 : }
60 9 : acl::AclLog::ACLSaveLog(logLevel, strLog);
61 9 : return;
62 : }
63 : #ifdef __cplusplus
64 : }
65 : #endif
|