Follow @Openwall on Twitter for new release announcements and other news
[<prev] [next>] [<thread-prev] [day] [month] [year] [list]
Message-ID: <20251114014636.GO1827@brightrain.aerifal.cx>
Date: Thu, 13 Nov 2025 20:46:36 -0500
From: Rich Felker <dalias@...c.org>
To: Demi Marie Obenour <demiobenour@...il.com>
Cc: musl@...ts.openwall.com
Subject: Re: fputs() et al do not return EBADF for read-only files

On Thu, Nov 13, 2025 at 08:21:34PM -0500, Rich Felker wrote:
> On Thu, Nov 13, 2025 at 05:21:56PM -0500, Demi Marie Obenour wrote:
> > See https://github.com/systemd/systemd/pull/39721 which works around this.
> 
> This is expected. Per ISO C, calling an output function on a stream
> not opened for output has undefined behavior. Performing an additional
> mode check in each putc operation would be relatively costly and
> unjustified. This is not an exceptional condition that can happen at
> runtime like out-of-memory, insufficient permission, missing file,
> etc. Attempting to perform output on an input stream or vice versa is
> purely a programming error and the buggy code should be fixed.

As I was just reminded of it off-list, I'll add that there's a common
misconception here because POSIX does specify EBADF as a "shall fail".
However, the conditions for it are:

    "The fputc() function shall fail if either the stream is
    unbuffered or the stream's buffer needs to be flushed, and:
    
    ...
    
    [EBADF] The file descriptor underlying stream is not a valid file
    descriptor open for writing."

This is a condition on the underlying file descriptor, not on the
stdio FILE stream, and it's only specified to happen under conditions
where an operation on the underlying fd would occur. It can only occur
if fdopen did not check the mode of the file descriptor (not required
IIRC) or if dup2 was used to replace the file descriptor associated
with the stream, or if the stream is stdout or stderr and the process
inherited a file descriptor not open for writing or did not inherit
any file descriptor 1 or 2 at all.

Rich

Powered by blists - more mailing lists

Confused about mailing lists and their use? Read about mailing lists on Wikipedia and check out these guidelines on proper formatting of your messages.