Debian Codegraph @

vmtest/enter_kdump.py

raw
1 # Copyright (c) Meta Platforms, Inc. and affiliates.
2 # SPDX-License-Identifier: LGPL-2.1-or-later
3
4 import ctypes
5 import os
6 import re
7 import subprocess
8 import sys
9
10 from _drgn_util.platform import NORMALIZED_MACHINE_NAME, SYS
11
12 KEXEC_FILE_ON_CRASH = 2
13 KEXEC_FILE_NO_INITRAMFS = 4
14
15
16 def main() -> None:
17 with open("/proc/cmdline", "rb") as f:
18 cmdline = f.read().rstrip(b"\n")
19 cmdline = re.sub(rb"(^|\s)crashkernel=\S+", b"", cmdline)
20 # `nokaslr` is required to avoid sporadically failing to reserve space for the
21 # capture kernel
22 cmdline += b" nokaslr"
23 if os.getenv("KDUMP_NEEDS_NOSMP"):
24 # `nosmp` is required to avoid QEMU sporadically failing an internal
25 # assertion when using emulation.
26 cmdline += b" nosmp"
27
28 # On RISC-V, kexec_file_load() is supported for Image (vmlinuz) files only
29 # since Linux kernel commit 809a11eea8e8 ("riscv: kexec_file: Support
30 # loading Image binary file") (in v6.16), but for ELF files since Linux
31 # kernel commit 6261586e0c91 ("RISC-V: Add kexec_file support") (in v5.19).
32 if NORMALIZED_MACHINE_NAME == "riscv64":
33 kernel_image = f"/lib/modules/{os.uname().release}/build/vmlinux"
34 else:
35 kernel_image = f"/lib/modules/{os.uname().release}/vmlinuz"
36
37 # On x86-64 and RISC-V, kexec_file_load() is supported on all kernel
38 # versions we care about, and it's simple enough to call ourselves. On
39 # other architectures, we just use kexec(8).
40 if NORMALIZED_MACHINE_NAME in {"x86_64", "riscv64"}:
41 syscall = ctypes.CDLL(None, use_errno=True).syscall
42 syscall.restype = ctypes.c_long
43
44 with open(kernel_image, "rb") as kernel:
45 if syscall(
46 ctypes.c_long(SYS["kexec_file_load"]),
47 ctypes.c_int(kernel.fileno()),
48 ctypes.c_int(-1),
49 ctypes.c_ulong(len(cmdline) + 1),
50 ctypes.c_char_p(cmdline + b"\0"),
51 ctypes.c_ulong(KEXEC_FILE_ON_CRASH | KEXEC_FILE_NO_INITRAMFS),
52 ):
53 errno = ctypes.get_errno()
54 raise OSError(errno, os.strerror(errno))
55 else:
56 subprocess.check_call(
57 [
58 "kexec",
59 "--load-panic",
60 "--kexec-syscall-auto",
61 "--command-line=" + cmdline.decode(),
62 kernel_image,
63 ]
64 )
65
66 with open("/proc/self/comm", "w") as f:
67 f.write("selfdestruct")
68
69 # Avoid panicking from CPU 0 on s390x. See _skip_if_cpu0_on_s390x().
70 if NORMALIZED_MACHINE_NAME == "s390x":
71 cpus = os.sched_getaffinity(0)
72 cpus.remove(0)
73 if cpus:
74 os.sched_setaffinity(0, cpus)
75
76 # Try the drgn_test kmod crash method first.
77 try:
78 with open("/sys/kernel/drgn_test/crash", "w") as f:
79 f.write("1")
80 except FileNotFoundError:
81 pass
82
83 # Fall back to sysrq-trigger.
84 with open("/proc/sysrq-trigger", "w") as f:
85 f.write("c")
86
87
88 if __name__ == "__main__":
89 if os.path.exists("/proc/vmcore") and len(sys.argv) > 1:
90 # We're in the kdump kernel already. Assume the user wanted to run
91 # a command within it.
92 os.execvp(sys.argv[1], sys.argv[1:])
93 main()