From 874350d2a148c1f23cd6cc67c568d5d9ade13207 Mon Sep 17 00:00:00 2001 From: truckman Date: Wed, 1 Jun 2016 17:47:34 +0000 Subject: [PATCH] MFC r300692 Close the input FILE * in read_file() and the output FILE * in write_file() if read_stream() or write_stream() fails to avoid leaking the FILE. Reported by: Coverity CID: 977702 Reviewed by: pfg Differential Revision: https://reviews.freebsd.org/D6554 git-svn-id: svn://svn.freebsd.org/base/stable/10@301155 ccf9f872-aa2e-dd11-9fc8-001c23d0bc1f --- bin/ed/io.c | 27 ++++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/bin/ed/io.c b/bin/ed/io.c index cf2e95906..1907e7a95 100644 --- a/bin/ed/io.c +++ b/bin/ed/io.c @@ -36,20 +36,24 @@ read_file(char *fn, long n) { FILE *fp; long size; - + int cs; fp = (*fn == '!') ? popen(fn + 1, "r") : fopen(strip_escapes(fn), "r"); if (fp == NULL) { fprintf(stderr, "%s: %s\n", fn, strerror(errno)); errmsg = "cannot open input file"; return ERR; - } else if ((size = read_stream(fp, n)) < 0) - return ERR; - else if (((*fn == '!') ? pclose(fp) : fclose(fp)) < 0) { + } + if ((size = read_stream(fp, n)) < 0) { + fprintf(stderr, "%s: %s\n", fn, strerror(errno)); + errmsg = "error reading input file"; + } + if ((cs = (*fn == '!') ? pclose(fp) : fclose(fp)) < 0) { fprintf(stderr, "%s: %s\n", fn, strerror(errno)); errmsg = "cannot close input file"; - return ERR; } + if (size < 0 || cs < 0) + return ERR; if (!scripted) fprintf(stdout, "%lu\n", size); return current_addr - n; @@ -143,19 +147,24 @@ write_file(char *fn, const char *mode, long n, long m) { FILE *fp; long size; + int cs; fp = (*fn == '!') ? popen(fn+1, "w") : fopen(strip_escapes(fn), mode); if (fp == NULL) { fprintf(stderr, "%s: %s\n", fn, strerror(errno)); errmsg = "cannot open output file"; return ERR; - } else if ((size = write_stream(fp, n, m)) < 0) - return ERR; - else if (((*fn == '!') ? pclose(fp) : fclose(fp)) < 0) { + } + if ((size = write_stream(fp, n, m)) < 0) { + fprintf(stderr, "%s: %s\n", fn, strerror(errno)); + errmsg = "error writing output file"; + } + if ((cs = (*fn == '!') ? pclose(fp) : fclose(fp)) < 0) { fprintf(stderr, "%s: %s\n", fn, strerror(errno)); errmsg = "cannot close output file"; - return ERR; } + if (size < 0 || cs < 0) + return ERR; if (!scripted) fprintf(stdout, "%lu\n", size); return n ? m - n + 1 : 0; -- 2.45.0