1 /*
2  * Copyright (c) 2022 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 #include "tbox.h"
16 
17 #include <unistd.h>
18 
19 #include <regex>
20 #include "calc_fingerprint.h"
21 #include "file_util.h"
22 #include "log_parse.h"
23 #include "securec.h"
24 #include "string_util.h"
25 #include "time_util.h"
26 
27 using namespace std;
28 namespace OHOS {
29 namespace HiviewDFX {
30 DEFINE_LOG_TAG("Tbox");
31 
32 const string Tbox::ARRAY_STR = "ARRAY :";
33 const string Tbox::CAUSEDBY_HEADER = "Caused by:";
34 const string Tbox::SUPPRESSED_HEADER = "Suppressed:";
35 
Tbox()36 Tbox::Tbox()
37 {
38 }
39 
~Tbox()40 Tbox::~Tbox()
41 {
42 }
43 
CalcFingerPrint(const string & val,size_t mask,int mode)44 string Tbox::CalcFingerPrint(const string& val, size_t mask, int mode)
45 {
46     char hash[HAS_LEN] = {'0'};
47     int err = -1;
48     switch (mode) {
49         case FP_FILE:
50             err = CalcFingerprint::CalcFileSha(val, hash, sizeof(hash));
51             break;
52         case FP_BUFFER:
53             err = CalcFingerprint::CalcBufferSha(val, val.size(), hash, sizeof(hash));
54             break;
55         default:
56             break;
57     }
58 
59     if (err != 0) {
60         // if file not exist, API will return ENOENT
61         HIVIEW_LOGE("ProcessedEvent: calc fingerprint failed, err is %{public}d.", err);
62     }
63     return string(hash);
64 }
65 
GetPartial(const string & src,const string & res,string & des)66 bool Tbox::GetPartial(const string& src, const string& res, string& des)
67 {
68     des = "";
69     regex reNew(res);
70     smatch result;
71     if (regex_search(src, result, reNew)) {
72         for (size_t i = 1; i < result.size(); ++i) {
73             if (!result.str(i).empty()) {
74                 des = string(result.str(i));
75                 break;
76             }
77         }
78         return true;
79     }
80     return false;
81 }
82 
IsCallStack(const string & line)83 bool Tbox::IsCallStack(const string& line)
84 {
85     if (regex_search(line, regex("^\\s+at (.*)\\(.*")) ||
86         regex_search(line, regex("^\\s*at .*")) ||
87         regex_search(line, regex("^\\s+- (.*)\\(.*")) ||
88         regex_search(line, regex("\\s+#\\d+")) ||
89         regex_search(line, regex("[0-9a-zA-Z_]+\\+0x[0-9a-f]+/0x[0-9a-f]+")) ||
90         regex_search(line, regex("#\\d+")) ||
91         regex_search(line, regex("\\.*"))) {
92         return true;
93     }
94     return false;
95 }
96 
HasCausedBy(const string & line)97 bool Tbox::HasCausedBy(const string& line)
98 {
99     if ((line.find(CAUSEDBY_HEADER) != string::npos) ||
100         (line.find(SUPPRESSED_HEADER) != string::npos)) {
101         return true;
102     }
103     return false;
104 }
105 
106 /*
107  * format1:  com.ohos.launcher:extension
108  * format2:  #06 pc 00000000000bb328  /system/lib/libart.so (__epoll_pwait+8)
109  */
GetStackName(const string & line)110 string Tbox::GetStackName(const string& line)
111 {
112     string stackname = UNKNOWN_STR;
113     string str;
114     if (GetPartial(line, "^\\s+at (.*)\\).*", str) ||
115         GetPartial(line, "^\\s*at (.*)", str) || // for jsCrash
116         GetPartial(line, "#\\d+ pc [0-9a-f]+ (.*\\+\\d+)\\)", str) ||
117         GetPartial(line, "#\\d+ pc [0-9a-f]+ (.*)", str) ||
118         GetPartial(line, "([0-9a-zA-Z_]+\\+0x[0-9a-f]+/0x[0-9a-f]+)", str)) {
119         stackname = str;
120     } else if (GetPartial(line, "^\\s+- (.*)\\(.*", str)) {
121         size_t ret = str.find_last_of("+");
122         if (ret != string::npos) {
123             str.replace(ret, string::npos, ")\0");
124             stackname = str;
125         } else {
126             stackname = UNKNOWN_STR;
127         }
128     } else if (IsCallStack(line)) {
129         stackname = line;
130     } else {
131         return stackname;
132     }
133     regex re("(.+?)-(.+)==(.+)");
134     stackname = regex_replace(stackname, re, "$1$3");
135     return stackname;
136 }
137 
FilterTrace(std::map<std::string,std::string> & eventInfo,string eventType)138 void Tbox::FilterTrace(std::map<std::string, std::string>& eventInfo, string eventType)
139 {
140     auto iterEndStack = eventInfo.find(PARAMETER_ENDSTACK);
141     if (eventInfo.empty() || iterEndStack == eventInfo.end() || iterEndStack->second.empty()) {
142         return;
143     }
144     std::vector<std::string> trace;
145     LogParse logparse;
146     std::string block = logparse.GetFilterTrace(iterEndStack->second, trace, eventType);
147     eventInfo[PARAMETER_ENDSTACK] = block;
148     std::stack<std::string> stackTop = logparse.GetStackTop(trace, 3);  // 3 : first/second/last frame
149     logparse.SetFrame(stackTop, eventInfo);
150 }
151 
WaitForDoneFile(const std::string & file,unsigned int timeout)152 bool Tbox::WaitForDoneFile(const std::string& file, unsigned int timeout)
153 {
154     uint64_t remainedTime = timeout * NS_PER_SECOND;
155     while (remainedTime > 0) {
156         if (FileUtil::FileExists(file)) {
157             HIVIEW_LOGD("Done file exist: %{public}s", file.c_str());
158             return true;
159         }
160         uint64_t startTime = TimeUtil::GetNanoTime();
161         sleep(1);
162         uint64_t duration = TimeUtil::GetNanoTime() - startTime;
163         remainedTime = (remainedTime > duration) ? (remainedTime - duration) : 0;
164     }
165     return false;
166 }
167 
GetHappenTime(const string & src,const string & regex)168 int64_t Tbox::GetHappenTime(const string& src, const string& regex)
169 {
170     int64_t happenTime = HAPPEN_TIME_DEFAULT;
171     std::regex recordRegex(regex);
172     struct tm tmHappenTime;
173     (void)memset_s(&tmHappenTime, sizeof(struct tm), 0, sizeof(struct tm));
174     std::smatch matches;
175     if (!std::regex_match(src, matches, recordRegex)) {
176         HIVIEW_LOGE("unmatch event:%{public}s, skip", src.c_str());
177         return happenTime;
178     }
179 
180     string timeStr;
181     for (size_t i = 1; i < matches.size(); ++i) {
182         timeStr += matches[i].str();
183     }
184     strptime(timeStr.c_str(), "%Y%m%d%H%M%S", &tmHappenTime);
185     happenTime = mktime(&tmHappenTime);
186     //if the HappenTime is 1970, return as original information
187     if (tmHappenTime.tm_year == 70) { // 70: The number of years since the HappenTime in 1900
188         return happenTime;
189     }
190 
191     time_t now = time(nullptr);
192     struct tm result;
193     gmtime_r(&now, &result);
194     double offset = difftime(now, mktime(&result)); // zone offset with second. Example, 1 zone is 3600 sec
195     if (difftime(now, happenTime) > offset) {
196         happenTime = timegm(&tmHappenTime);
197     }
198     return happenTime;
199 }
200 }
201 }
202