From mboxrd@z Thu Jan 1 00:00:00 1970 X-Spam-Checker-Version: SpamAssassin 3.4.4 (2020-01-24) on inbox.vuxu.org X-Spam-Level: X-Spam-Status: No, score=-3.3 required=5.0 tests=MAILING_LIST_MULTI, RCVD_IN_DNSWL_MED,RCVD_IN_MSPIKE_H3,RCVD_IN_MSPIKE_WL autolearn=ham autolearn_force=no version=3.4.4 Received: (qmail 20049 invoked from network); 25 Jun 2020 15:38:22 -0000 Received: from mother.openwall.net (195.42.179.200) by inbox.vuxu.org with ESMTPUTF8; 25 Jun 2020 15:38:22 -0000 Received: (qmail 7556 invoked by uid 550); 25 Jun 2020 15:38:17 -0000 Mailing-List: contact musl-help@lists.openwall.com; run by ezmlm Precedence: bulk List-Post: List-Help: List-Unsubscribe: List-Subscribe: List-ID: Reply-To: musl@lists.openwall.com Received: (qmail 7535 invoked from network); 25 Jun 2020 15:38:16 -0000 Date: Thu, 25 Jun 2020 11:38:04 -0400 From: Rich Felker To: Stefan Ciotec Cc: "'musl@lists.openwall.com'" , Vasile Iliescu Message-ID: <20200625153803.GO6430@brightrain.aerifal.cx> References: MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline In-Reply-To: User-Agent: Mutt/1.5.21 (2010-09-15) Subject: Re: [musl] errno not set to EBADF when reading from invalid descriptor On Thu, Jun 25, 2020 at 01:21:05PM +0000, Stefan Ciotec wrote: > Hi, > > We are using MUSL C-library 1.1.22. > According to the POSIX standard, EOF should be returned and errno > should be set to EBADF for the read group of functions (i.e. > fgetc(), getc(), getc_unlocked()) when attempting to read from a > stream with an invalid file descriptor open for reading. > However, in our tests with MUSL, we discovered that EOF is returned, > but errno is not set to EBADF (it's 0 instead), for the following > code: I think you're misreading the standard. Per ISO C, it's undefined behavior to call a read function on a FILE stream not opened for read or update. The POSIX "shall fail" text you're looking at applies when the FILE stream is open for read or update but the underlying fd is not open for reading; this can happen with fdopen, when inheriting an unsuitable fd for stdin via exec, or when using dup2 to replace fileno(f) for some already-opened FILE with a reference to a different open file that was opened for write only. Note that the POSIX text is not very well aligned with the C text, but the DESCRIPTION in POSIX refers to "the input stream pointed to by stream". This reflects that it's a constraint, and passing an inappropriate stream pointer is a constraint violation. Note that there are lots of other reasons you can't safely use stdio read functions on a stream you don't know is suitable for it. Switching from writing to reading without a successful flush produces UB, and switching the other direction without a successful seek does, even if the FILE stream is open for both. Rich