From 7c20ceebdd9ca7ad30dd8035c5550875fd71d0cc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=BD=D0=B0=D0=B1?= Date: Wed, 19 May 2021 14:04:19 +0200 Subject: [PATCH] libzfs: run_process: reuse line, don't leak it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit line will grow as wide as it needs (glibc starts off at 120), we can store a narrower view; this also fixes leaks in a few scenarios Reviewed-by: John Kennedy Reviewed-by: Brian Behlendorf Signed-off-by: Ahelenia ZiemiaƄska Closes #12082 --- lib/libzfs/libzfs_util.c | 23 ++++++++++------------- 1 file changed, 10 insertions(+), 13 deletions(-) diff --git a/lib/libzfs/libzfs_util.c b/lib/libzfs/libzfs_util.c index d348bf8f5..0fffbaaf7 100644 --- a/lib/libzfs/libzfs_util.c +++ b/lib/libzfs/libzfs_util.c @@ -847,17 +847,11 @@ libzfs_read_stdout_from_fd(int fd, char **lines[]) size_t len = 0; char *line = NULL; char **tmp_lines = NULL, **tmp; - char *nl = NULL; - int rc; fp = fdopen(fd, "r"); if (fp == NULL) return (0); - while (1) { - rc = getline(&line, &len, fp); - if (rc == -1) - break; - + while (getline(&line, &len, fp) != -1) { tmp = realloc(tmp_lines, sizeof (*tmp_lines) * (lines_cnt + 1)); if (tmp == NULL) { /* Return the lines we were able to process */ @@ -865,13 +859,16 @@ libzfs_read_stdout_from_fd(int fd, char **lines[]) } tmp_lines = tmp; - /* Terminate newlines */ - if ((nl = strchr(line, '\n')) != NULL) - *nl = '\0'; - tmp_lines[lines_cnt] = line; - lines_cnt++; - line = NULL; + /* Remove newline if not EOF */ + if (line[strlen(line) - 1] == '\n') + line[strlen(line) - 1] = '\0'; + + tmp_lines[lines_cnt] = strdup(line); + if (tmp_lines[lines_cnt] == NULL) + break; + ++lines_cnt; } + free(line); fclose(fp); *lines = tmp_lines; return (lines_cnt);