• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2021 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 <iostream>
16 #include <fstream>
17 #include <sstream>
18 #include <algorithm>
19 #include <unistd.h>
20 #include <dirent.h>
21 #include <cstdio>
22 #include <cstdlib>
23 #include <climits>
24 #include <cctype>
25 #include <climits>
26 #include <sys/utsname.h>
27 #include "sys/time.h"
28 #include "securec.h"
29 #include "include/sp_utils.h"
30 #include "include/sp_log.h"
31 #include "include/common.h"
32 #include "cpu_collector.h"
33 #include "collect_result.h"
34 #include "include/FPS.h"
35 #include "include/GPU.h"
36 #include "include/Power.h"
37 #include "include/DDR.h"
38 #include "include/profiler_fps.h"
39 
40 using namespace OHOS::HiviewDFX;
41 using namespace OHOS::HiviewDFX::UCollectUtil;
42 using namespace OHOS::HiviewDFX::UCollect;
43 
44 namespace OHOS {
45 namespace SmartPerf {
46 const unsigned int INT_MAX_LEN = 10;
47 const unsigned int CHAR_NUM_DIFF = 48;
48 const unsigned int UI_DECIMALISM = 10;
49 const unsigned int UI_INDEX_2 = 2;
50 const int BUFFER_SIZE = 1024;
FileAccess(const std::string & fileName)51 bool SPUtils::FileAccess(const std::string &fileName)
52 {
53     return (access(fileName.c_str(), F_OK) == 0);
54 }
HasNumber(const std::string & str)55 bool SPUtils::HasNumber(const std::string &str)
56 {
57     return std::any_of(str.begin(), str.end(), [](char c) { return std::isdigit(c); });
58 }
Cmp(const std::string & a,const std::string & b)59 bool SPUtils::Cmp(const std::string &a, const std::string &b)
60 {
61     if (HasNumber(a) && HasNumber(b)) {
62         std::string stra = a.substr(0, a.find_first_of("0123456789"));
63         std::string strb = b.substr(0, b.find_first_of("0123456789"));
64         if (stra != strb) {
65             return stra < strb;
66         }
67         int numa = SPUtilesTye::StringToSometype<int>(a.substr(stra.length()));
68         int numb = SPUtilesTye::StringToSometype<int>(b.substr(strb.length()));
69         return numa < numb;
70     }
71     return false;
72 }
73 
LoadFile(const std::string & filePath,std::string & content)74 bool SPUtils::LoadFile(const std::string &filePath, std::string &content)
75 {
76     char realPath[PATH_MAX] = {0x00};
77     if ((realpath(filePath.c_str(), realPath) == nullptr)) {
78         std::cout << "" << std::endl;
79     }
80     std::ifstream file(realPath);
81     if (!file.is_open()) {
82         return false;
83     }
84 
85     file.seekg(0, std::ios::end);
86     file.tellg();
87 
88     content.clear();
89     file.seekg(0, std::ios::beg);
90     copy(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>(), std::back_inserter(content));
91     // remove '' \n\r
92     ReplaceString(content);
93     return true;
94 }
95 
LoadCmdWithLinkBreak(const std::string & cmd,bool isClearLinkBreak,std::string & result)96 bool SPUtils::LoadCmdWithLinkBreak(const std::string &cmd, bool isClearLinkBreak, std::string &result)
97 {
98     const std::string cmdExc = cmd;
99     FILE *fd = popen(cmdExc.c_str(), "r");
100     if (fd == nullptr) {
101         return false;
102     }
103     char buf[4096] = {'\0'};
104     size_t ret = fread(buf, sizeof(buf), 1, fd);
105     if (ret >= 0) {
106         result = buf;
107     }
108     if (pclose(fd) == -1) {
109         LOGE("Error: Failed to close file");
110         return false;
111     }
112 
113     if (isClearLinkBreak) {
114         // remove '' \n\r
115         ReplaceString(result);
116     }
117 
118     return ret >= 0 ? true : false;
119 }
120 
LoadCmd(const std::string & cmd,std::string & result)121 bool SPUtils::LoadCmd(const std::string &cmd, std::string &result)
122 {
123     return LoadCmdWithLinkBreak(cmd, true, result);
124 }
125 
IncludePathDelimiter(const std::string & path)126 std::string SPUtils::IncludePathDelimiter(const std::string &path)
127 {
128     if (!path.empty() && path.back() != '/') {
129         return path + "/";
130     } else {
131         return path;
132     }
133 }
134 
ForDirFiles(const std::string & path,std::vector<std::string> & files)135 void SPUtils::ForDirFiles(const std::string &path, std::vector<std::string> &files)
136 {
137     std::string pathStringWithDelimiter;
138     DIR *dir = opendir(path.c_str());
139     if (dir == nullptr) {
140         return;
141     }
142 
143     while (true) {
144         struct dirent *ptr = readdir(dir);
145         if (ptr == nullptr) {
146             break;
147         }
148 
149         // current dir OR parent dir
150         if ((strcmp(ptr->d_name, ".") == 0) || (strcmp(ptr->d_name, "..") == 0)) {
151             continue;
152         } else if (ptr->d_type == DT_DIR) {
153             pathStringWithDelimiter = IncludePathDelimiter(path) + std::string(ptr->d_name);
154             ForDirFiles(pathStringWithDelimiter, files);
155         } else {
156             files.push_back(IncludePathDelimiter(path) + std::string(ptr->d_name));
157         }
158     }
159     closedir(dir);
160 }
161 
IsSubString(const std::string & str,const std::string & sub)162 bool SPUtils::IsSubString(const std::string &str, const std::string &sub)
163 {
164     if (sub.empty() || str.empty()) {
165         return false;
166     }
167 
168     return str.find(sub) != std::string::npos;
169 }
170 
StrSplit(const std::string & content,const std::string & sp,std::vector<std::string> & out)171 void SPUtils::StrSplit(const std::string &content, const std::string &sp, std::vector<std::string> &out)
172 {
173     size_t index = 0;
174     while (index != std::string::npos) {
175         size_t tEnd = content.find_first_of(sp, index);
176         std::string tmp = content.substr(index, tEnd - index);
177         if (tmp != "" && tmp != " ") {
178             out.push_back(tmp);
179         }
180         if (tEnd == std::string::npos) {
181             break;
182         }
183         index = tEnd + 1;
184     }
185 }
186 
ExtractNumber(const std::string & str)187 std::string SPUtils::ExtractNumber(const std::string &str)
188 {
189     int cntInt = 0;
190     const int shift = 10;
191     for (int i = 0; str[i] != '\0'; ++i) {
192         if (str[i] >= '0' && str[i] <= '9') {
193             cntInt *= shift;
194             cntInt += str[i] - '0';
195         }
196     }
197     return std::to_string(cntInt);
198 }
199 
ReplaceString(std::string & res)200 void SPUtils::ReplaceString(std::string &res)
201 {
202     std::string flagOne = "\r";
203     std::string flagTwo = "\n";
204     std::string::size_type ret = res.find(flagOne);
205     while (ret != res.npos) {
206         res.replace(ret, 1, "");
207         ret = res.find(flagOne);
208     }
209     ret = res.find(flagTwo);
210     while (ret != res.npos) {
211         res.replace(ret, 1, "");
212         ret = res.find(flagTwo);
213     }
214 }
215 
GetCurTime()216 long long SPUtils::GetCurTime()
217 {
218     struct timeval tv;
219     gettimeofday(&tv, nullptr);
220     long long timestamp = tv.tv_sec * 1000 + tv.tv_usec / 1000;
221     return timestamp;
222 }
223 
GetTopPkgName()224 std::string SPUtils::GetTopPkgName()
225 {
226     std::string cmd = HIDUMPER_CMD_MAP.at(HidumperCmd::DUMPER_HEAD);
227     std::string curTopPkgStr = "";
228     LoadCmd(cmd, curTopPkgStr);
229     uint64_t left = curTopPkgStr.find_first_of("[");
230     uint64_t right = curTopPkgStr.find_first_of("]");
231     std::string topPkg = curTopPkgStr.substr(left + 1, static_cast<int64_t>(right) - static_cast<int64_t>(left) - 1);
232     return topPkg;
233 }
234 
GetRadar()235 std::string SPUtils::GetRadar()
236 {
237     std::string cmd = HISYSEVENT_CMD_MAP.at(HisyseventCmd::HISYS_APP_START);
238     std::string curRadar = "";
239     LoadCmd(cmd, curRadar);
240     return curRadar;
241 }
GetScreen()242 std::string SPUtils::GetScreen()
243 {
244     std::string cmd = HIDUMPER_CMD_MAP.at(HidumperCmd::DUMPER_SCREEN);
245     std::string screenStr = "";
246     LoadCmd(cmd, screenStr);
247     uint64_t left = screenStr.find("activeMode");
248     uint64_t right = screenStr.find("capability");
249     std::string screen = screenStr.substr(left, right - left);
250     return screen;
251 }
GetRadarFrame()252 std::string SPUtils::GetRadarFrame()
253 {
254     std::string cmd = HISYSEVENT_CMD_MAP.at(HisyseventCmd::HISYS_JANK);
255     std::string curRadar = "";
256     LoadCmd(cmd, curRadar);
257     return curRadar;
258 }
GetRadarResponse()259 std::string SPUtils::GetRadarResponse()
260 {
261     std::string cmd = HISYSEVENT_CMD_MAP.at(HisyseventCmd::HISYS_RESPONSE);
262     std::string curRadar = "";
263     LoadCmd(cmd, curRadar);
264     return curRadar;
265 }
GetRadarComplete()266 std::string SPUtils::GetRadarComplete()
267 {
268     std::string cmd = HISYSEVENT_CMD_MAP.at(HisyseventCmd::HISYS_COMPLETED);
269     std::string curRadar = "";
270     LoadCmd(cmd, curRadar);
271     return curRadar;
272 }
GetSplitOne(std::string cmd)273 static std::string GetSplitOne(std::string cmd)
274 {
275     std::string result;
276     SPUtils::LoadCmd(cmd, result);
277     return result;
278 }
279 
GetDeviceInfoMap()280 std::string SPUtils::GetDeviceInfoMap()
281 {
282     size_t len = 2;
283     bool isTcpMessage = false;
284     std::map<std::string, std::string> deviceInfoMap;
285     std::map<std::string, std::string> cpuInfo = GetCpuInfo(isTcpMessage);
286     std::map<std::string, std::string> gpuInfo = GetGpuInfo(isTcpMessage);
287     std::map<std::string, std::string> deviceInfo = GetDeviceInfo();
288     std::string screenInfos = GetScreen();
289     size_t pos = screenInfos.find(": ");
290     size_t pos1 = screenInfos.find(",");
291     std::string screenSize = screenInfos.substr(pos + len, pos1 - pos - len);
292     deviceInfoMap.insert(cpuInfo.begin(), cpuInfo.end());
293     deviceInfoMap.insert(gpuInfo.begin(), gpuInfo.end());
294     deviceInfoMap.insert(deviceInfo.begin(), deviceInfo.end());
295     deviceInfoMap["activeMode"] = screenSize;
296     if (deviceInfoMap.empty()) {
297         LOGE("Failed to obtain device information");
298     }
299     for (auto iter = deviceInfoMap.cbegin(); iter != deviceInfoMap.cend(); ++iter) {
300         printf("%s: %s\n", iter->first.c_str(), iter->second.c_str());
301     }
302     std::cout << "" << std::endl;
303     return std::string("command exec finished!");
304 }
305 
GetDeviceInfo()306 std::map<std::string, std::string> SPUtils::GetDeviceInfo()
307 {
308     std::map<std::string, std::string> resultMap;
309     std::string sn = GetSplitOne(DEVICE_CMD_MAP.at(DeviceCmd::SN));
310     std::string deviceTypeName = GetSplitOne(DEVICE_CMD_MAP.at(DeviceCmd::DEVICET_NAME));
311     std::string brand = GetSplitOne(DEVICE_CMD_MAP.at(DeviceCmd::BRAND));
312     std::string version = GetSplitOne(DEVICE_CMD_MAP.at(DeviceCmd::VERSION));
313     std::string abilist = GetSplitOne(DEVICE_CMD_MAP.at(DeviceCmd::ABILIST));
314     std::string name = GetSplitOne(DEVICE_CMD_MAP.at(DeviceCmd::NAME));
315     std::string model = GetSplitOne(DEVICE_CMD_MAP.at(DeviceCmd::MODEL));
316     std::string fullname = GetSplitOne(DEVICE_CMD_MAP.at(DeviceCmd::FULL_NAME));
317     resultMap["sn"] = sn;
318     resultMap["deviceTypeName"] = deviceTypeName;
319     resultMap["brand"] = brand;
320     resultMap["board"] = "hw";
321     resultMap["version"] = version;
322     resultMap["abilist"] = abilist;
323     resultMap["name"] = name;
324     resultMap["model"] = model;
325     resultMap["fullname"] = fullname;
326     resultMap["daemonPerfVersion"] = SMART_PERF_VERSION;
327     return resultMap;
328 }
GetCpuInfo(bool isTcpMessage)329 std::map<std::string, std::string> SPUtils::GetCpuInfo(bool isTcpMessage)
330 {
331     std::string clusterNames;
332     std::vector<std::string> policyFiles;
333     std::map<std::string, std::string> resultMap;
334     std::string basePath = "/sys/devices/system/cpu/cpufreq/";
335     DIR *dir = opendir(basePath.c_str());
336     if (dir == nullptr) {
337         return resultMap;
338     }
339     while (true) {
340         struct dirent *ptr = readdir(dir);
341         if (ptr == nullptr) {
342             break;
343         }
344         if ((strcmp(ptr->d_name, ".") == 0) || (strcmp(ptr->d_name, "..") == 0)) {
345             continue;
346         }
347         std::string clusterName = std::string(ptr->d_name);
348         if (!isTcpMessage) {
349             clusterNames += clusterName + " ";
350             resultMap["cpu_cluster_name"] = clusterNames;
351         }
352         policyFiles.push_back(IncludePathDelimiter(basePath) + clusterName);
353     }
354     closedir(dir);
355     for (size_t i = 0; i < policyFiles.size(); i++) {
356         std::string cpus;
357         LoadFile(policyFiles[i] + "/affected_cpus", cpus);
358         std::string max;
359         LoadFile(policyFiles[i] + "/cpuinfo_max_freq", max);
360         std::string min;
361         LoadFile(policyFiles[i] + "/cpuinfo_min_freq", min);
362         std::string nameBase;
363         if (!isTcpMessage) {
364             nameBase = "cpu_c" + std::to_string(i + 1) + "_";
365         } else {
366             nameBase = "cpu-c" + std::to_string(i + 1) + "-";
367         }
368         resultMap[nameBase + "cluster"] = cpus;
369         resultMap[nameBase + "max"] = max;
370         resultMap[nameBase + "min"] = min;
371     }
372     return resultMap;
373 }
GetGpuInfo(bool isTcpMessage)374 std::map<std::string, std::string> SPUtils::GetGpuInfo(bool isTcpMessage)
375 {
376     const std::vector<std::string> gpuCurFreqPaths = {
377         "/sys/class/devfreq/fde60000.gpu/",
378         "/sys/class/devfreq/gpufreq/",
379     };
380     std::map<std::string, std::string> resultMap;
381     for (auto path : gpuCurFreqPaths) {
382         if (FileAccess(path)) {
383             std::string max;
384             SPUtils::LoadFile(path + "/max_freq", max);
385             std::string min;
386             SPUtils::LoadFile(path + "/min_freq", min);
387             resultMap["gpu_max_freq"] = max;
388             resultMap["gpu_min_freq"] = min;
389         }
390     }
391     return resultMap;
392 }
393 
RemoveSpace(std::string & str)394 void SPUtils::RemoveSpace(std::string &str)
395 {
396     int len = 0;
397 
398     for (size_t i = 0; i < str.length(); i++) {
399         if (str[i] != ' ') {
400             break;
401         }
402 
403         ++len;
404     }
405 
406     if (len > 0) {
407         str = str.substr(len);
408     }
409 
410     len = 0;
411     for (size_t i = str.length(); i > 0; --i) {
412         if (str[i - 1] != ' ') {
413             break;
414         }
415 
416         ++len;
417     }
418 
419     if (len > 0) {
420         for (int i = 0; i < len; i++) {
421             str.pop_back();
422         }
423     }
424 }
425 
426 
IntegerVerification(std::string str,std::string errorInfo)427 bool SPUtils::IntegerVerification(std::string str, std::string errorInfo)
428 {
429     uint64_t dest = 0;
430     bool isValid = false;
431 
432     if (str.empty()) {
433         errorInfo = "option requires an argument";
434         LOGE("sour(%s) error(%s)", str.c_str(), errorInfo.c_str());
435         return false;
436     }
437     if (str.length() > INT_MAX_LEN) {
438         errorInfo = "invalid option parameters";
439         LOGE("sour(%s) error(%s)", str.c_str(), errorInfo.c_str());
440         return false;
441     }
442 
443     for (size_t i = 0; i < str.length(); i++) {
444         if (str[i] < '0' || str[i] > '9') {
445             errorInfo = "invalid option parameters";
446             LOGE("sour(%s) error(%s)", str.c_str(), errorInfo.c_str());
447             return false;
448         }
449 
450         if (!isValid && (str[i] == '0')) {
451             continue;
452         }
453 
454         isValid = true;
455         dest *= UI_DECIMALISM;
456         dest += (str[i] - CHAR_NUM_DIFF);
457     }
458 
459     if (dest == 0 || dest > INT_MAX) {
460         errorInfo = "option parameter out of range";
461         LOGE("sour(%s) dest(%u) error(%s)", str.c_str(), dest, errorInfo.c_str());
462         return false;
463     }
464 
465     return true;
466 }
467 
VeriyParameter(std::set<std::string> & keys,std::string param,std::string & errorInfo)468 bool SPUtils::VeriyParameter(std::set<std::string> &keys, std::string param, std::string &errorInfo)
469 {
470     std::string keyParam;
471     std::string valueParm;
472     std::vector<std::string> out;
473     std::vector<std::string> subOut;
474     std::map<std::string, std::string> mapInfo;
475 
476     if (param.empty()) {
477         errorInfo = "The parameter cannot be empty";
478         return false;
479     }
480 
481     SPUtils::StrSplit(param, "-", out);
482 
483     for (auto it = out.begin(); it != out.end(); ++it) { // Parsing keys and values
484         subOut.clear();
485         SPUtils::StrSplit(*it, " ", subOut);
486         if (mapInfo.end() != mapInfo.find(subOut[0])) {
487             errorInfo = "duplicate parameters -- '" + subOut[0] + "'";
488             return false;
489         }
490 
491         if (subOut.size() >= UI_INDEX_2) {
492             keyParam = subOut[0];
493             valueParm = subOut[1];
494             SPUtils::RemoveSpace(keyParam);
495             SPUtils::RemoveSpace(valueParm);
496             mapInfo[keyParam] = valueParm;
497         } else if (subOut.size() >= 1) {
498             keyParam = subOut[0];
499             SPUtils::RemoveSpace(keyParam);
500             mapInfo[keyParam] = "";
501         }
502     }
503 
504     if (!VeriyKey(keys, mapInfo, errorInfo)) {
505         LOGE("%s", errorInfo.c_str());
506         return false;
507     }
508 
509     if (!VerifyValueStr(mapInfo, errorInfo)) {
510         LOGE("%s", errorInfo.c_str());
511         return false;
512     }
513 
514     if (!IntegerValueVerification(keys, mapInfo, errorInfo)) {
515         LOGE("%s", errorInfo.c_str());
516         return false;
517     }
518     return true;
519 }
520 
VeriyKey(std::set<std::string> & keys,std::map<std::string,std::string> & mapInfo,std::string & errorInfo)521 bool SPUtils::VeriyKey(std::set<std::string> &keys, std::map<std::string, std::string> &mapInfo,
522     std::string &errorInfo)
523 {
524     for (auto it = mapInfo.begin(); it != mapInfo.end(); ++it) {
525         if (keys.end() == keys.find(it->first)) {
526             errorInfo = "invalid parameter -- '" + it->first + "'";
527             return false;
528         }
529     }
530 
531     return true;
532 }
533 
VerifyValueStr(std::map<std::string,std::string> & mapInfo,std::string & errorInfo)534 bool SPUtils::VerifyValueStr(std::map<std::string, std::string> &mapInfo, std::string &errorInfo)
535 {
536     auto a = mapInfo.find("VIEW");
537     if (mapInfo.end() != a && a->second.empty()) { // Cannot be null
538         errorInfo += "option requires an argument -- '" + a->first + "'";
539         return false;
540     }
541     a = mapInfo.find("PKG");
542     if (mapInfo.end() != a && a->second.empty()) { // Cannot be null
543         errorInfo += "option requires an argument -- '" + a->first + "'";
544         return false;
545     }
546     a = mapInfo.find("OUT");
547     if (mapInfo.end() != a) {
548         if (a->second.empty()) {
549             errorInfo += "option requires an argument -- '" + a->first + "'";
550             return false;
551         }
552         // The total length of file path and name cannot exceed PATH_MAX
553         if (a->second.length() >= PATH_MAX) {
554             errorInfo +=
555                 "invalid parameter, file path cannot exceed " + std::to_string(PATH_MAX) + " -- '" + a->first + "'";
556             return false;
557         }
558         size_t pos = a->second.rfind('/');
559         if (pos == a->second.length()) { // not file name
560             errorInfo += "invalid parameter,not file name -- '" + a->first + "'";
561             return false;
562         }
563         if (std::string::npos != pos &&
564             (!SPUtils::FileAccess(a->second.substr(0, pos)))) { // determine if the directory exists
565             errorInfo += "invalid parameter,file path not found -- '" + a->first + "'";
566             return false;
567         }
568         std::string outStr = a->second;
569         std::vector<std::string> outList;
570         SPUtils::StrSplit(outStr, "/", outList);
571         for (auto it = outList.begin(); outList.end() != it; ++it) {
572             if ((*it).length() >= NAME_MAX) {
573                 errorInfo += "invalid parameter, file directory or name cannot exceed 255 -- '" + a->first + "'";
574                 return false;
575             }
576         }
577     }
578     return true;
579 }
580 
IntegerValueVerification(std::set<std::string> & keys,std::map<std::string,std::string> & mapInfo,std::string & errorInfo)581 bool SPUtils::IntegerValueVerification(std::set<std::string> &keys, std::map<std::string, std::string> &mapInfo,
582     std::string &errorInfo)
583 {
584     std::vector<std::string> integerCheck; // Number of integers to be detected
585 
586     if (keys.end() != keys.find("N")) {
587         integerCheck.push_back("N");
588     }
589     if (keys.end() != keys.find("fl")) {
590         integerCheck.push_back("fl");
591     }
592     if (keys.end() != keys.find("ftl")) {
593         integerCheck.push_back("ftl");
594     }
595 
596     for (auto it = integerCheck.begin(); it != integerCheck.end(); ++it) {
597         auto a = mapInfo.find(*it);
598         if (mapInfo.end() != a) {
599             if (a->second.empty()) {
600                 errorInfo += "option requires an argument -- '" + a->first + "'";
601                 return false;
602             }
603             if (!SPUtils::IntegerVerification(a->second, errorInfo)) {
604                 errorInfo += "option parameter out of range -- '" + a->first + "'";
605                 return false;
606             }
607         }
608     }
609 
610     return true;
611 }
612 
IsHmKernel()613 bool SPUtils::IsHmKernel()
614 {
615     bool isHM = false;
616     utsname unameBuf;
617     if ((uname(&unameBuf)) == 0) {
618         std::string osRelease = unameBuf.release;
619         isHM = osRelease.find("HongMeng") != std::string::npos;
620     }
621     return isHM;
622 }
623 
GetCpuNum()624 std::string SPUtils::GetCpuNum()
625 {
626     std::string cpuCores = "cpuCores||";
627     std::shared_ptr<CpuCollector> collector = CpuCollector::Create();
628     CollectResult<std::vector<CpuFreq>> result = collector->CollectCpuFrequency();
629     std::vector<CpuFreq> &cpufreq = result.data;
630     size_t cpuNum = cpufreq.size();
631     cpuCores += std::to_string(cpuNum);
632     if (cpuNum == 0) {
633         std::cout << "CPU frequency collection failed." << std::endl;
634         LOGE("CPU frequency collection failed.");
635     }
636     return cpuCores;
637 }
GetCurrentTime(int num,int prevTime)638 void SPUtils::GetCurrentTime(int num, int prevTime)
639 {
640     unsigned long sleepNowTime = 10000;
641     for (int i = 0; i < num; i++) {
642         struct timespec time1 = { 0 };
643         clock_gettime(CLOCK_MONOTONIC, &time1);
644         int curTimeNow = static_cast<int>(time1.tv_sec - 1);
645         if (curTimeNow == prevTime) {
646             usleep(sleepNowTime);
647         } else {
648             break;
649         }
650     }
651 }
IsForeGround(const std::string & pkg)652 bool SPUtils::IsForeGround(const std::string &pkg)
653 {
654     bool isFoundAppName = false;
655     bool isForeground = false;
656     std::string result = "";
657     const std::string cmd = "hidumper -s AbilityManagerService -a -l";
658     if (cmd.empty()) {
659         LOGE("cmd is null");
660         return false;
661     }
662 
663     FILE *fd = popen(cmd.c_str(), "r");
664     if (fd == nullptr) {
665         return false;
666     }
667     size_t bytesRead;
668     std::array<char, BUFFER_SIZE> buf;
669     while ((bytesRead = fread(buf.data(), 1, buf.size(), fd)) > 0) {
670         result.append(buf.data(), bytesRead);
671     }
672     if (pclose(fd) == -1) {
673         LOGE("Error: Failed to close file");
674         return false;
675     }
676 
677     std::istringstream iss(result);
678     std::string line;
679     while (std::getline(iss, line)) {
680         if (!isFoundAppName && line.find("mission name #[#" + pkg) != std::string::npos) {
681             isFoundAppName = true;
682         }
683         if (isFoundAppName) {
684             if (line.find("state #FOREGROUND") != std::string::npos) {
685                 isForeground = true;
686                 break;
687             }
688         }
689     }
690     return isForeground;
691 }
692 
IsFindAbilist()693 bool SPUtils::IsFindAbilist()
694 {
695     std::string abilist = GetSplitOne(DEVICE_CMD_MAP.at(DeviceCmd::ABILIST));
696     std::string brand = GetSplitOne(DEVICE_CMD_MAP.at(DeviceCmd::BRAND));
697     if (abilist.find("arm") != std::string::npos && brand.find("HUA") != std::string::npos) {
698         return true;
699     } else if (abilist.find("arm") != std::string::npos && brand.find("HUA") == std::string::npos) {
700         return OHOS::SmartPerf::FPS::GetInstance().SetOtherDeviceFlag();
701     } else {
702         return false;
703     }
704 }
SetRkFlag()705 void SPUtils::SetRkFlag()
706 {
707     bool findAbilistResult = IsFindAbilist();
708     if (!findAbilistResult) {
709         OHOS::SmartPerf::FPS::GetInstance().SetRkFlag();
710         OHOS::SmartPerf::Power::GetInstance().SetRkFlag();
711         OHOS::SmartPerf::GPU::GetInstance().SetRkFlag();
712         OHOS::SmartPerf::ProfilerFPS::GetInstance().SetRkFlag();
713         OHOS::SmartPerf::DDR::GetInstance().SetRkFlag();
714     }
715 }
GetPathPermissions(const std::string & path)716 bool SPUtils::GetPathPermissions(const std::string &path)
717 {
718     const std::string dataCsv = "/data/local/tmp/data.csv";
719     const std::string indexInfoCsv = "/data/local/tmp/smartperf/1/t_index_info.csv";
720     int isDataCsv = strcmp(path.c_str(), dataCsv.c_str());
721     int isIndexInfoCsv = strcmp(path.c_str(), indexInfoCsv.c_str());
722     if (!path.empty()) {
723         std::string cmdResult;
724         std::string cmd;
725         if (isDataCsv == 0 || isIndexInfoCsv == 0) {
726             cmd = "ls -l " + path;
727             LoadCmd(cmd, cmdResult);
728             std::string result = cmdResult.substr(0, 10);
729             return result == "-rw-r--r--";
730         } else {
731             LOGE("the path is false");
732             return false;
733         }
734     } else {
735         LOGE("THE path is empty");
736         return false;
737     }
738 }
739 
GetIsGameApp(std::string pkg)740 bool SPUtils::GetIsGameApp(std::string pkg)
741 {
742     bool isGame = false;
743     const std::string cmd = "hidumper -s 66006 -a '-t " + pkg + "'";
744     LOGD("SPUtils::GetIsGameApp cmd (%s)", cmd.c_str());
745     FILE *fd = popen(cmd.c_str(), "r");
746     if (fd == nullptr) {
747         LOGD("ProfilerFPS::fd is empty");
748     }
749     char buf[1024] = {'\0'};
750     while ((fgets(buf, sizeof(buf), fd)) != nullptr) {
751         std::string line(buf);
752         if (line.find("---") != std::string::npos || line.length() <= 1) {
753             continue;
754         }
755         if (line.find("bundleName unknown") != std::string::npos) {
756             isGame = false;
757             break;
758         } else {
759             std::vector<std::string> params;
760             SPUtils::StrSplit(line, " ", params);
761             if (params[0] == "1" && params[1] == pkg) {
762                 isGame = true;
763                 LOGD("SPUtils::GetIsGameApp isGame", isGame);
764                 break;
765             }
766         }
767     }
768     if (pclose(fd) == -1) {
769         LOGE("SPUtils::IsGameApp Error Failed to close file");
770     }
771     return isGame;
772 }
773 }
774 }
775