From cca9d5ee9ddde2ffe7cac0d043e1f9449b1f2039 Mon Sep 17 00:00:00 2001 From: cheloha Date: Tue, 16 Nov 2021 23:34:24 +0000 Subject: [PATCH] wc(1): fix NULL pointer dereference in cnt() If the "file" argument to cnt() is NULL and we call warn(3) we will get a NULL dereference. Change the name of the argument to "path" and make "file" a local variable. Ensure that we set "file" to a valid C-string, even if "path" is NULL. While we're here, const the file name pointers, too. Thread: https://marc.info/?l=openbsd-tech&m=163708784422157&w=2 ok millert@ --- usr.bin/wc/wc.c | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/usr.bin/wc/wc.c b/usr.bin/wc/wc.c index a0f6ce45db2..8a3c4c1cd57 100644 --- a/usr.bin/wc/wc.c +++ b/usr.bin/wc/wc.c @@ -1,4 +1,4 @@ -/* $OpenBSD: wc.c,v 1.27 2021/10/24 21:24:18 deraadt Exp $ */ +/* $OpenBSD: wc.c,v 1.28 2021/11/16 23:34:24 cheloha Exp $ */ /* * Copyright (c) 1980, 1987, 1991, 1993 @@ -48,9 +48,9 @@ int doline, doword, dochar, humanchar, multibyte; int rval; extern char *__progname; -static void print_counts(int64_t, int64_t, int64_t, char *); +static void print_counts(int64_t, int64_t, int64_t, const char *); static void format_and_print(int64_t); -static void cnt(char *); +static void cnt(const char *); int main(int argc, char *argv[]) @@ -115,12 +115,13 @@ main(int argc, char *argv[]) } static void -cnt(char *file) +cnt(const char *path) { static char *buf; static size_t bufsz; FILE *stream; + const char *file; char *C; wchar_t wc; short gotsp; @@ -131,13 +132,15 @@ cnt(char *file) linect = wordct = charct = 0; stream = NULL; - if (file) { + if (path != NULL) { + file = path; if ((fd = open(file, O_RDONLY)) == -1) { warn("%s", file); rval = 1; return; } } else { + file = "(stdin)"; fd = STDIN_FILENO; } @@ -191,7 +194,7 @@ cnt(char *file) } } } else { - if (file == NULL) + if (path == NULL) stream = stdin; else if ((stream = fdopen(fd, "r")) == NULL) { warn("%s", file); @@ -249,7 +252,7 @@ cnt(char *file) } } - print_counts(linect, wordct, charct, file); + print_counts(linect, wordct, charct, path); /* * Don't bother checking doline, doword, or dochar -- speeds @@ -279,7 +282,7 @@ format_and_print(int64_t v) } static void -print_counts(int64_t lines, int64_t words, int64_t chars, char *name) +print_counts(int64_t lines, int64_t words, int64_t chars, const char *name) { if (doline) format_and_print(lines); -- 2.20.1