Bug 11039 - getopt mishandles optstring of "+:"
Summary: getopt mishandles optstring of "+:"
Status: RESOLVED FIXED
Alias: None
Product: glibc
Classification: Unclassified
Component: libc (show other bugs)
Version: 2.11
: P2 normal
Target Milestone: ---
Assignee: Ulrich Drepper
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2009-12-01 16:27 UTC by Eric Blake
Modified: 2014-06-30 20:36 UTC (History)
1 user (show)

See Also:
Host:
Target:
Build:
Last reconfirmed:
fweimer: security-


Attachments
patch (607 bytes, patch)
2009-12-01 16:32 UTC, Eric Blake
Details | Diff

Note You need to log in before you can comment on or make changes to this bug.
Description Eric Blake 2009-12-01 16:27:50 UTC
According to the getopt man pages, for example:

http://www.kernel.org/doc/man-pages/online/pages/man3/getopt.3.html

If the first character (following any optional '+' or '-' described above) of
optstring is a colon (':'), then getopt() returns ':' instead of '?' to indicate
a missing option argument.

However, the code in getopt.c does not consistently follow this rule.

$ cat foo.c
#include <unistd.h>
#include <stdio.h>
int
main (int argc, char **argv)
{
  int c = getopt (argc, argv, "+:a:b");
  if (c == -1)
    puts ("got -1");
  else
    printf ("got %c\n", c);
  c = getopt (argc, argv, "+:a:b");
  if (c == -1)
    puts ("got -1");
  else
    printf ("got %c\n", c);
  return 0;
}
$ ./foo -a
./foo2: option requires an argument -- a
got :
got -1
$ ./foo -b -a
got b
./foo2: option requires an argument -- a
got ?

Expected behavior - stderr should be silent, and the -a without argument should
return ':', not '?'.

Workaround: code can set opterr=0 before the first getopt{,_long} call (to
silence the spurious warning if argv[1] is missing an argument), then leave off
the leading '-' or '+' of opstring for all subsequent calls for a given
argc/argv parse (to silence the warning and return ':' instead of '?' if any
subsequent argv is missing an argument).
Comment 1 Eric Blake 2009-12-01 16:32:03 UTC
Created attachment 4435 [details]
patch

2009-12-01  Eric Blake	<ebb9@byu.net>

	* posix/getopt.c (_getopt_internal_r): Skip optional - or + before
	checking lead byte of optstring for :.
Comment 2 Eric Blake 2009-12-02 22:17:25 UTC
Another related problem, which is also fixed by the previously posted patch:

$ cat foo.c
#include <unistd.h>
#include <stdio.h>
int
main (int argc, char **argv)
{
  int i, c;
  for (i = 0; i <= 1; i++)
    {
      optind = i;
      c = getopt (argc, argv, "+a");
      if (c == -1)
        printf ("got -1, optind %d\n", optind);
      else
        printf ("got %c, optind %d\n", c, optind);
    }
  return 0;
}
$ ./foo -+
foo: invalid option -- '+'
got ?, optind 2
got +, optind 2

Expected behavior is for the error message to occur twice on stderr, with both
passes returning '?'.
Comment 3 Ulrich Drepper 2010-04-08 00:56:56 UTC
Fixed in git.