Subject: [PATCH] Fix handling of ? option

From: Quentin Rameau <[email-masked]>
Date: Sun, 25 Aug 2019 20:45:29 +0200

Using optind to check back the original given option this way is bogus
and could lead to dereferencing argv out of bounds with a missing
argument to an option.

The proper way to verify if an error has occured is to check if optopt
has been set.
---
 src/bin/psql/startup.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/src/bin/psql/startup.c b/src/bin/psql/startup.c
index 4730c73396..333b49985a 100644
--- a/src/bin/psql/startup.c
+++ b/src/bin/psql/startup.c
@@ -507,6 +507,7 @@ parse_psql_options(int argc, char *argv[], struct adhoc_opts *options)
 	int			c;
 
 	memset(options, 0, sizeof *options);
+	optopt = 0;
 
 	while ((c = getopt_long(argc, argv, "aAbc:d:eEf:F:h:HlL:no:p:P:qR:sStT:U:v:VwWxXz?01",
 							long_options, &optindex)) != -1)
@@ -667,7 +668,7 @@ parse_psql_options(int argc, char *argv[], struct adhoc_opts *options)
 				break;
 			case '?':
 				/* Actual help option given */
-				if (strcmp(argv[optind - 1], "-?") == 0)
+				if (!optopt)
 				{
 					usage(NOPAGER);
 					exit(EXIT_SUCCESS);
-- 
2.23.0

--MP_/oEcYY8373P4jignUOgMh8T.--