4 * getopt_long(), or at least a common subset thereof:
6 * - Option reordering is not supported
7 * - -W foo is not supported
8 * - First optstring character "-" not supported.
10 * This file was imported from the klibc library from hpa
20 int optind = 0, opterr = 0, optopt = 0;
22 static struct getopt_private_state {
24 const char *last_optstring;
25 char *const *last_argv;
28 static inline const char *option_matches(const char *arg_str,
31 while (*arg_str != '\0' && *arg_str != '=') {
32 if (*arg_str++ != *opt_name++)
42 int getopt_long_only(int argc, char *const *argv, const char *optstring,
43 const struct option *longopts, int *longindex)
51 /* getopt() relies on a number of different global state
52 variables, which can make this really confusing if there is
53 more than one use of getopt() in the same program. This
54 attempts to detect that situation by detecting if the
55 "optstring" or "argv" argument have changed since last time
56 we were called; if so, reinitialize the query state. */
58 if (optstring != pvt.last_optstring || argv != pvt.last_argv ||
59 optind < 1 || optind > argc) {
60 /* optind doesn't match the current query */
61 pvt.last_optstring = optstring;
69 /* First, eliminate all non-option cases */
71 if (!carg || carg[0] != '-' || !carg[1])
75 const struct option *lo;
76 const char *opt_end = NULL;
80 /* Either it's a long option, or it's -- */
86 for (lo = longopts; lo->name; lo++) {
87 if ((opt_end = option_matches(carg+2, lo->name)))
94 *longindex = lo-longopts;
96 if (*opt_end == '=') {
98 optarg = (char *)opt_end+1;
101 } else if (lo->has_arg == 1) {
102 if (!(optarg = argv[optind]))
115 if ((uintptr_t) (pvt.optptr - carg) > (uintptr_t) strlen(carg)) {
116 /* Someone frobbed optind, change to new opt. */
117 pvt.optptr = carg + 1;
122 if (opt != ':' && (osptr = strchr(optstring, opt))) {
123 if (osptr[1] == ':') {
125 /* Argument-taking option with attached
127 optarg = (char *)pvt.optptr;
130 /* Argument-taking option with non-attached
132 if (osptr[2] == ':') {
133 if (argv[optind + 1]) {
134 optarg = (char *)argv[optind+1];
141 } else if (argv[optind + 1]) {
142 optarg = (char *)argv[optind+1];
145 /* Missing argument */
147 return (optstring[0] == ':')
153 /* Non-argument-taking option */
154 /* pvt.optptr will remember the exact position to