]> git.ipfire.org Git - thirdparty/kernel/linux.git/commitdiff
perf tools: Fix thread__set_comm_from_proc() on empty comm file
authorArnaldo Carvalho de Melo <acme@redhat.com>
Mon, 8 Jun 2026 01:37:55 +0000 (22:37 -0300)
committerArnaldo Carvalho de Melo <acme@redhat.com>
Wed, 10 Jun 2026 21:56:01 +0000 (18:56 -0300)
thread__set_comm_from_proc() calls procfs__read_str() then strips
the trailing newline via comm[sz - 1] = '\0'.  procfs__read_str()
allocates the buffer before reading, so on an empty /proc/pid/comm
(reachable during late exit teardown) it returns success with sz = 0
and an unterminated heap buffer.

The sz - 1 underflow was the original sashiko finding: it writes a
null byte before the allocation.  But even with a sz > 0 guard on
the newline strip, the unterminated buffer would still be passed to
thread__set_comm() which calls strlen() — an unbounded heap read.

Fix by treating sz == 0 as failure: free the buffer and return -1.
This is consistent with pmu.c's perf_pmu__parse_scale/unit which
already treat len == 0 from filename__read_str as an error.

Fixes: 2f3027ac28bf6bc3 ("perf thread: Introduce method to set comm from /proc/pid/self")
Reported-by: sashiko-bot <sashiko-bot@kernel.org>
Assisted-by: Claude:claude-opus-4.6
Signed-off-by: Arnaldo Carvalho de Melo <acme@redhat.com>
tools/perf/util/thread.c

index ba33c0dfc18fe2427f1f8bbd6b001aea65df8ed8..e483ffcb5d937fbce3b54382e2b332a2d5c5ca53 100644 (file)
@@ -295,6 +295,11 @@ int thread__set_comm_from_proc(struct thread *thread)
        if (!(snprintf(path, sizeof(path), "%d/task/%d/comm",
                       thread__pid(thread), thread__tid(thread)) >= (int)sizeof(path)) &&
            procfs__read_str(path, &comm, &sz) == 0) {
+               /* sz==0: read got nothing, e.g. race during exit teardown */
+               if (sz == 0) {
+                       free(comm);
+                       return -1;
+               }
                comm[sz - 1] = '\0';
                err = thread__set_comm(thread, comm, 0);
        }