libzfs: run_process: reuse line, don't leak it

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 <john.kennedy@delphix.com>
Reviewed-by: Brian Behlendorf <behlendorf1@llnl.gov>
Signed-off-by: Ahelenia Ziemiańska <nabijaczleweli@nabijaczleweli.xyz>
Closes #12082
This commit is contained in:
наб 2021-05-19 14:04:19 +02:00 committed by Brian Behlendorf
parent 30dadd5c04
commit 7c20ceebdd

View File

@ -847,17 +847,11 @@ libzfs_read_stdout_from_fd(int fd, char **lines[])
size_t len = 0; size_t len = 0;
char *line = NULL; char *line = NULL;
char **tmp_lines = NULL, **tmp; char **tmp_lines = NULL, **tmp;
char *nl = NULL;
int rc;
fp = fdopen(fd, "r"); fp = fdopen(fd, "r");
if (fp == NULL) if (fp == NULL)
return (0); return (0);
while (1) { while (getline(&line, &len, fp) != -1) {
rc = getline(&line, &len, fp);
if (rc == -1)
break;
tmp = realloc(tmp_lines, sizeof (*tmp_lines) * (lines_cnt + 1)); tmp = realloc(tmp_lines, sizeof (*tmp_lines) * (lines_cnt + 1));
if (tmp == NULL) { if (tmp == NULL) {
/* Return the lines we were able to process */ /* Return the lines we were able to process */
@ -865,13 +859,16 @@ libzfs_read_stdout_from_fd(int fd, char **lines[])
} }
tmp_lines = tmp; tmp_lines = tmp;
/* Terminate newlines */ /* Remove newline if not EOF */
if ((nl = strchr(line, '\n')) != NULL) if (line[strlen(line) - 1] == '\n')
*nl = '\0'; line[strlen(line) - 1] = '\0';
tmp_lines[lines_cnt] = line;
lines_cnt++; tmp_lines[lines_cnt] = strdup(line);
line = NULL; if (tmp_lines[lines_cnt] == NULL)
break;
++lines_cnt;
} }
free(line);
fclose(fp); fclose(fp);
*lines = tmp_lines; *lines = tmp_lines;
return (lines_cnt); return (lines_cnt);