diff --git a/include/getopt.h b/include/getopt.h index 6d85c0b6ba68313a5ab0760e069e56fc845253fa..c1d0df928f749ac0f3094b80f2422abce23b2dfa 100644 --- a/include/getopt.h +++ b/include/getopt.h @@ -7,7 +7,7 @@ extern "C" { int getopt(int, char * const [], const char *); extern char *optarg; -extern int optind, opterr, optopt; +extern int optind, opterr, optopt, optreset; struct option { diff --git a/src/misc/getopt.c b/src/misc/getopt.c index abf0e8477f5f71a7e58bd84b6ce92228f36a770d..35880a090719e8f3913bbcd63c0238214490826a 100644 --- a/src/misc/getopt.c +++ b/src/misc/getopt.c @@ -3,10 +3,13 @@ #include #include #include +#include "libc.h" char *optarg; -int optind=1, opterr=1, optopt; -static int optpos; +int optind=1, opterr=1, optopt, __optpos, __optreset=0; + +#define optpos __optpos +weak_alias(__optreset, optreset); int getopt(int argc, char * const argv[], const char *optstring) { @@ -15,6 +18,12 @@ int getopt(int argc, char * const argv[], const char *optstring) int k, l; char *optchar; + if (!optind || __optreset) { + __optreset = 0; + __optpos = 0; + optind = 1; + } + if (optind >= argc || !argv[optind] || argv[optind][0] != '-' || !argv[optind][1]) return -1; if (argv[optind][1] == '-' && !argv[optind][2]) diff --git a/src/misc/getopt_long.c b/src/misc/getopt_long.c index 6d3a4a6e644e5dc4ba3156ba3a7ce4a0c006c9cb..4ef5a5c7a861d8ea3fe8cefb1f248e60d35db981 100644 --- a/src/misc/getopt_long.c +++ b/src/misc/getopt_long.c @@ -3,8 +3,15 @@ #include #include +extern int __optpos, __optreset; + static int __getopt_long(int argc, char *const *argv, const char *optstring, const struct option *longopts, int *idx, int longonly) { + if (!optind || __optreset) { + __optreset = 0; + __optpos = 0; + optind = 1; + } if (optind >= argc || !argv[optind] || argv[optind][0] != '-') return -1; if ((longonly && argv[optind][1]) || (argv[optind][1] == '-' && argv[optind][2]))