llvm-project icon indicating copy to clipboard operation
llvm-project copied to clipboard

[Flang] Reading byte-swapped unformatted sequential file gives incorrect record length error

Open jonathonpenix opened this issue 4 years ago • 7 comments

A small reproducer is below:

program test_convert
  implicit none
  integer, parameter :: n = 4
  integer, parameter :: fid = 20
  real :: arr(n)
  real :: buf(n)
  integer :: i
  arr = (/1.0, 2.0, 3.0, 4.0/)

  open(fid, file="test.txt", form='UNFORMATTED', status='new')
  write(fid) arr
  close(fid)

  open(fid, file="test.txt", form='UNFORMATTED', status='old')
  read(fid) buf
  close(fid)
end program

When building with flang and running with the command FORT_CONVERT='SWAP' ./a.out, I see the following error:

fatal Fortran runtime error(./test.f90:15): Unformatted variable-length sequential file input failed at record #1 (file offset 0): hit EOF reading record with length 268435456 bytes
Aborted

When building with gfortran and running with the command GFORTRAN_CONVERT_UNIT='SWAP' ./a.out, the program executes as expected.

I think the fix is to make sure that the header and footer lengths here (and potentially other places) are also byte-swapped as appropriate, but I need to investigate further (and assuming I'm not doing something incorrect in the Fortran source).

jonathonpenix avatar Aug 12 '22 22:08 jonathonpenix

@llvm/issue-subscribers-flang-runtime

llvmbot avatar Aug 12 '22 22:08 llvmbot

I think your guess is spot on -- the header/footer lengths don't go through the same datapath as payload data, and are always in native host byte order.

klausler avatar Aug 12 '22 23:08 klausler

It turns out that headers & footers are properly endianness-swapped when necessary on the output path, but not on the input path. Fix coming.

klausler avatar Aug 18 '22 16:08 klausler

Do you already have the patch ready to go? If not, I think I have one that tested ok last night that I can post. Apologies for the mix-up/maybe duplicated effort!

jonathonpenix avatar Aug 18 '22 17:08 jonathonpenix

I do, and can put it into phabricator today if that's soon enough for you.

klausler avatar Aug 18 '22 17:08 klausler

Ok, sounds good! Yep, no rush. Thanks!

jonathonpenix avatar Aug 18 '22 17:08 jonathonpenix

https://reviews.llvm.org/D132168

klausler avatar Aug 18 '22 18:08 klausler