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)
49 /* getopt() relies on a number of different global state
50 variables, which can make this really confusing if there is
51 more than one use of getopt() in the same program. This
52 attempts to detect that situation by detecting if the
53 "optstring" or "argv" argument have changed since last time
54 we were called; if so, reinitialize the query state. */
56 if (optstring != pvt.last_optstring || argv != pvt.last_argv ||
57 optind < 1 || optind > argc) {
58 /* optind doesn't match the current query */
59 pvt.last_optstring = optstring;
67 /* First, eliminate all non-option cases */
69 if (!carg || carg[0] != '-' || !carg[1])
73 const struct option *lo;
74 const char *opt_end = NULL;
78 /* Either it's a long option, or it's -- */
84 for (lo = longopts; lo->name; lo++) {
85 if ((opt_end = option_matches(carg+2, lo->name)))
92 *longindex = lo-longopts;
94 if (*opt_end == '=') {
96 optarg = (char *)opt_end+1;
99 } else if (lo->has_arg == 1) {
100 if (!(optarg = argv[optind]))
113 if ((uintptr_t) (pvt.optptr - carg) > (uintptr_t) strlen(carg)) {
114 /* Someone frobbed optind, change to new opt. */
115 pvt.optptr = carg + 1;
120 if (opt != ':' && (osptr = strchr(optstring, opt))) {
121 if (osptr[1] == ':') {
123 /* Argument-taking option with attached
125 optarg = (char *)pvt.optptr;
128 /* Argument-taking option with non-attached
130 if (osptr[2] == ':') {
131 if (argv[optind + 1]) {
132 optarg = (char *)argv[optind+1];
139 } else if (argv[optind + 1]) {
140 optarg = (char *)argv[optind+1];
143 /* Missing argument */
145 return (optstring[0] == ':')
151 /* Non-argument-taking option */
152 /* pvt.optptr will remember the exact position to