https://gcc.gnu.org/bugzilla/show_bug.cgi?id=92836
Andrew Benson <abensonca at gcc dot gnu.org> changed:
What |Removed |Added
----------------------------------------------------------------------------
CC| |abensonca at gcc dot gnu.org
--- Comment #19 from Andrew Benson <abensonca at gcc dot gnu.org> ---
This appears to be fixed on trunk by r17-6022-gbcf14085d82 (PR 118935, "Fix
data race on the unit stream pointer").
The cause is the race that commit describes: find_file0 (used by
INQUIRE(FILE=...)) walks the unit tree holding unit_rwlock only for reading and
dereferences each unit's stream pointer, while a CLOSE in another thread frees
that stream (close_unit_1 -> sclose -> raw_close) without unit_rwlock.
A small reproducer: half the threads repeatedly open, write and close their own
files, and the other half INQUIRE by file name.
program inquireRace
use omp_lib
implicit none
integer :: i, u, t
logical :: e
character(len=64) :: f
!$omp parallel private(i,u,t,e,f)
t=omp_get_thread_num()
write (f,'(a,i0,a)') 'scratch_',t,'.txt'
do i=1,20000
if (mod(t,2) == 0) then
open(newunit=u,file=trim(f),status='replace',form='formatted')
write (u,*) i
close(u)
else
inquire(file='scratch_0.txt',exist=e)
end if
end do
!$omp end parallel
write (*,*) "COMPLETED"
end program inquireRace
$ gfortran -g -fopenmp pr92836.f90
$ OMP_NUM_THREADS=4 valgrind --fair-sched=yes ./a.out
With the libgfortran from 16.0.1 and from the 16 branch (16.2.1 20261115),
valgrind reports 4 invalid reads of this form:
Invalid read of size 8
at find_file0 (unix.c:1724)
by find_file0 (unix.c:1740)
by _gfortrani_find_file (unix.c:1778)
by _gfortran_st_inquire (inquire.c:875)
by MAIN__._omp_fn.0 (pr92836.f90:17)
Address ... is 72 bytes inside a block of size 96 free'd
at free
by raw_close (unix.c:488)
by sclose (unix.h:95)
With trunk's libgfortran (17.0.0 20261115, which includes r17-6022) it reports
none.
So I think this can be closed as a duplicate of PR 118935. Since the fix is not
on releases/gcc-16, could it be considered for backport to
the 16 branch? We hit this crash in production runs (OpenMP plus MPI), and
currently work around it by calling POSIX access() instead of
INQUIRE(FILE=...,EXIST=...).