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