>From 34b6b3c88d3c25562641ca9ed107ba93f08158b0 Mon Sep 17 00:00:00 2001 From: Paul Eggert Date: Sun, 21 Aug 2016 23:22:35 -0700 Subject: [PATCH] grep: minor tweaks of initial buffer alloc * src/grep.c (main): Allocate input buffer only when about to do I/O. Avoid int overflow on systems with 2 GiB pages. Fix size_t overflow check. --- src/grep.c | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/src/grep.c b/src/grep.c index 63487d6..0c84b2a 100644 --- a/src/grep.c +++ b/src/grep.c @@ -2320,12 +2320,6 @@ main (int argc, char **argv) set_program_name (argv[0]); program_name = argv[0]; - pagesize = getpagesize (); - if (pagesize == 0 || 2 * pagesize + 1 <= pagesize) - abort (); - bufalloc = (ALIGN_TO (INITIAL_BUFSIZE, pagesize) + pagesize + sizeof (uword)); - buffer = xmalloc (bufalloc); - keys = NULL; keycc = 0; with_filenames = false; @@ -2777,6 +2771,18 @@ main (int argc, char **argv) if (max_count == 0) return EXIT_FAILURE; + /* Prefer sysconf for page size, as getpagesize typically returns int. */ +#ifdef _SC_PAGESIZE + long psize = sysconf (_SC_PAGESIZE); +#else + long psize = getpagesize (); +#endif + if (! (0 < psize && psize <= (SIZE_MAX - sizeof (uword)) / 2)) + abort (); + pagesize = psize; + bufalloc = ALIGN_TO (INITIAL_BUFSIZE, pagesize) + pagesize + sizeof (uword); + buffer = xmalloc (bufalloc); + if (fts_options & FTS_LOGICAL && devices == READ_COMMAND_LINE_DEVICES) devices = READ_DEVICES; -- 2.5.5