When a WRITE statement includes ERR= and/or IOSTAT= specifiers and is executed after ENDFILE, flang incorrectly aborts with a fatal runtime error:
fatal Fortran runtime error: WRITE after ENDFILE
Per Fortran 2018 §12.11.2, it should instead set IOSTAT to a non-zero value and branch to the ERR= label if provided.
Relevant Standard (F2018 §12.11.2):
If an error condition occurs during execution of an input/output statement that contains neither an ERR= nor IOSTAT= specifier, error termination occurs.
Error termination is only permitted when an I/O statement has neither ERR= nor IOSTAT=.
Reproducer:
program write_after_endfile
implicit none
integer :: n, k, l
logical :: ok
ok = .true.
open(5, err=500, iostat=n)
k = 45
goto 505
500 continue
k = 46
505 continue
print *, 'k after OPEN:', k
ok = ok .and. (k == 45)
close(5, err=510, iostat=n)
k = 55
goto 515
510 continue
k = 56
515 continue
print *, 'k after CLOSE:', k
ok = ok .and. (k == 55)
read(5, err=520, iostat=n) l
k = 65
goto 523
520 continue
k = 66
523 continue
print *, 'iostat after read:', n, ' k:', k
ok = ok .and. (k == 66)
l = 34
write(5, err=525, iostat=n) l
k = 65
goto 528
525 continue
k = 66
528 continue
print *, 'iostat after write:', n, ' k:', k
ok = ok .and. (k == 66)
if (ok) then
print *, 'PASS'
else
print *, 'FAIL'
end if
end program write_after_endfile
Expected Behaviour
Program doesnt crash and Pass
Actual Behaviour
The issue is in flang-rt/lib/runtime/unit.cpp. The ExternalFileUnit::Emit() function calls handler.SignalError(IostatWriteAfterEndfile), which triggers a fatal abort when no error handler is detected at that point. However, ERR=/IOSTAT= specifiers are present — the error is being signaled too early, before the I/O statement's error handling context is fully established.
gfortran handles this case correctly.
Testcase Added : 396
Fix : 191633
When a WRITE statement includes ERR= and/or IOSTAT= specifiers and is executed after ENDFILE, flang incorrectly aborts with a fatal runtime error:
Per Fortran 2018 §12.11.2, it should instead set IOSTAT to a non-zero value and branch to the ERR= label if provided.
Relevant Standard (F2018 §12.11.2):
Reproducer:
Expected Behaviour
Program doesnt crash and Pass
Actual Behaviour
The issue is in flang-rt/lib/runtime/unit.cpp. The ExternalFileUnit::Emit() function calls handler.SignalError(IostatWriteAfterEndfile), which triggers a fatal abort when no error handler is detected at that point. However, ERR=/IOSTAT= specifiers are present — the error is being signaled too early, before the I/O statement's error handling context is fully established.
gfortran handles this case correctly.
Testcase Added : 396
Fix : 191633