1 /*
2 * Copyright (C) 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 #include "cpu_collector.h"
16 #include "collect_result.h"
17 #include "include/common.h"
18 #include "include/sp_utils.h"
19 #include "include/sp_log.h"
20 #include "include/Threads.h"
21
22 using namespace OHOS::HiviewDFX;
23 using namespace OHOS::HiviewDFX::UCollectUtil;
24 using namespace OHOS::HiviewDFX::UCollect;
25 namespace OHOS {
26 namespace SmartPerf {
GetThreads(const std::string & pid,std::string & tid)27 std::string Threads::GetThreads(const std::string &pid, std::string &tid)
28 {
29 std::shared_ptr<CpuCollector> collector = CpuCollector::Create();
30 auto threadCollector = collector->CreateThreadCollector(SPUtilesTye::StringToSometype<int>(pid));
31 auto collectResult = threadCollector->CollectThreadStatInfos(false);
32 if (collectResult.retCode == UcError::SUCCESS) {
33 size_t cnt = collectResult.data.size();
34 for (size_t i = 0; i < cnt; i++) {
35 if (i < cnt - 1) {
36 tid.append(std::to_string(collectResult.data[i].tid)).append(" ");
37 } else {
38 tid.append(std::to_string(collectResult.data[i].tid));
39 }
40 }
41 return std::to_string(cnt);
42 } else {
43 #ifndef FUZZ_TEST
44 processId.erase(std::remove(processId.begin(), processId.end(), pid), processId.end());
45 LOGD("Collect thread info fail (%d)", collectResult.retCode);
46 #endif
47 return "";
48 }
49 }
50
ItemData()51 std::map<std::string, std::string> Threads::ItemData()
52 {
53 std::map<std::string, std::string> result;
54 std::string& threadsNum = result["threadsNum"];
55 std::string& tids = result["tids"];
56 size_t idNum = processId.size();
57 for (size_t i = 0; i < idNum; i++) {
58 std::string tid = "";
59 std::string num = GetThreads(processId[i], tid);
60 threadsNum.append(processId[i]).append(":").append(num);
61 tids.append(processId[i]).append(":").append(tid);
62 if (idNum > 1) {
63 threadsNum.append("|");
64 tids.append("|");
65 }
66 }
67 return result;
68 }
69
SetPackageName(const std::string & pName)70 void Threads::SetPackageName(const std::string &pName)
71 {
72 packageName = pName;
73 }
74
SetProcessId(const std::string & pid)75 void Threads::SetProcessId(const std::string &pid)
76 {
77 processId.clear();
78 SPUtils::StrSplit(pid, " ", processId);
79 }
80
SetProcessIdForFuzzTest(const std::vector<std::string> & pid)81 void Threads::SetProcessIdForFuzzTest(const std::vector<std::string> &pid)
82 {
83 processId = pid;
84 }
85 }
86 }