Skip to content

Commit 20a17dd

Browse files
acmelgregkh
authored andcommitted
tools lib api: Fix missing null termination in filename__read_int/ull()
[ Upstream commit 52b1f96 ] filename__read_int() passes a stack buffer to read() using the full sizeof(line) and then hands it to atoi() without null-terminating. If a sysfs file fills the 64-byte buffer exactly, atoi() reads past the array into uninitialized stack memory. filename__read_ull_base() has the same issue with strtoull(). Fix both by reading sizeof(line) - 1 bytes and explicitly null-terminating after a successful read. Fixes: 3a35112 ("tools lib fs: Adopt filename__read_int from tools/perf/") 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> Signed-off-by: Sasha Levin <sashal@kernel.org>
1 parent 05457b1 commit 20a17dd

1 file changed

Lines changed: 8 additions & 2 deletions

File tree

  • tools/lib/api/fs

tools/lib/api/fs/fs.c

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -293,11 +293,14 @@ int filename__read_int(const char *filename, int *value)
293293
{
294294
char line[64];
295295
int fd = open(filename, O_RDONLY), err = -1;
296+
ssize_t n;
296297

297298
if (fd < 0)
298299
return -1;
299300

300-
if (read(fd, line, sizeof(line)) > 0) {
301+
n = read(fd, line, sizeof(line) - 1);
302+
if (n > 0) {
303+
line[n] = '\0';
301304
*value = atoi(line);
302305
err = 0;
303306
}
@@ -311,11 +314,14 @@ static int filename__read_ull_base(const char *filename,
311314
{
312315
char line[64];
313316
int fd = open(filename, O_RDONLY), err = -1;
317+
ssize_t n;
314318

315319
if (fd < 0)
316320
return -1;
317321

318-
if (read(fd, line, sizeof(line)) > 0) {
322+
n = read(fd, line, sizeof(line) - 1);
323+
if (n > 0) {
324+
line[n] = '\0';
319325
*value = strtoull(line, NULL, base);
320326
if (*value != ULLONG_MAX)
321327
err = 0;

0 commit comments

Comments
 (0)