1 /*
2  * Copyright (C) 2019 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 "EventHub.h"
18 
19 #include "UinputDevice.h"
20 
21 #include <gtest/gtest.h>
22 #include <inttypes.h>
23 #include <linux/uinput.h>
24 #include <log/log.h>
25 #include <chrono>
26 
27 #define TAG "EventHub_test"
28 
29 using android::createUinputDevice;
30 using android::EventHub;
31 using android::EventHubInterface;
32 using android::InputDeviceIdentifier;
33 using android::RawEvent;
34 using android::sp;
35 using android::UinputHomeKey;
36 using std::chrono_literals::operator""ms;
37 using std::chrono_literals::operator""s;
38 
39 static constexpr bool DEBUG = false;
40 
dumpEvents(const std::vector<RawEvent> & events)41 static void dumpEvents(const std::vector<RawEvent>& events) {
42     for (const RawEvent& event : events) {
43         if (event.type >= EventHubInterface::FIRST_SYNTHETIC_EVENT) {
44             switch (event.type) {
45                 case EventHubInterface::DEVICE_ADDED:
46                     ALOGI("Device added: %i", event.deviceId);
47                     break;
48                 case EventHubInterface::DEVICE_REMOVED:
49                     ALOGI("Device removed: %i", event.deviceId);
50                     break;
51                 case EventHubInterface::FINISHED_DEVICE_SCAN:
52                     ALOGI("Finished device scan.");
53                     break;
54             }
55         } else {
56             ALOGI("Device %" PRId32 " : time = %" PRId64 ", type %i, code %i, value %i",
57                   event.deviceId, event.when, event.type, event.code, event.value);
58         }
59     }
60 }
61 
62 // --- EventHubTest ---
63 class EventHubTest : public testing::Test {
64 protected:
65     std::unique_ptr<EventHubInterface> mEventHub;
66     // We are only going to emulate a single input device currently.
67     std::unique_ptr<UinputHomeKey> mKeyboard;
68     int32_t mDeviceId;
69 
SetUp()70     virtual void SetUp() override {
71 #if !defined(__ANDROID__)
72         GTEST_SKIP() << "It's only possible to interact with uinput on device";
73 #endif
74         mEventHub = std::make_unique<EventHub>();
75         consumeInitialDeviceAddedEvents();
76         mKeyboard = createUinputDevice<UinputHomeKey>();
77         ASSERT_NO_FATAL_FAILURE(mDeviceId = waitForDeviceCreation());
78     }
TearDown()79     virtual void TearDown() override {
80 #if !defined(__ANDROID__)
81         return;
82 #endif
83         mKeyboard.reset();
84         waitForDeviceClose(mDeviceId);
85         assertNoMoreEvents();
86     }
87 
88     /**
89      * Return the device id of the created device.
90      */
91     int32_t waitForDeviceCreation();
92     void waitForDeviceClose(int32_t deviceId);
93     void consumeInitialDeviceAddedEvents();
94     void assertNoMoreEvents();
95     /**
96      * Read events from the EventHub.
97      *
98      * If expectedEvents is set, wait for a significant period of time to try and ensure that
99      * the expected number of events has been read. The number of returned events
100      * may be smaller (if timeout has been reached) or larger than expectedEvents.
101      *
102      * If expectedEvents is not set, return all of the immediately available events.
103      */
104     std::vector<RawEvent> getEvents(std::optional<size_t> expectedEvents = std::nullopt);
105 };
106 
getEvents(std::optional<size_t> expectedEvents)107 std::vector<RawEvent> EventHubTest::getEvents(std::optional<size_t> expectedEvents) {
108     std::vector<RawEvent> events;
109 
110     while (true) {
111         std::chrono::milliseconds timeout = 0s;
112         if (expectedEvents) {
113             timeout = 2s;
114         }
115 
116         std::vector<RawEvent> newEvents = mEventHub->getEvents(timeout.count());
117         if (newEvents.empty()) {
118             break;
119         }
120         events.insert(events.end(), newEvents.begin(), newEvents.end());
121         if (expectedEvents && events.size() >= *expectedEvents) {
122             break;
123         }
124     }
125     if (DEBUG) {
126         dumpEvents(events);
127     }
128     return events;
129 }
130 
131 /**
132  * Since the test runs on a real platform, there will be existing devices
133  * in addition to the test devices being added. Therefore, when EventHub is first created,
134  * it will return a lot of "device added" type of events.
135  */
consumeInitialDeviceAddedEvents()136 void EventHubTest::consumeInitialDeviceAddedEvents() {
137     std::vector<RawEvent> events = getEvents();
138     std::set<int32_t /*deviceId*/> existingDevices;
139     // All of the events should be DEVICE_ADDED type, except the last one.
140     for (size_t i = 0; i < events.size() - 1; i++) {
141         const RawEvent& event = events[i];
142         EXPECT_EQ(EventHubInterface::DEVICE_ADDED, event.type);
143         existingDevices.insert(event.deviceId);
144     }
145     // None of the existing system devices should be changing while this test is run.
146     // Check that the returned device ids are unique for all of the existing devices.
147     EXPECT_EQ(existingDevices.size(), events.size() - 1);
148     // The last event should be "finished device scan"
149     EXPECT_EQ(EventHubInterface::FINISHED_DEVICE_SCAN, events[events.size() - 1].type);
150 }
151 
waitForDeviceCreation()152 int32_t EventHubTest::waitForDeviceCreation() {
153     // Wait a little longer than usual, to ensure input device has time to be created
154     std::vector<RawEvent> events = getEvents(2);
155     if (events.size() != 2) {
156         ADD_FAILURE() << "Instead of 2 events, received " << events.size();
157         return 0; // this value is unused
158     }
159     const RawEvent& deviceAddedEvent = events[0];
160     EXPECT_EQ(static_cast<int32_t>(EventHubInterface::DEVICE_ADDED), deviceAddedEvent.type);
161     InputDeviceIdentifier identifier = mEventHub->getDeviceIdentifier(deviceAddedEvent.deviceId);
162     const int32_t deviceId = deviceAddedEvent.deviceId;
163     EXPECT_EQ(identifier.name, mKeyboard->getName());
164     const RawEvent& finishedDeviceScanEvent = events[1];
165     EXPECT_EQ(static_cast<int32_t>(EventHubInterface::FINISHED_DEVICE_SCAN),
166               finishedDeviceScanEvent.type);
167     return deviceId;
168 }
169 
waitForDeviceClose(int32_t deviceId)170 void EventHubTest::waitForDeviceClose(int32_t deviceId) {
171     std::vector<RawEvent> events = getEvents(2);
172     ASSERT_EQ(2U, events.size());
173     const RawEvent& deviceRemovedEvent = events[0];
174     EXPECT_EQ(static_cast<int32_t>(EventHubInterface::DEVICE_REMOVED), deviceRemovedEvent.type);
175     EXPECT_EQ(deviceId, deviceRemovedEvent.deviceId);
176     const RawEvent& finishedDeviceScanEvent = events[1];
177     EXPECT_EQ(static_cast<int32_t>(EventHubInterface::FINISHED_DEVICE_SCAN),
178               finishedDeviceScanEvent.type);
179 }
180 
assertNoMoreEvents()181 void EventHubTest::assertNoMoreEvents() {
182     std::vector<RawEvent> events = getEvents();
183     ASSERT_TRUE(events.empty());
184 }
185 
186 /**
187  * Ensure that two identical devices get assigned unique descriptors from EventHub.
188  */
TEST_F(EventHubTest,DevicesWithMatchingUniqueIdsAreUnique)189 TEST_F(EventHubTest, DevicesWithMatchingUniqueIdsAreUnique) {
190     std::unique_ptr<UinputHomeKey> keyboard2 = createUinputDevice<UinputHomeKey>();
191     int32_t deviceId2;
192     ASSERT_NO_FATAL_FAILURE(deviceId2 = waitForDeviceCreation());
193 
194     ASSERT_NE(mEventHub->getDeviceIdentifier(mDeviceId).descriptor,
195               mEventHub->getDeviceIdentifier(deviceId2).descriptor);
196     keyboard2.reset();
197     waitForDeviceClose(deviceId2);
198 }
199 
200 /**
201  * Ensure that input_events are generated with monotonic clock.
202  * That means input_event should receive a timestamp that is in the future of the time
203  * before the event was sent.
204  * Input system uses CLOCK_MONOTONIC everywhere in the code base.
205  */
TEST_F(EventHubTest,InputEvent_TimestampIsMonotonic)206 TEST_F(EventHubTest, InputEvent_TimestampIsMonotonic) {
207     nsecs_t lastEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
208     ASSERT_NO_FATAL_FAILURE(mKeyboard->pressAndReleaseHomeKey());
209 
210     std::vector<RawEvent> events = getEvents(4);
211     ASSERT_EQ(4U, events.size()) << "Expected to receive 2 keys and 2 syncs, total of 4 events";
212     for (const RawEvent& event : events) {
213         // Cannot use strict comparison because the events may happen too quickly
214         ASSERT_LE(lastEventTime, event.when) << "Event must have occurred after the key was sent";
215         ASSERT_LT(std::chrono::nanoseconds(event.when - lastEventTime), 100ms)
216                 << "Event times are too far apart";
217         lastEventTime = event.when; // Ensure all returned events are monotonic
218     }
219 }
220 
221 // --- BitArrayTest ---
222 class BitArrayTest : public testing::Test {
223 protected:
224     static constexpr size_t SINGLE_ELE_BITS = 32UL;
225     static constexpr size_t MULTI_ELE_BITS = 256UL;
226 
SetUp()227     virtual void SetUp() override {
228         mBitmaskSingle.loadFromBuffer(mBufferSingle);
229         mBitmaskMulti.loadFromBuffer(mBufferMulti);
230     }
231 
232     android::BitArray<SINGLE_ELE_BITS> mBitmaskSingle;
233     android::BitArray<MULTI_ELE_BITS> mBitmaskMulti;
234 
235 private:
236     const typename android::BitArray<SINGLE_ELE_BITS>::Buffer mBufferSingle = {
237             0x800F0F0FUL // bit 0 - 31
238     };
239     const typename android::BitArray<MULTI_ELE_BITS>::Buffer mBufferMulti = {
240             0xFFFFFFFFUL, // bit 0 - 31
241             0x01000001UL, // bit 32 - 63
242             0x00000000UL, // bit 64 - 95
243             0x80000000UL, // bit 96 - 127
244             0x00000000UL, // bit 128 - 159
245             0x00000000UL, // bit 160 - 191
246             0x80000008UL, // bit 192 - 223
247             0x00000000UL, // bit 224 - 255
248     };
249 };
250 
TEST_F(BitArrayTest,SetBit)251 TEST_F(BitArrayTest, SetBit) {
252     ASSERT_TRUE(mBitmaskSingle.test(0));
253     ASSERT_TRUE(mBitmaskSingle.test(31));
254     ASSERT_FALSE(mBitmaskSingle.test(7));
255 
256     ASSERT_TRUE(mBitmaskMulti.test(32));
257     ASSERT_TRUE(mBitmaskMulti.test(56));
258     ASSERT_FALSE(mBitmaskMulti.test(192));
259     ASSERT_TRUE(mBitmaskMulti.test(223));
260     ASSERT_FALSE(mBitmaskMulti.test(255));
261 }
262 
TEST_F(BitArrayTest,AnyBit)263 TEST_F(BitArrayTest, AnyBit) {
264     ASSERT_TRUE(mBitmaskSingle.any(31, 32));
265     ASSERT_FALSE(mBitmaskSingle.any(12, 16));
266 
267     ASSERT_TRUE(mBitmaskMulti.any(31, 32));
268     ASSERT_FALSE(mBitmaskMulti.any(33, 33));
269     ASSERT_TRUE(mBitmaskMulti.any(32, 55));
270     ASSERT_TRUE(mBitmaskMulti.any(33, 57));
271     ASSERT_FALSE(mBitmaskMulti.any(33, 55));
272     ASSERT_FALSE(mBitmaskMulti.any(130, 190));
273 
274     ASSERT_FALSE(mBitmaskMulti.any(128, 195));
275     ASSERT_TRUE(mBitmaskMulti.any(128, 196));
276     ASSERT_TRUE(mBitmaskMulti.any(128, 224));
277     ASSERT_FALSE(mBitmaskMulti.any(255, 256));
278 }
279 
TEST_F(BitArrayTest,SetBit_InvalidBitIndex)280 TEST_F(BitArrayTest, SetBit_InvalidBitIndex) {
281     ASSERT_FALSE(mBitmaskSingle.test(32));
282     ASSERT_FALSE(mBitmaskMulti.test(256));
283 }
284 
TEST_F(BitArrayTest,AnyBit_InvalidBitIndex)285 TEST_F(BitArrayTest, AnyBit_InvalidBitIndex) {
286     ASSERT_FALSE(mBitmaskSingle.any(32, 32));
287     ASSERT_FALSE(mBitmaskSingle.any(33, 34));
288 
289     ASSERT_FALSE(mBitmaskMulti.any(256, 256));
290     ASSERT_FALSE(mBitmaskMulti.any(257, 258));
291     ASSERT_FALSE(mBitmaskMulti.any(0, 0));
292 }
293