1 //===-- runtime/unit.cpp --------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "unit.h"
10 #include "environment.h"
11 #include "io-error.h"
12 #include "lock.h"
13 #include "unit-map.h"
14 #include <cstdio>
15 #include <limits>
16 #include <utility>
17 
18 namespace Fortran::runtime::io {
19 
20 // The per-unit data structures are created on demand so that Fortran I/O
21 // should work without a Fortran main program.
22 static Lock unitMapLock;
23 static UnitMap *unitMap{nullptr};
24 static ExternalFileUnit *defaultInput{nullptr};
25 static ExternalFileUnit *defaultOutput{nullptr};
26 
27 void FlushOutputOnCrash(const Terminator &terminator) {
28   if (!defaultOutput) {
29     return;
30   }
31   CriticalSection critical{unitMapLock};
32   if (defaultOutput) {
33     IoErrorHandler handler{terminator};
34     handler.HasIoStat(); // prevent nested crash if flush has error
35     defaultOutput->FlushOutput(handler);
36   }
37 }
38 
39 ExternalFileUnit *ExternalFileUnit::LookUp(int unit) {
40   return GetUnitMap().LookUp(unit);
41 }
42 
43 ExternalFileUnit &ExternalFileUnit::LookUpOrCrash(
44     int unit, const Terminator &terminator) {
45   ExternalFileUnit *file{LookUp(unit)};
46   if (!file) {
47     terminator.Crash("Not an open I/O unit number: %d", unit);
48   }
49   return *file;
50 }
51 
52 ExternalFileUnit &ExternalFileUnit::LookUpOrCreate(
53     int unit, const Terminator &terminator, bool &wasExtant) {
54   return GetUnitMap().LookUpOrCreate(unit, terminator, wasExtant);
55 }
56 
57 ExternalFileUnit &ExternalFileUnit::LookUpOrCreateAnonymous(int unit,
58     Direction dir, std::optional<bool> isUnformatted,
59     const Terminator &terminator) {
60   bool exists{false};
61   ExternalFileUnit &result{
62       GetUnitMap().LookUpOrCreate(unit, terminator, exists)};
63   if (!exists) {
64     IoErrorHandler handler{terminator};
65     result.OpenAnonymousUnit(
66         dir == Direction::Input ? OpenStatus::Unknown : OpenStatus::Replace,
67         Action::ReadWrite, Position::Rewind, Convert::Native, handler);
68     result.isUnformatted = isUnformatted;
69   }
70   return result;
71 }
72 
73 ExternalFileUnit *ExternalFileUnit::LookUp(const char *path) {
74   return GetUnitMap().LookUp(path);
75 }
76 
77 ExternalFileUnit &ExternalFileUnit::CreateNew(
78     int unit, const Terminator &terminator) {
79   bool wasExtant{false};
80   ExternalFileUnit &result{
81       GetUnitMap().LookUpOrCreate(unit, terminator, wasExtant)};
82   RUNTIME_CHECK(terminator, !wasExtant);
83   return result;
84 }
85 
86 ExternalFileUnit *ExternalFileUnit::LookUpForClose(int unit) {
87   return GetUnitMap().LookUpForClose(unit);
88 }
89 
90 ExternalFileUnit &ExternalFileUnit::NewUnit(
91     const Terminator &terminator, bool forChildIo) {
92   ExternalFileUnit &unit{GetUnitMap().NewUnit(terminator)};
93   unit.createdForInternalChildIo_ = forChildIo;
94   return unit;
95 }
96 
97 void ExternalFileUnit::OpenUnit(std::optional<OpenStatus> status,
98     std::optional<Action> action, Position position, OwningPtr<char> &&newPath,
99     std::size_t newPathLength, Convert convert, IoErrorHandler &handler) {
100   if (executionEnvironment.conversion != Convert::Unknown) {
101     convert = executionEnvironment.conversion;
102   }
103   swapEndianness_ = convert == Convert::Swap ||
104       (convert == Convert::LittleEndian && !isHostLittleEndian) ||
105       (convert == Convert::BigEndian && isHostLittleEndian);
106   if (IsOpen()) {
107     bool isSamePath{newPath.get() && path() && pathLength() == newPathLength &&
108         std::memcmp(path(), newPath.get(), newPathLength) == 0};
109     if (status && *status != OpenStatus::Old && isSamePath) {
110       handler.SignalError("OPEN statement for connected unit may not have "
111                           "explicit STATUS= other than 'OLD'");
112       return;
113     }
114     if (!newPath.get() || isSamePath) {
115       // OPEN of existing unit, STATUS='OLD' or unspecified, not new FILE=
116       newPath.reset();
117       return;
118     }
119     // Otherwise, OPEN on open unit with new FILE= implies CLOSE
120     DoImpliedEndfile(handler);
121     FlushOutput(handler);
122     Close(CloseStatus::Keep, handler);
123   }
124   set_path(std::move(newPath), newPathLength);
125   Open(status.value_or(OpenStatus::Unknown), action, position, handler);
126   auto totalBytes{knownSize()};
127   if (access == Access::Direct) {
128     if (!isFixedRecordLength || !recordLength) {
129       handler.SignalError(IostatOpenBadRecl,
130           "OPEN(UNIT=%d,ACCESS='DIRECT'): record length is not known",
131           unitNumber());
132     } else if (*recordLength <= 0) {
133       handler.SignalError(IostatOpenBadRecl,
134           "OPEN(UNIT=%d,ACCESS='DIRECT',RECL=%jd): record length is invalid",
135           unitNumber(), static_cast<std::intmax_t>(*recordLength));
136     } else if (totalBytes && (*totalBytes % *recordLength != 0)) {
137       handler.SignalError(IostatOpenBadAppend,
138           "OPEN(UNIT=%d,ACCESS='DIRECT',RECL=%jd): record length is not an "
139           "even divisor of the file size %jd",
140           unitNumber(), static_cast<std::intmax_t>(*recordLength),
141           static_cast<std::intmax_t>(*totalBytes));
142     }
143   }
144   endfileRecordNumber.reset();
145   currentRecordNumber = 1;
146   if (totalBytes && recordLength && *recordLength) {
147     endfileRecordNumber = 1 + (*totalBytes / *recordLength);
148   }
149   if (position == Position::Append) {
150     if (!endfileRecordNumber) {
151       // Fake it so that we can backspace relative from the end
152       endfileRecordNumber = std::numeric_limits<std::int64_t>::max() - 2;
153     }
154     currentRecordNumber = *endfileRecordNumber;
155   }
156 }
157 
158 void ExternalFileUnit::OpenAnonymousUnit(std::optional<OpenStatus> status,
159     std::optional<Action> action, Position position, Convert convert,
160     IoErrorHandler &handler) {
161   // I/O to an unconnected unit reads/creates a local file, e.g. fort.7
162   std::size_t pathMaxLen{32};
163   auto path{SizedNew<char>{handler}(pathMaxLen)};
164   std::snprintf(path.get(), pathMaxLen, "fort.%d", unitNumber_);
165   OpenUnit(status, action, position, std::move(path), std::strlen(path.get()),
166       convert, handler);
167 }
168 
169 void ExternalFileUnit::CloseUnit(CloseStatus status, IoErrorHandler &handler) {
170   DoImpliedEndfile(handler);
171   FlushOutput(handler);
172   Close(status, handler);
173 }
174 
175 void ExternalFileUnit::DestroyClosed() {
176   GetUnitMap().DestroyClosed(*this); // destroys *this
177 }
178 
179 bool ExternalFileUnit::SetDirection(
180     Direction direction, IoErrorHandler &handler) {
181   if (direction == Direction::Input) {
182     if (mayRead()) {
183       direction_ = Direction::Input;
184       return true;
185     } else {
186       handler.SignalError(IostatReadFromWriteOnly,
187           "READ(UNIT=%d) with ACTION='WRITE'", unitNumber());
188       return false;
189     }
190   } else {
191     if (mayWrite()) {
192       direction_ = Direction::Output;
193       return true;
194     } else {
195       handler.SignalError(IostatWriteToReadOnly,
196           "WRITE(UNIT=%d) with ACTION='READ'", unitNumber());
197       return false;
198     }
199   }
200 }
201 
202 UnitMap &ExternalFileUnit::GetUnitMap() {
203   if (unitMap) {
204     return *unitMap;
205   }
206   CriticalSection critical{unitMapLock};
207   if (unitMap) {
208     return *unitMap;
209   }
210   Terminator terminator{__FILE__, __LINE__};
211   IoErrorHandler handler{terminator};
212   UnitMap *newUnitMap{New<UnitMap>{terminator}().release()};
213   bool wasExtant{false};
214   ExternalFileUnit &out{newUnitMap->LookUpOrCreate(6, terminator, wasExtant)};
215   RUNTIME_CHECK(terminator, !wasExtant);
216   out.Predefine(1);
217   out.SetDirection(Direction::Output, handler);
218   defaultOutput = &out;
219   ExternalFileUnit &in{newUnitMap->LookUpOrCreate(5, terminator, wasExtant)};
220   RUNTIME_CHECK(terminator, !wasExtant);
221   in.Predefine(0);
222   in.SetDirection(Direction::Input, handler);
223   defaultInput = &in;
224   // TODO: Set UTF-8 mode from the environment
225   unitMap = newUnitMap;
226   return *unitMap;
227 }
228 
229 void ExternalFileUnit::CloseAll(IoErrorHandler &handler) {
230   CriticalSection critical{unitMapLock};
231   if (unitMap) {
232     unitMap->CloseAll(handler);
233     FreeMemoryAndNullify(unitMap);
234   }
235   defaultOutput = nullptr;
236 }
237 
238 void ExternalFileUnit::FlushAll(IoErrorHandler &handler) {
239   CriticalSection critical{unitMapLock};
240   if (unitMap) {
241     unitMap->FlushAll(handler);
242   }
243 }
244 
245 static void SwapEndianness(
246     char *data, std::size_t bytes, std::size_t elementBytes) {
247   if (elementBytes > 1) {
248     auto half{elementBytes >> 1};
249     for (std::size_t j{0}; j + elementBytes <= bytes; j += elementBytes) {
250       for (std::size_t k{0}; k < half; ++k) {
251         std::swap(data[j + k], data[j + elementBytes - 1 - k]);
252       }
253     }
254   }
255 }
256 
257 bool ExternalFileUnit::Emit(const char *data, std::size_t bytes,
258     std::size_t elementBytes, IoErrorHandler &handler) {
259   auto furthestAfter{std::max(furthestPositionInRecord,
260       positionInRecord + static_cast<std::int64_t>(bytes))};
261   if (recordLength) {
262     // It is possible for recordLength to have a value now for a
263     // variable-length output record if the previous operation
264     // was a BACKSPACE or non advancing input statement.
265     if (!isFixedRecordLength) {
266       recordLength.reset();
267       beganReadingRecord_ = false;
268     } else if (furthestAfter > *recordLength) {
269       handler.SignalError(IostatRecordWriteOverrun,
270           "Attempt to write %zd bytes to position %jd in a fixed-size record "
271           "of %jd bytes",
272           bytes, static_cast<std::intmax_t>(positionInRecord),
273           static_cast<std::intmax_t>(*recordLength));
274       return false;
275     }
276   }
277   WriteFrame(frameOffsetInFile_, recordOffsetInFrame_ + furthestAfter, handler);
278   if (positionInRecord > furthestPositionInRecord) {
279     std::memset(Frame() + recordOffsetInFrame_ + furthestPositionInRecord, ' ',
280         positionInRecord - furthestPositionInRecord);
281   }
282   char *to{Frame() + recordOffsetInFrame_ + positionInRecord};
283   std::memcpy(to, data, bytes);
284   if (swapEndianness_) {
285     SwapEndianness(to, bytes, elementBytes);
286   }
287   positionInRecord += bytes;
288   furthestPositionInRecord = furthestAfter;
289   return true;
290 }
291 
292 bool ExternalFileUnit::Receive(char *data, std::size_t bytes,
293     std::size_t elementBytes, IoErrorHandler &handler) {
294   RUNTIME_CHECK(handler, direction_ == Direction::Input);
295   auto furthestAfter{std::max(furthestPositionInRecord,
296       positionInRecord + static_cast<std::int64_t>(bytes))};
297   if (furthestAfter > recordLength.value_or(furthestAfter)) {
298     handler.SignalError(IostatRecordReadOverrun,
299         "Attempt to read %zd bytes at position %jd in a record of %jd bytes",
300         bytes, static_cast<std::intmax_t>(positionInRecord),
301         static_cast<std::intmax_t>(*recordLength));
302     return false;
303   }
304   auto need{recordOffsetInFrame_ + furthestAfter};
305   auto got{ReadFrame(frameOffsetInFile_, need, handler)};
306   if (got >= need) {
307     std::memcpy(data, Frame() + recordOffsetInFrame_ + positionInRecord, bytes);
308     if (swapEndianness_) {
309       SwapEndianness(data, bytes, elementBytes);
310     }
311     positionInRecord += bytes;
312     furthestPositionInRecord = furthestAfter;
313     return true;
314   } else {
315     // EOF or error: can be handled & has been signaled
316     endfileRecordNumber = currentRecordNumber;
317     return false;
318   }
319 }
320 
321 std::size_t ExternalFileUnit::GetNextInputBytes(
322     const char *&p, IoErrorHandler &handler) {
323   RUNTIME_CHECK(handler, direction_ == Direction::Input);
324   p = FrameNextInput(handler, 1);
325   return p ? recordLength.value_or(positionInRecord + 1) - positionInRecord : 0;
326 }
327 
328 std::optional<char32_t> ExternalFileUnit::GetCurrentChar(
329     IoErrorHandler &handler) {
330   const char *p{nullptr};
331   std::size_t bytes{GetNextInputBytes(p, handler)};
332   if (bytes == 0) {
333     return std::nullopt;
334   } else {
335     // TODO: UTF-8 decoding; may have to get more bytes in a loop
336     return *p;
337   }
338 }
339 
340 const char *ExternalFileUnit::FrameNextInput(
341     IoErrorHandler &handler, std::size_t bytes) {
342   RUNTIME_CHECK(handler, isUnformatted.has_value() && !*isUnformatted);
343   if (static_cast<std::int64_t>(positionInRecord + bytes) <=
344       recordLength.value_or(positionInRecord + bytes)) {
345     auto at{recordOffsetInFrame_ + positionInRecord};
346     auto need{static_cast<std::size_t>(at + bytes)};
347     auto got{ReadFrame(frameOffsetInFile_, need, handler)};
348     SetSequentialVariableFormattedRecordLength();
349     if (got >= need) {
350       return Frame() + at;
351     }
352     handler.SignalEnd();
353     endfileRecordNumber = currentRecordNumber;
354   }
355   return nullptr;
356 }
357 
358 bool ExternalFileUnit::SetSequentialVariableFormattedRecordLength() {
359   if (recordLength || access != Access::Sequential) {
360     return true;
361   } else if (FrameLength() > recordOffsetInFrame_) {
362     const char *record{Frame() + recordOffsetInFrame_};
363     std::size_t bytes{FrameLength() - recordOffsetInFrame_};
364     if (const char *nl{
365             reinterpret_cast<const char *>(std::memchr(record, '\n', bytes))}) {
366       recordLength = nl - record;
367       if (*recordLength > 0 && record[*recordLength - 1] == '\r') {
368         --*recordLength;
369       }
370       return true;
371     }
372   }
373   return false;
374 }
375 
376 void ExternalFileUnit::SetLeftTabLimit() {
377   leftTabLimit = furthestPositionInRecord;
378   positionInRecord = furthestPositionInRecord;
379 }
380 
381 bool ExternalFileUnit::BeginReadingRecord(IoErrorHandler &handler) {
382   RUNTIME_CHECK(handler, direction_ == Direction::Input);
383   if (!beganReadingRecord_) {
384     beganReadingRecord_ = true;
385     if (access == Access::Sequential) {
386       if (endfileRecordNumber && currentRecordNumber >= *endfileRecordNumber) {
387         handler.SignalEnd();
388       } else if (isFixedRecordLength && access == Access::Direct) {
389         RUNTIME_CHECK(handler, recordLength.has_value());
390         auto need{
391             static_cast<std::size_t>(recordOffsetInFrame_ + *recordLength)};
392         auto got{ReadFrame(frameOffsetInFile_, need, handler)};
393         if (got < need) {
394           handler.SignalEnd();
395         }
396       } else {
397         RUNTIME_CHECK(handler, isUnformatted.has_value());
398         if (isUnformatted.value_or(false)) {
399           BeginSequentialVariableUnformattedInputRecord(handler);
400         } else { // formatted
401           BeginSequentialVariableFormattedInputRecord(handler);
402         }
403       }
404     }
405   }
406   RUNTIME_CHECK(handler,
407       access != Access::Sequential || recordLength.has_value() ||
408           handler.InError());
409   return !handler.InError();
410 }
411 
412 void ExternalFileUnit::FinishReadingRecord(IoErrorHandler &handler) {
413   RUNTIME_CHECK(handler, direction_ == Direction::Input && beganReadingRecord_);
414   beganReadingRecord_ = false;
415   if (handler.InError() && handler.GetIoStat() != IostatEor) {
416     // avoid bogus crashes in END/ERR circumstances
417   } else if (access == Access::Sequential) {
418     RUNTIME_CHECK(handler, recordLength.has_value());
419     recordOffsetInFrame_ += *recordLength;
420     if (isFixedRecordLength && access == Access::Direct) {
421       frameOffsetInFile_ += recordOffsetInFrame_;
422       recordOffsetInFrame_ = 0;
423     } else {
424       RUNTIME_CHECK(handler, isUnformatted.has_value());
425       recordLength.reset();
426       if (isUnformatted.value_or(false)) {
427         // Retain footer in frame for more efficient BACKSPACE
428         frameOffsetInFile_ += recordOffsetInFrame_;
429         recordOffsetInFrame_ = sizeof(std::uint32_t);
430       } else { // formatted
431         if (FrameLength() > recordOffsetInFrame_ &&
432             Frame()[recordOffsetInFrame_] == '\r') {
433           ++recordOffsetInFrame_;
434         }
435         if (FrameLength() >= recordOffsetInFrame_ &&
436             Frame()[recordOffsetInFrame_] == '\n') {
437           ++recordOffsetInFrame_;
438         }
439         if (!pinnedFrame || mayPosition()) {
440           frameOffsetInFile_ += recordOffsetInFrame_;
441           recordOffsetInFrame_ = 0;
442         }
443       }
444     }
445   }
446   ++currentRecordNumber;
447   BeginRecord();
448 }
449 
450 bool ExternalFileUnit::AdvanceRecord(IoErrorHandler &handler) {
451   if (direction_ == Direction::Input) {
452     FinishReadingRecord(handler);
453     return BeginReadingRecord(handler);
454   } else { // Direction::Output
455     bool ok{true};
456     RUNTIME_CHECK(handler, isUnformatted.has_value());
457     if (isFixedRecordLength && recordLength &&
458         furthestPositionInRecord < *recordLength) {
459       // Pad remainder of fixed length record
460       WriteFrame(
461           frameOffsetInFile_, recordOffsetInFrame_ + *recordLength, handler);
462       std::memset(Frame() + recordOffsetInFrame_ + furthestPositionInRecord,
463           isUnformatted.value_or(false) ? 0 : ' ',
464           *recordLength - furthestPositionInRecord);
465       furthestPositionInRecord = *recordLength;
466     }
467     if (!(isFixedRecordLength && access == Access::Direct)) {
468       positionInRecord = furthestPositionInRecord;
469       if (isUnformatted.value_or(false)) {
470         // Append the length of a sequential unformatted variable-length record
471         // as its footer, then overwrite the reserved first four bytes of the
472         // record with its length as its header.  These four bytes were skipped
473         // over in BeginUnformattedIO<Output>().
474         // TODO: Break very large records up into subrecords with negative
475         // headers &/or footers
476         std::uint32_t length;
477         length = furthestPositionInRecord - sizeof length;
478         ok = ok &&
479             Emit(reinterpret_cast<const char *>(&length), sizeof length,
480                 sizeof length, handler);
481         positionInRecord = 0;
482         ok = ok &&
483             Emit(reinterpret_cast<const char *>(&length), sizeof length,
484                 sizeof length, handler);
485       } else {
486         // Terminate formatted variable length record
487         ok = ok && Emit("\n", 1, 1, handler); // TODO: Windows CR+LF
488       }
489     }
490     CommitWrites();
491     impliedEndfile_ = true;
492     ++currentRecordNumber;
493     if (endfileRecordNumber && currentRecordNumber >= *endfileRecordNumber) {
494       endfileRecordNumber.reset();
495     }
496     return ok;
497   }
498 }
499 
500 void ExternalFileUnit::BackspaceRecord(IoErrorHandler &handler) {
501   if (access != Access::Sequential) {
502     handler.SignalError(IostatBackspaceNonSequential,
503         "BACKSPACE(UNIT=%d) on non-sequential file", unitNumber());
504   } else {
505     if (endfileRecordNumber && currentRecordNumber > *endfileRecordNumber) {
506       // BACKSPACE after explicit ENDFILE
507       currentRecordNumber = *endfileRecordNumber;
508     } else {
509       DoImpliedEndfile(handler);
510       if (frameOffsetInFile_ + recordOffsetInFrame_ > 0) {
511         --currentRecordNumber;
512         if (isFixedRecordLength && access == Access::Direct) {
513           BackspaceFixedRecord(handler);
514         } else {
515           RUNTIME_CHECK(handler, isUnformatted.has_value());
516           if (isUnformatted.value_or(false)) {
517             BackspaceVariableUnformattedRecord(handler);
518           } else {
519             BackspaceVariableFormattedRecord(handler);
520           }
521         }
522       }
523     }
524     BeginRecord();
525   }
526 }
527 
528 void ExternalFileUnit::FlushOutput(IoErrorHandler &handler) {
529   if (!mayPosition()) {
530     auto frameAt{FrameAt()};
531     if (frameOffsetInFile_ >= frameAt &&
532         frameOffsetInFile_ <
533             static_cast<std::int64_t>(frameAt + FrameLength())) {
534       // A Flush() that's about to happen to a non-positionable file
535       // needs to advance frameOffsetInFile_ to prevent attempts at
536       // impossible seeks
537       CommitWrites();
538     }
539   }
540   Flush(handler);
541 }
542 
543 void ExternalFileUnit::FlushIfTerminal(IoErrorHandler &handler) {
544   if (isTerminal()) {
545     FlushOutput(handler);
546   }
547 }
548 
549 void ExternalFileUnit::Endfile(IoErrorHandler &handler) {
550   if (access != Access::Sequential) {
551     handler.SignalError(IostatEndfileNonSequential,
552         "ENDFILE(UNIT=%d) on non-sequential file", unitNumber());
553   } else if (!mayWrite()) {
554     handler.SignalError(IostatEndfileUnwritable,
555         "ENDFILE(UNIT=%d) on read-only file", unitNumber());
556   } else if (endfileRecordNumber &&
557       currentRecordNumber > *endfileRecordNumber) {
558     // ENDFILE after ENDFILE
559   } else {
560     DoEndfile(handler);
561     // Explicit ENDFILE leaves position *after* the endfile record
562     RUNTIME_CHECK(handler, endfileRecordNumber.has_value());
563     currentRecordNumber = *endfileRecordNumber + 1;
564   }
565 }
566 
567 void ExternalFileUnit::Rewind(IoErrorHandler &handler) {
568   if (access == Access::Direct) {
569     handler.SignalError(IostatRewindNonSequential,
570         "REWIND(UNIT=%d) on non-sequential file", unitNumber());
571   } else {
572     DoImpliedEndfile(handler);
573     SetPosition(0);
574     currentRecordNumber = 1;
575   }
576 }
577 
578 void ExternalFileUnit::EndIoStatement() {
579   io_.reset();
580   u_.emplace<std::monostate>();
581   lock_.Drop();
582 }
583 
584 void ExternalFileUnit::BeginSequentialVariableUnformattedInputRecord(
585     IoErrorHandler &handler) {
586   std::int32_t header{0}, footer{0};
587   std::size_t need{recordOffsetInFrame_ + sizeof header};
588   std::size_t got{ReadFrame(frameOffsetInFile_, need, handler)};
589   // Try to emit informative errors to help debug corrupted files.
590   const char *error{nullptr};
591   if (got < need) {
592     if (got == recordOffsetInFrame_) {
593       handler.SignalEnd();
594     } else {
595       error = "Unformatted variable-length sequential file input failed at "
596               "record #%jd (file offset %jd): truncated record header";
597     }
598   } else {
599     std::memcpy(&header, Frame() + recordOffsetInFrame_, sizeof header);
600     recordLength = sizeof header + header; // does not include footer
601     need = recordOffsetInFrame_ + *recordLength + sizeof footer;
602     got = ReadFrame(frameOffsetInFile_, need, handler);
603     if (got < need) {
604       error = "Unformatted variable-length sequential file input failed at "
605               "record #%jd (file offset %jd): hit EOF reading record with "
606               "length %jd bytes";
607     } else {
608       std::memcpy(&footer, Frame() + recordOffsetInFrame_ + *recordLength,
609           sizeof footer);
610       if (footer != header) {
611         error = "Unformatted variable-length sequential file input failed at "
612                 "record #%jd (file offset %jd): record header has length %jd "
613                 "that does not match record footer (%jd)";
614       }
615     }
616   }
617   if (error) {
618     handler.SignalError(error, static_cast<std::intmax_t>(currentRecordNumber),
619         static_cast<std::intmax_t>(frameOffsetInFile_),
620         static_cast<std::intmax_t>(header), static_cast<std::intmax_t>(footer));
621     // TODO: error recovery
622   }
623   positionInRecord = sizeof header;
624 }
625 
626 void ExternalFileUnit::BeginSequentialVariableFormattedInputRecord(
627     IoErrorHandler &handler) {
628   if (this == defaultInput && defaultOutput) {
629     defaultOutput->FlushOutput(handler);
630   }
631   std::size_t length{0};
632   do {
633     std::size_t need{length + 1};
634     length =
635         ReadFrame(frameOffsetInFile_, recordOffsetInFrame_ + need, handler) -
636         recordOffsetInFrame_;
637     if (length < need) {
638       if (length > 0) {
639         // final record w/o \n
640         recordLength = length;
641       } else {
642         handler.SignalEnd();
643       }
644       break;
645     }
646   } while (!SetSequentialVariableFormattedRecordLength());
647 }
648 
649 void ExternalFileUnit::BackspaceFixedRecord(IoErrorHandler &handler) {
650   RUNTIME_CHECK(handler, recordLength.has_value());
651   if (frameOffsetInFile_ < *recordLength) {
652     handler.SignalError(IostatBackspaceAtFirstRecord);
653   } else {
654     frameOffsetInFile_ -= *recordLength;
655   }
656 }
657 
658 void ExternalFileUnit::BackspaceVariableUnformattedRecord(
659     IoErrorHandler &handler) {
660   std::int32_t header{0}, footer{0};
661   auto headerBytes{static_cast<std::int64_t>(sizeof header)};
662   frameOffsetInFile_ += recordOffsetInFrame_;
663   recordOffsetInFrame_ = 0;
664   if (frameOffsetInFile_ <= headerBytes) {
665     handler.SignalError(IostatBackspaceAtFirstRecord);
666     return;
667   }
668   // Error conditions here cause crashes, not file format errors, because the
669   // validity of the file structure before the current record will have been
670   // checked informatively in NextSequentialVariableUnformattedInputRecord().
671   std::size_t got{
672       ReadFrame(frameOffsetInFile_ - headerBytes, headerBytes, handler)};
673   RUNTIME_CHECK(handler, got >= sizeof footer);
674   std::memcpy(&footer, Frame(), sizeof footer);
675   recordLength = footer;
676   RUNTIME_CHECK(handler, frameOffsetInFile_ >= *recordLength + 2 * headerBytes);
677   frameOffsetInFile_ -= *recordLength + 2 * headerBytes;
678   if (frameOffsetInFile_ >= headerBytes) {
679     frameOffsetInFile_ -= headerBytes;
680     recordOffsetInFrame_ = headerBytes;
681   }
682   auto need{static_cast<std::size_t>(
683       recordOffsetInFrame_ + sizeof header + *recordLength)};
684   got = ReadFrame(frameOffsetInFile_, need, handler);
685   RUNTIME_CHECK(handler, got >= need);
686   std::memcpy(&header, Frame() + recordOffsetInFrame_, sizeof header);
687   RUNTIME_CHECK(handler, header == *recordLength);
688 }
689 
690 // There's no portable memrchr(), unfortunately, and strrchr() would
691 // fail on a record with a NUL, so we have to do it the hard way.
692 static const char *FindLastNewline(const char *str, std::size_t length) {
693   for (const char *p{str + length}; p-- > str;) {
694     if (*p == '\n') {
695       return p;
696     }
697   }
698   return nullptr;
699 }
700 
701 void ExternalFileUnit::BackspaceVariableFormattedRecord(
702     IoErrorHandler &handler) {
703   // File offset of previous record's newline
704   auto prevNL{
705       frameOffsetInFile_ + static_cast<std::int64_t>(recordOffsetInFrame_) - 1};
706   if (prevNL < 0) {
707     handler.SignalError(IostatBackspaceAtFirstRecord);
708     return;
709   }
710   while (true) {
711     if (frameOffsetInFile_ < prevNL) {
712       if (const char *p{
713               FindLastNewline(Frame(), prevNL - 1 - frameOffsetInFile_)}) {
714         recordOffsetInFrame_ = p - Frame() + 1;
715         recordLength = prevNL - (frameOffsetInFile_ + recordOffsetInFrame_);
716         break;
717       }
718     }
719     if (frameOffsetInFile_ == 0) {
720       recordOffsetInFrame_ = 0;
721       recordLength = prevNL;
722       break;
723     }
724     frameOffsetInFile_ -= std::min<std::int64_t>(frameOffsetInFile_, 1024);
725     auto need{static_cast<std::size_t>(prevNL + 1 - frameOffsetInFile_)};
726     auto got{ReadFrame(frameOffsetInFile_, need, handler)};
727     RUNTIME_CHECK(handler, got >= need);
728   }
729   RUNTIME_CHECK(handler, Frame()[recordOffsetInFrame_ + *recordLength] == '\n');
730   if (*recordLength > 0 &&
731       Frame()[recordOffsetInFrame_ + *recordLength - 1] == '\r') {
732     --*recordLength;
733   }
734 }
735 
736 void ExternalFileUnit::DoImpliedEndfile(IoErrorHandler &handler) {
737   if (impliedEndfile_) {
738     impliedEndfile_ = false;
739     if (access == Access::Sequential && mayPosition()) {
740       DoEndfile(handler);
741     }
742   }
743 }
744 
745 void ExternalFileUnit::DoEndfile(IoErrorHandler &handler) {
746   endfileRecordNumber = currentRecordNumber;
747   Truncate(frameOffsetInFile_ + recordOffsetInFrame_, handler);
748   BeginRecord();
749   impliedEndfile_ = false;
750 }
751 
752 void ExternalFileUnit::CommitWrites() {
753   frameOffsetInFile_ +=
754       recordOffsetInFrame_ + recordLength.value_or(furthestPositionInRecord);
755   recordOffsetInFrame_ = 0;
756   BeginRecord();
757 }
758 
759 ChildIo &ExternalFileUnit::PushChildIo(IoStatementState &parent) {
760   OwningPtr<ChildIo> current{std::move(child_)};
761   Terminator &terminator{parent.GetIoErrorHandler()};
762   OwningPtr<ChildIo> next{New<ChildIo>{terminator}(parent, std::move(current))};
763   child_.reset(next.release());
764   return *child_;
765 }
766 
767 void ExternalFileUnit::PopChildIo(ChildIo &child) {
768   if (child_.get() != &child) {
769     child.parent().GetIoErrorHandler().Crash(
770         "ChildIo being popped is not top of stack");
771   }
772   child_.reset(child.AcquirePrevious().release()); // deletes top child
773 }
774 
775 void ChildIo::EndIoStatement() {
776   io_.reset();
777   u_.emplace<std::monostate>();
778 }
779 
780 bool ChildIo::CheckFormattingAndDirection(Terminator &terminator,
781     const char *what, bool unformatted, Direction direction) {
782   bool parentIsInput{!parent_.get_if<IoDirectionState<Direction::Output>>()};
783   bool parentIsFormatted{parentIsInput
784           ? parent_.get_if<FormattedIoStatementState<Direction::Input>>() !=
785               nullptr
786           : parent_.get_if<FormattedIoStatementState<Direction::Output>>() !=
787               nullptr};
788   bool parentIsUnformatted{!parentIsFormatted};
789   if (unformatted != parentIsUnformatted) {
790     terminator.Crash("Child %s attempted on %s parent I/O unit", what,
791         parentIsUnformatted ? "unformatted" : "formatted");
792     return false;
793   } else if (parentIsInput != (direction == Direction::Input)) {
794     terminator.Crash("Child %s attempted on %s parent I/O unit", what,
795         parentIsInput ? "input" : "output");
796     return false;
797   } else {
798     return true;
799   }
800 }
801 
802 } // namespace Fortran::runtime::io
803