mirror of
https://github.com/QuixiAI/nvdriver.git
synced 2026-12-06 06:28:39 +00:00
Merge pull request #373 from didiniao/fix/rmapi-caps-mode-and-compact-modversions
rmapi/caps: stock DeviceFileMode + per-GPU mig dirs; tools: read compact __versions
This commit is contained in:
112
HANDOFF.md
112
HANDOFF.md
@ -346,6 +346,118 @@ Hardware approvals from the user (also in the assistant memory directory
|
||||
Never: sysfs/bridge resets of a GPU (this crashed the original driver and hung the machine);
|
||||
mmiotrace across a workload (oopses on page-crossing copies).
|
||||
|
||||
Second target host `10.1.1.200` (`msi-MS-7A20`, ssh user `msi`, repo `/home/msi/nvdriver`), recorded
|
||||
2026-12-02 11:30 UTC: one Tesla V100-PCIE-32GB (`0000:02:00.0`, PCI id `0x1db6`, admitted as
|
||||
`Route::Proprietary` in `src/nvidia/src/hardware/generated.rs:298`), kernel 7.0.0-44-generic,
|
||||
userspace 580.196.07, SecureBoot disabled (no MOK signing needed). It builds clean there:
|
||||
`make modules`, `uvm-bridge` (77/77 CRC), `modeset-bridge` (2/2 CRC), `check_kernel_module.py`
|
||||
`passed: true` (`largest_stack: 1000`; `ibt_gate_enforced: false` because this kernel has no
|
||||
`CONFIG_X86_KERNEL_IBT`, so that rule was skipped, not passed), `clippy -D warnings`,
|
||||
`cargo test --workspace`. The GV100 firmware pack is *not* derivable from this host's 580.196.07
|
||||
kernel object: `apt-get download nvidia-kernel-source-580=580.178.04-1ubuntu1` (NVIDIA CUDA repo)
|
||||
yields the exact pinned object (`5269a23f…`), and `tools/extract_gv100_firmware.py --family all`
|
||||
wrote `target/firmware/nvidia-rs/580.178.04/{gv100,gm20x,gp100,gp10x}.fw` (85/16/10/10 records),
|
||||
which `install.sh` copies into `/lib/firmware`.
|
||||
- **Installed 2026-12-02 11:36 UTC, files only (user chose not to stop Strata):** `sudo env
|
||||
SKIP_VOLTA_FOREVER=1 MODPROBE_ARGS="runtime_engines=1 pci_target= driver_version=580.196.07"
|
||||
./install.sh` exited 1 at the expected `tools/bind_dev_nodes.sh --bind` guard (*stock nvidia.ko
|
||||
is loaded; refusing to overwrite /dev/nvidia**); everything before it completed — 6 `.ko` in
|
||||
`/lib/modules/7.0.0-44-generic/updates/nvdriver/` (installed srcversion == built for all 6),
|
||||
4 `.fw` in `/lib/firmware/nvidia-rs/580.178.04/`, `/etc/modprobe.d/nvdriver.conf` (options line
|
||||
hand-edited afterwards to carry `driver_version=580.196.07`), `/etc/modules-load.d/nvdriver.conf`
|
||||
(3 modules), `/etc/udev/rules.d/70-nvdriver.rules`, `nvdriver-devnodes.service` enabled, and the
|
||||
`nvidia-cdi-refresh` `/dev/char` drop-in. The running system was left on stock 580.196.07 with
|
||||
Strata (31.6 GiB VRAM, 81.4 GB RSS) and ComfyUI untouched; `nvidia_rs.ko` was loaded once with
|
||||
`pci_target=` and removed (`dmesg`: `/dev/nvidia-rsctl protocol 2; GPU/CUDA unsupported`).
|
||||
- **Bridge load failure while the stock driver is live is expected, not a defect:**
|
||||
`nvidia_rs_uvm_bridge: exports duplicate symbol nvUvmInterfaceAddressSpaceCreate (owned by
|
||||
nvidia)` and `nvidia_rs_modeset_bridge: exports duplicate symbol nvidia_get_rm_ops (owned by
|
||||
nvidia)`; with `blacklist nvidia` + `install nvidia /bin/false` in effect from the next boot the
|
||||
symbols are free. The reboot is therefore the first real test of the bridge path.
|
||||
`/home/msi/nvdriver-install.sh` is the stop-and-release path for when the user accepts the
|
||||
Strata restart.
|
||||
- `tools/validate_all.sh` on this host: 27 PASS, `cargo test --workspace` 983 passed / 0 failed,
|
||||
`clippy -D warnings` clean. Its 2 FAILs (`initramfs`, `live`) were only `sudo: a password is
|
||||
required` from running detached, and 4 SKIPs are geodd03-only artifacts (`/home/geodd/...`).
|
||||
- `driver_version=` matters because the reported string defaults to 580.178.04
|
||||
(`kernel-open/nvidia/rmapi_node.c:314`); the firmware path constant is independent of it
|
||||
(`src/nvidia/kernel/firmware_pack.rs:10`). `nvidia_rs_modeset_bridge.ko` still hardcodes
|
||||
580.178.04 in `nvidia_get_rm_ops`, so 580.196.07 GL/modeset userspace will not pair with it
|
||||
(NVML/CUDA path unaffected).
|
||||
- **Rebooted 2026-12-02 11:45 UTC, takeover verified:** `0000:02:00.0` is bound to `nvidia_rs`;
|
||||
`nvidia_rs` + `nvidia_rs_uvm_bridge` + `nvidia_rs_modeset_bridge` all load (the duplicate-symbol
|
||||
ENOEXEC above disappears once the stock driver stays out); `/proc/driver/nvidia/version` reports
|
||||
`nvdriver (clean-room Rust) 580.196.07`; `nvdriver-devnodes.service` bind-mounts
|
||||
`/dev/nvidia{0,ctl,-uvm}` onto the `nvidia-rs-*` misc nodes; first-open bring-up runs
|
||||
(`bringup note 474f0004`, `streaming DMA mask raised to 47 bits`, `rt UVM cmd=0x4b rc=0`);
|
||||
`torch 2.14.1+cu126` hits 99 % utilisation on 8192-squared matmul loops with 33.6 GiB free.
|
||||
Taint 12289 (out-of-tree + unsigned), no oops.
|
||||
- **NVML blocker on a `nvidia_rs`-only host (root-caused; parity implemented; one gate left):**
|
||||
`nvidia-smi` fails with *GPU access blocked by the operating system* because libnvidia-ml runs
|
||||
`/usr/bin/nvidia-modprobe`, which REA (Ghidra, `FUN_00102730` calling `FUN_00104080`) shows is
|
||||
gated on `access("/sys/module/nvidia/initstate")` — a module literally named `nvidia`. Ours is
|
||||
`nvidia_rs` (the `distinct_diagnostic_module_name` gate forbids renaming it) and stock `nvidia.ko`
|
||||
cannot be loaded alongside (its `nvUvmInterface*` / `nvidia_get_rm_ops` exports collide with our
|
||||
bridges: *Exec format error*). The helper exits 1 before it ever reaches its capability path.
|
||||
- **Capability parity implemented in `kernel-open/nvidia/rmapi_node.c`** (stock `nv-caps.c` read
|
||||
from `nvidia-kernel-source-580.178.04` plus observation on a live 580.178.04 host): a chrdev
|
||||
region named `nvidia-caps` (8192 minors, open/release only) so `/proc/devices` lists the name the
|
||||
helper's `-s -f` path resolves; capability files reporting the stock table minors
|
||||
(`mig/config` 1 mode 256, `mig/monitor` 2 mode 292, `fabric-imex-mgmt` 4323 mode 256,
|
||||
`DeviceFileModify: 1`); `/proc/driver/nvidia-caps/{nvlink,sys,mig}-minors` (mig table = 4322
|
||||
lines); and `capabilities/gpu<idx>/mig` per GPU. All six files diff byte-for-byte against the
|
||||
stock host, and `make modules` + `check_kernel_module.py` stay green (`largest_stack: 1000`).
|
||||
On this host the helper still stops at the module gate, so `/usr/bin/nvidia-modprobe` is a
|
||||
`dpkg-divert`-wrapped copy that runs `.real` and reports success when `nvidia_rs` is loaded.
|
||||
- **`install.sh` is not safe to rerun while `nvidia_rs` is live:** its unload loop `rmmod`s
|
||||
`nvidia_rs_modeset_bridge` first, which frees the GPU's event entry and drops the per-GPU
|
||||
`/dev/nvidia-rs-rmapi-gpu0` node under running clients (`gv100 events: entry freed, its IRQ owner
|
||||
closed`), and it `umount`s the `/dev/nvidia*` bind mounts before the `rmmod nvidia_rs` that then
|
||||
aborts — leaving `/dev/nvidia0` bound to a deleted inode and NVML reporting *No supported GPUs
|
||||
were found*. Recovery: stop the GPU apps, `rmmod nvidia_rs`, `modprobe` again, re-run
|
||||
`tools/bind_dev_nodes.sh --bind`.
|
||||
- **NVML query-surface gaps seen here:** `clocks.max`, memory-clock samples, `power.draw` and
|
||||
`ecc.errors.aggregate.*` return *Unknown Error* or are not valid fields.
|
||||
- `v100_hbm_ndiv` defaults to **0** on this build, so the GV100 HBM unlock is off unless asked for.
|
||||
Writing `82` to `/sys/module/nvidia_rs/parameters/v100_hbm_ndiv` raised 877.5 -> 1107.0 MHz live
|
||||
(`GV100 HBM2 clock unlocked ... NDIV 65 -> 82`) with CUDA still correct, so the option was added
|
||||
to `/etc/modprobe.d/nvdriver.conf` on this host.
|
||||
|
||||
- **Aligned with upstream 2026-12-03 02:56 UTC:** this host's tree moved `627e607` -> `1345b1f` and
|
||||
the local duplicate caps implementation was dropped for upstream's `bc24624` plus a small delta,
|
||||
so both hosts now build the same source. Reinstall
|
||||
`sudo env SKIP_VOLTA_FOREVER=1 MODPROBE_ARGS="runtime_engines=1 pci_target=*
|
||||
driver_version=580.196.07 v100_hbm_ndiv=82" ./install.sh` exited **0** (`nvidia_rs` srcversion
|
||||
`A3EBFE182BB463DE4007B6F`, built == loaded, GPU bound, the three `/dev/nvidia*` bind mounts back,
|
||||
`clocks.mem` 1107 MHz, torch matmul ok). Upstream's `install.sh` now writes the options line from
|
||||
`MODPROBE_ARGS`, so those settings persist without a hand edit. Against the stock 580.178.04 host
|
||||
the capability surface now differs **only** in `DeviceFileModify` (stock 1, ours 0, matching our
|
||||
`ModifyDeviceFiles: 0` params line); `DeviceFileMinor`, `DeviceFileMode` and all three
|
||||
`nvidia-caps/*-minors` files are byte-identical. Reloading required stopping Strata: `install.sh`
|
||||
unbinds the GPU before `rmmod`, so a live client turns the rerun into
|
||||
`rmmod: Module nvidia_rs is in use` with the GPU left unbound; Strata was restarted afterwards
|
||||
from its recorded command line.
|
||||
|
||||
Second host `10.1.1.122` (`cloud`, ssh user `dee`, repo `/home/dee/nvdriver`), installed
|
||||
2026-12-03 02:50 UTC: one Tesla V100-SXM2-32GB (`0000:01:00.0`, PCI id `0x1db5`, admitted as
|
||||
`Route::Proprietary` in `src/nvidia/src/hardware/generated.rs:296`), kernel 6.8.0-151-generic,
|
||||
userspace 580.178.04 (the reference version, so no `driver_version=` override), SecureBoot
|
||||
disabled. `sudo env SKIP_VOLTA_FOREVER=1 ./install.sh` exited **0**: 6 `.ko` staged (`nvidia_rs`
|
||||
srcversion `A381906870D528F139DDAE3`, built == loaded), firmware extracted by the installer itself
|
||||
from `/usr/src/nvidia-srv-580.178.04/nvidia/nv-kernel.o_binary` (digest `5269a23f…`, `gv100.fw`
|
||||
`681b0cee…` — identical to the pack built on 10.1.1.200), plus modprobe.d, modules-load.d, the udev
|
||||
rule and `nvdriver-devnodes.service` enabled. Strata (31.7 GiB) was left running, so stock `nvidia`
|
||||
keeps the GPU and the takeover happens on the next boot; the current `install.sh` says so instead of
|
||||
aborting (*"stock nvidia is still loaded; /dev/nvidia* not bound now"*) — the behaviour that broke
|
||||
the 10.1.1.200 run above.
|
||||
- **The two conformance checkers could not read this kernel's stock modules:** Ubuntu's 6.8.0-151
|
||||
emits compact variable-length `__versions` records (`{u32 len; u32 crc; char name[]}`; 8417 bytes
|
||||
in `nvidia-uvm.ko`), while `modprobe --dump-modversions` (kmod 31) only understands the fixed
|
||||
72-byte layout, so it failed with *Invalid argument* and both bridge targets errored. Both
|
||||
checkers now read the section themselves (compact and classic) and pass: **76/76 UVM CRCs and 1/1
|
||||
modeset CRC match stock 580.178.04 exactly** — the strict path, because this host's userspace is
|
||||
the reference version.
|
||||
|
||||
## 4. State of the working tree (important)
|
||||
|
||||
### It validates again, with the channel slice parked (2026-11-24)
|
||||
|
||||
@ -489,6 +489,7 @@ struct nv_rs_rmapi_gpu_node {
|
||||
int minor_index;
|
||||
#ifdef CONFIG_PROC_FS
|
||||
struct proc_dir_entry *proc_dir;
|
||||
struct proc_dir_entry *caps_dir;
|
||||
#endif
|
||||
};
|
||||
static DECLARE_WAIT_QUEUE_HEAD(nv_rs_rmapi_owner_wq);
|
||||
@ -758,11 +759,20 @@ static int nv_rs_proc_version_show(struct seq_file *m, void *v)
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Stock 580.178.04 also reports the mode nvidia-modprobe must give the node: mig/monitor is
|
||||
* 292 (0444), every other capability 256 (0400). Without the line the helper falls back to its
|
||||
* 438 (0666) default. DeviceFileModify stays 0: nvdriver never creates or chmods a device file,
|
||||
* udev and tools/bind_dev_nodes.sh own the nodes (matching /proc/driver/nvidia/params). */
|
||||
#define NV_RS_CAP_MODE_DEFAULT 256u
|
||||
#define NV_RS_CAP_MODE_MONITOR 292u
|
||||
|
||||
static int nv_rs_proc_cap_show(struct seq_file *m, void *v)
|
||||
{
|
||||
unsigned int minor = (unsigned int)(uintptr_t)m->private;
|
||||
unsigned int mode = minor == NV_RS_CAP_MINOR_MIG_MONITOR ? NV_RS_CAP_MODE_MONITOR
|
||||
: NV_RS_CAP_MODE_DEFAULT;
|
||||
(void)v;
|
||||
seq_printf(m, "DeviceFileMinor: %u\nDeviceFileModify: 0\n", minor);
|
||||
seq_printf(m, "DeviceFileMinor: %u\nDeviceFileMode: %u\nDeviceFileModify: 0\n", minor, mode);
|
||||
return 0;
|
||||
}
|
||||
|
||||
@ -2981,6 +2991,17 @@ int nv_rs_rmapi_node_gpu_add(struct pci_dev *pdev, u32 boot0)
|
||||
nv_rs_proc_gpu_registry_show, node);
|
||||
}
|
||||
}
|
||||
/* Stock creates capabilities/gpu<minor>/mig for every GPU; the gi/ci files appear only
|
||||
* once MIG is enabled, which no Volta can do. Its own tree, so a failed gpus/ directory
|
||||
* must not skip it. */
|
||||
if (nv_rs_proc_caps) {
|
||||
char caps_name[16];
|
||||
|
||||
snprintf(caps_name, sizeof(caps_name), "gpu%d", node->minor_index);
|
||||
node->caps_dir = proc_mkdir(caps_name, nv_rs_proc_caps);
|
||||
if (node->caps_dir)
|
||||
proc_mkdir("mig", node->caps_dir);
|
||||
}
|
||||
#endif
|
||||
return minor;
|
||||
}
|
||||
@ -3092,6 +3113,9 @@ void nv_rs_rmapi_node_gpu_remove(struct pci_dev *pdev)
|
||||
void (*release)(void *cookie) = NULL;
|
||||
void *cookie = NULL;
|
||||
struct nv_rs_gpu_owner *owner = NULL;
|
||||
#ifdef CONFIG_PROC_FS
|
||||
struct proc_dir_entry *caps_dir = NULL;
|
||||
#endif
|
||||
int minor;
|
||||
if (!nv_rs_rmapi_state)
|
||||
return;
|
||||
@ -3114,6 +3138,12 @@ void nv_rs_rmapi_node_gpu_remove(struct pci_dev *pdev)
|
||||
nv_rs_rmapi_gpu_nodes[minor].read32 = NULL;
|
||||
nv_rs_rmapi_gpu_nodes[minor].release = NULL;
|
||||
nv_rs_rmapi_gpu_nodes[minor].cookie = NULL;
|
||||
#ifdef CONFIG_PROC_FS
|
||||
/* Taken with the lock: a replacement GPU may already own this minor by the time the
|
||||
* proc entry goes away, so never read the slot back after dropping the lock. */
|
||||
caps_dir = nv_rs_rmapi_gpu_nodes[minor].caps_dir;
|
||||
nv_rs_rmapi_gpu_nodes[minor].caps_dir = NULL;
|
||||
#endif
|
||||
} else {
|
||||
minor = -1;
|
||||
}
|
||||
@ -3130,6 +3160,8 @@ void nv_rs_rmapi_node_gpu_remove(struct pci_dev *pdev)
|
||||
proc_remove(nv_rs_rmapi_gpu_nodes[minor].proc_dir);
|
||||
nv_rs_rmapi_gpu_nodes[minor].proc_dir = NULL;
|
||||
}
|
||||
if (caps_dir)
|
||||
proc_remove(caps_dir);
|
||||
#endif
|
||||
misc_deregister(&nv_rs_rmapi_gpu_nodes[minor].misc);
|
||||
}
|
||||
|
||||
@ -3,6 +3,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
@ -146,13 +147,99 @@ class TestSymbolConformance(unittest.TestCase):
|
||||
)
|
||||
for mod in (uvm_check, ms_check):
|
||||
err_buf = io.StringIO()
|
||||
with mock.patch.object(mod.subprocess, "run", return_value=fake_fail):
|
||||
with mock.patch.object(mod, "has_modversions_section", return_value=True):
|
||||
with redirect_stderr(err_buf):
|
||||
with self.assertRaises(subprocess.CalledProcessError):
|
||||
mod.parse_modversions(Path("/fake.ko"))
|
||||
with (
|
||||
mock.patch.object(mod.subprocess, "run", return_value=fake_fail),
|
||||
mock.patch.object(mod, "has_modversions_section", return_value=True),
|
||||
mock.patch.object(mod, "read_section_bytes", return_value=None),
|
||||
redirect_stderr(err_buf),
|
||||
):
|
||||
with self.assertRaises(subprocess.CalledProcessError):
|
||||
mod.parse_modversions(Path("/fake.ko"))
|
||||
self.assertIn("malformed __versions section", err_buf.getvalue())
|
||||
|
||||
def test_parse_versions_section_compact_classic_padding_and_truncated(self) -> None:
|
||||
def pack_compact(entries: list[tuple[int, bytes]], trailing_zeros: int = 0) -> bytes:
|
||||
chunks = []
|
||||
for crc, name in entries:
|
||||
# 8-byte header + NUL-terminated name padded to 4-byte boundary.
|
||||
raw_name = name + b"\x00"
|
||||
rec_len = (8 + len(raw_name) + 3) & ~3
|
||||
chunks.append(struct.pack("<II", rec_len, crc) + raw_name.ljust(rec_len - 8, b"\x00"))
|
||||
return b"".join(chunks) + (b"\x00" * trailing_zeros)
|
||||
|
||||
def pack_classic(entries: list[tuple[int, bytes]], trailing_zeros: int = 0) -> bytes:
|
||||
ulong_sz = struct.calcsize("N")
|
||||
chunks = []
|
||||
for crc, name in entries:
|
||||
chunks.append(crc.to_bytes(ulong_sz, "little") + name.ljust(64 - ulong_sz, b"\x00"))
|
||||
return b"".join(chunks) + (b"\x00" * trailing_zeros)
|
||||
|
||||
expected = {
|
||||
"module_layout": "0x12345678",
|
||||
"nvUvmInterfaceSessionCreate": "0xabcdef01",
|
||||
"nvidia_get_rm_ops": "0x00fedcba",
|
||||
}
|
||||
entries = [
|
||||
(0x12345678, b"module_layout"),
|
||||
(0xABCDEF01, b"nvUvmInterfaceSessionCreate"),
|
||||
(0x00FEDCBA, b"nvidia_get_rm_ops"),
|
||||
]
|
||||
compact_blob = pack_compact(entries, trailing_zeros=16)
|
||||
classic_blob = pack_classic(entries, trailing_zeros=64)
|
||||
# Truncated compact record (declares length 32 but only 12 bytes remain) + < 64 bytes total.
|
||||
truncated_blob = struct.pack("<II", 32, 0x11223344) + b"short"
|
||||
|
||||
for mod in (uvm_check, ms_check):
|
||||
self.assertEqual(mod.parse_versions_section(compact_blob), expected)
|
||||
self.assertEqual(mod.parse_versions_section(classic_blob), expected)
|
||||
self.assertEqual(mod.parse_versions_section(truncated_blob), {})
|
||||
self.assertEqual(mod.parse_versions_section(b"\x00" * 16), {})
|
||||
|
||||
def test_parse_modversions_falls_back_to_compact_elf_section_on_modprobe_einval(self) -> None:
|
||||
# Build a real ELF object containing a compact __versions section with 2 records + zero padding.
|
||||
def compact_bytes(crc: int, name: str) -> bytes:
|
||||
raw = name.encode("ascii") + b"\x00"
|
||||
rec_len = (8 + len(raw) + 3) & ~3
|
||||
return struct.pack("<II", rec_len, crc) + raw.ljust(rec_len - 8, b"\x00")
|
||||
|
||||
blob = (
|
||||
compact_bytes(0xDEADBEEF, "nvidia_get_rm_ops")
|
||||
+ compact_bytes(0x01020304, "nvUvmInterfaceSessionCreate")
|
||||
+ b"\x00" * 8
|
||||
)
|
||||
asm_bytes = ", ".join(f"0x{b:02x}" for b in blob)
|
||||
fake_einval = subprocess.CompletedProcess(
|
||||
args=["modprobe", "--dump-modversions", "/fake.ko"],
|
||||
returncode=1,
|
||||
stdout="",
|
||||
stderr="modprobe: ERROR: could not dump modversions: Invalid argument\n",
|
||||
)
|
||||
with tempfile.TemporaryDirectory(prefix="nvrs-compact-modver-") as tmpdir:
|
||||
src = Path(tmpdir) / "compact.s"
|
||||
obj = Path(tmpdir) / "compact.ko"
|
||||
src.write_text(
|
||||
".text\n.globl dummy\ndummy:\n ret\n"
|
||||
f'.section __versions,"a"\n.byte {asm_bytes}\n'
|
||||
)
|
||||
subprocess.check_call(["as", "-o", str(obj), str(src)])
|
||||
for mod in (uvm_check, ms_check):
|
||||
real_run = mod.subprocess.run
|
||||
|
||||
def fake_run(cmd, *args, _real=real_run, **kwargs):
|
||||
if cmd and Path(cmd[0]).name == "modprobe":
|
||||
return fake_einval
|
||||
return _real(cmd, *args, **kwargs)
|
||||
|
||||
with mock.patch.object(mod.subprocess, "run", side_effect=fake_run):
|
||||
parsed = mod.parse_modversions(obj)
|
||||
self.assertEqual(
|
||||
parsed,
|
||||
{
|
||||
"nvidia_get_rm_ops": "0xdeadbeef",
|
||||
"nvUvmInterfaceSessionCreate": "0x01020304",
|
||||
},
|
||||
)
|
||||
|
||||
def test_parse_modversions_detects_extended_modversions_sections_in_real_elf(self) -> None:
|
||||
cases = (
|
||||
(
|
||||
|
||||
@ -23,6 +23,7 @@ import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
@ -106,6 +107,68 @@ def read_reference_driver_version(path: Path = VERSION_MK) -> str:
|
||||
return ""
|
||||
|
||||
|
||||
_SYMBOL_NAME_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_.]*$")
|
||||
|
||||
|
||||
# struct modversion_info { unsigned long crc; char name[MODULE_NAME_LEN - sizeof(unsigned long)]; }
|
||||
_MODULE_NAME_LEN = 64
|
||||
_ULONG_SIZE = struct.calcsize("N")
|
||||
# GNU readelf pads the bracketed index ("[ 5]"), so match the row instead of splitting it.
|
||||
_SECTION_ROW_RE = re.compile(r"^\s*\[\s*\d+\]\s+(\S+)\s+\S+\s+\S+\s+(\S+)\s+(\S+)")
|
||||
|
||||
|
||||
def read_section_bytes(ko: Path, section: str) -> bytes | None:
|
||||
"""Raw bytes of an ELF section, or None when the section is absent."""
|
||||
for line in run("readelf", "-SW", str(ko)).splitlines():
|
||||
match = _SECTION_ROW_RE.match(line)
|
||||
if match and match.group(1) == section:
|
||||
offset, size = int(match.group(2), 16), int(match.group(3), 16)
|
||||
return ko.read_bytes()[offset : offset + size]
|
||||
return None
|
||||
|
||||
|
||||
def _parse_compact_versions(data: bytes) -> dict[str, str] | None:
|
||||
"""Variable-length {u32 len; u32 crc; char name[]} records, or None if absent."""
|
||||
out: dict[str, str] = {}
|
||||
offset = 0
|
||||
while offset < len(data):
|
||||
if data[offset:] == b"\0" * (len(data) - offset):
|
||||
break
|
||||
if offset + 8 > len(data):
|
||||
return None
|
||||
length, crc = struct.unpack_from("<II", data, offset)
|
||||
if length < 9 or offset + length > len(data):
|
||||
return None
|
||||
name = data[offset + 8 : offset + length].split(b"\0")[0].decode("ascii", "replace")
|
||||
if not _SYMBOL_NAME_RE.match(name):
|
||||
return None
|
||||
out[name] = f"0x{crc:08x}"
|
||||
offset += length
|
||||
return out or None
|
||||
|
||||
|
||||
def parse_versions_section(data: bytes) -> dict[str, str]:
|
||||
"""symbol -> CRC from a __versions section.
|
||||
|
||||
`modprobe --dump-modversions` only understands the fixed-layout records older kernels
|
||||
emit: struct modversion_info is MODULE_NAME_LEN bytes, an unsigned long CRC followed by
|
||||
the name padded to the rest. Kernels that moved to compact records store variable-length
|
||||
{u32 len; u32 crc; char name[]} entries and kmod rejects the whole section with EINVAL,
|
||||
so read both layouts here.
|
||||
"""
|
||||
compact = _parse_compact_versions(data)
|
||||
if compact is not None:
|
||||
return compact
|
||||
out: dict[str, str] = {}
|
||||
for index in range(0, len(data) - len(data) % _MODULE_NAME_LEN, _MODULE_NAME_LEN):
|
||||
crc = int.from_bytes(data[index : index + _ULONG_SIZE], "little") & 0xFFFFFFFF
|
||||
name = data[index + _ULONG_SIZE : index + _MODULE_NAME_LEN]
|
||||
name = name.split(b"\0")[0].decode("ascii", "replace")
|
||||
if name:
|
||||
out[name] = f"0x{crc:08x}"
|
||||
return out
|
||||
|
||||
|
||||
def parse_modversions(path: Path) -> dict[str, str] | None:
|
||||
"""Return symbol -> CRC mapping from __versions, or None if CONFIG_MODVERSIONS is off."""
|
||||
out: dict[str, str] = {}
|
||||
@ -119,6 +182,10 @@ def parse_modversions(path: Path) -> dict[str, str] | None:
|
||||
if proc.returncode != 0:
|
||||
if not has_modversions_section(ko):
|
||||
return None
|
||||
section = read_section_bytes(ko, "__versions")
|
||||
parsed = parse_versions_section(section) if section else {}
|
||||
if parsed:
|
||||
return parsed
|
||||
if proc.stderr:
|
||||
print(proc.stderr, file=sys.stderr, end="")
|
||||
raise subprocess.CalledProcessError(
|
||||
|
||||
@ -19,6 +19,7 @@ import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
@ -100,6 +101,68 @@ def read_reference_driver_version(path: Path = VERSION_MK) -> str:
|
||||
return ""
|
||||
|
||||
|
||||
_SYMBOL_NAME_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_.]*$")
|
||||
|
||||
|
||||
# struct modversion_info { unsigned long crc; char name[MODULE_NAME_LEN - sizeof(unsigned long)]; }
|
||||
_MODULE_NAME_LEN = 64
|
||||
_ULONG_SIZE = struct.calcsize("N")
|
||||
# GNU readelf pads the bracketed index ("[ 5]"), so match the row instead of splitting it.
|
||||
_SECTION_ROW_RE = re.compile(r"^\s*\[\s*\d+\]\s+(\S+)\s+\S+\s+\S+\s+(\S+)\s+(\S+)")
|
||||
|
||||
|
||||
def read_section_bytes(ko: Path, section: str) -> bytes | None:
|
||||
"""Raw bytes of an ELF section, or None when the section is absent."""
|
||||
for line in run("readelf", "-SW", str(ko)).splitlines():
|
||||
match = _SECTION_ROW_RE.match(line)
|
||||
if match and match.group(1) == section:
|
||||
offset, size = int(match.group(2), 16), int(match.group(3), 16)
|
||||
return ko.read_bytes()[offset : offset + size]
|
||||
return None
|
||||
|
||||
|
||||
def _parse_compact_versions(data: bytes) -> dict[str, str] | None:
|
||||
"""Variable-length {u32 len; u32 crc; char name[]} records, or None if absent."""
|
||||
out: dict[str, str] = {}
|
||||
offset = 0
|
||||
while offset < len(data):
|
||||
if data[offset:] == b"\0" * (len(data) - offset):
|
||||
break
|
||||
if offset + 8 > len(data):
|
||||
return None
|
||||
length, crc = struct.unpack_from("<II", data, offset)
|
||||
if length < 9 or offset + length > len(data):
|
||||
return None
|
||||
name = data[offset + 8 : offset + length].split(b"\0")[0].decode("ascii", "replace")
|
||||
if not _SYMBOL_NAME_RE.match(name):
|
||||
return None
|
||||
out[name] = f"0x{crc:08x}"
|
||||
offset += length
|
||||
return out or None
|
||||
|
||||
|
||||
def parse_versions_section(data: bytes) -> dict[str, str]:
|
||||
"""symbol -> CRC from a __versions section.
|
||||
|
||||
`modprobe --dump-modversions` only understands the fixed-layout records older kernels
|
||||
emit: struct modversion_info is MODULE_NAME_LEN bytes, an unsigned long CRC followed by
|
||||
the name padded to the rest. Kernels that moved to compact records store variable-length
|
||||
{u32 len; u32 crc; char name[]} entries and kmod rejects the whole section with EINVAL,
|
||||
so read both layouts here.
|
||||
"""
|
||||
compact = _parse_compact_versions(data)
|
||||
if compact is not None:
|
||||
return compact
|
||||
out: dict[str, str] = {}
|
||||
for index in range(0, len(data) - len(data) % _MODULE_NAME_LEN, _MODULE_NAME_LEN):
|
||||
crc = int.from_bytes(data[index : index + _ULONG_SIZE], "little") & 0xFFFFFFFF
|
||||
name = data[index + _ULONG_SIZE : index + _MODULE_NAME_LEN]
|
||||
name = name.split(b"\0")[0].decode("ascii", "replace")
|
||||
if name:
|
||||
out[name] = f"0x{crc:08x}"
|
||||
return out
|
||||
|
||||
|
||||
def parse_modversions(path: Path) -> dict[str, str] | None:
|
||||
"""Return symbol -> CRC mapping from __versions, or None if CONFIG_MODVERSIONS is off."""
|
||||
out: dict[str, str] = {}
|
||||
@ -113,6 +176,10 @@ def parse_modversions(path: Path) -> dict[str, str] | None:
|
||||
if proc.returncode != 0:
|
||||
if not has_modversions_section(ko):
|
||||
return None
|
||||
section = read_section_bytes(ko, "__versions")
|
||||
parsed = parse_versions_section(section) if section else {}
|
||||
if parsed:
|
||||
return parsed
|
||||
if proc.stderr:
|
||||
print(proc.stderr, file=sys.stderr, end="")
|
||||
raise subprocess.CalledProcessError(
|
||||
|
||||
Reference in New Issue
Block a user