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/time.h"
27 #include "securec.h"
28 #include "include/sp_utils.h"
29 #include "include/sp_log.h"
30
31
32 namespace OHOS {
33 namespace SmartPerf {
34 const unsigned int INT_MAX_LEN = 10;
35 const unsigned int CHAR_NUM_DIFF = 48;
36 const unsigned int UI_DECIMALISM = 10;
37 const unsigned int UI_INDEX_2 = 2;
FileAccess(const std::string & fileName)38 bool SPUtils::FileAccess(const std::string &fileName)
39 {
40 return (access(fileName.c_str(), F_OK) == 0);
41 }
HasNumber(const std::string & str)42 bool SPUtils::HasNumber(const std::string &str)
43 {
44 return std::any_of(str.begin(), str.end(), [](char c) { return std::isdigit(c); });
45 }
Cmp(const std::string & a,const std::string & b)46 bool SPUtils::Cmp(const std::string &a, const std::string &b)
47 {
48 if (HasNumber(a) && HasNumber(b)) {
49 std::string str1 = a.substr(0, a.find_first_of("0123456789"));
50 std::string str2 = b.substr(0, b.find_first_of("0123456789"));
51 if (str1 != str2) {
52 return str1 < str2;
53 }
54 int num1 = std::stoi(a.substr(str1.length()));
55 int num2 = std::stoi(b.substr(str2.length()));
56 return num1 < num2;
57 }
58 return false;
59 }
60
LoadFile(const std::string & filePath,std::string & content)61 bool SPUtils::LoadFile(const std::string &filePath, std::string &content)
62 {
63 char realPath[PATH_MAX] = {0x00};
64 if (realpath(filePath.c_str(), realPath) == nullptr) {
65 std::cout << "" << std::endl;
66 }
67 std::ifstream file(realPath);
68 if (!file.is_open()) {
69 return false;
70 }
71
72 file.seekg(0, std::ios::end);
73 file.tellg();
74
75 content.clear();
76 file.seekg(0, std::ios::beg);
77 copy(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>(), std::back_inserter(content));
78 // remove '' \n\r
79 ReplaceString(content);
80 return true;
81 }
82
LoadCmd(const std::string & cmd,std::string & result)83 bool SPUtils::LoadCmd(const std::string &cmd, std::string &result)
84 {
85 std::string cmdExc = cmd;
86 FILE *fd = popen(cmdExc.c_str(), "r");
87 if (fd == nullptr) {
88 return false;
89 }
90 char buf[1024] = {'\0'};
91 int ret = fread(buf, sizeof(buf), 1, fd);
92 if (ret >= 0) {
93 result = buf;
94 }
95 if (pclose(fd) == -1) {
96 std::cout << "" << std::endl;
97 }
98 // remove '' \n\r
99 ReplaceString(result);
100 return ret >= 0 ? true : false;
101 }
102
IncludePathDelimiter(const std::string & path)103 std::string SPUtils::IncludePathDelimiter(const std::string &path)
104 {
105 if (!path.empty() && path.back() != '/') {
106 return path + "/";
107 } else {
108 return path;
109 }
110 }
111
ForDirFiles(const std::string & path,std::vector<std::string> & files)112 void SPUtils::ForDirFiles(const std::string &path, std::vector<std::string> &files)
113 {
114 std::string pathStringWithDelimiter;
115 DIR *dir = opendir(path.c_str());
116 if (dir == nullptr) {
117 return;
118 }
119
120 while (true) {
121 struct dirent *ptr = readdir(dir);
122 if (ptr == nullptr) {
123 break;
124 }
125
126 // current dir OR parent dir
127 if ((strcmp(ptr->d_name, ".") == 0) || (strcmp(ptr->d_name, "..") == 0)) {
128 continue;
129 } else if (ptr->d_type == DT_DIR) {
130 pathStringWithDelimiter = IncludePathDelimiter(path) + std::string(ptr->d_name);
131 ForDirFiles(pathStringWithDelimiter, files);
132 } else {
133 files.push_back(IncludePathDelimiter(path) + std::string(ptr->d_name));
134 }
135 }
136 closedir(dir);
137 }
138
IsSubString(const std::string & str,const std::string & sub)139 bool SPUtils::IsSubString(const std::string &str, const std::string &sub)
140 {
141 if (sub.empty() || str.empty()) {
142 return false;
143 }
144
145 return str.find(sub) != std::string::npos;
146 }
147
StrSplit(const std::string & content,const std::string & sp,std::vector<std::string> & out)148 void SPUtils::StrSplit(const std::string &content, const std::string &sp, std::vector<std::string> &out)
149 {
150 size_t index = 0;
151 while (index != std::string::npos) {
152 size_t tEnd = content.find_first_of(sp, index);
153 std::string tmp = content.substr(index, tEnd - index);
154 if (tmp != "" && tmp != " ") {
155 out.push_back(tmp);
156 }
157 if (tEnd == std::string::npos) {
158 break;
159 }
160 index = tEnd + 1;
161 }
162 }
163
ExtractNumber(const std::string & str)164 std::string SPUtils::ExtractNumber(const std::string &str)
165 {
166 int cntInt = 0;
167 const int shift = 10;
168 for (int i = 0; str[i] != '\0'; ++i) {
169 if (str[i] >= '0' && str[i] <= '9') {
170 cntInt *= shift;
171 cntInt += str[i] - '0';
172 }
173 }
174 return std::to_string(cntInt);
175 }
176
ReplaceString(std::string & res)177 void SPUtils::ReplaceString(std::string &res)
178 {
179 std::string flagOne = "\r";
180 std::string flagTwo = "\n";
181 std::string::size_type ret = res.find(flagOne);
182 while (ret != res.npos) {
183 res.replace(ret, 1, "");
184 ret = res.find(flagOne);
185 }
186 ret = res.find(flagTwo);
187 while (ret != res.npos) {
188 res.replace(ret, 1, "");
189 ret = res.find(flagTwo);
190 }
191 }
192
GetCurTime()193 long long SPUtils::GetCurTime()
194 {
195 struct timeval tv;
196 gettimeofday(&tv, nullptr);
197 long long timestamp = tv.tv_sec * 1000 + tv.tv_usec / 1000;
198 return timestamp;
199 }
200
GetTopPkgName()201 std::string SPUtils::GetTopPkgName()
202 {
203 std::string cmd = "hidumper -s AbilityManagerService -a '-a' | grep 'bundle name' | head -n 1";
204 std::string curTopPkgStr = "";
205 LoadCmd(cmd, curTopPkgStr);
206 uint64_t left = curTopPkgStr.find_first_of("[");
207 uint64_t right = curTopPkgStr.find_first_of("]");
208 std::string topPkg = curTopPkgStr.substr(left + 1, static_cast<int64_t>(right) - static_cast<int64_t>(left) - 1);
209 return topPkg;
210 }
211
GetRadar()212 std::string SPUtils::GetRadar()
213 {
214 std::string cmd = "hisysevent -r -o PERFORMANCE -n APP_START";
215 std::string curRadar = "";
216 LoadCmd(cmd, curRadar);
217 return curRadar;
218 }
GetScreen()219 std::string SPUtils::GetScreen()
220 {
221 std::string cmd = "hidumper -s 10 -a screen";
222 std::string screenStr = "";
223 LoadCmd(cmd, screenStr);
224 uint64_t left = screenStr.find("activeMode");
225 uint64_t right = screenStr.find("capability");
226 std::string screen = screenStr.substr(left, right - left);
227 return screen;
228 }
GetRadarFrame()229 std::string SPUtils::GetRadarFrame()
230 {
231 std::string cmd = "hisysevent -r -o PERFORMANCE -n INTERACTION_JANK";
232 std::string curRadar = "";
233 LoadCmd(cmd, curRadar);
234 return curRadar;
235 }
GetRadarResponse()236 std::string SPUtils::GetRadarResponse()
237 {
238 std::string cmd = "hisysevent -r -n INTERACTION_RESPONSE_LATENCY";
239 std::string curRadar = "";
240 LoadCmd(cmd, curRadar);
241 return curRadar;
242 }
GetRadarComplete()243 std::string SPUtils::GetRadarComplete()
244 {
245 std::string cmd = "hisysevent -r -n INTERACTION_COMPLETED_LATENCY";
246 std::string curRadar = "";
247 LoadCmd(cmd, curRadar);
248 return curRadar;
249 }
GetSplitOne(std::string cmd)250 static std::string GetSplitOne(std::string cmd)
251 {
252 std::string result;
253 SPUtils::LoadCmd(cmd, result);
254 return result;
255 }
256
GetDeviceInfo()257 std::map<std::string, std::string> SPUtils::GetDeviceInfo()
258 {
259 std::map<std::string, std::string> resultMap;
260 std::string sn = GetSplitOne("param get ohos.boot.sn");
261 std::string deviceTypeName = GetSplitOne("param get ohos.boot.hardware");
262 std::string brand = GetSplitOne("param get const.product.brand");
263 std::string version = GetSplitOne("param get const.product.software.version");
264 resultMap["sn"] = sn;
265 resultMap["deviceTypeName"] = deviceTypeName;
266 resultMap["brand"] = brand;
267 resultMap["board"] = "hw";
268 resultMap["version"] = version;
269 return resultMap;
270 }
GetCpuInfo()271 std::map<std::string, std::string> SPUtils::GetCpuInfo()
272 {
273 std::vector<std::string> policyFiles;
274 std::map<std::string, std::string> resultMap;
275 std::string basePath = "/sys/devices/system/cpu/cpufreq/";
276 std::cout << "policyFiles size:" << policyFiles.size() << std::endl;
277 DIR *dir = opendir(basePath.c_str());
278 if (dir == nullptr) {
279 return resultMap;
280 }
281 while (true) {
282 struct dirent *ptr = readdir(dir);
283 if (ptr == nullptr) {
284 break;
285 }
286 if ((strcmp(ptr->d_name, ".") == 0) || (strcmp(ptr->d_name, "..") == 0)) {
287 continue;
288 }
289 policyFiles.push_back(IncludePathDelimiter(basePath) + std::string(ptr->d_name));
290 }
291 for (size_t i = 0; i < policyFiles.size(); i++) {
292 std::string cpus;
293 LoadFile(policyFiles[i] + "/affected_cpus", cpus);
294 std::string max;
295 LoadFile(policyFiles[i] + "/cpuinfo_max_freq", max);
296 std::string min;
297 LoadFile(policyFiles[i] + "/cpuinfo_min_freq", min);
298 std::string nameBase = "cpu-c" + std::to_string(i + 1) + "-";
299 resultMap[nameBase + "cluster"] = cpus;
300 resultMap[nameBase + "max"] = max;
301 resultMap[nameBase + "min"] = min;
302 }
303 return resultMap;
304 }
GetGpuInfo()305 std::map<std::string, std::string> SPUtils::GetGpuInfo()
306 {
307 const std::vector<std::string> gpuCurFreqPaths = {
308 "/sys/class/devfreq/fde60000.gpu/",
309 "/sys/class/devfreq/gpufreq/",
310 };
311 std::map<std::string, std::string> resultMap;
312 for (auto path : gpuCurFreqPaths) {
313 if (FileAccess(path)) {
314 std::string max;
315 SPUtils::LoadFile(path + "/max_freq", max);
316 std::string min;
317 SPUtils::LoadFile(path + "/min_freq", min);
318 resultMap["gpu_max_freq"] = max;
319 resultMap["gpu_min_freq"] = min;
320 }
321 }
322 return resultMap;
323 }
324
RemoveSpace(std::string & str)325 void SPUtils::RemoveSpace(std::string &str)
326 {
327 int len = 0;
328
329 for (size_t i = 0; i < str.length(); i++) {
330 if (str[i] != ' ') {
331 break;
332 }
333
334 ++len;
335 }
336
337 if (len > 0) {
338 str = str.substr(len);
339 }
340
341 len = 0;
342 for (size_t i = str.length(); i > 0; --i) {
343 if (str[i - 1] != ' ') {
344 break;
345 }
346
347 ++len;
348 }
349
350 if (len > 0) {
351 for (int i = 0; i < len; i++) {
352 str.pop_back();
353 }
354 }
355 }
356
357
IntegerVerification(std::string str,std::string errorInfo)358 bool SPUtils::IntegerVerification(std::string str, std::string errorInfo)
359 {
360 unsigned int dest = 0;
361 bool isValid = false;
362
363 if (str.empty()) {
364 errorInfo = "option requires an argument";
365 LOGE("sour(%s) error(%s)", str.c_str(), errorInfo.c_str());
366 return false;
367 }
368 if (str.length() > INT_MAX_LEN) {
369 errorInfo = "invalid option parameters";
370 LOGE("sour(%s) error(%s)", str.c_str(), errorInfo.c_str());
371 return false;
372 }
373
374 for (size_t i = 0; i < str.length(); i++) {
375 if (str[i] < '0' || str[i] > '9') {
376 errorInfo = "invalid option parameters";
377 LOGE("sour(%s) error(%s)", str.c_str(), errorInfo.c_str());
378 return false;
379 }
380
381 if (!isValid && (str[i] == '0')) {
382 continue;
383 }
384
385 isValid = true;
386 dest *= UI_DECIMALISM;
387 dest += (str[i] - CHAR_NUM_DIFF);
388 }
389
390 if (dest == 0 || dest > INT_MAX) {
391 errorInfo = "option parameter out of range";
392 LOGE("sour(%s) dest(%u) error(%s)", str.c_str(), dest, errorInfo.c_str());
393 return false;
394 }
395
396 return true;
397 }
398
VeriyParameter(std::set<std::string> & keys,std::string param,std::string & errorInfo)399 bool SPUtils::VeriyParameter(std::set<std::string> &keys, std::string param, std::string &errorInfo)
400 {
401 std::string keyParam;
402 std::string valueParm;
403 std::vector<std::string> out;
404 std::vector<std::string> subOut;
405 std::map<std::string, std::string> mapInfo;
406
407 if (param.empty()) {
408 errorInfo = "The parameter cannot be empty";
409 return false;
410 }
411
412 SPUtils::StrSplit(param, "-", out);
413
414 for (auto it = out.begin(); it != out.end(); ++it) { // Parsing keys and values
415 subOut.clear();
416 SPUtils::StrSplit(*it, " ", subOut);
417 if (mapInfo.end() != mapInfo.find(subOut[0])) {
418 errorInfo = "duplicate parameters -- '" + subOut[0] + "'";
419 return false;
420 }
421
422 if (subOut.size() >= UI_INDEX_2) {
423 keyParam = subOut[0];
424 valueParm = subOut[1];
425 SPUtils::RemoveSpace(keyParam);
426 SPUtils::RemoveSpace(valueParm);
427 mapInfo[keyParam] = valueParm;
428 } else if (subOut.size() >= 1) {
429 keyParam = subOut[0];
430 SPUtils::RemoveSpace(keyParam);
431 mapInfo[keyParam] = "";
432 }
433 }
434
435 if (!VeriyKey(keys, mapInfo, errorInfo)) {
436 LOGE("%s", errorInfo.c_str());
437 return false;
438 }
439
440 if (!VerifyValueStr(mapInfo, errorInfo)) {
441 LOGE("%s", errorInfo.c_str());
442 return false;
443 }
444
445 if (!IntegerValueVerification(keys, mapInfo, errorInfo)) {
446 LOGE("%s", errorInfo.c_str());
447 return false;
448 }
449 return true;
450 }
451
VeriyKey(std::set<std::string> & keys,std::map<std::string,std::string> & mapInfo,std::string & errorInfo)452 bool SPUtils::VeriyKey(std::set<std::string> &keys, std::map<std::string, std::string> &mapInfo,
453 std::string &errorInfo)
454 {
455 for (auto it = mapInfo.begin(); it != mapInfo.end(); ++it) {
456 if (keys.end() == keys.find(it->first)) {
457 errorInfo = "invalid parameter -- '" + it->first + "'";
458 return false;
459 }
460 }
461
462 return true;
463 }
464
VerifyValueStr(std::map<std::string,std::string> & mapInfo,std::string & errorInfo)465 bool SPUtils::VerifyValueStr(std::map<std::string, std::string> &mapInfo, std::string &errorInfo)
466 {
467 auto a = mapInfo.find("VIEW");
468 if (mapInfo.end() != a && a->second.empty()) { // Cannot be null
469 errorInfo += "option requires an argument -- '" + a->first + "'";
470 return false;
471 }
472 a = mapInfo.find("PKG");
473 if (mapInfo.end() != a && a->second.empty()) { // Cannot be null
474 errorInfo += "option requires an argument -- '" + a->first + "'";
475 return false;
476 }
477 a = mapInfo.find("OUT");
478 if (mapInfo.end() != a) {
479 if (a->second.empty()) {
480 errorInfo += "option requires an argument -- '" + a->first + "'";
481 return false;
482 }
483 // The total length of file path and name cannot exceed PATH_MAX
484 if (a->second.length() >= PATH_MAX) {
485 errorInfo +=
486 "invalid parameter, file path cannot exceed " + std::to_string(PATH_MAX) + " -- '" + a->first + "'";
487 return false;
488 }
489 size_t pos = a->second.rfind('/');
490 if (pos == a->second.length()) { // not file name
491 errorInfo += "invalid parameter,not file name -- '" + a->first + "'";
492 return false;
493 }
494 if (std::string::npos != pos &&
495 (!SPUtils::FileAccess(a->second.substr(0, pos)))) { // determine if the directory exists
496 errorInfo += "invalid parameter,file path not found -- '" + a->first + "'";
497 return false;
498 }
499 std::string outStr = a->second;
500 std::vector<std::string> outList;
501 SPUtils::StrSplit(outStr, "/", outList);
502 for (auto it = outList.begin(); outList.end() != it; ++it) {
503 if ((*it).length() >= NAME_MAX) {
504 errorInfo += "invalid parameter, file directory or name cannot exceed 255 -- '" + a->first + "'";
505 return false;
506 }
507 }
508 }
509 return true;
510 }
511
IntegerValueVerification(std::set<std::string> & keys,std::map<std::string,std::string> & mapInfo,std::string & errorInfo)512 bool SPUtils::IntegerValueVerification(std::set<std::string> &keys, std::map<std::string, std::string> &mapInfo,
513 std::string &errorInfo)
514 {
515 std::vector<std::string> integerCheck; // Number of integers to be detected
516
517 if (keys.end() != keys.find("N")) {
518 integerCheck.push_back("N");
519 }
520 if (keys.end() != keys.find("fl")) {
521 integerCheck.push_back("fl");
522 }
523 if (keys.end() != keys.find("ftl")) {
524 integerCheck.push_back("ftl");
525 }
526
527 for (auto it = integerCheck.begin(); it != integerCheck.end(); ++it) {
528 auto a = mapInfo.find(*it);
529 if (mapInfo.end() != a) {
530 if (a->second.empty()) {
531 errorInfo += "option requires an argument -- '" + a->first + "'";
532 return false;
533 }
534 if (!SPUtils::IntegerVerification(a->second, errorInfo)) {
535 errorInfo += "option parameter out of range -- '" + a->first + "'";
536 return false;
537 }
538 }
539 }
540
541 return true;
542 }
543 }
544 }
545