1 /*
2  * Copyright (C) 2020 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "AnrTracker.h"
18 
19 namespace android::inputdispatcher {
20 
21 template <typename T>
max(const T & a,const T & b)22 static T max(const T& a, const T& b) {
23     return a < b ? b : a;
24 }
25 
insert(nsecs_t timeoutTime,sp<IBinder> token)26 void AnrTracker::insert(nsecs_t timeoutTime, sp<IBinder> token) {
27     mAnrTimeouts.insert(std::make_pair(timeoutTime, std::move(token)));
28 }
29 
30 /**
31  * Erase a single entry only. If there are multiple duplicate entries
32  * (same time, same connection), then only remove one of them.
33  */
erase(nsecs_t timeoutTime,const sp<IBinder> & token)34 void AnrTracker::erase(nsecs_t timeoutTime, const sp<IBinder>& token) {
35     auto pair = std::make_pair(timeoutTime, token);
36     auto it = mAnrTimeouts.find(pair);
37     if (it != mAnrTimeouts.end()) {
38         mAnrTimeouts.erase(it);
39     }
40 }
41 
eraseToken(const sp<IBinder> & token)42 void AnrTracker::eraseToken(const sp<IBinder>& token) {
43     for (auto it = mAnrTimeouts.begin(); it != mAnrTimeouts.end();) {
44         if (it->second == token) {
45             it = mAnrTimeouts.erase(it);
46         } else {
47             ++it;
48         }
49     }
50 }
51 
empty() const52 bool AnrTracker::empty() const {
53     return mAnrTimeouts.empty();
54 }
55 
56 // If empty() is false, return the time at which the next connection should cause an ANR
57 // If empty() is true, return LONG_LONG_MAX
firstTimeout() const58 nsecs_t AnrTracker::firstTimeout() const {
59     if (mAnrTimeouts.empty()) {
60         return std::numeric_limits<nsecs_t>::max();
61     }
62     return mAnrTimeouts.begin()->first;
63 }
64 
firstToken() const65 const sp<IBinder>& AnrTracker::firstToken() const {
66     return mAnrTimeouts.begin()->second;
67 }
68 
clear()69 void AnrTracker::clear() {
70     mAnrTimeouts.clear();
71 }
72 
73 } // namespace android::inputdispatcher
74