From 6a679043e63e66571e6e363a5d5dcd5af3fce1ce Mon Sep 17 00:00:00 2001 From: Gregory Nutt Date: Sun, 4 Apr 2021 09:53:45 -0600 Subject: [PATCH] testing/ostest: More improvements to getopt() testing/ostest Fix optind range checking. optind may index through argc (to the NULL argv entry) on the last option since optind is required to always point to the next command line argument. Add two more test cases were the final thing on the command line is an invalid long option. Fix a check that used an older, obsoleted hard-coded value that was not updated. This should have no impact other than to the getopt() test cases of the OS test. Tested on the simulator using a modified NSH configuration. --- testing/ostest/getopt.c | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/testing/ostest/getopt.c b/testing/ostest/getopt.c index 36898c24c..1c76799e9 100644 --- a/testing/ostest/getopt.c +++ b/testing/ostest/getopt.c @@ -192,7 +192,11 @@ static int getopt_short_test(int noptions, int argc, FAR char **argv, (ret = getopt(argc, argv, optstring)) != ERROR && ndx < noptions; ndx++) { - if (optind < 1 || optind >= argc) + /* optind may index through argc (to the NULL argv entry) since it is + * required to always point to the next command line argument. + */ + + if (optind < 1 || optind > argc) { printf("ERROR: optind=%d\n", optind); } @@ -250,7 +254,11 @@ static int getopt_long_test(int noptions, int argc, FAR char **argv, longindex)) != ERROR; ndx++) { - if (optind < 1 || optind >= argc) + /* optind may index through argc (to the NULL argv entry) since it is + * required to always point to the next command line argument. + */ + + if (optind < 1 || optind > argc) { printf("ERROR: optind=%d\n", optind); } @@ -315,7 +323,11 @@ static int getopt_longonly_test(int noptions, int argc, FAR char **argv, longindex)) != ERROR; ndx++) { - if (optind < 1 || optind > 7) + /* optind may index through argc (to the NULL argv entry) since it is + * required to always point to the next command line argument. + */ + + if (optind < 1 || optind > argc) { printf("ERROR: optind=%d\n", optind); } @@ -413,6 +425,9 @@ int getopt_test(void) getopt_short_test(5, 9, argv, g_optstring, results); + argv[8] = NULL; + getopt_short_test(5, 8, argv, g_optstring, results); + printf("getopt(): Missing optional argument\n"); argv[0] = NULL; @@ -490,6 +505,10 @@ int getopt_test(void) getopt_long_test(5, 9, argv, g_optstring, long_options, NULL, results); + argv[8] = NULL; + getopt_long_test(5, 8, argv, g_optstring, long_options, NULL, + results); + printf("getopt_long(): Mixed long and short options\n"); argv[0] = NULL;