getopt_test_libc_bug.tests 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. # This test can fail with libc with buggy getopt() implementation.
  2. # If getopt() wants to parse multi-option args (-abc),
  3. # it needs to remember a position within current arg.
  4. #
  5. # If this position is kept as a POINTER, not an offset,
  6. # and if argv[] ADDRESSES (not contents!) change, it blows up.
  7. (
  8. echo "*** optstring:'ac' args:-a -b -c -d e"
  9. getopts "ac" var -a -b -c -d e; echo "1 rc:$? var:'$var' OPTIND:$OPTIND OPTARG:'$OPTARG'"
  10. getopts "ac" var -a -b -c -d e; echo "2 rc:$? var:'$var' OPTIND:$OPTIND OPTARG:'$OPTARG'"
  11. getopts "ac" var -a -b -c -d e; echo "3 rc:$? var:'$var' OPTIND:$OPTIND OPTARG:'$OPTARG'"
  12. getopts "ac" var -a -b -c -d e; echo "4 rc:$? var:'$var' OPTIND:$OPTIND OPTARG:'$OPTARG'"
  13. getopts "ac" var -a -b -c -d e; echo "5 rc:$? var:'$var' OPTIND:$OPTIND OPTARG:'$OPTARG'"
  14. # Above: args are (usually) in the same locations in memory.
  15. # Below: variable allocations change the location.
  16. echo
  17. echo "*** optstring:'ac' args:-a -b -c -d e"
  18. unset OPTIND
  19. OPTARG=QWERTY; getopts "ac" var -a -b -c -d e; echo "1 rc:$? var:'$var' OPTIND:$OPTIND OPTARG:'$OPTARG'"
  20. NEWVAR=NEWVAL; getopts "ac" var -a -b -c -d e; echo "2 rc:$? var:'$var' OPTIND:$OPTIND OPTARG:'$OPTARG'"
  21. VAR111=NEWVAL; getopts "ac" var -a -b -c -d e; echo "3 rc:$? var:'$var' OPTIND:$OPTIND OPTARG:'$OPTARG'"
  22. VAR222=NEWVAL; getopts "ac" var -a -b -c -d e; echo "4 rc:$? var:'$var' OPTIND:$OPTIND OPTARG:'$OPTARG'"
  23. VAR333=NEWVAL; getopts "ac" var -a -b -c -d e; echo "5 rc:$? var:'$var' OPTIND:$OPTIND OPTARG:'$OPTARG'"
  24. # Slightly different attempts to force reallocations
  25. echo
  26. echo "*** optstring:'ac' args:-a -b -c -d e"
  27. unset OPTIND
  28. export OPTARG; getopts "ac" var -a -b -c -d e; echo "1 rc:$? var:'$var' OPTIND:$OPTIND OPTARG:'$OPTARG'"
  29. export NEWVAR; getopts "ac" var -a -b -c -d e; echo "2 rc:$? var:'$var' OPTIND:$OPTIND OPTARG:'$OPTARG'"
  30. export VAR111; getopts "ac" var -a -b -c -d e; echo "3 rc:$? var:'$var' OPTIND:$OPTIND OPTARG:'$OPTARG'"
  31. export VAR222; getopts "ac" var -a -b -c -d e; echo "4 rc:$? var:'$var' OPTIND:$OPTIND OPTARG:'$OPTARG'"
  32. export VAR333; getopts "ac" var -a -b -c -d e; echo "5 rc:$? var:'$var' OPTIND:$OPTIND OPTARG:'$OPTARG'"
  33. # All copies of code above should generate identical output
  34. ) 2>&1 \
  35. | sed -e 's/ unrecognized option: / invalid option -- /' \
  36. -e 's/ illegal option -- / invalid option -- /' \