Skip to content

Commit 2f2a06d

Browse files
spholznico
authored andcommitted
LibC: Correctly reset the getopt state on optind = 0
515f313 incorrectly made getopt only reset its state when `optind` is set to 1. However, the Linux man page says that setting it to 0 also reinitializes its state and additionally checks for some GNU extensions. stress-ng relies on this behavior. The POSIX man page only says that setting it to 0 results in undefined behavior.
1 parent bbdbdab commit 2f2a06d

File tree

2 files changed

+4
-3
lines changed

2 files changed

+4
-3
lines changed

Userland/Libraries/LibC/bits/getopt.h

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,8 @@ extern int optopt;
1717
// Index of the next argument to process upon a getopt*() call.
1818
extern int optind;
1919
// If set, reset the internal state kept by getopt*(). You may also want to set
20-
// optind to 1 in that case.
20+
// optind to 1 in that case. Alternatively, setting optind to 0 is treated like
21+
// doing both of the above.
2122
extern int optreset;
2223
// After parsing an option that accept an argument, set to point to the argument
2324
// value.

Userland/Libraries/LibC/getopt.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ int getopt(int argc, char* const* argv, char const* short_options)
3333
for (auto i = 1; i < argc; ++i)
3434
s_args.append({ argv[i], strlen(argv[i]) });
3535

36-
if (optind == 1 || optreset == 1) {
36+
if (optind <= 1 || optreset == 1) {
3737
s_parser.reset_state();
3838
optind = 1;
3939
optreset = 0;
@@ -75,7 +75,7 @@ int getopt_long(int argc, char* const* argv, char const* short_options, const st
7575
});
7676
}
7777

78-
if (optind == 1 || optreset == 1) {
78+
if (optind <= 1 || optreset == 1) {
7979
s_parser.reset_state();
8080
optind = 1;
8181
optreset = 0;

0 commit comments

Comments
 (0)