1 /*
2  * Copyright (c) 2023 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 "process_cpu_data.h"
16 
17 #include <cstdlib>
18 
19 #include "securec.h"
20 
21 namespace OHOS {
22 namespace HiviewDFX {
ProcessCpuData(int magic,int pid,unsigned int count)23 ProcessCpuData::ProcessCpuData(int magic, int pid, unsigned int count): entry_(nullptr), current_(0)
24 {
25     Init(magic, count, pid);
26 }
27 
Init(int magic,unsigned int totalCount,int pid)28 void ProcessCpuData::Init(int magic, unsigned int totalCount, int pid)
29 {
30     unsigned int totalSize = sizeof(struct ucollection_process_cpu_entry)
31         + sizeof(struct ucollection_process_cpu_item) * totalCount;
32     entry_ = (struct ucollection_process_cpu_entry *)malloc(totalSize);
33     if (entry_ == NULL) {
34         return;
35     }
36     memset_s(entry_, totalSize, 0, totalSize);
37     entry_->magic = magic;
38     entry_->total_count = totalCount;
39     entry_->cur_count = 0;
40     entry_->filter.pid = pid;
41 }
42 
~ProcessCpuData()43 ProcessCpuData::~ProcessCpuData()
44 {
45     if (entry_ == NULL) {
46         return;
47     }
48     free(entry_);
49     entry_ = nullptr;
50 }
51 
GetNextProcess()52 struct ucollection_process_cpu_item* ProcessCpuData::GetNextProcess()
53 {
54     if (entry_ == NULL || current_ >= entry_->cur_count) {
55         return nullptr;
56     }
57 
58     struct ucollection_process_cpu_item *item = &entry_->datas[current_];
59     current_++;
60     return item;
61 }
62 } // HiviewDFX
63 } // OHOS