[AI generated] Linux process rename corrupts memory and thread counts
Describe the bug
On Linux, a process that changes its name after btop first samples it can acquire a fictitious memory usage and thread count. A small process can appear to use tens of GiB without allocating more memory. Restarting btop clears the incorrect values.
The trigger is a change in the number of spaces in the process name. This affects the process statistics, beyond the stale display name discussed in #318.
To reproduce
Run this Python program in one terminal:
import ctypes
import os
libc = ctypes.CDLL(None, use_errno=True)
def rename(name):
if libc.prctl(15, ctypes.c_char_p(name), 0, 0, 0) != 0:
raise OSError(ctypes.get_errno(), "PR_SET_NAME failed")
rename(b"statworker")
print(f"PID: {os.getpid()}", flush=True)
input("Start btop, find statworker, wait for a sample, then press Enter: ")
rename(b"worker exec job")
input("Observe its memory and thread count in btop; Enter restores the name: ")
rename(b"statworker")
input("Observe the restored values; Enter exits: ")In another terminal, run btop --filter statworker. Enable memory values in bytes if needed. Compare the displayed values with /proc/PID/status or ps -p PID -o rss,nlwp before and after the rename.
In a live reproduction against the current upstream code, btop displayed 11M / 1 thread, then 36G / 20 threads after the rename. Kernel RSS stayed at 11,620 KiB with one thread. Restoring the original name restored the correct display. The fictitious memory value depends on process start time and system uptime.
Expected behavior
Renaming a process must not change which numeric fields btop reads. Memory usage, thread count, state, nice value, and CPU accounting should remain correct.
Environment
- btop 1.4.7, Fedora package; also reproduced with a release build of upstream commit
612e18f5bd598fe987b30d041b39e5d7b3e0794f. - Linux, x86_64, Fedora 44.
- Reproduced in an isolated pseudo-terminal; no particular terminal emulator or font is required.
Cause and proposed fix
The Linux collector caches name_offset from /proc/PID/comm when a PID is first seen, then reuses it to tokenize subsequent /proc/PID/stat reads. If the name gains two spaces, the RSS field is read from field 22 (start time) instead of field 24. Multiplying that value by page size produces the fictitious allocation. The same shift reads the priority field as the thread count.
A rename between the initial comm and stat reads can also corrupt the first sample. Parse past the final closing parenthesis of the name in the same stat record instead of relying on the cached offset. The name itself may contain spaces, parentheses, or newlines.
A targeted fix and regression tests are prepared. The patched build retains the correct values throughout the same live reproduction.
Source: aristocratos/btop