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
16 #include "xcollie_utils.h"
17 #include <ctime>
18 #include <cinttypes>
19 #include <algorithm>
20 #include <cstdlib>
21 #include <csignal>
22 #include <sstream>
23 #include <securec.h>
24 #include <iostream>
25 #include <unistd.h>
26 #include <fcntl.h>
27 #include <sys/prctl.h>
28 #include <sys/stat.h>
29 #include <set>
30 #include "directory_ex.h"
31 #include "file_ex.h"
32 #include "storage_acl.h"
33 #include "parameter.h"
34 #include "parameters.h"
35 #include <dlfcn.h>
36
37 namespace OHOS {
38 namespace HiviewDFX {
39 namespace {
40 constexpr int64_t SEC_TO_MANOSEC = 1000000000;
41 constexpr int64_t SEC_TO_MICROSEC = 1000000;
42 constexpr uint64_t MAX_FILE_SIZE = 10 * 1024 * 1024; // 10M
43 const int MAX_NAME_SIZE = 128;
44 const int MIN_WAIT_NUM = 3;
45 const int TIME_INDEX_MAX = 32;
46 const int INIT_PID = 1;
47 const int TIMES_ARR_SIZE = 6;
48 const uint64_t TIMES_AVE_PARAM = 2;
49 const int32_t APP_MIN_UID = 20000;
50 const uint64_t START_TIME_INDEX = 21;
51 const int START_PATH_LEN = 128;
52 constexpr int64_t MAX_TIME_BUFF = 64;
53 constexpr int64_t SEC_TO_MILLISEC = 1000;
54 constexpr const char* const LOGGER_TEANSPROC_PATH = "/proc/transaction_proc";
55 constexpr const char* const WATCHDOG_DIR = "/data/storage/el2/log/watchdog";
56 constexpr const char* const KEY_DEVELOPER_MODE_STATE = "const.security.developermode.state";
57 constexpr const char* const KEY_BETA_TYPE = "const.logsystem.versiontype";
58 constexpr const char* const ENABLE_VAULE = "true";
59 constexpr const char* const ENABLE_BETA_VAULE = "beta";
60
61 static std::string g_curProcName;
62 static int32_t g_lastPid;
63 static std::mutex g_lock;
64 }
GetCurrentTickMillseconds()65 uint64_t GetCurrentTickMillseconds()
66 {
67 struct timespec t;
68 t.tv_sec = 0;
69 t.tv_nsec = 0;
70 clock_gettime(CLOCK_MONOTONIC, &t);
71 return static_cast<uint64_t>((t.tv_sec) * SEC_TO_MANOSEC + t.tv_nsec) / SEC_TO_MICROSEC;
72 }
73
GetCurrentBootMillseconds()74 uint64_t GetCurrentBootMillseconds()
75 {
76 struct timespec t;
77 t.tv_sec = 0;
78 t.tv_nsec = 0;
79 clock_gettime(CLOCK_BOOTTIME, &t);
80 return static_cast<uint64_t>((t.tv_sec) * SEC_TO_MANOSEC + t.tv_nsec) / SEC_TO_MICROSEC;
81 }
82
CalculateTimes(uint64_t & bootTimeStart,uint64_t & monoTimeStart)83 void CalculateTimes(uint64_t& bootTimeStart, uint64_t& monoTimeStart)
84 {
85 uint64_t timesArr[TIMES_ARR_SIZE] = {0};
86 uint64_t minTimeDiff = UINT64_MAX;
87 size_t index = 1;
88
89 for (size_t i = 0; i < TIMES_ARR_SIZE ; i++) {
90 timesArr[i] = (i & 1) ? GetCurrentTickMillseconds() : GetCurrentBootMillseconds();
91 if (i <= 1) {
92 continue;
93 }
94 uint64_t tmpDiff = GetNumsDiffAbs(timesArr[i], timesArr[i - 2]);
95 if (tmpDiff < minTimeDiff) {
96 minTimeDiff = tmpDiff;
97 index = i - 1;
98 }
99 }
100 bootTimeStart = (index & 1) ? (timesArr[index - 1] + timesArr[index + 1]) / TIMES_AVE_PARAM : timesArr[index];
101 monoTimeStart = (index & 1) ? timesArr[index] : (timesArr[index - 1] + timesArr[index + 1]) / TIMES_AVE_PARAM;
102 }
103
GetNumsDiffAbs(const uint64_t & numOne,const uint64_t & numTwo)104 uint64_t GetNumsDiffAbs(const uint64_t& numOne, const uint64_t& numTwo)
105 {
106 return (numOne > numTwo) ? (numOne - numTwo) : (numTwo - numOne);
107 }
108
IsFileNameFormat(char c)109 bool IsFileNameFormat(char c)
110 {
111 if (c >= '0' && c <= '9') {
112 return false;
113 }
114
115 if (c >= 'a' && c <= 'z') {
116 return false;
117 }
118
119 if (c >= 'A' && c <= 'Z') {
120 return false;
121 }
122
123 if (c == '.' || c == '-' || c == '_') {
124 return false;
125 }
126
127 return true;
128 }
129
GetSelfProcName()130 std::string GetSelfProcName()
131 {
132 std::string ret = GetProcessNameFromProcCmdline();
133 ret.erase(std::remove_if(ret.begin(), ret.end(), IsFileNameFormat), ret.end());
134 return ret;
135 }
136
GetFirstLine(const std::string & path)137 std::string GetFirstLine(const std::string& path)
138 {
139 char checkPath[PATH_MAX] = {0};
140 if (realpath(path.c_str(), checkPath) == nullptr) {
141 XCOLLIE_LOGE("canonicalize failed. path is %{public}s", path.c_str());
142 return "";
143 }
144
145 std::ifstream inFile(checkPath);
146 if (!inFile) {
147 return "";
148 }
149 std::string firstLine;
150 getline(inFile, firstLine);
151 inFile.close();
152 return firstLine;
153 }
154
IsDeveloperOpen()155 bool IsDeveloperOpen()
156 {
157 static std::string isDeveloperOpen;
158 if (!isDeveloperOpen.empty()) {
159 return (isDeveloperOpen.find(ENABLE_VAULE) != std::string::npos);
160 }
161 isDeveloperOpen = system::GetParameter(KEY_DEVELOPER_MODE_STATE, "");
162 return (isDeveloperOpen.find(ENABLE_VAULE) != std::string::npos);
163 }
164
IsBetaVersion()165 bool IsBetaVersion()
166 {
167 static std::string isBetaVersion;
168 if (!isBetaVersion.empty()) {
169 return (isBetaVersion.find(ENABLE_BETA_VAULE) != std::string::npos);
170 }
171 isBetaVersion = system::GetParameter(KEY_BETA_TYPE, "");
172 return (isBetaVersion.find(ENABLE_BETA_VAULE) != std::string::npos);
173 }
174
GetProcessNameFromProcCmdline(int32_t pid)175 std::string GetProcessNameFromProcCmdline(int32_t pid)
176 {
177 if (pid > 0) {
178 g_lock.lock();
179 if (!g_curProcName.empty() && g_lastPid == pid) {
180 g_lock.unlock();
181 return g_curProcName;
182 }
183 }
184
185 std::string pidStr = pid > 0 ? std::to_string(pid) : "self";
186 std::string procCmdlinePath = "/proc/" + pidStr + "/cmdline";
187 std::string procCmdlineContent = GetFirstLine(procCmdlinePath);
188 if (procCmdlineContent.empty()) {
189 if (pid > 0) {
190 g_lock.unlock();
191 }
192 return "";
193 }
194
195 size_t procNameStartPos = 0;
196 size_t procNameEndPos = procCmdlineContent.size();
197 for (size_t i = 0; i < procCmdlineContent.size(); i++) {
198 if (procCmdlineContent[i] == '/') {
199 procNameStartPos = i + 1;
200 } else if (procCmdlineContent[i] == '\0') {
201 procNameEndPos = i;
202 break;
203 }
204 }
205 size_t endPos = procNameEndPos - procNameStartPos;
206 if (pid <= 0) {
207 return procCmdlineContent.substr(procNameStartPos, endPos);
208 }
209 g_curProcName = procCmdlineContent.substr(procNameStartPos, endPos);
210 g_lastPid = pid;
211 g_lock.unlock();
212 XCOLLIE_LOGD("g_curProcName is empty, name %{public}s pid %{public}d", g_curProcName.c_str(), pid);
213 return g_curProcName;
214 }
215
GetLimitedSizeName(std::string name)216 std::string GetLimitedSizeName(std::string name)
217 {
218 if (name.size() > MAX_NAME_SIZE) {
219 return name.substr(0, MAX_NAME_SIZE);
220 }
221 return name;
222 }
223
IsProcessDebug(int32_t pid)224 bool IsProcessDebug(int32_t pid)
225 {
226 const int buffSize = 128;
227 char paramBundle[buffSize] = {0};
228 GetParameter("hiviewdfx.appfreeze.filter_bundle_name", "", paramBundle, buffSize - 1);
229 std::string debugBundle(paramBundle);
230 std::string procCmdlineContent = GetProcessNameFromProcCmdline(pid);
231 if (procCmdlineContent.compare(debugBundle) == 0) {
232 XCOLLIE_LOGI("appfreeze filtration %{public}s_%{public}s don't exit.",
233 debugBundle.c_str(), procCmdlineContent.c_str());
234 return true;
235 }
236 return false;
237 }
238
DelayBeforeExit(unsigned int leftTime)239 void DelayBeforeExit(unsigned int leftTime)
240 {
241 while (leftTime > 0) {
242 leftTime = sleep(leftTime);
243 }
244 }
245
TrimStr(const std::string & str,const char cTrim)246 std::string TrimStr(const std::string& str, const char cTrim)
247 {
248 std::string strTmp = str;
249 strTmp.erase(0, strTmp.find_first_not_of(cTrim));
250 strTmp.erase(strTmp.find_last_not_of(cTrim) + sizeof(char));
251 return strTmp;
252 }
253
SplitStr(const std::string & str,const std::string & sep,std::vector<std::string> & strs,bool canEmpty,bool needTrim)254 void SplitStr(const std::string& str, const std::string& sep,
255 std::vector<std::string>& strs, bool canEmpty, bool needTrim)
256 {
257 strs.clear();
258 std::string strTmp = needTrim ? TrimStr(str) : str;
259 std::string strPart;
260 while (true) {
261 std::string::size_type pos = strTmp.find(sep);
262 if (pos == std::string::npos || sep.empty()) {
263 strPart = needTrim ? TrimStr(strTmp) : strTmp;
264 if (!strPart.empty() || canEmpty) {
265 strs.push_back(strPart);
266 }
267 break;
268 } else {
269 strPart = needTrim ? TrimStr(strTmp.substr(0, pos)) : strTmp.substr(0, pos);
270 if (!strPart.empty() || canEmpty) {
271 strs.push_back(strPart);
272 }
273 strTmp = strTmp.substr(sep.size() + pos, strTmp.size() - sep.size() - pos);
274 }
275 }
276 }
277
ParsePeerBinderPid(std::ifstream & fin,int32_t pid)278 int ParsePeerBinderPid(std::ifstream& fin, int32_t pid)
279 {
280 const int decimal = 10;
281 std::string line;
282 bool isBinderMatchup = false;
283 while (getline(fin, line)) {
284 if (isBinderMatchup) {
285 break;
286 }
287
288 if (line.find("async\t") != std::string::npos) {
289 continue;
290 }
291
292 std::istringstream lineStream(line);
293 std::vector<std::string> strList;
294 std::string tmpstr;
295 while (lineStream >> tmpstr) {
296 strList.push_back(tmpstr);
297 }
298
299 auto splitPhase = [](const std::string& str, uint16_t index) -> std::string {
300 std::vector<std::string> strings;
301 SplitStr(str, ":", strings);
302 if (index < strings.size()) {
303 return strings[index];
304 }
305 return "";
306 };
307
308 if (strList.size() >= 7) { // 7: valid array size
309 // 2: peer id,
310 std::string server = splitPhase(strList[2], 0);
311 // 0: local id,
312 std::string client = splitPhase(strList[0], 0);
313 // 5: wait time, s
314 std::string wait = splitPhase(strList[5], 1);
315 if (server == "" || client == "" || wait == "") {
316 continue;
317 }
318 int serverNum = std::strtol(server.c_str(), nullptr, decimal);
319 int clientNum = std::strtol(client.c_str(), nullptr, decimal);
320 int waitNum = std::strtol(wait.c_str(), nullptr, decimal);
321 XCOLLIE_LOGI("server:%{public}d, client:%{public}d, wait:%{public}d",
322 serverNum, clientNum, waitNum);
323 if (clientNum != pid || waitNum < MIN_WAIT_NUM) {
324 continue;
325 }
326 return serverNum;
327 }
328 if (line.find("context") != line.npos) {
329 isBinderMatchup = true;
330 }
331 }
332 return -1;
333 }
334
KillProcessByPid(int32_t pid)335 bool KillProcessByPid(int32_t pid)
336 {
337 std::ifstream fin;
338 std::string path = std::string(LOGGER_TEANSPROC_PATH);
339 char resolvePath[PATH_MAX] = {0};
340 if (realpath(path.c_str(), resolvePath) == nullptr) {
341 XCOLLIE_LOGI("GetBinderPeerPids realpath error");
342 return false;
343 }
344 fin.open(resolvePath);
345 if (!fin.is_open()) {
346 XCOLLIE_LOGI("open file failed, %{public}s.", resolvePath);
347 return false;
348 }
349
350 int peerBinderPid = ParsePeerBinderPid(fin, pid);
351 fin.close();
352 if (peerBinderPid <= INIT_PID || peerBinderPid == pid) {
353 XCOLLIE_LOGI("No PeerBinder process freeze occurs in the current process. "
354 "peerBinderPid=%{public}d, pid=%{public}d", peerBinderPid, pid);
355 return false;
356 }
357 int32_t uid = GetUidByPid(peerBinderPid);
358 if (uid < APP_MIN_UID) {
359 XCOLLIE_LOGI("Current peer process can not kill, "
360 "peerBinderPid=%{public}d, uid=%{public}d", peerBinderPid, uid);
361 return false;
362 }
363
364 int32_t ret = kill(peerBinderPid, SIGKILL);
365 if (ret == -1) {
366 XCOLLIE_LOGI("Kill PeerBinder process failed");
367 } else {
368 XCOLLIE_LOGI("Kill PeerBinder process success, name=%{public}s, pid=%{public}d",
369 GetProcessNameFromProcCmdline(peerBinderPid).c_str(), peerBinderPid);
370 }
371 return (ret >= 0);
372 }
373
CreateWatchdogDir()374 bool CreateWatchdogDir()
375 {
376 constexpr mode_t defaultLogDirMode = 0770;
377 if (!OHOS::FileExists(WATCHDOG_DIR)) {
378 OHOS::ForceCreateDirectory(WATCHDOG_DIR);
379 OHOS::ChangeModeDirectory(WATCHDOG_DIR, defaultLogDirMode);
380 }
381 if (OHOS::StorageDaemon::AclSetAccess(WATCHDOG_DIR, "g:1201:rwx") != 0) {
382 XCOLLIE_LOGI("Failed to AclSetAccess");
383 return false;
384 }
385 return true;
386 }
387
WriteStackToFd(int32_t pid,std::string & path,std::string & stack,const std::string & eventName,bool & isOverLimit)388 bool WriteStackToFd(int32_t pid, std::string& path, std::string& stack, const std::string& eventName,
389 bool& isOverLimit)
390 {
391 if (!CreateWatchdogDir()) {
392 return false;
393 }
394 std::string time = GetFormatDate();
395 std::string realPath;
396 if (!OHOS::PathToRealPath(WATCHDOG_DIR, realPath)) {
397 XCOLLIE_LOGE("Path to realPath failed.");
398 return false;
399 }
400 path = realPath + "/" + eventName + "_" + time.c_str() + "_" +
401 std::to_string(pid).c_str() + ".txt";
402 uint64_t stackSize = stack.size();
403 uint64_t fileSize = OHOS::GetFolderSize(realPath) + stackSize;
404 if (fileSize > MAX_FILE_SIZE) {
405 isOverLimit = true;
406 XCOLLIE_LOGE("CurrentDir is over limit: %{public}d. Will not write to stack file."
407 "MainThread fileSize: %{public}" PRIu64 " MAX_FILE_SIZE: %{public}" PRIu64 ".",
408 isOverLimit, fileSize, MAX_FILE_SIZE);
409 return true;
410 }
411 constexpr mode_t defaultLogFileMode = 0644;
412 auto fd = open(path.c_str(), O_CREAT | O_WRONLY | O_TRUNC, defaultLogFileMode);
413 if (fd < 0) {
414 XCOLLIE_LOGE("Failed to create path");
415 return false;
416 } else {
417 XCOLLIE_LOGE("path=%{public}s", path.c_str());
418 }
419 OHOS::SaveStringToFd(fd, stack);
420 close(fd);
421
422 return true;
423 }
424
GetFormatDate()425 std::string GetFormatDate()
426 {
427 time_t t = time(nullptr);
428 char tmp[TIME_INDEX_MAX] = {0};
429 strftime(tmp, sizeof(tmp), "%Y%m%d%H%M%S", localtime(&t));
430 std::string date(tmp);
431 return date;
432 }
433
FormatTime(const std::string & format)434 std::string FormatTime(const std::string &format)
435 {
436 auto now = std::chrono::system_clock::now();
437 auto millisecs = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch());
438 auto timestamp = millisecs.count();
439 std::time_t tt = static_cast<std::time_t>(timestamp / SEC_TO_MILLISEC);
440 std::tm t = *std::localtime(&tt);
441 char buffer[MAX_TIME_BUFF] = {0};
442 std::strftime(buffer, sizeof(buffer), format.c_str(), &t);
443 return std::string(buffer);
444 }
445
GetTimeStamp()446 int64_t GetTimeStamp()
447 {
448 std::chrono::nanoseconds ms = std::chrono::duration_cast< std::chrono::nanoseconds >(
449 std::chrono::system_clock::now().time_since_epoch());
450 return ms.count();
451 }
452
FunctionOpen(void * funcHandler,const char * funcName)453 void* FunctionOpen(void* funcHandler, const char* funcName)
454 {
455 dlerror();
456 char* err = nullptr;
457 void* func = dlsym(funcHandler, funcName);
458 err = dlerror();
459 if (err != nullptr) {
460 XCOLLIE_LOGE("dlopen %{public}s failed. %{public}s\n", funcName, err);
461 return nullptr;
462 }
463 return func;
464 }
465
GetUidByPid(const int32_t pid)466 int32_t GetUidByPid(const int32_t pid)
467 {
468 std::string uidFlag = "Uid:";
469 std::string cmdLinePath = "/proc/" + std::to_string(pid) + "/status";
470 std::string realPath = "";
471 if (!OHOS::PathToRealPath(cmdLinePath, realPath)) {
472 XCOLLIE_LOGE("Path to realPath failed.");
473 return -1;
474 }
475 std::ifstream file(realPath);
476 if (!file.is_open()) {
477 XCOLLIE_LOGE("open realPath failed.");
478 return -1;
479 }
480 int32_t uid = -1;
481 std::string line;
482 while (std::getline(file, line)) {
483 if (line.compare(0, uidFlag.size(), uidFlag) == 0) {
484 std::istringstream iss(line);
485 std::string temp;
486 if (std::getline(iss, temp, ':') && std::getline(iss, line)) {
487 std::istringstream(line) >> uid;
488 XCOLLIE_LOGI("get uid is %{public}d.", uid);
489 break;
490 }
491 }
492 }
493 file.close();
494 return uid;
495 }
496
GetAppStartTime(int32_t pid,int64_t tid)497 int64_t GetAppStartTime(int32_t pid, int64_t tid)
498 {
499 static int32_t startTime = -1;
500 static int32_t lastTid = -1;
501 if (startTime > 0 && lastTid == tid) {
502 return startTime;
503 }
504 char filePath[START_PATH_LEN] = {0};
505 if (snprintf_s(filePath, START_PATH_LEN, START_PATH_LEN - 1, "/proc/%d/task/%d/stat", pid, tid) < 0) {
506 XCOLLIE_LOGE("failed to build path, tid=%{public}" PRId64, tid);
507 }
508 std::string realPath = "";
509 if (!OHOS::PathToRealPath(filePath, realPath)) {
510 XCOLLIE_LOGE("Path to realPath failed.");
511 return startTime;
512 }
513 std::string content = "";
514 OHOS::LoadStringFromFile(realPath, content);
515 if (!content.empty()) {
516 std::vector<std::string> strings;
517 SplitStr(content, " ", strings);
518 if (strings.size() <= START_TIME_INDEX) {
519 XCOLLIE_LOGE("get startTime failed.");
520 return startTime;
521 }
522 content = strings[START_TIME_INDEX];
523 if (std::all_of(std::begin(content), std::end(content), [] (const char &c) {
524 return isdigit(c);
525 })) {
526 startTime = std::stoi(content);
527 lastTid = tid;
528 }
529 }
530 return startTime;
531 }
532 } // end of HiviewDFX
533 } // end of OHOS