patch for freopen(NULL,...)

Eric Blake ebb9@byu.net
Tue Dec 27 20:16:00 GMT 2005


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

POSIX states that freopen(NULL,...) should attempt to change the mode of
the existing underlying file descriptor, with an implementation-defined
list of valid changes, rather than closing the underlying file descriptor:
http://www.opengroup.org/onlinepubs/009695399/functions/freopen.html.

Currently, newlib freopen(NULL) blindly calls open(NULL), which in the
worst case causes a core dump for violating the POSIX interface of open,
and in the best case violates POSIX for returning EFAULT instead of EBADF
(if open has the extension of returning EFAULT).  Even though POSIX allows
an implementation the cop-out of always returning EBADF when filename is
NULL, it is more useful to provide a non-trivial implementation: this
feature of freopen is useful for changing append vs. seek status on files
open for writing; and on cygwin it is useful for changing binary vs. text
modes.  In fact, coreutils 5.93 now uses the idiom freopen(NULL, "rb",
stdin) to ensure that stdin is in binary mode (I have patched the cygwin
release of coreutils 5.93 to use a replacement freopen, but think the
patch belongs better in newlib itself).

Some notes about this patch: __SCLE is currently only defined for cygwin,
and cygwin documents that fcntl(F_SETFL) does not alter binary/text mode,
and that setmode() should not be called on ttys.  Also, POSIX states that
freopen may return EBADF when filename was NULL but the conversion cannot
be performed; and since I know of no easy way to change the mode of an
open file descriptor from O_RDONLY to O_WRONLY, my patch has the
implementation-defined limitation that freopen(NULL) will only succeed if
the access mode (read, write, or read-write) is unchanged.

2005-12-26  Eric Blake  <ebb9@byu.net>

	* libc/stdio/freopen.c (_freopen_r): Accept NULL filename.
	* libc/stdio64/freopen64.c (_freopen64_r): Likewise.

- --
Life is short - so eat dessert first!

Eric Blake             ebb9@byu.net
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.1 (Cygwin)
Comment: Public key at home.comcast.net/~ericblake/eblake.gpg
Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org

iD8DBQFDsBXX84KuGfSFAYARAiJdAJ0UGksI1Bhu/AZ5BaPz7BPCJ7nJEACeLF6c
Vy1KK8RbAacnrDFmEelx66s=
=PMcl
-----END PGP SIGNATURE-----
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: newlib.patch
URL: <http://sourceware.org/pipermail/newlib/attachments/20051227/9ffc7706/attachment.ksh>


More information about the Newlib mailing list