1 /*
2  * Copyright 2023 Google LLC
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <errno.h>
8 #include <fcntl.h>
9 #include <linux/input.h>
10 #include <nsi_tracing.h>
11 #include <string.h>
12 #include <unistd.h>
13 
14 #include "linux_evdev_bottom.h"
15 
linux_evdev_read(int fd,uint16_t * type,uint16_t * code,int32_t * value)16 int linux_evdev_read(int fd, uint16_t *type, uint16_t *code, int32_t *value)
17 {
18 	struct input_event ev;
19 	int ret;
20 
21 	ret = read(fd, &ev, sizeof(ev));
22 	if (ret < 0) {
23 		if (errno == EAGAIN || errno == EINTR) {
24 			return NATIVE_LINUX_EVDEV_NO_DATA;
25 		}
26 		nsi_print_warning("Read error: %s", strerror(errno));
27 		return -EIO;
28 	} else if (ret < sizeof(ev)) {
29 		nsi_print_warning("Unexpected read size: %d, expecting %d",
30 				  ret, sizeof(ev));
31 		return -EIO;
32 	}
33 
34 	*type = ev.type;
35 	*code = ev.code;
36 	*value = ev.value;
37 
38 	return 0;
39 }
40 
linux_evdev_open(const char * path)41 int linux_evdev_open(const char *path)
42 {
43 	int fd;
44 
45 	fd = open(path, O_RDONLY | O_NONBLOCK);
46 	if (fd < 0) {
47 		nsi_print_error_and_exit(
48 				"Failed to open the evdev device %s: %s\n",
49 				path, strerror(errno));
50 	}
51 
52 	return fd;
53 }
54