Debian Codegraph @

tests/linux_kernel/helpers/test_printk.py

raw
1 # Copyright (c) Meta Platforms, Inc. and affiliates.
2 # SPDX-License-Identifier: LGPL-2.1-or-later
3
4 import errno
5 import os
6 import re
7
8 from drgn.helpers.linux.printk import PrintkRecord, get_printk_records
9 from tests.linux_kernel import LinuxKernelTestCase
10
11
12 def unescape_text(s):
13 return re.sub(
14 rb"\\x([0-9A-Fa-f]{2})", lambda match: bytes([int(match.group(1), 16)]), s
15 )
16
17
18 def get_kmsg_records():
19 result = []
20 with open("/dev/kmsg", "rb") as f:
21 fd = f.fileno()
22 os.set_blocking(fd, False)
23 while True:
24 try:
25 record = os.read(fd, 4096)
26 except OSError as e:
27 if e.errno == errno.EAGAIN:
28 break
29 else:
30 raise
31 prefix, _, escaped = record.partition(b";")
32 fields = prefix.split(b",")
33 syslog = int(fields[0])
34 escaped_lines = escaped.splitlines()
35 context = {}
36 for escaped_line in escaped_lines[1:]:
37 assert escaped_line.startswith(b" ")
38 key, value = escaped_line[1:].split(b"=", 1)
39 context[unescape_text(key)] = unescape_text(value)
40 result.append(
41 PrintkRecord(
42 text=unescape_text(escaped_lines[0]),
43 facility=syslog >> 3,
44 level=syslog & 7,
45 seq=int(fields[1]),
46 timestamp=int(fields[2]) * 1000,
47 caller_tid=None,
48 caller_cpu=None,
49 continuation=b"c" in fields[3],
50 context=context,
51 )
52 )
53 return result
54
55
56 class TestPrintk(LinuxKernelTestCase):
57 def test_get_printk_records(self):
58 self.assertEqual(
59 get_kmsg_records(),
60 [
61 record._replace(
62 # Round timestamp down since /dev/kmsg only has microsecond
63 # granularity.
64 timestamp=record.timestamp // 1000 * 1000,
65 # Remove caller ID since it's only available from /dev/kmsg
66 # when the kernel is compiled with CONFIG_PRINTK_CALLER.
67 caller_tid=None,
68 caller_cpu=None,
69 )
70 for record in get_printk_records(self.prog)
71 ],
72 )