1 /*
2 * Copyright 2024 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 "FakeInputTracingBackend.h"
18
19 #include <android-base/logging.h>
20 #include <utils/Errors.h>
21
22 namespace android::inputdispatcher {
23
24 namespace {
25
26 // Use a larger timeout while waiting for events to be traced, compared to the timeout used while
27 // waiting to receive events through the input channel. Events are traced from a separate thread,
28 // which does not have the same high thread priority as the InputDispatcher's thread, so the tracer
29 // is expected to lag behind the Dispatcher at times.
30 constexpr auto TRACE_TIMEOUT = std::chrono::seconds(5);
31
error(const std::ostringstream & ss)32 base::ResultError<> error(const std::ostringstream& ss) {
33 return base::ResultError(ss.str(), BAD_VALUE);
34 }
35
getId(const trace::TracedEvent & v)36 inline auto getId(const trace::TracedEvent& v) {
37 return std::visit([](const auto& event) { return event.id; }, v);
38 }
39
toInputEvent(const trace::TracedMotionEvent & e,const trace::WindowDispatchArgs & dispatchArgs,const std::array<uint8_t,32> & hmac)40 MotionEvent toInputEvent(const trace::TracedMotionEvent& e,
41 const trace::WindowDispatchArgs& dispatchArgs,
42 const std::array<uint8_t, 32>& hmac) {
43 MotionEvent traced;
44 traced.initialize(e.id, e.deviceId, e.source, e.displayId, hmac, e.action, e.actionButton,
45 dispatchArgs.resolvedFlags, e.edgeFlags, e.metaState, e.buttonState,
46 e.classification, dispatchArgs.transform, e.xPrecision, e.yPrecision,
47 e.xCursorPosition, e.yCursorPosition, dispatchArgs.rawTransform, e.downTime,
48 e.eventTime, e.pointerProperties.size(), e.pointerProperties.data(),
49 e.pointerCoords.data());
50 return traced;
51 }
52
toInputEvent(const trace::TracedKeyEvent & e,const trace::WindowDispatchArgs & dispatchArgs,const std::array<uint8_t,32> & hmac)53 KeyEvent toInputEvent(const trace::TracedKeyEvent& e, const trace::WindowDispatchArgs& dispatchArgs,
54 const std::array<uint8_t, 32>& hmac) {
55 KeyEvent traced;
56 traced.initialize(e.id, e.deviceId, e.source, e.displayId, hmac, e.action,
57 dispatchArgs.resolvedFlags, e.keyCode, e.scanCode, e.metaState,
58 dispatchArgs.resolvedKeyRepeatCount, e.downTime, e.eventTime);
59 return traced;
60 }
61
62 } // namespace
63
64 // --- VerifyingTrace ---
65
expectKeyDispatchTraced(const KeyEvent & event,int32_t windowId)66 void VerifyingTrace::expectKeyDispatchTraced(const KeyEvent& event, int32_t windowId) {
67 std::scoped_lock lock(mLock);
68 mExpectedEvents.emplace_back(event, windowId);
69 }
70
expectMotionDispatchTraced(const MotionEvent & event,int32_t windowId)71 void VerifyingTrace::expectMotionDispatchTraced(const MotionEvent& event, int32_t windowId) {
72 std::scoped_lock lock(mLock);
73 mExpectedEvents.emplace_back(event, windowId);
74 }
75
verifyExpectedEventsTraced()76 void VerifyingTrace::verifyExpectedEventsTraced() {
77 std::unique_lock lock(mLock);
78 base::ScopedLockAssertion assumeLocked(mLock);
79
80 // Poll for all expected events to be traced, and keep track of the latest poll result.
81 base::Result<void> result;
82 mEventTracedCondition.wait_for(lock, TRACE_TIMEOUT, [&]() REQUIRES(mLock) {
83 for (const auto& [expectedEvent, windowId] : mExpectedEvents) {
84 std::visit([&](const auto& event)
85 REQUIRES(mLock) { result = verifyEventTraced(event, windowId); },
86 expectedEvent);
87 if (!result.ok()) {
88 return false;
89 }
90 }
91 return true;
92 });
93
94 EXPECT_TRUE(result.ok())
95 << "Timed out waiting for all expected events to be traced successfully: "
96 << result.error().message();
97 }
98
reset()99 void VerifyingTrace::reset() {
100 std::scoped_lock lock(mLock);
101 mTracedEvents.clear();
102 mTracedWindowDispatches.clear();
103 mExpectedEvents.clear();
104 }
105
106 template <typename Event>
verifyEventTraced(const Event & expectedEvent,int32_t expectedWindowId) const107 base::Result<void> VerifyingTrace::verifyEventTraced(const Event& expectedEvent,
108 int32_t expectedWindowId) const {
109 std::ostringstream msg;
110
111 auto tracedEventsIt = mTracedEvents.find(expectedEvent.getId());
112 if (tracedEventsIt == mTracedEvents.end()) {
113 msg << "Expected event with ID 0x" << std::hex << expectedEvent.getId()
114 << " to be traced, but it was not.\n"
115 << "Expected event: " << expectedEvent;
116 return error(msg);
117 }
118
119 auto tracedDispatchesIt =
120 std::find_if(mTracedWindowDispatches.begin(), mTracedWindowDispatches.end(),
121 [&](const trace::WindowDispatchArgs& args) {
122 return args.windowId == expectedWindowId &&
123 getId(args.eventEntry) == expectedEvent.getId();
124 });
125 if (tracedDispatchesIt == mTracedWindowDispatches.end()) {
126 msg << "Expected dispatch of event with ID 0x" << std::hex << expectedEvent.getId()
127 << " to window with ID 0x" << expectedWindowId << " to be traced, but it was not.\n"
128 << "Expected event: " << expectedEvent;
129 return error(msg);
130 }
131
132 // Verify that the traced event matches the expected event exactly.
133 return std::visit(
134 [&](const auto& traced) -> base::Result<void> {
135 Event tracedEvent;
136 using T = std::decay_t<decltype(traced)>;
137 if constexpr (std::is_same_v<Event, MotionEvent> &&
138 std::is_same_v<T, trace::TracedMotionEvent>) {
139 tracedEvent =
140 toInputEvent(traced, *tracedDispatchesIt, expectedEvent.getHmac());
141 } else if constexpr (std::is_same_v<Event, KeyEvent> &&
142 std::is_same_v<T, trace::TracedKeyEvent>) {
143 tracedEvent =
144 toInputEvent(traced, *tracedDispatchesIt, expectedEvent.getHmac());
145 } else {
146 msg << "Received the wrong event type!\n"
147 << "Expected event: " << expectedEvent;
148 return error(msg);
149 }
150
151 const auto result = testing::internal::CmpHelperEQ("expectedEvent", "tracedEvent",
152 expectedEvent, tracedEvent);
153 if (!result) {
154 msg << result.failure_message();
155 return error(msg);
156 }
157 return {};
158 },
159 tracedEventsIt->second);
160 }
161
162 // --- FakeInputTracingBackend ---
163
traceKeyEvent(const trace::TracedKeyEvent & event,const trace::TracedEventMetadata &)164 void FakeInputTracingBackend::traceKeyEvent(const trace::TracedKeyEvent& event,
165 const trace::TracedEventMetadata&) {
166 {
167 std::scoped_lock lock(mTrace->mLock);
168 mTrace->mTracedEvents.emplace(event.id, event);
169 }
170 mTrace->mEventTracedCondition.notify_all();
171 }
172
traceMotionEvent(const trace::TracedMotionEvent & event,const trace::TracedEventMetadata &)173 void FakeInputTracingBackend::traceMotionEvent(const trace::TracedMotionEvent& event,
174 const trace::TracedEventMetadata&) {
175 {
176 std::scoped_lock lock(mTrace->mLock);
177 mTrace->mTracedEvents.emplace(event.id, event);
178 }
179 mTrace->mEventTracedCondition.notify_all();
180 }
181
traceWindowDispatch(const trace::WindowDispatchArgs & args,const trace::TracedEventMetadata &)182 void FakeInputTracingBackend::traceWindowDispatch(const trace::WindowDispatchArgs& args,
183 const trace::TracedEventMetadata&) {
184 {
185 std::scoped_lock lock(mTrace->mLock);
186 mTrace->mTracedWindowDispatches.push_back(args);
187 }
188 mTrace->mEventTracedCondition.notify_all();
189 }
190
191 } // namespace android::inputdispatcher
192