瀏覽代碼

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 4 月之前
父節點
當前提交
139bb70c28
共有 1 個文件被更改,包括 9 次插入0 次删除
  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? */