1 //
2 // Copyright 2010 The Android Open Source Project
3 //
4 // Provides a shared memory transport for input events.
5 //
6 #define LOG_TAG "InputTransport"
7 #define ATRACE_TAG ATRACE_TAG_INPUT
8
9 #include <errno.h>
10 #include <fcntl.h>
11 #include <inttypes.h>
12 #include <math.h>
13 #include <poll.h>
14 #include <sys/socket.h>
15 #include <sys/types.h>
16 #include <unistd.h>
17
18 #include <android-base/logging.h>
19 #include <android-base/properties.h>
20 #include <android-base/stringprintf.h>
21 #include <binder/Parcel.h>
22 #include <cutils/properties.h>
23 #include <ftl/enum.h>
24 #include <log/log.h>
25 #include <utils/Trace.h>
26
27 #include <com_android_input_flags.h>
28 #include <input/InputTransport.h>
29 #include <input/PrintTools.h>
30 #include <input/TraceTools.h>
31
32 namespace input_flags = com::android::input::flags;
33
34 namespace android {
35
36 namespace {
37
38 /**
39 * Log debug messages about channel messages (send message, receive message).
40 * Enable this via "adb shell setprop log.tag.InputTransportMessages DEBUG"
41 * (requires restart)
42 */
43 const bool DEBUG_CHANNEL_MESSAGES =
44 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Messages", ANDROID_LOG_INFO);
45
46 /**
47 * Log debug messages whenever InputChannel objects are created/destroyed.
48 * Enable this via "adb shell setprop log.tag.InputTransportLifecycle DEBUG"
49 * (requires restart)
50 */
51 const bool DEBUG_CHANNEL_LIFECYCLE =
52 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Lifecycle", ANDROID_LOG_INFO);
53
54 const bool IS_DEBUGGABLE_BUILD =
55 #if defined(__ANDROID__)
56 android::base::GetBoolProperty("ro.debuggable", false);
57 #else
58 true;
59 #endif
60
61 /**
62 * Log debug messages relating to the producer end of the transport channel.
63 * Enable this via "adb shell setprop log.tag.InputTransportPublisher DEBUG".
64 * This requires a restart on non-debuggable (e.g. user) builds, but should take effect immediately
65 * on debuggable builds (e.g. userdebug).
66 */
debugTransportPublisher()67 bool debugTransportPublisher() {
68 if (!IS_DEBUGGABLE_BUILD) {
69 static const bool DEBUG_TRANSPORT_PUBLISHER =
70 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Publisher", ANDROID_LOG_INFO);
71 return DEBUG_TRANSPORT_PUBLISHER;
72 }
73 return __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Publisher", ANDROID_LOG_INFO);
74 }
75
dupChannelFd(int fd)76 android::base::unique_fd dupChannelFd(int fd) {
77 android::base::unique_fd newFd(::dup(fd));
78 if (!newFd.ok()) {
79 ALOGE("Could not duplicate fd %i : %s", fd, strerror(errno));
80 const bool hitFdLimit = errno == EMFILE || errno == ENFILE;
81 // If this process is out of file descriptors, then throwing that might end up exploding
82 // on the other side of a binder call, which isn't really helpful.
83 // Better to just crash here and hope that the FD leak is slow.
84 // Other failures could be client errors, so we still propagate those back to the caller.
85 LOG_ALWAYS_FATAL_IF(hitFdLimit, "Too many open files, could not duplicate input channel");
86 return {};
87 }
88 return newFd;
89 }
90
91 // Socket buffer size. The default is typically about 128KB, which is much larger than
92 // we really need. So we make it smaller. It just needs to be big enough to hold
93 // a few dozen large multi-finger motion events in the case where an application gets
94 // behind processing touches.
95 constexpr size_t SOCKET_BUFFER_SIZE = 32 * 1024;
96
97 /**
98 * Crash if the events that are getting sent to the InputPublisher are inconsistent.
99 * Enable this via "adb shell setprop log.tag.InputTransportVerifyEvents DEBUG"
100 */
verifyEvents()101 bool verifyEvents() {
102 return input_flags::enable_outbound_event_verification() ||
103 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "VerifyEvents", ANDROID_LOG_INFO);
104 }
105
106 } // namespace
107
108 using android::base::Result;
109 using android::base::StringPrintf;
110
111 // --- InputMessage ---
112
isValid(size_t actualSize) const113 bool InputMessage::isValid(size_t actualSize) const {
114 if (size() != actualSize) {
115 ALOGE("Received message of incorrect size %zu (expected %zu)", actualSize, size());
116 return false;
117 }
118
119 switch (header.type) {
120 case Type::KEY:
121 return true;
122 case Type::MOTION: {
123 const bool valid =
124 body.motion.pointerCount > 0 && body.motion.pointerCount <= MAX_POINTERS;
125 if (!valid) {
126 ALOGE("Received invalid MOTION: pointerCount = %" PRIu32, body.motion.pointerCount);
127 }
128 return valid;
129 }
130 case Type::FINISHED:
131 case Type::FOCUS:
132 case Type::CAPTURE:
133 case Type::DRAG:
134 case Type::TOUCH_MODE:
135 return true;
136 case Type::TIMELINE: {
137 const nsecs_t gpuCompletedTime =
138 body.timeline.graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME];
139 const nsecs_t presentTime =
140 body.timeline.graphicsTimeline[GraphicsTimeline::PRESENT_TIME];
141 const bool valid = presentTime > gpuCompletedTime;
142 if (!valid) {
143 ALOGE("Received invalid TIMELINE: gpuCompletedTime = %" PRId64
144 " presentTime = %" PRId64,
145 gpuCompletedTime, presentTime);
146 }
147 return valid;
148 }
149 }
150 ALOGE("Invalid message type: %s", ftl::enum_string(header.type).c_str());
151 return false;
152 }
153
size() const154 size_t InputMessage::size() const {
155 switch (header.type) {
156 case Type::KEY:
157 return sizeof(Header) + body.key.size();
158 case Type::MOTION:
159 return sizeof(Header) + body.motion.size();
160 case Type::FINISHED:
161 return sizeof(Header) + body.finished.size();
162 case Type::FOCUS:
163 return sizeof(Header) + body.focus.size();
164 case Type::CAPTURE:
165 return sizeof(Header) + body.capture.size();
166 case Type::DRAG:
167 return sizeof(Header) + body.drag.size();
168 case Type::TIMELINE:
169 return sizeof(Header) + body.timeline.size();
170 case Type::TOUCH_MODE:
171 return sizeof(Header) + body.touchMode.size();
172 }
173 return sizeof(Header);
174 }
175
176 /**
177 * There could be non-zero bytes in-between InputMessage fields. Force-initialize the entire
178 * memory to zero, then only copy the valid bytes on a per-field basis.
179 */
getSanitizedCopy(InputMessage * msg) const180 void InputMessage::getSanitizedCopy(InputMessage* msg) const {
181 memset(msg, 0, sizeof(*msg));
182
183 // Write the header
184 msg->header.type = header.type;
185 msg->header.seq = header.seq;
186
187 // Write the body
188 switch(header.type) {
189 case InputMessage::Type::KEY: {
190 // int32_t eventId
191 msg->body.key.eventId = body.key.eventId;
192 // nsecs_t eventTime
193 msg->body.key.eventTime = body.key.eventTime;
194 // int32_t deviceId
195 msg->body.key.deviceId = body.key.deviceId;
196 // int32_t source
197 msg->body.key.source = body.key.source;
198 // int32_t displayId
199 msg->body.key.displayId = body.key.displayId;
200 // std::array<uint8_t, 32> hmac
201 msg->body.key.hmac = body.key.hmac;
202 // int32_t action
203 msg->body.key.action = body.key.action;
204 // int32_t flags
205 msg->body.key.flags = body.key.flags;
206 // int32_t keyCode
207 msg->body.key.keyCode = body.key.keyCode;
208 // int32_t scanCode
209 msg->body.key.scanCode = body.key.scanCode;
210 // int32_t metaState
211 msg->body.key.metaState = body.key.metaState;
212 // int32_t repeatCount
213 msg->body.key.repeatCount = body.key.repeatCount;
214 // nsecs_t downTime
215 msg->body.key.downTime = body.key.downTime;
216 break;
217 }
218 case InputMessage::Type::MOTION: {
219 // int32_t eventId
220 msg->body.motion.eventId = body.motion.eventId;
221 // uint32_t pointerCount
222 msg->body.motion.pointerCount = body.motion.pointerCount;
223 // nsecs_t eventTime
224 msg->body.motion.eventTime = body.motion.eventTime;
225 // int32_t deviceId
226 msg->body.motion.deviceId = body.motion.deviceId;
227 // int32_t source
228 msg->body.motion.source = body.motion.source;
229 // int32_t displayId
230 msg->body.motion.displayId = body.motion.displayId;
231 // std::array<uint8_t, 32> hmac
232 msg->body.motion.hmac = body.motion.hmac;
233 // int32_t action
234 msg->body.motion.action = body.motion.action;
235 // int32_t actionButton
236 msg->body.motion.actionButton = body.motion.actionButton;
237 // int32_t flags
238 msg->body.motion.flags = body.motion.flags;
239 // int32_t metaState
240 msg->body.motion.metaState = body.motion.metaState;
241 // int32_t buttonState
242 msg->body.motion.buttonState = body.motion.buttonState;
243 // MotionClassification classification
244 msg->body.motion.classification = body.motion.classification;
245 // int32_t edgeFlags
246 msg->body.motion.edgeFlags = body.motion.edgeFlags;
247 // nsecs_t downTime
248 msg->body.motion.downTime = body.motion.downTime;
249
250 msg->body.motion.dsdx = body.motion.dsdx;
251 msg->body.motion.dtdx = body.motion.dtdx;
252 msg->body.motion.dtdy = body.motion.dtdy;
253 msg->body.motion.dsdy = body.motion.dsdy;
254 msg->body.motion.tx = body.motion.tx;
255 msg->body.motion.ty = body.motion.ty;
256
257 // float xPrecision
258 msg->body.motion.xPrecision = body.motion.xPrecision;
259 // float yPrecision
260 msg->body.motion.yPrecision = body.motion.yPrecision;
261 // float xCursorPosition
262 msg->body.motion.xCursorPosition = body.motion.xCursorPosition;
263 // float yCursorPosition
264 msg->body.motion.yCursorPosition = body.motion.yCursorPosition;
265
266 msg->body.motion.dsdxRaw = body.motion.dsdxRaw;
267 msg->body.motion.dtdxRaw = body.motion.dtdxRaw;
268 msg->body.motion.dtdyRaw = body.motion.dtdyRaw;
269 msg->body.motion.dsdyRaw = body.motion.dsdyRaw;
270 msg->body.motion.txRaw = body.motion.txRaw;
271 msg->body.motion.tyRaw = body.motion.tyRaw;
272
273 //struct Pointer pointers[MAX_POINTERS]
274 for (size_t i = 0; i < body.motion.pointerCount; i++) {
275 // PointerProperties properties
276 msg->body.motion.pointers[i].properties.id = body.motion.pointers[i].properties.id;
277 msg->body.motion.pointers[i].properties.toolType =
278 body.motion.pointers[i].properties.toolType,
279 // PointerCoords coords
280 msg->body.motion.pointers[i].coords.bits = body.motion.pointers[i].coords.bits;
281 const uint32_t count = BitSet64::count(body.motion.pointers[i].coords.bits);
282 memcpy(&msg->body.motion.pointers[i].coords.values[0],
283 &body.motion.pointers[i].coords.values[0],
284 count * (sizeof(body.motion.pointers[i].coords.values[0])));
285 msg->body.motion.pointers[i].coords.isResampled =
286 body.motion.pointers[i].coords.isResampled;
287 }
288 break;
289 }
290 case InputMessage::Type::FINISHED: {
291 msg->body.finished.handled = body.finished.handled;
292 msg->body.finished.consumeTime = body.finished.consumeTime;
293 break;
294 }
295 case InputMessage::Type::FOCUS: {
296 msg->body.focus.eventId = body.focus.eventId;
297 msg->body.focus.hasFocus = body.focus.hasFocus;
298 break;
299 }
300 case InputMessage::Type::CAPTURE: {
301 msg->body.capture.eventId = body.capture.eventId;
302 msg->body.capture.pointerCaptureEnabled = body.capture.pointerCaptureEnabled;
303 break;
304 }
305 case InputMessage::Type::DRAG: {
306 msg->body.drag.eventId = body.drag.eventId;
307 msg->body.drag.x = body.drag.x;
308 msg->body.drag.y = body.drag.y;
309 msg->body.drag.isExiting = body.drag.isExiting;
310 break;
311 }
312 case InputMessage::Type::TIMELINE: {
313 msg->body.timeline.eventId = body.timeline.eventId;
314 msg->body.timeline.graphicsTimeline = body.timeline.graphicsTimeline;
315 break;
316 }
317 case InputMessage::Type::TOUCH_MODE: {
318 msg->body.touchMode.eventId = body.touchMode.eventId;
319 msg->body.touchMode.isInTouchMode = body.touchMode.isInTouchMode;
320 }
321 }
322 }
323
324 // --- InputChannel ---
325
create(const std::string & name,android::base::unique_fd fd,sp<IBinder> token)326 std::unique_ptr<InputChannel> InputChannel::create(const std::string& name,
327 android::base::unique_fd fd, sp<IBinder> token) {
328 const int result = fcntl(fd, F_SETFL, O_NONBLOCK);
329 if (result != 0) {
330 LOG_ALWAYS_FATAL("channel '%s' ~ Could not make socket (%d) non-blocking: %s", name.c_str(),
331 fd.get(), strerror(errno));
332 return nullptr;
333 }
334 // using 'new' to access a non-public constructor
335 return std::unique_ptr<InputChannel>(new InputChannel(name, std::move(fd), token));
336 }
337
create(android::os::InputChannelCore && parceledChannel)338 std::unique_ptr<InputChannel> InputChannel::create(
339 android::os::InputChannelCore&& parceledChannel) {
340 return InputChannel::create(parceledChannel.name, parceledChannel.fd.release(),
341 parceledChannel.token);
342 }
343
InputChannel(const std::string name,android::base::unique_fd fd,sp<IBinder> token)344 InputChannel::InputChannel(const std::string name, android::base::unique_fd fd, sp<IBinder> token) {
345 this->name = std::move(name);
346 this->fd.reset(std::move(fd));
347 this->token = std::move(token);
348 ALOGD_IF(DEBUG_CHANNEL_LIFECYCLE, "Input channel constructed: name='%s', fd=%d",
349 getName().c_str(), getFd());
350 }
351
~InputChannel()352 InputChannel::~InputChannel() {
353 ALOGD_IF(DEBUG_CHANNEL_LIFECYCLE, "Input channel destroyed: name='%s', fd=%d",
354 getName().c_str(), getFd());
355 }
356
openInputChannelPair(const std::string & name,std::unique_ptr<InputChannel> & outServerChannel,std::unique_ptr<InputChannel> & outClientChannel)357 status_t InputChannel::openInputChannelPair(const std::string& name,
358 std::unique_ptr<InputChannel>& outServerChannel,
359 std::unique_ptr<InputChannel>& outClientChannel) {
360 int sockets[2];
361 if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets)) {
362 status_t result = -errno;
363 ALOGE("channel '%s' ~ Could not create socket pair. errno=%s(%d)", name.c_str(),
364 strerror(errno), errno);
365 outServerChannel.reset();
366 outClientChannel.reset();
367 return result;
368 }
369
370 int bufferSize = SOCKET_BUFFER_SIZE;
371 setsockopt(sockets[0], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
372 setsockopt(sockets[0], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
373 setsockopt(sockets[1], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
374 setsockopt(sockets[1], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
375
376 sp<IBinder> token = sp<BBinder>::make();
377
378 android::base::unique_fd serverFd(sockets[0]);
379 outServerChannel = InputChannel::create(name, std::move(serverFd), token);
380
381 android::base::unique_fd clientFd(sockets[1]);
382 outClientChannel = InputChannel::create(name, std::move(clientFd), token);
383 return OK;
384 }
385
sendMessage(const InputMessage * msg)386 status_t InputChannel::sendMessage(const InputMessage* msg) {
387 ATRACE_NAME_IF(ATRACE_ENABLED(),
388 StringPrintf("sendMessage(inputChannel=%s, seq=0x%" PRIx32 ", type=%s)",
389 name.c_str(), msg->header.seq,
390 ftl::enum_string(msg->header.type).c_str()));
391 const size_t msgLength = msg->size();
392 InputMessage cleanMsg;
393 msg->getSanitizedCopy(&cleanMsg);
394 ssize_t nWrite;
395 do {
396 nWrite = ::send(getFd(), &cleanMsg, msgLength, MSG_DONTWAIT | MSG_NOSIGNAL);
397 } while (nWrite == -1 && errno == EINTR);
398
399 if (nWrite < 0) {
400 int error = errno;
401 ALOGD_IF(DEBUG_CHANNEL_MESSAGES, "channel '%s' ~ error sending message of type %s, %s",
402 name.c_str(), ftl::enum_string(msg->header.type).c_str(), strerror(error));
403 if (error == EAGAIN || error == EWOULDBLOCK) {
404 return WOULD_BLOCK;
405 }
406 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED || error == ECONNRESET) {
407 return DEAD_OBJECT;
408 }
409 return -error;
410 }
411
412 if (size_t(nWrite) != msgLength) {
413 ALOGD_IF(DEBUG_CHANNEL_MESSAGES,
414 "channel '%s' ~ error sending message type %s, send was incomplete", name.c_str(),
415 ftl::enum_string(msg->header.type).c_str());
416 return DEAD_OBJECT;
417 }
418
419 ALOGD_IF(DEBUG_CHANNEL_MESSAGES, "channel '%s' ~ sent message of type %s", name.c_str(),
420 ftl::enum_string(msg->header.type).c_str());
421
422 return OK;
423 }
424
receiveMessage()425 android::base::Result<InputMessage> InputChannel::receiveMessage() {
426 ssize_t nRead;
427 InputMessage msg;
428 do {
429 nRead = ::recv(getFd(), &msg, sizeof(InputMessage), MSG_DONTWAIT);
430 } while (nRead == -1 && errno == EINTR);
431
432 if (nRead < 0) {
433 int error = errno;
434 ALOGD_IF(DEBUG_CHANNEL_MESSAGES, "channel '%s' ~ receive message failed, errno=%d",
435 name.c_str(), errno);
436 if (error == EAGAIN || error == EWOULDBLOCK) {
437 return android::base::Error(WOULD_BLOCK);
438 }
439 if (error == EPIPE) {
440 return android::base::ResultError("Got EPIPE", DEAD_OBJECT);
441 }
442 if (error == ENOTCONN) {
443 return android::base::ResultError("Got ENOTCONN", DEAD_OBJECT);
444 }
445 if (error == ECONNREFUSED) {
446 return android::base::ResultError("Got ECONNREFUSED", DEAD_OBJECT);
447 }
448 if (error == ECONNRESET) {
449 // This means that the client has closed the channel while there was
450 // still some data in the buffer. In most cases, subsequent reads
451 // would result in more data. However, that is not guaranteed, so we
452 // should not return WOULD_BLOCK here to try again.
453 return android::base::ResultError("Got ECONNRESET", DEAD_OBJECT);
454 }
455 return android::base::Error(-error);
456 }
457
458 if (nRead == 0) { // check for EOF
459 LOG_IF(INFO, DEBUG_CHANNEL_MESSAGES)
460 << "channel '" << name << "' ~ receive message failed because peer was closed";
461 return android::base::ResultError("::recv returned 0", DEAD_OBJECT);
462 }
463
464 if (!msg.isValid(nRead)) {
465 ALOGE("channel '%s' ~ received invalid message of size %zd", name.c_str(), nRead);
466 return android::base::Error(BAD_VALUE);
467 }
468
469 ALOGD_IF(DEBUG_CHANNEL_MESSAGES, "channel '%s' ~ received message of type %s", name.c_str(),
470 ftl::enum_string(msg.header.type).c_str());
471 if (ATRACE_ENABLED()) {
472 // Add an additional trace point to include data about the received message.
473 std::string message =
474 StringPrintf("receiveMessage(inputChannel=%s, seq=0x%" PRIx32 ", type=%s)",
475 name.c_str(), msg.header.seq,
476 ftl::enum_string(msg.header.type).c_str());
477 ATRACE_NAME(message.c_str());
478 }
479 return msg;
480 }
481
probablyHasInput() const482 bool InputChannel::probablyHasInput() const {
483 struct pollfd pfds = {.fd = fd.get(), .events = POLLIN};
484 if (::poll(&pfds, /*nfds=*/1, /*timeout=*/0) <= 0) {
485 // This can be a false negative because EINTR and ENOMEM are not handled. The latter should
486 // be extremely rare. The EINTR is also unlikely because it happens only when the signal
487 // arrives while the syscall is executed, and the syscall is quick. Hitting EINTR too often
488 // would be a sign of having too many signals, which is a bigger performance problem. A
489 // common tradition is to repeat the syscall on each EINTR, but it is not necessary here.
490 // In other words, the missing one liner is replaced by a multiline explanation.
491 return false;
492 }
493 // From poll(2): The bits returned in |revents| can include any of those specified in |events|,
494 // or one of the values POLLERR, POLLHUP, or POLLNVAL.
495 return (pfds.revents & POLLIN) != 0;
496 }
497
waitForMessage(std::chrono::milliseconds timeout) const498 void InputChannel::waitForMessage(std::chrono::milliseconds timeout) const {
499 if (timeout < 0ms) {
500 LOG(FATAL) << "Timeout cannot be negative, received " << timeout.count();
501 }
502 struct pollfd pfds = {.fd = fd.get(), .events = POLLIN};
503 int ret;
504 std::chrono::time_point<std::chrono::steady_clock> stopTime =
505 std::chrono::steady_clock::now() + timeout;
506 std::chrono::milliseconds remaining = timeout;
507 do {
508 ret = ::poll(&pfds, /*nfds=*/1, /*timeout=*/remaining.count());
509 remaining = std::chrono::duration_cast<std::chrono::milliseconds>(
510 stopTime - std::chrono::steady_clock::now());
511 } while (ret == -1 && errno == EINTR && remaining > 0ms);
512 }
513
dup() const514 std::unique_ptr<InputChannel> InputChannel::dup() const {
515 base::unique_fd newFd(dupChannelFd(fd.get()));
516 return InputChannel::create(getName(), std::move(newFd), getConnectionToken());
517 }
518
copyTo(android::os::InputChannelCore & outChannel) const519 void InputChannel::copyTo(android::os::InputChannelCore& outChannel) const {
520 outChannel.name = getName();
521 outChannel.fd.reset(dupChannelFd(fd.get()));
522 outChannel.token = getConnectionToken();
523 }
524
moveChannel(std::unique_ptr<InputChannel> from,android::os::InputChannelCore & outChannel)525 void InputChannel::moveChannel(std::unique_ptr<InputChannel> from,
526 android::os::InputChannelCore& outChannel) {
527 outChannel.name = from->getName();
528 outChannel.fd = android::os::ParcelFileDescriptor(std::move(from->fd));
529 outChannel.token = from->getConnectionToken();
530 }
531
getConnectionToken() const532 sp<IBinder> InputChannel::getConnectionToken() const {
533 return token;
534 }
535
536 // --- InputPublisher ---
537
InputPublisher(const std::shared_ptr<InputChannel> & channel)538 InputPublisher::InputPublisher(const std::shared_ptr<InputChannel>& channel)
539 : mChannel(channel), mInputVerifier(mChannel->getName()) {}
540
~InputPublisher()541 InputPublisher::~InputPublisher() {
542 }
543
publishKeyEvent(uint32_t seq,int32_t eventId,int32_t deviceId,int32_t source,ui::LogicalDisplayId displayId,std::array<uint8_t,32> hmac,int32_t action,int32_t flags,int32_t keyCode,int32_t scanCode,int32_t metaState,int32_t repeatCount,nsecs_t downTime,nsecs_t eventTime)544 status_t InputPublisher::publishKeyEvent(uint32_t seq, int32_t eventId, int32_t deviceId,
545 int32_t source, ui::LogicalDisplayId displayId,
546 std::array<uint8_t, 32> hmac, int32_t action,
547 int32_t flags, int32_t keyCode, int32_t scanCode,
548 int32_t metaState, int32_t repeatCount, nsecs_t downTime,
549 nsecs_t eventTime) {
550 ATRACE_NAME_IF(ATRACE_ENABLED(),
551 StringPrintf("publishKeyEvent(inputChannel=%s, action=%s, keyCode=%s)",
552 mChannel->getName().c_str(), KeyEvent::actionToString(action),
553 KeyEvent::getLabel(keyCode)));
554 ALOGD_IF(debugTransportPublisher(),
555 "channel '%s' publisher ~ %s: seq=%u, id=%d, deviceId=%d, source=%s, "
556 "action=%s, flags=0x%x, keyCode=%s, scanCode=%d, metaState=0x%x, repeatCount=%d,"
557 "downTime=%" PRId64 ", eventTime=%" PRId64,
558 mChannel->getName().c_str(), __func__, seq, eventId, deviceId,
559 inputEventSourceToString(source).c_str(), KeyEvent::actionToString(action), flags,
560 KeyEvent::getLabel(keyCode), scanCode, metaState, repeatCount, downTime, eventTime);
561
562 if (!seq) {
563 ALOGE("Attempted to publish a key event with sequence number 0.");
564 return BAD_VALUE;
565 }
566
567 InputMessage msg;
568 msg.header.type = InputMessage::Type::KEY;
569 msg.header.seq = seq;
570 msg.body.key.eventId = eventId;
571 msg.body.key.deviceId = deviceId;
572 msg.body.key.source = source;
573 msg.body.key.displayId = displayId.val();
574 msg.body.key.hmac = std::move(hmac);
575 msg.body.key.action = action;
576 msg.body.key.flags = flags;
577 msg.body.key.keyCode = keyCode;
578 msg.body.key.scanCode = scanCode;
579 msg.body.key.metaState = metaState;
580 msg.body.key.repeatCount = repeatCount;
581 msg.body.key.downTime = downTime;
582 msg.body.key.eventTime = eventTime;
583 return mChannel->sendMessage(&msg);
584 }
585
publishMotionEvent(uint32_t seq,int32_t eventId,int32_t deviceId,int32_t source,ui::LogicalDisplayId displayId,std::array<uint8_t,32> hmac,int32_t action,int32_t actionButton,int32_t flags,int32_t edgeFlags,int32_t metaState,int32_t buttonState,MotionClassification classification,const ui::Transform & transform,float xPrecision,float yPrecision,float xCursorPosition,float yCursorPosition,const ui::Transform & rawTransform,nsecs_t downTime,nsecs_t eventTime,uint32_t pointerCount,const PointerProperties * pointerProperties,const PointerCoords * pointerCoords)586 status_t InputPublisher::publishMotionEvent(
587 uint32_t seq, int32_t eventId, int32_t deviceId, int32_t source,
588 ui::LogicalDisplayId displayId, std::array<uint8_t, 32> hmac, int32_t action,
589 int32_t actionButton, int32_t flags, int32_t edgeFlags, int32_t metaState,
590 int32_t buttonState, MotionClassification classification, const ui::Transform& transform,
591 float xPrecision, float yPrecision, float xCursorPosition, float yCursorPosition,
592 const ui::Transform& rawTransform, nsecs_t downTime, nsecs_t eventTime,
593 uint32_t pointerCount, const PointerProperties* pointerProperties,
594 const PointerCoords* pointerCoords) {
595 ATRACE_NAME_IF(ATRACE_ENABLED(),
596 StringPrintf("publishMotionEvent(inputChannel=%s, action=%s)",
597 mChannel->getName().c_str(),
598 MotionEvent::actionToString(action).c_str()));
599 if (debugTransportPublisher()) {
600 std::string transformString;
601 transform.dump(transformString, "transform", " ");
602 ALOGD("channel '%s' publisher ~ %s: seq=%u, id=%d, deviceId=%d, source=%s, "
603 "displayId=%s, "
604 "action=%s, actionButton=0x%08x, flags=0x%x, edgeFlags=0x%x, "
605 "metaState=0x%x, buttonState=0x%x, classification=%s,"
606 "xPrecision=%f, yPrecision=%f, downTime=%" PRId64 ", eventTime=%" PRId64 ", "
607 "pointerCount=%" PRIu32 "\n%s",
608 mChannel->getName().c_str(), __func__, seq, eventId, deviceId,
609 inputEventSourceToString(source).c_str(), displayId.toString().c_str(),
610 MotionEvent::actionToString(action).c_str(), actionButton, flags, edgeFlags,
611 metaState, buttonState, motionClassificationToString(classification), xPrecision,
612 yPrecision, downTime, eventTime, pointerCount, transformString.c_str());
613 }
614
615 if (!seq) {
616 ALOGE("Attempted to publish a motion event with sequence number 0.");
617 return BAD_VALUE;
618 }
619
620 if (pointerCount > MAX_POINTERS || pointerCount < 1) {
621 ALOGE("channel '%s' publisher ~ Invalid number of pointers provided: %" PRIu32 ".",
622 mChannel->getName().c_str(), pointerCount);
623 return BAD_VALUE;
624 }
625
626 InputMessage msg;
627 msg.header.type = InputMessage::Type::MOTION;
628 msg.header.seq = seq;
629 msg.body.motion.eventId = eventId;
630 msg.body.motion.deviceId = deviceId;
631 msg.body.motion.source = source;
632 msg.body.motion.displayId = displayId.val();
633 msg.body.motion.hmac = std::move(hmac);
634 msg.body.motion.action = action;
635 msg.body.motion.actionButton = actionButton;
636 msg.body.motion.flags = flags;
637 msg.body.motion.edgeFlags = edgeFlags;
638 msg.body.motion.metaState = metaState;
639 msg.body.motion.buttonState = buttonState;
640 msg.body.motion.classification = classification;
641 msg.body.motion.dsdx = transform.dsdx();
642 msg.body.motion.dtdx = transform.dtdx();
643 msg.body.motion.dtdy = transform.dtdy();
644 msg.body.motion.dsdy = transform.dsdy();
645 msg.body.motion.tx = transform.tx();
646 msg.body.motion.ty = transform.ty();
647 msg.body.motion.xPrecision = xPrecision;
648 msg.body.motion.yPrecision = yPrecision;
649 msg.body.motion.xCursorPosition = xCursorPosition;
650 msg.body.motion.yCursorPosition = yCursorPosition;
651 msg.body.motion.dsdxRaw = rawTransform.dsdx();
652 msg.body.motion.dtdxRaw = rawTransform.dtdx();
653 msg.body.motion.dtdyRaw = rawTransform.dtdy();
654 msg.body.motion.dsdyRaw = rawTransform.dsdy();
655 msg.body.motion.txRaw = rawTransform.tx();
656 msg.body.motion.tyRaw = rawTransform.ty();
657 msg.body.motion.downTime = downTime;
658 msg.body.motion.eventTime = eventTime;
659 msg.body.motion.pointerCount = pointerCount;
660 for (uint32_t i = 0; i < pointerCount; i++) {
661 msg.body.motion.pointers[i].properties = pointerProperties[i];
662 msg.body.motion.pointers[i].coords = pointerCoords[i];
663 }
664 const status_t status = mChannel->sendMessage(&msg);
665
666 if (status == OK && verifyEvents()) {
667 Result<void> result = mInputVerifier.processMovement(deviceId, source, action, actionButton,
668 pointerCount, pointerProperties,
669 pointerCoords, flags, buttonState);
670 if (!result.ok()) {
671 LOG(ERROR) << "Bad stream: " << result.error();
672 return BAD_VALUE;
673 }
674 }
675 return status;
676 }
677
publishFocusEvent(uint32_t seq,int32_t eventId,bool hasFocus)678 status_t InputPublisher::publishFocusEvent(uint32_t seq, int32_t eventId, bool hasFocus) {
679 ATRACE_NAME_IF(ATRACE_ENABLED(),
680 StringPrintf("publishFocusEvent(inputChannel=%s, hasFocus=%s)",
681 mChannel->getName().c_str(), toString(hasFocus)));
682 ALOGD_IF(debugTransportPublisher(), "channel '%s' publisher ~ %s: seq=%u, id=%d, hasFocus=%s",
683 mChannel->getName().c_str(), __func__, seq, eventId, toString(hasFocus));
684
685 InputMessage msg;
686 msg.header.type = InputMessage::Type::FOCUS;
687 msg.header.seq = seq;
688 msg.body.focus.eventId = eventId;
689 msg.body.focus.hasFocus = hasFocus;
690 return mChannel->sendMessage(&msg);
691 }
692
publishCaptureEvent(uint32_t seq,int32_t eventId,bool pointerCaptureEnabled)693 status_t InputPublisher::publishCaptureEvent(uint32_t seq, int32_t eventId,
694 bool pointerCaptureEnabled) {
695 ATRACE_NAME_IF(ATRACE_ENABLED(),
696 StringPrintf("publishCaptureEvent(inputChannel=%s, pointerCaptureEnabled=%s)",
697 mChannel->getName().c_str(), toString(pointerCaptureEnabled)));
698 ALOGD_IF(debugTransportPublisher(),
699 "channel '%s' publisher ~ %s: seq=%u, id=%d, pointerCaptureEnabled=%s",
700 mChannel->getName().c_str(), __func__, seq, eventId, toString(pointerCaptureEnabled));
701
702 InputMessage msg;
703 msg.header.type = InputMessage::Type::CAPTURE;
704 msg.header.seq = seq;
705 msg.body.capture.eventId = eventId;
706 msg.body.capture.pointerCaptureEnabled = pointerCaptureEnabled;
707 return mChannel->sendMessage(&msg);
708 }
709
publishDragEvent(uint32_t seq,int32_t eventId,float x,float y,bool isExiting)710 status_t InputPublisher::publishDragEvent(uint32_t seq, int32_t eventId, float x, float y,
711 bool isExiting) {
712 ATRACE_NAME_IF(ATRACE_ENABLED(),
713 StringPrintf("publishDragEvent(inputChannel=%s, x=%f, y=%f, isExiting=%s)",
714 mChannel->getName().c_str(), x, y, toString(isExiting)));
715 ALOGD_IF(debugTransportPublisher(),
716 "channel '%s' publisher ~ %s: seq=%u, id=%d, x=%f, y=%f, isExiting=%s",
717 mChannel->getName().c_str(), __func__, seq, eventId, x, y, toString(isExiting));
718
719 InputMessage msg;
720 msg.header.type = InputMessage::Type::DRAG;
721 msg.header.seq = seq;
722 msg.body.drag.eventId = eventId;
723 msg.body.drag.isExiting = isExiting;
724 msg.body.drag.x = x;
725 msg.body.drag.y = y;
726 return mChannel->sendMessage(&msg);
727 }
728
publishTouchModeEvent(uint32_t seq,int32_t eventId,bool isInTouchMode)729 status_t InputPublisher::publishTouchModeEvent(uint32_t seq, int32_t eventId, bool isInTouchMode) {
730 ATRACE_NAME_IF(ATRACE_ENABLED(),
731 StringPrintf("publishTouchModeEvent(inputChannel=%s, isInTouchMode=%s)",
732 mChannel->getName().c_str(), toString(isInTouchMode)));
733 ALOGD_IF(debugTransportPublisher(),
734 "channel '%s' publisher ~ %s: seq=%u, id=%d, isInTouchMode=%s",
735 mChannel->getName().c_str(), __func__, seq, eventId, toString(isInTouchMode));
736
737 InputMessage msg;
738 msg.header.type = InputMessage::Type::TOUCH_MODE;
739 msg.header.seq = seq;
740 msg.body.touchMode.eventId = eventId;
741 msg.body.touchMode.isInTouchMode = isInTouchMode;
742 return mChannel->sendMessage(&msg);
743 }
744
receiveConsumerResponse()745 android::base::Result<InputPublisher::ConsumerResponse> InputPublisher::receiveConsumerResponse() {
746 android::base::Result<InputMessage> result = mChannel->receiveMessage();
747 if (!result.ok()) {
748 if (debugTransportPublisher() && result.error().code() != WOULD_BLOCK) {
749 LOG(INFO) << "channel '" << mChannel->getName() << "' publisher ~ " << __func__ << ": "
750 << result.error().message();
751 }
752 return result.error();
753 }
754
755 const InputMessage& msg = *result;
756 if (msg.header.type == InputMessage::Type::FINISHED) {
757 ALOGD_IF(debugTransportPublisher(),
758 "channel '%s' publisher ~ %s: finished: seq=%u, handled=%s",
759 mChannel->getName().c_str(), __func__, msg.header.seq,
760 toString(msg.body.finished.handled));
761 return Finished{
762 .seq = msg.header.seq,
763 .handled = msg.body.finished.handled,
764 .consumeTime = msg.body.finished.consumeTime,
765 };
766 }
767
768 if (msg.header.type == InputMessage::Type::TIMELINE) {
769 ALOGD_IF(debugTransportPublisher(), "channel '%s' publisher ~ %s: timeline: id=%d",
770 mChannel->getName().c_str(), __func__, msg.body.timeline.eventId);
771 return Timeline{
772 .inputEventId = msg.body.timeline.eventId,
773 .graphicsTimeline = msg.body.timeline.graphicsTimeline,
774 };
775 }
776
777 ALOGE("channel '%s' publisher ~ Received unexpected %s message from consumer",
778 mChannel->getName().c_str(), ftl::enum_string(msg.header.type).c_str());
779 return android::base::Error(UNKNOWN_ERROR);
780 }
781
operator <<(std::ostream & out,const InputMessage & msg)782 std::ostream& operator<<(std::ostream& out, const InputMessage& msg) {
783 out << ftl::enum_string(msg.header.type);
784 return out;
785 }
786
787 } // namespace android
788