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 #ifndef _UI_INPUT_INPUTDISPATCHER_ANRTRACKER_H
18 #define _UI_INPUT_INPUTDISPATCHER_ANRTRACKER_H
19 
20 #include <binder/IBinder.h>
21 #include <utils/Timers.h>
22 #include <set>
23 
24 namespace android::inputdispatcher {
25 
26 /**
27  * Keeps track of the times when each connection is going to ANR.
28  * Provides the ability to quickly find the connection that is going to cause ANR next.
29  */
30 class AnrTracker {
31 public:
32     void insert(nsecs_t timeoutTime, sp<IBinder> token);
33     void erase(nsecs_t timeoutTime, const sp<IBinder>& token);
34     void eraseToken(const sp<IBinder>& token);
35     void clear();
36 
37     bool empty() const;
38     // If empty() is false, return the time at which the next connection should cause an ANR
39     // If empty() is true, return LONG_LONG_MAX
40     nsecs_t firstTimeout() const;
41     // Return the token of the next connection that should cause an ANR.
42     // Do not call this unless empty() is false, you will encounter undefined behaviour.
43     const sp<IBinder>& firstToken() const;
44 
45 private:
46     // Optimization: use a multiset to keep track of the event timeouts. When an event is sent
47     // to the InputConsumer, we add an entry to this structure. We look at the smallest value to
48     // determine if any of the connections is unresponsive, and to determine when we should wake
49     // next for the future ANR check.
50     // Using a multiset helps quickly look up the next timeout due.
51     //
52     // We must use a multi-set, because it is plausible (although highly unlikely) to have entries
53     // from the same connection and same timestamp, but different sequence numbers.
54     // We are not tracking sequence numbers, and just allow duplicates to exist.
55     std::multiset<std::pair<nsecs_t /*timeoutTime*/, sp<IBinder> /*connectionToken*/>> mAnrTimeouts;
56 };
57 
58 } // namespace android::inputdispatcher
59 
60 #endif // _UI_INPUT_INPUTDISPATCHER_ANRTRACKER_H
61