<table border="1" cellspacing="0" cellpadding="8">
    <tr>
        <th>Issue</th>
        <td>
            <a href=https://github.com/llvm/llvm-project/issues/57126>57126</a>
        </td>
    </tr>

    <tr>
        <th>Summary</th>
        <td>
            [Flang] Reading byte-swapped unformatted sequential file gives incorrect record length error
        </td>
    </tr>

    <tr>
      <th>Labels</th>
      <td>
            flang:runtime
      </td>
    </tr>

    <tr>
      <th>Assignees</th>
      <td>
            jpenix-quic
      </td>
    </tr>

    <tr>
      <th>Reporter</th>
      <td>
          jpenix-quic
      </td>
    </tr>
</table>

<pre>
    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](https://github.com/llvm/llvm-project/blob/2366c6adfc95e1aca9afbbbf5251a61552865b55/flang/runtime/unit.cpp#L720-L731) (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). 
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJy1VU1v2zgQ_TX2hbAgUZZsHXzwJvEiQDdZZJP2GFDSSGZLiSpJ5ePf7yMtOWlRtNvDGob5MeTMm3lv6FLXr7s9s51QihkajK7HigyTlpWk9PMi3S_iy0U8_-bx9A1LHG-N6Jgj6x4r3T-RcScLY7IblKykY73u6bzZO2rJLPgFGwRukkMsHyPdsx6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