[flang][runtime] Make ENDFILE work after non-advancing READ
authorPeter Klausler <pklausler@nvidia.com>
Wed, 29 Jun 2022 00:48:15 +0000 (17:48 -0700)
committerPeter Klausler <pklausler@nvidia.com>
Thu, 7 Jul 2022 00:30:33 +0000 (17:30 -0700)
An ENDFILE statement executed when a non-advancing READ has
left the unit in the middle of a record must truncate the file
at that position.

Differential Revision: https://reviews.llvm.org/D129019

flang/runtime/unit.cpp

index e0daf8c..a96b43d 100644 (file)
@@ -887,16 +887,20 @@ void ExternalFileUnit::DoImpliedEndfile(IoErrorHandler &handler) {
 
 void ExternalFileUnit::DoEndfile(IoErrorHandler &handler) {
   if (IsRecordFile() && access != Access::Direct) {
+    furthestPositionInRecord =
+        std::max(positionInRecord, furthestPositionInRecord);
     if (furthestPositionInRecord > 0) {
-      // Last write was non-advancing, so AdvanceRecord() was not called.
+      // Last read/write was non-advancing, so AdvanceRecord() was not called.
       leftTabLimit.reset();
       ++currentRecordNumber;
     }
     endfileRecordNumber = currentRecordNumber;
   }
-  FlushOutput(handler);
-  Truncate(frameOffsetInFile_ + recordOffsetInFrame_ + furthestPositionInRecord,
-      handler);
+  frameOffsetInFile_ += recordOffsetInFrame_ + furthestPositionInRecord;
+  recordOffsetInFrame_ = 0;
+  // Flush (if dirty) and reset the frame (even if reading)
+  WriteFrame(frameOffsetInFile_, 0, handler);
+  Truncate(frameOffsetInFile_, handler);
   BeginRecord();
   impliedEndfile_ = false;
 }