getopt: clean up error reporting
commit544ce845def4540de11d9484df888df94876b14e
authorZack Weinberg <zackw@panix.com>
Sat, 1 Apr 2017 14:17:44 +0000 (1 10:17 -0400)
committerZack Weinberg <zackw@panix.com>
Fri, 7 Apr 2017 11:48:57 +0000 (7 07:48 -0400)
treedbd8eae480b47ab43e70bafb636a83c1963abb86
parent7e161bef0bc9d5ea5e6f3dd490ecd5da6f642671
getopt: clean up error reporting

getopt can print a whole bunch of error messages, and when used
standalone (from gnulib) it uses fprintf to do that.  But fprintf is a
cancellation point and getopt isn't, and also applying fprintf to a
stream in wide-character mode is not allowed.

glibc has an internal function called __fxprintf that writes a narrow
format string to a stream regardless of mode, but it only handles
ASCII format strings, and it's still a cancellation point.  getopt's
messages are translated, so they might not be ASCII.  So getopt has an
error message to an asprintf buffer, monkeys with internal flag bits
on stderr to disable cancellation, and then calls
__fxprintf(stderr, "%s", buffer).  There isn't even a helper function,
the code is duplicated every time.

This patch fixes __fxprintf to handle arbitrary multibyte format
strings, and adds a variant __fxprintf_nocancel that does the same
thing but also isn't a cancellation point.  (It still _works_ by
monkeying with internal flag bits on the FILE, but that's not really a
layering violation for code in stdio-common.)  All of the #ifdef _LIBC
blocks can then be reduced to their standalone versions with a little
help from some macros at the top of the file.

I also wrote a test case to verify that getopt really isn't a
cancellation point, and I'm glad I did, because it found two bugs, one
of which wasn't even to do with cancellation (see previous patch).

* stdio-common/fxprintf.c (__fxprintf_nocancel): New function.
(locked_vfxprintf): New helper function. Handle arbitrary
multibyte strings, not just ASCII.
* include/stdio.h: Declare __fxprintf_nocancel.

* posix/getopt.c: When _LIBC is defined, define fprintf to
__fxprintf_nocancel, flockfile to _IO_flockfile, and
funlockfile to _IO_funlockfile.  When neither _LIBC nor
_POSIX_THREAD_SAFE_FUNCTIONS is defined, define flockfile and
funlockfile as no-ops.  (_getopt_internal_r): Remove all
internal #ifdef _LIBC blocks; the standalone error-printing
code can now be used for libc as well.  Add an
flockfile/funlockfile pair around one case where the error
message is printed in several chunks.  Don't use fputc.

* posix/tst-getopt-cancel.c: New test.
* posix/Makefile: Run it.
ChangeLog
include/stdio.h
posix/Makefile
posix/getopt.c
posix/tst-getopt-cancel.c [new file with mode: 0644]
stdio-common/fxprintf.c