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
16 #include "memory_level_info.h"
17
18 #include "hilog_tag_wrapper.h"
19
20 namespace OHOS {
21 namespace AppExecFwk {
22 namespace {
23 constexpr int MAX_PARCEL_SIZE = 100000;
24 }
25
MemoryLevelInfo(const std::map<pid_t,MemoryLevel> & procLevelMap)26 MemoryLevelInfo::MemoryLevelInfo(const std::map<pid_t, MemoryLevel> &procLevelMap) : procLevelMap_(procLevelMap)
27 {
28 }
29
Marshalling(Parcel & parcel) const30 bool MemoryLevelInfo::Marshalling(Parcel &parcel) const
31 {
32 if (!parcel.WriteUint32(procLevelMap_.size())) {
33 return false;
34 }
35 for (auto it = procLevelMap_.begin(); it != procLevelMap_.end(); ++it) {
36 if (!parcel.WriteInt32(it->first)) {
37 return false;
38 }
39 if (!parcel.WriteInt32(it->second)) {
40 return false;
41 }
42 }
43 return true;
44 }
45
Unmarshalling(Parcel & parcel)46 MemoryLevelInfo *MemoryLevelInfo::Unmarshalling(Parcel &parcel)
47 {
48 MemoryLevelInfo *object = new (std::nothrow) MemoryLevelInfo();
49 if ((object != nullptr) && !object->ReadFromParcel(parcel)) {
50 delete object;
51 object = nullptr;
52 }
53
54 return object;
55 }
56
GetProcLevelMap() const57 const std::map<pid_t, MemoryLevel> &MemoryLevelInfo::GetProcLevelMap() const
58 {
59 return procLevelMap_;
60 }
61
62
ReadFromParcel(Parcel & parcel)63 bool MemoryLevelInfo::ReadFromParcel(Parcel &parcel)
64 {
65 uint32_t count = parcel.ReadUint32();
66 if (count < 0 || count > MAX_PARCEL_SIZE) {
67 count = 0;
68 return false;
69 }
70
71 for (uint32_t i = 0; i < count; ++i) {
72 pid_t pid = parcel.ReadInt32();
73 int32_t tempLevel = parcel.ReadInt32();
74 MemoryLevel level = MEMORY_LEVEL_MODERATE;
75 switch (tempLevel) {
76 case MEMORY_LEVEL_MODERATE:
77 case MEMORY_LEVEL_LOW:
78 case MEMORY_LEVEL_CRITICAL:
79 level = static_cast<MemoryLevel>(tempLevel);
80 break;
81 default:
82 TAG_LOGE(AAFwkTag::APPMGR, "temp memory level=%{public}d is not valid.", tempLevel);
83 continue;
84 }
85 procLevelMap_[pid] = level;
86 }
87 return true;
88 }
89
90 } // namespace AppExecFwk
91 } // namespace OHOS