1 /*
2 * Copyright (c) 2022-2024 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
16 #include "exception_branch_checker.h"
17 #include "hilog/log.h"
18 #include "securec.h"
19
20 #define MAX_LOG_LEN 1024
21 #define PERMISSION_NUM 3
22
23 namespace {
24 std::vector<std::string> g_hilogPermissionList = {"{public}", "{private}", "{protect}"};
25
RemoveHilogModifiers(const char * fmt,char * modifiedFmt)26 void RemoveHilogModifiers(const char *fmt, char *modifiedFmt)
27 {
28 std::string strTypeFmt = fmt;
29 std::string::size_type pos = 0;
30 for (int i = 0; i < PERMISSION_NUM; i++) {
31 while ((pos = strTypeFmt.find(g_hilogPermissionList[i], pos)) != std::string::npos) {
32 strTypeFmt.erase(pos, g_hilogPermissionList[i].length());
33 }
34 }
35 if (strcpy_s(modifiedFmt, strTypeFmt.length() + 1, strTypeFmt.c_str()) != EOK) {
36 return;
37 }
38 }
39 }
40
HiLogPrint(LogType type,LogLevel level,unsigned int domain,const char * tag,const char * fmt,...)41 int32_t HiLogPrint(LogType type, LogLevel level, unsigned int domain, const char *tag, const char *fmt, ...)
42 {
43 va_list args = { 0 };
44 char buffer[MAX_LOG_LEN] = { 0 };
45 char modifiedFmt[MAX_LOG_LEN] = { 0 };
46
47 RemoveHilogModifiers(fmt, modifiedFmt);
48
49 va_start(args, fmt);
50 int32_t ret = vsprintf_s(&buffer[0], sizeof(buffer), modifiedFmt, args);
51 va_end(args);
52 if (ret < 0) {
53 return ret;
54 }
55
56 auto *checker = ExceptionBranchChecker::GetCurrentInstance();
57 if (checker != nullptr) {
58 checker->WriteLog(buffer);
59 }
60
61 return ret;
62 }
63
GetCurrentInstance()64 ExceptionBranchChecker* ExceptionBranchChecker::GetCurrentInstance()
65 {
66 return instance_.load();
67 }
68
ExceptionBranchChecker(const std::string & branch)69 ExceptionBranchChecker::ExceptionBranchChecker(const std::string &branch)
70 : isMatched_(false), matchBranch_(branch)
71 {
72 instance_.store(this);
73 }
74
~ExceptionBranchChecker()75 ExceptionBranchChecker::~ExceptionBranchChecker()
76 {
77 instance_.store(nullptr);
78 }
79
WriteLog(const std::string & log)80 void ExceptionBranchChecker::WriteLog(const std::string& log)
81 {
82 if (log.find(matchBranch_) != std::string::npos) {
83 isMatched_ = true;
84 }
85 }
86
GetResult() const87 bool ExceptionBranchChecker::GetResult() const
88 {
89 return isMatched_;
90 }