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 "command/rs_command_verify_helper.h"
17 
18 namespace OHOS {
19 namespace Rosen {
20 
21 constexpr int SURFACENODE_CREAET_LIMIT = 500;
22 
GetInstance()23 RsCommandVerifyHelper &RsCommandVerifyHelper::GetInstance()
24 {
25     static RsCommandVerifyHelper instance;
26     return instance;
27 }
28 
RegisterNonSystemPid(pid_t pid)29 void RsCommandVerifyHelper::RegisterNonSystemPid(pid_t pid)
30 {
31     std::unique_lock<std::mutex> lock(commandMutex_);
32     if (nonSystemSurfaceNodeCreateCnt_.count(pid) == 0) {
33         nonSystemSurfaceNodeCreateCnt_[pid] = 0;
34     }
35 }
36 
AddSurfaceNodeCreateCnt(pid_t pid)37 void RsCommandVerifyHelper::AddSurfaceNodeCreateCnt(pid_t pid)
38 {
39     std::unique_lock<std::mutex> lock(commandMutex_);
40     if (nonSystemSurfaceNodeCreateCnt_.find(pid) != nonSystemSurfaceNodeCreateCnt_.end()) {
41         if (nonSystemSurfaceNodeCreateCnt_[pid] < SURFACENODE_CREAET_LIMIT) {
42             nonSystemSurfaceNodeCreateCnt_[pid]++;
43         }
44     }
45 }
46 
SubSurfaceNodeCreateCnt(pid_t pid)47 void RsCommandVerifyHelper::SubSurfaceNodeCreateCnt(pid_t pid)
48 {
49     std::unique_lock<std::mutex> lock(commandMutex_);
50     if (nonSystemSurfaceNodeCreateCnt_.find(pid) != nonSystemSurfaceNodeCreateCnt_.end()) {
51         if (nonSystemSurfaceNodeCreateCnt_[pid] > 0) {
52             nonSystemSurfaceNodeCreateCnt_[pid]--;
53         }
54     }
55 }
56 
RemoveCntWithPid(pid_t pid)57 void RsCommandVerifyHelper::RemoveCntWithPid(pid_t pid)
58 {
59     std::unique_lock<std::mutex> lock(commandMutex_);
60     nonSystemSurfaceNodeCreateCnt_.erase(pid);
61 }
62 
IsSurfaceNodeCreateCommandVaild(pid_t pid)63 bool RsCommandVerifyHelper::IsSurfaceNodeCreateCommandVaild(pid_t pid)
64 {
65     std::unique_lock<std::mutex> lock(commandMutex_);
66     if ((nonSystemSurfaceNodeCreateCnt_.find(pid) != nonSystemSurfaceNodeCreateCnt_.end())) {
67         if (nonSystemSurfaceNodeCreateCnt_[pid] >= SURFACENODE_CREAET_LIMIT) {
68             return false;
69         }
70     }
71     return true;
72 }
73 } // namespace Rosen
74 } // namespace OHOS
75