base.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. #!/bin/env python3
  2. # SPDX-License-Identifier: GPL-2.0
  3. # -*- coding: utf-8 -*-
  4. #
  5. # Copyright (c) 2017 Benjamin Tissoires <benjamin.tissoires@gmail.com>
  6. # Copyright (c) 2017 Red Hat, Inc.
  7. import dataclasses
  8. import libevdev
  9. import os
  10. import pytest
  11. import shutil
  12. import subprocess
  13. import time
  14. import logging
  15. from .base_device import BaseDevice, EvdevMatch, SysfsFile
  16. from pathlib import Path
  17. from typing import Final, List, Tuple
  18. logger = logging.getLogger("hidtools.test.base")
  19. # application to matches
  20. application_matches: Final = {
  21. # pyright: ignore
  22. "Accelerometer": EvdevMatch(
  23. req_properties=[
  24. libevdev.INPUT_PROP_ACCELEROMETER,
  25. ]
  26. ),
  27. "Game Pad": EvdevMatch( # in systemd, this is a lot more complex, but that will do
  28. requires=[
  29. libevdev.EV_ABS.ABS_X,
  30. libevdev.EV_ABS.ABS_Y,
  31. libevdev.EV_ABS.ABS_RX,
  32. libevdev.EV_ABS.ABS_RY,
  33. libevdev.EV_KEY.BTN_START,
  34. ],
  35. excl_properties=[
  36. libevdev.INPUT_PROP_ACCELEROMETER,
  37. ],
  38. ),
  39. "Joystick": EvdevMatch( # in systemd, this is a lot more complex, but that will do
  40. requires=[
  41. libevdev.EV_ABS.ABS_RX,
  42. libevdev.EV_ABS.ABS_RY,
  43. libevdev.EV_KEY.BTN_START,
  44. ],
  45. excl_properties=[
  46. libevdev.INPUT_PROP_ACCELEROMETER,
  47. ],
  48. ),
  49. "Key": EvdevMatch(
  50. requires=[
  51. libevdev.EV_KEY.KEY_A,
  52. ],
  53. excl_properties=[
  54. libevdev.INPUT_PROP_ACCELEROMETER,
  55. libevdev.INPUT_PROP_DIRECT,
  56. libevdev.INPUT_PROP_POINTER,
  57. ],
  58. ),
  59. "Mouse": EvdevMatch(
  60. requires=[
  61. libevdev.EV_REL.REL_X,
  62. libevdev.EV_REL.REL_Y,
  63. libevdev.EV_KEY.BTN_LEFT,
  64. ],
  65. excl_properties=[
  66. libevdev.INPUT_PROP_ACCELEROMETER,
  67. ],
  68. ),
  69. "Pad": EvdevMatch(
  70. requires=[
  71. libevdev.EV_KEY.BTN_0,
  72. ],
  73. excludes=[
  74. libevdev.EV_KEY.BTN_TOOL_PEN,
  75. libevdev.EV_KEY.BTN_TOUCH,
  76. libevdev.EV_ABS.ABS_DISTANCE,
  77. ],
  78. excl_properties=[
  79. libevdev.INPUT_PROP_ACCELEROMETER,
  80. ],
  81. ),
  82. "Pen": EvdevMatch(
  83. requires=[
  84. libevdev.EV_KEY.BTN_STYLUS,
  85. libevdev.EV_ABS.ABS_X,
  86. libevdev.EV_ABS.ABS_Y,
  87. ],
  88. excl_properties=[
  89. libevdev.INPUT_PROP_ACCELEROMETER,
  90. ],
  91. ),
  92. "Stylus": EvdevMatch(
  93. requires=[
  94. libevdev.EV_KEY.BTN_STYLUS,
  95. libevdev.EV_ABS.ABS_X,
  96. libevdev.EV_ABS.ABS_Y,
  97. ],
  98. excl_properties=[
  99. libevdev.INPUT_PROP_ACCELEROMETER,
  100. ],
  101. ),
  102. "Touch Pad": EvdevMatch(
  103. requires=[
  104. libevdev.EV_KEY.BTN_LEFT,
  105. libevdev.EV_ABS.ABS_X,
  106. libevdev.EV_ABS.ABS_Y,
  107. ],
  108. excludes=[libevdev.EV_KEY.BTN_TOOL_PEN, libevdev.EV_KEY.BTN_STYLUS],
  109. req_properties=[
  110. libevdev.INPUT_PROP_POINTER,
  111. ],
  112. excl_properties=[
  113. libevdev.INPUT_PROP_ACCELEROMETER,
  114. ],
  115. ),
  116. "Touch Screen": EvdevMatch(
  117. requires=[
  118. libevdev.EV_KEY.BTN_TOUCH,
  119. libevdev.EV_ABS.ABS_X,
  120. libevdev.EV_ABS.ABS_Y,
  121. ],
  122. excludes=[libevdev.EV_KEY.BTN_TOOL_PEN, libevdev.EV_KEY.BTN_STYLUS],
  123. req_properties=[
  124. libevdev.INPUT_PROP_DIRECT,
  125. ],
  126. excl_properties=[
  127. libevdev.INPUT_PROP_ACCELEROMETER,
  128. ],
  129. ),
  130. }
  131. class UHIDTestDevice(BaseDevice):
  132. def __init__(self, name, application, rdesc_str=None, rdesc=None, input_info=None):
  133. super().__init__(name, application, rdesc_str, rdesc, input_info)
  134. self.application_matches = application_matches
  135. if name is None:
  136. name = f"uhid test {self.__class__.__name__}"
  137. if not name.startswith("uhid test "):
  138. name = "uhid test " + self.name
  139. self.name = name
  140. @dataclasses.dataclass
  141. class HidBpf:
  142. object_name: str
  143. has_rdesc_fixup: bool
  144. @dataclasses.dataclass
  145. class KernelModule:
  146. driver_name: str
  147. module_name: str
  148. class BaseTestCase:
  149. class TestUhid(object):
  150. syn_event = libevdev.InputEvent(libevdev.EV_SYN.SYN_REPORT) # type: ignore
  151. key_event = libevdev.InputEvent(libevdev.EV_KEY) # type: ignore
  152. abs_event = libevdev.InputEvent(libevdev.EV_ABS) # type: ignore
  153. rel_event = libevdev.InputEvent(libevdev.EV_REL) # type: ignore
  154. msc_event = libevdev.InputEvent(libevdev.EV_MSC.MSC_SCAN) # type: ignore
  155. # List of kernel modules to load before starting the test
  156. # if any module is not available (not compiled), the test will skip.
  157. # Each element is a KernelModule object, for example
  158. # KernelModule("playstation", "hid-playstation")
  159. kernel_modules: List[KernelModule] = []
  160. # List of in kernel HID-BPF object files to load
  161. # before starting the test
  162. # Any existing pre-loaded HID-BPF module will be removed
  163. # before the ones in this list will be manually loaded.
  164. # Each Element is a HidBpf object, for example
  165. # 'HidBpf("xppen-ArtistPro16Gen2.bpf.o", True)'
  166. # If 'has_rdesc_fixup' is True, the test needs to wait
  167. # for one unbind and rebind before it can be sure the kernel is
  168. # ready
  169. hid_bpfs: List[HidBpf] = []
  170. def assertInputEventsIn(self, expected_events, effective_events):
  171. effective_events = effective_events.copy()
  172. for ev in expected_events:
  173. assert ev in effective_events
  174. effective_events.remove(ev)
  175. return effective_events
  176. def assertInputEvents(self, expected_events, effective_events):
  177. remaining = self.assertInputEventsIn(expected_events, effective_events)
  178. assert remaining == []
  179. @classmethod
  180. def debug_reports(cls, reports, uhdev=None, events=None):
  181. data = [" ".join([f"{v:02x}" for v in r]) for r in reports]
  182. if uhdev is not None:
  183. human_data = [
  184. uhdev.parsed_rdesc.format_report(r, split_lines=True)
  185. for r in reports
  186. ]
  187. try:
  188. human_data = [
  189. f'\n\t {" " * h.index("/")}'.join(h.split("\n"))
  190. for h in human_data
  191. ]
  192. except ValueError:
  193. # '/' not found: not a numbered report
  194. human_data = ["\n\t ".join(h.split("\n")) for h in human_data]
  195. data = [f"{d}\n\t ====> {h}" for d, h in zip(data, human_data)]
  196. reports = data
  197. if len(reports) == 1:
  198. print("sending 1 report:")
  199. else:
  200. print(f"sending {len(reports)} reports:")
  201. for report in reports:
  202. print("\t", report)
  203. if events is not None:
  204. print("events received:", events)
  205. def create_device(self):
  206. raise Exception("please reimplement me in subclasses")
  207. def _load_kernel_module(self, kernel_driver, kernel_module):
  208. sysfs_path = Path("/sys/bus/hid/drivers")
  209. if kernel_driver is not None:
  210. sysfs_path /= kernel_driver
  211. else:
  212. # special case for when testing all available modules:
  213. # we don't know beforehand the name of the module from modinfo
  214. sysfs_path = Path("/sys/module") / kernel_module.replace("-", "_")
  215. if not sysfs_path.exists():
  216. ret = subprocess.run(["/usr/sbin/modprobe", kernel_module])
  217. if ret.returncode != 0:
  218. pytest.skip(
  219. f"module {kernel_module} could not be loaded, skipping the test"
  220. )
  221. @pytest.fixture()
  222. def load_kernel_module(self):
  223. for k in self.kernel_modules:
  224. self._load_kernel_module(k.driver_name, k.module_name)
  225. yield
  226. def load_hid_bpfs(self):
  227. # this function will only work when run in the kernel tree
  228. script_dir = Path(os.path.dirname(os.path.realpath(__file__)))
  229. root_dir = (script_dir / "../../../../..").resolve()
  230. bpf_dir = root_dir / "drivers/hid/bpf/progs"
  231. if not bpf_dir.exists():
  232. pytest.skip("looks like we are not in the kernel tree, skipping")
  233. udev_hid_bpf = shutil.which("udev-hid-bpf")
  234. if not udev_hid_bpf:
  235. pytest.skip("udev-hid-bpf not found in $PATH, skipping")
  236. wait = any(b.has_rdesc_fixup for b in self.hid_bpfs)
  237. for hid_bpf in self.hid_bpfs:
  238. # We need to start `udev-hid-bpf` in the background
  239. # and dispatch uhid events in case the kernel needs
  240. # to fetch features on the device
  241. process = subprocess.Popen(
  242. [
  243. "udev-hid-bpf",
  244. "--verbose",
  245. "add",
  246. str(self.uhdev.sys_path),
  247. str(bpf_dir / hid_bpf.object_name),
  248. ],
  249. )
  250. while process.poll() is None:
  251. self.uhdev.dispatch(1)
  252. if process.returncode != 0:
  253. pytest.fail(
  254. f"Couldn't insert hid-bpf program '{hid_bpf}', marking the test as failed"
  255. )
  256. if wait:
  257. # the HID-BPF program exports a rdesc fixup, so it needs to be
  258. # unbound by the kernel and then rebound.
  259. # Ensure we get the bound event exactly 2 times (one for the normal
  260. # uhid loading, and then the reload from HID-BPF)
  261. now = time.time()
  262. while self.uhdev.kernel_ready_count < 2 and time.time() - now < 2:
  263. self.uhdev.dispatch(1)
  264. if self.uhdev.kernel_ready_count < 2:
  265. pytest.fail(
  266. f"Couldn't insert hid-bpf programs, marking the test as failed"
  267. )
  268. def unload_hid_bpfs(self):
  269. ret = subprocess.run(
  270. ["udev-hid-bpf", "--verbose", "remove", str(self.uhdev.sys_path)],
  271. )
  272. if ret.returncode != 0:
  273. pytest.fail(
  274. f"Couldn't unload hid-bpf programs, marking the test as failed"
  275. )
  276. @pytest.fixture()
  277. def new_uhdev(self, load_kernel_module):
  278. return self.create_device()
  279. def assertName(self, uhdev):
  280. evdev = uhdev.get_evdev()
  281. assert uhdev.name in evdev.name
  282. @pytest.fixture(autouse=True)
  283. def context(self, new_uhdev, request):
  284. try:
  285. with HIDTestUdevRule.instance():
  286. with new_uhdev as self.uhdev:
  287. for skip_cond in request.node.iter_markers("skip_if_uhdev"):
  288. test, message, *rest = skip_cond.args
  289. if test(self.uhdev):
  290. pytest.skip(message)
  291. self.uhdev.create_kernel_device()
  292. now = time.time()
  293. while not self.uhdev.is_ready() and time.time() - now < 5:
  294. self.uhdev.dispatch(1)
  295. if self.hid_bpfs:
  296. self.load_hid_bpfs()
  297. if self.uhdev.get_evdev() is None:
  298. logger.warning(
  299. f"available list of input nodes: (default application is '{self.uhdev.application}')"
  300. )
  301. logger.warning(self.uhdev.input_nodes)
  302. yield
  303. if self.hid_bpfs:
  304. self.unload_hid_bpfs()
  305. self.uhdev = None
  306. except PermissionError:
  307. pytest.skip("Insufficient permissions, run me as root")
  308. @pytest.fixture(autouse=True)
  309. def check_taint(self):
  310. # we are abusing SysfsFile here, it's in /proc, but meh
  311. taint_file = SysfsFile("/proc/sys/kernel/tainted")
  312. taint = taint_file.int_value
  313. yield
  314. assert taint_file.int_value == taint
  315. def test_creation(self):
  316. """Make sure the device gets processed by the kernel and creates
  317. the expected application input node.
  318. If this fail, there is something wrong in the device report
  319. descriptors."""
  320. uhdev = self.uhdev
  321. assert uhdev is not None
  322. assert uhdev.get_evdev() is not None
  323. self.assertName(uhdev)
  324. assert len(uhdev.next_sync_events()) == 0
  325. assert uhdev.get_evdev() is not None
  326. class HIDTestUdevRule(object):
  327. _instance = None
  328. """
  329. A context-manager compatible class that sets up our udev rules file and
  330. deletes it on context exit.
  331. This class is tailored to our test setup: it only sets up the udev rule
  332. on the **second** context and it cleans it up again on the last context
  333. removed. This matches the expected pytest setup: we enter a context for
  334. the session once, then once for each test (the first of which will
  335. trigger the udev rule) and once the last test exited and the session
  336. exited, we clean up after ourselves.
  337. """
  338. def __init__(self):
  339. self.refs = 0
  340. self.rulesfile = None
  341. def __enter__(self):
  342. self.refs += 1
  343. if self.refs == 2 and self.rulesfile is None:
  344. self.create_udev_rule()
  345. self.reload_udev_rules()
  346. def __exit__(self, exc_type, exc_value, traceback):
  347. self.refs -= 1
  348. if self.refs == 0 and self.rulesfile:
  349. os.remove(self.rulesfile.name)
  350. self.reload_udev_rules()
  351. def reload_udev_rules(self):
  352. subprocess.run("udevadm control --reload-rules".split())
  353. subprocess.run("systemd-hwdb update".split())
  354. def create_udev_rule(self):
  355. import tempfile
  356. os.makedirs("/run/udev/rules.d", exist_ok=True)
  357. with tempfile.NamedTemporaryFile(
  358. prefix="91-uhid-test-device-REMOVEME-",
  359. suffix=".rules",
  360. mode="w+",
  361. dir="/run/udev/rules.d",
  362. delete=False,
  363. ) as f:
  364. f.write(
  365. """
  366. KERNELS=="*input*", ATTRS{name}=="*uhid test *", ENV{LIBINPUT_IGNORE_DEVICE}="1"
  367. KERNELS=="*hid*", ENV{HID_NAME}=="*uhid test *", ENV{HID_BPF_IGNORE_DEVICE}="1"
  368. KERNELS=="*input*", ATTRS{name}=="*uhid test * System Multi Axis", ENV{ID_INPUT_TOUCHSCREEN}="", ENV{ID_INPUT_SYSTEM_MULTIAXIS}="1"
  369. """
  370. )
  371. self.rulesfile = f
  372. @classmethod
  373. def instance(cls):
  374. if not cls._instance:
  375. cls._instance = HIDTestUdevRule()
  376. return cls._instance