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;
21 static struct getopt_private_state {
23 const char *last_optstring;
24 char *const *last_argv;
27 static inline const char *option_matches(const char *arg_str,
30 while (*arg_str != '\0' && *arg_str != '=') {
31 if (*arg_str++ != *opt_name++)
41 int getopt_long_only(int argc, char *const *argv, const char *optstring,
42 const struct option *longopts, int *longindex)
48 /* getopt() relies on a number of different global state
49 variables, which can make this really confusing if there is
50 more than one use of getopt() in the same program. This
51 attempts to detect that situation by detecting if the
52 "optstring" or "argv" argument have changed since last time
53 we were called; if so, reinitialize the query state. */
55 if (optstring != pvt.last_optstring || argv != pvt.last_argv ||
56 optind < 1 || optind > argc) {
57 /* optind doesn't match the current query */
58 pvt.last_optstring = optstring;
66 /* First, eliminate all non-option cases */
68 if (!carg || carg[0] != '-' || !carg[1])
72 const struct option *lo;
73 const char *opt_end = NULL;
77 /* Either it's a long option, or it's -- */
83 for (lo = longopts; lo->name; lo++) {
84 if ((opt_end = option_matches(carg+2, lo->name)))
91 *longindex = lo-longopts;
93 if (*opt_end == '=') {
95 optarg = (char *)opt_end+1;
98 } else if (lo->has_arg == 1) {
99 if (!(optarg = argv[optind]))
112 if ((uintptr_t) (pvt.optptr - carg) > (uintptr_t) strlen(carg)) {
113 /* Someone frobbed optind, change to new opt. */
114 pvt.optptr = carg + 1;
119 if (opt != ':' && (osptr = strchr(optstring, opt))) {
120 if (osptr[1] == ':') {
122 /* Argument-taking option with attached
124 optarg = (char *)pvt.optptr;
127 /* Argument-taking option with non-attached
129 if (argv[optind + 1]) {
130 optarg = (char *)argv[optind+1];
133 /* Missing argument */
135 return (optstring[0] == ':')
141 /* Non-argument-taking option */
142 /* pvt.optptr will remember the exact position to