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, opterr, optopt;
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,
29 const char *opt_name, int smatch)
31 while (*arg_str != '\0' && *arg_str != '=') {
32 if (*arg_str++ != *opt_name++)
36 if (*opt_name && !smatch)
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 opt_end = option_matches(carg+2, lo->name, 0);
92 * The GNU getopt_long_only() apparently allows a short match,
93 * if it's unique and if we don't have a full match. Let's
94 * do the same here, search and see if there is one (and only
98 const struct option *lo_match = NULL;
100 for (lo = longopts; lo->name; lo++) {
103 ret = option_matches(carg+2, lo->name, 1);
120 *longindex = lo-longopts;
122 if (*opt_end == '=') {
124 optarg = (char *)opt_end+1;
127 } else if (lo->has_arg == 1) {
128 if (!(optarg = argv[optind]))
141 if ((uintptr_t) (pvt.optptr - carg) > (uintptr_t) strlen(carg)) {
142 /* Someone frobbed optind, change to new opt. */
143 pvt.optptr = carg + 1;
148 if (opt != ':' && (osptr = strchr(optstring, opt))) {
149 if (osptr[1] == ':') {
151 /* Argument-taking option with attached
153 optarg = (char *)pvt.optptr;
156 /* Argument-taking option with non-attached
158 if (osptr[2] == ':') {
159 if (argv[optind + 1]) {
160 optarg = (char *)argv[optind+1];
167 } else if (argv[optind + 1]) {
168 optarg = (char *)argv[optind+1];
171 /* Missing argument */
173 return (optstring[0] == ':')
179 /* Non-argument-taking option */
180 /* pvt.optptr will remember the exact position to