Forráskód Böngészése

getopt-susv3: add support for reseting the scan by setting optind to zero

Busybox (among other programs) relies on the ability to reset arg scanning
by setting optind to zero. POSIX says that the behavior of getopt upon
encountering optind == 0 is unspecified, but glibc introduced the idea of
using it as a reset indicator, and enough programs do it that essentially
all libcs (musl, dietlibc, picolibc, and libcs from {Open,Net}BSD) have
adopted the convention (even if begrudgingly so).

Signed-off-by: Charles Mirabile <cmirabil@redhat.com>
Charles Mirabile 3 hete
szülő
commit
139bb70c28
1 módosított fájl, 9 hozzáadás és 0 törlés
  1. 9 0
      libc/unistd/getopt-susv3.c

+ 9 - 0
libc/unistd/getopt-susv3.c

@@ -46,6 +46,15 @@ int getopt(int argc, char * const argv[], const char *optstring)
 	optopt = 0;
 	optarg = NULL;
 
+	/*
+	 * POSIX says behavior when optind == 0 is unspecified, but other
+	 * libcs use this wiggle room to allow reseting getopt; we can too
+	 */
+	if (!optind) {
+		o = NULL;
+		optind = 1;
+	}
+
 	if (!o) {				/* Not in a multi-option arg. */
 		if ((optind >= argc)	/* No more args? */
 			|| ((p = argv[optind]) == NULL) /* Missing? */