When the seek in st_rewind fails, st_rewind reports the error and
returns with the unit still locked.  The seek fails on every unit
that is neither buffered nor seekable: fd_to_stream buffers only
regular files, so this includes any preconnected unit on a pipe or a
terminal.  With IOSTAT= or ERR= the program goes on, and the next
statement on the unit finds it locked: a data transfer statement fails
with "Recursive I/O not allowed", and a file positioning statement
waits forever for the lock.

Unlock the unit, and the asynchronous I/O lock if it was taken, before
returning.  Also initialize needs_unlock to false, as st_backspace,
st_endfile and st_flush do: it becomes true only once that lock is
taken, so a REWIND of a direct-access unit with asynchronous I/O no
longer unlocks a lock it does not hold.

PR libfortran/128875

libgfortran/ChangeLog:

* io/file_pos.c (st_rewind): Initialize needs_unlock to false.
Unlock the unit and the asynchronous I/O lock when the seek
fails.

gcc/testsuite/ChangeLog:

* gfortran.dg/rewind_2.f90: New test.

Signed-off-by: Federico Perini <[email protected]>
---
Bugzilla: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=128875

I found this while testing my fix for PR 128486, but it has nothing to
do with Windows: any REWIND that can't seek leaves the unit locked.
For example, with GCC 16.2.0 and standard output to a pipe:

  program p
    implicit none
    integer :: ios
    rewind (6, iostat=ios)
    print *, 'after REWIND, iostat =', ios
  end program p

  $ gfortran p.f90 && ./a.out | cat
  At line 5 of file p.f90 (unit = 6, file = 'stdout')
  Fortran runtime error: Recursive I/O not allowed

With the patch it prints "after REWIND, iostat = 29" (ESPIPE).  Without
it, a BACKSPACE instead of the PRINT hangs, and with GCC 15.3, which
lacks the recursive I/O check from PR 119136, so does the PRINT.

Regtested on x86_64-pc-linux-gnu (non-bootstrap, make
check-gcc-fortran): no new failures; the new test fails without the
fix and passes with it.

The async_wait error paths in st_backspace, st_endfile, st_rewind and
st_flush also leave the unit locked.  I can't test those, so I left
them out; happy to send a separate patch.

OK for master?  I don't have write access, so someone would need to
push it.

Thank you,
Federico

Assisted by: Claude Opus 5.5

Attachment: 0001-libgfortran-Unlock-the-unit-when-REWIND-fails-to-see.patch
Description: Binary data

Reply via email to