This is the mail archive of the newlib@sourceware.org mailing list for the newlib project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

BUG: getopt does not permute argv correctly


Hi!

I'm using cygwin64 with newlib 3.0.0. POSIXLY_CORRECT is not set.


Here's my test program:

#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>


void print_args(const char *s, int argc, char *argv[])
{
    printf("%s:\n", s);
    for (int i=0; i<argc; i++)
        printf("  %d: \"%s\"\n", i, argv[i]);
}


int main(int argc, char *argv[])
{
    int opt_a = 0;
    int opt_b = 0;
    int opt_c = 0;
    int opt;

    printf("Newlib v%s\n", _NEWLIB_VERSION);
    printf("POSIXLY_CORRECT=%p\n", getenv("POSIXLY_CORRECT"));

    print_args("before", argc, argv);

    while ((opt = getopt(argc, argv, "abc")) != -1) {
        switch (opt) {
        case 'a':   opt_a++;   break;
        case 'b':   opt_b++;   break;
        case 'c':   opt_c++;   break;
        }
    }

    print_args("after", argc, argv);

    printf("a=%d, b=%d, c=%d\n", opt_a, opt_b, opt_c);

    return 0;
}


- - - - -


$ make test
$ ./test -a -b -c 1 2 3

Newlib v3.0.0
POSIXLY_CORRECT=0x0
before:
  0: "./test"
  1: "-a"
  2: "-b"
  3: "-c"
  4: "1"
  5: "2"
  6: "3"
after:
  0: "./test"
  1: "-a"
  2: "-b"
  3: "-c"
  4: "1"
  5: "2"
  6: "3"
a=1, b=1, c=1

===> OK!



$ ./test 1 2 3 -a -b -c

Newlib v3.0.0
POSIXLY_CORRECT=0x0
before:
  0: "./test"
  1: "1"
  2: "2"
  3: "3"
  4: "-a"
  5: "-b"
  6: "-c"
after:
  0: "./test"
  1: "1"
  2: "2"
  3: "3"
  4: "-a"
  5: "-b"
  6: "-c"
a=0, b=0, c=0

===> Failure!

I would expect that argv is permuted, so that -a -b -c come first. Also, I
expect a=1, b=1, c=1.


- - - - -


I also tried this program on an embedded ARM Cortex-M4 target, using the
GNU Arm Embedded Toolchain and newlib v2.5.0:


Here, I see another, different behaviour:

> test 1 2 3 -a -b -c
Newlib v2.5.0
POSIXLY_CORRECT=0x0
before:
  0: "test"
  1: "1"
  2: "2"
  3: "3"
  4: "-a"
  5: "-b"
  6: "-c"
after:
  0: "test"
  1: "-a"
  2: "-b"
  3: "-c"
  4: "1"
  5: "2"
  6: "3"
a=1, b=1, c=1

===> (somewhat surprisingly) OK!


> test 1 2 3 -abc
Newlib v2.5.0
POSIXLY_CORRECT=0x0
before:
  0: "test"
  1: "1"
  2: "2"
  3: "3"
  4: "-abc"
after:
  0: "test"
  1: "1"
  2: "2"
  3: "3"
  4: "-abc"
a=1, b=1, c=1


===> Failure! a, b, c is parsed, but does not get permuted to argv[1].



The same program works as expected when using glibc under Linux.



best regards,
-- 
Thomas Kindler <mail+newlib@t-kindler.de>


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]