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.
265     if (!isFixedRecordLength) {
266       recordLength.reset();
267     } else if (furthestAfter > *recordLength) {
268       handler.SignalError(IostatRecordWriteOverrun,
269           "Attempt to write %zd bytes to position %jd in a fixed-size record "
270           "of %jd bytes",
271           bytes, static_cast<std::intmax_t>(positionInRecord),
272           static_cast<std::intmax_t>(*recordLength));
273       return false;
274     }
275   }
276   WriteFrame(frameOffsetInFile_, recordOffsetInFrame_ + furthestAfter, handler);
277   if (positionInRecord > furthestPositionInRecord) {
278     std::memset(Frame() + recordOffsetInFrame_ + furthestPositionInRecord, ' ',
279         positionInRecord - furthestPositionInRecord);
280   }
281   char *to{Frame() + recordOffsetInFrame_ + positionInRecord};
282   std::memcpy(to, data, bytes);
283   if (swapEndianness_) {
284     SwapEndianness(to, bytes, elementBytes);
285   }
286   positionInRecord += bytes;
287   furthestPositionInRecord = furthestAfter;
288   return true;
289 }
290 
291 bool ExternalFileUnit::Receive(char *data, std::size_t bytes,
292     std::size_t elementBytes, IoErrorHandler &handler) {
293   RUNTIME_CHECK(handler, direction_ == Direction::Input);
294   auto furthestAfter{std::max(furthestPositionInRecord,
295       positionInRecord + static_cast<std::int64_t>(bytes))};
296   if (furthestAfter > recordLength.value_or(furthestAfter)) {
297     handler.SignalError(IostatRecordReadOverrun,
298         "Attempt to read %zd bytes at position %jd in a record of %jd bytes",
299         bytes, static_cast<std::intmax_t>(positionInRecord),
300         static_cast<std::intmax_t>(*recordLength));
301     return false;
302   }
303   auto need{recordOffsetInFrame_ + furthestAfter};
304   auto got{ReadFrame(frameOffsetInFile_, need, handler)};
305   if (got >= need) {
306     std::memcpy(data, Frame() + recordOffsetInFrame_ + positionInRecord, bytes);
307     if (swapEndianness_) {
308       SwapEndianness(data, bytes, elementBytes);
309     }
310     positionInRecord += bytes;
311     furthestPositionInRecord = furthestAfter;
312     return true;
313   } else {
314     // EOF or error: can be handled & has been signaled
315     endfileRecordNumber = currentRecordNumber;
316     return false;
317   }
318 }
319 
320 std::optional<char32_t> ExternalFileUnit::GetCurrentChar(
321     IoErrorHandler &handler) {
322   RUNTIME_CHECK(handler, direction_ == Direction::Input);
323   if (const char *p{FrameNextInput(handler, 1)}) {
324     // TODO: UTF-8 decoding; may have to get more bytes in a loop
325     return *p;
326   }
327   return std::nullopt;
328 }
329 
330 const char *ExternalFileUnit::FrameNextInput(
331     IoErrorHandler &handler, std::size_t bytes) {
332   RUNTIME_CHECK(handler, isUnformatted.has_value() && !*isUnformatted);
333   if (static_cast<std::int64_t>(positionInRecord + bytes) <=
334       recordLength.value_or(positionInRecord + bytes)) {
335     auto at{recordOffsetInFrame_ + positionInRecord};
336     auto need{static_cast<std::size_t>(at + bytes)};
337     auto got{ReadFrame(frameOffsetInFile_, need, handler)};
338     SetSequentialVariableFormattedRecordLength();
339     if (got >= need) {
340       return Frame() + at;
341     }
342     handler.SignalEnd();
343     endfileRecordNumber = currentRecordNumber;
344   }
345   return nullptr;
346 }
347 
348 bool ExternalFileUnit::SetSequentialVariableFormattedRecordLength() {
349   if (recordLength || access != Access::Sequential) {
350     return true;
351   } else if (FrameLength() > recordOffsetInFrame_) {
352     const char *record{Frame() + recordOffsetInFrame_};
353     std::size_t bytes{FrameLength() - recordOffsetInFrame_};
354     if (const char *nl{
355             reinterpret_cast<const char *>(std::memchr(record, '\n', bytes))}) {
356       recordLength = nl - record;
357       if (*recordLength > 0 && record[*recordLength - 1] == '\r') {
358         --*recordLength;
359       }
360       return true;
361     }
362   }
363   return false;
364 }
365 
366 void ExternalFileUnit::SetLeftTabLimit() {
367   leftTabLimit = furthestPositionInRecord;
368   positionInRecord = furthestPositionInRecord;
369 }
370 
371 bool ExternalFileUnit::BeginReadingRecord(IoErrorHandler &handler) {
372   RUNTIME_CHECK(handler, direction_ == Direction::Input);
373   if (!beganReadingRecord_) {
374     beganReadingRecord_ = true;
375     if (access == Access::Sequential) {
376       if (endfileRecordNumber && currentRecordNumber >= *endfileRecordNumber) {
377         handler.SignalEnd();
378       } else if (isFixedRecordLength && access == Access::Direct) {
379         RUNTIME_CHECK(handler, recordLength.has_value());
380         auto need{
381             static_cast<std::size_t>(recordOffsetInFrame_ + *recordLength)};
382         auto got{ReadFrame(frameOffsetInFile_, need, handler)};
383         if (got < need) {
384           handler.SignalEnd();
385         }
386       } else {
387         RUNTIME_CHECK(handler, isUnformatted.has_value());
388         if (isUnformatted.value_or(false)) {
389           BeginSequentialVariableUnformattedInputRecord(handler);
390         } else { // formatted
391           BeginSequentialVariableFormattedInputRecord(handler);
392         }
393       }
394     }
395   }
396   RUNTIME_CHECK(handler,
397       access != Access::Sequential || recordLength.has_value() ||
398           handler.InError());
399   return !handler.InError();
400 }
401 
402 void ExternalFileUnit::FinishReadingRecord(IoErrorHandler &handler) {
403   RUNTIME_CHECK(handler, direction_ == Direction::Input && beganReadingRecord_);
404   beganReadingRecord_ = false;
405   if (handler.InError() && handler.GetIoStat() != IostatEor) {
406     // avoid bogus crashes in END/ERR circumstances
407   } else if (access == Access::Sequential) {
408     RUNTIME_CHECK(handler, recordLength.has_value());
409     recordOffsetInFrame_ += *recordLength;
410     if (isFixedRecordLength && access == Access::Direct) {
411       frameOffsetInFile_ += recordOffsetInFrame_;
412       recordOffsetInFrame_ = 0;
413     } else {
414       RUNTIME_CHECK(handler, isUnformatted.has_value());
415       recordLength.reset();
416       if (isUnformatted.value_or(false)) {
417         // Retain footer in frame for more efficient BACKSPACE
418         frameOffsetInFile_ += recordOffsetInFrame_;
419         recordOffsetInFrame_ = sizeof(std::uint32_t);
420       } else { // formatted
421         if (FrameLength() > recordOffsetInFrame_ &&
422             Frame()[recordOffsetInFrame_] == '\r') {
423           ++recordOffsetInFrame_;
424         }
425         if (FrameLength() >= recordOffsetInFrame_ &&
426             Frame()[recordOffsetInFrame_] == '\n') {
427           ++recordOffsetInFrame_;
428         }
429         if (!pinnedFrame || mayPosition()) {
430           frameOffsetInFile_ += recordOffsetInFrame_;
431           recordOffsetInFrame_ = 0;
432         }
433       }
434     }
435   }
436   ++currentRecordNumber;
437   BeginRecord();
438 }
439 
440 bool ExternalFileUnit::AdvanceRecord(IoErrorHandler &handler) {
441   if (direction_ == Direction::Input) {
442     FinishReadingRecord(handler);
443     return BeginReadingRecord(handler);
444   } else { // Direction::Output
445     bool ok{true};
446     RUNTIME_CHECK(handler, isUnformatted.has_value());
447     if (isFixedRecordLength && recordLength &&
448         furthestPositionInRecord < *recordLength) {
449       // Pad remainder of fixed length record
450       WriteFrame(
451           frameOffsetInFile_, recordOffsetInFrame_ + *recordLength, handler);
452       std::memset(Frame() + recordOffsetInFrame_ + furthestPositionInRecord,
453           isUnformatted.value_or(false) ? 0 : ' ',
454           *recordLength - furthestPositionInRecord);
455       furthestPositionInRecord = *recordLength;
456     }
457     if (!(isFixedRecordLength && access == Access::Direct)) {
458       positionInRecord = furthestPositionInRecord;
459       if (isUnformatted.value_or(false)) {
460         // Append the length of a sequential unformatted variable-length record
461         // as its footer, then overwrite the reserved first four bytes of the
462         // record with its length as its header.  These four bytes were skipped
463         // over in BeginUnformattedIO<Output>().
464         // TODO: Break very large records up into subrecords with negative
465         // headers &/or footers
466         std::uint32_t length;
467         length = furthestPositionInRecord - sizeof length;
468         ok = ok &&
469             Emit(reinterpret_cast<const char *>(&length), sizeof length,
470                 sizeof length, handler);
471         positionInRecord = 0;
472         ok = ok &&
473             Emit(reinterpret_cast<const char *>(&length), sizeof length,
474                 sizeof length, handler);
475       } else {
476         // Terminate formatted variable length record
477         ok = ok && Emit("\n", 1, 1, handler); // TODO: Windows CR+LF
478       }
479     }
480     CommitWrites();
481     impliedEndfile_ = true;
482     ++currentRecordNumber;
483     if (endfileRecordNumber && currentRecordNumber >= *endfileRecordNumber) {
484       endfileRecordNumber.reset();
485     }
486     return ok;
487   }
488 }
489 
490 void ExternalFileUnit::BackspaceRecord(IoErrorHandler &handler) {
491   if (access != Access::Sequential) {
492     handler.SignalError(IostatBackspaceNonSequential,
493         "BACKSPACE(UNIT=%d) on non-sequential file", unitNumber());
494   } else {
495     if (endfileRecordNumber && currentRecordNumber > *endfileRecordNumber) {
496       // BACKSPACE after explicit ENDFILE
497       currentRecordNumber = *endfileRecordNumber;
498     } else {
499       DoImpliedEndfile(handler);
500       if (frameOffsetInFile_ + recordOffsetInFrame_ > 0) {
501         --currentRecordNumber;
502         if (isFixedRecordLength && access == Access::Direct) {
503           BackspaceFixedRecord(handler);
504         } else {
505           RUNTIME_CHECK(handler, isUnformatted.has_value());
506           if (isUnformatted.value_or(false)) {
507             BackspaceVariableUnformattedRecord(handler);
508           } else {
509             BackspaceVariableFormattedRecord(handler);
510           }
511         }
512       }
513     }
514     BeginRecord();
515   }
516 }
517 
518 void ExternalFileUnit::FlushOutput(IoErrorHandler &handler) {
519   if (!mayPosition()) {
520     auto frameAt{FrameAt()};
521     if (frameOffsetInFile_ >= frameAt &&
522         frameOffsetInFile_ <
523             static_cast<std::int64_t>(frameAt + FrameLength())) {
524       // A Flush() that's about to happen to a non-positionable file
525       // needs to advance frameOffsetInFile_ to prevent attempts at
526       // impossible seeks
527       CommitWrites();
528     }
529   }
530   Flush(handler);
531 }
532 
533 void ExternalFileUnit::FlushIfTerminal(IoErrorHandler &handler) {
534   if (isTerminal()) {
535     FlushOutput(handler);
536   }
537 }
538 
539 void ExternalFileUnit::Endfile(IoErrorHandler &handler) {
540   if (access != Access::Sequential) {
541     handler.SignalError(IostatEndfileNonSequential,
542         "ENDFILE(UNIT=%d) on non-sequential file", unitNumber());
543   } else if (!mayWrite()) {
544     handler.SignalError(IostatEndfileUnwritable,
545         "ENDFILE(UNIT=%d) on read-only file", unitNumber());
546   } else if (endfileRecordNumber &&
547       currentRecordNumber > *endfileRecordNumber) {
548     // ENDFILE after ENDFILE
549   } else {
550     DoEndfile(handler);
551     // Explicit ENDFILE leaves position *after* the endfile record
552     RUNTIME_CHECK(handler, endfileRecordNumber.has_value());
553     currentRecordNumber = *endfileRecordNumber + 1;
554   }
555 }
556 
557 void ExternalFileUnit::Rewind(IoErrorHandler &handler) {
558   if (access == Access::Direct) {
559     handler.SignalError(IostatRewindNonSequential,
560         "REWIND(UNIT=%d) on non-sequential file", unitNumber());
561   } else {
562     DoImpliedEndfile(handler);
563     SetPosition(0);
564     currentRecordNumber = 1;
565   }
566 }
567 
568 void ExternalFileUnit::EndIoStatement() {
569   io_.reset();
570   u_.emplace<std::monostate>();
571   lock_.Drop();
572 }
573 
574 void ExternalFileUnit::BeginSequentialVariableUnformattedInputRecord(
575     IoErrorHandler &handler) {
576   std::int32_t header{0}, footer{0};
577   std::size_t need{recordOffsetInFrame_ + sizeof header};
578   std::size_t got{ReadFrame(frameOffsetInFile_, need, handler)};
579   // Try to emit informative errors to help debug corrupted files.
580   const char *error{nullptr};
581   if (got < need) {
582     if (got == recordOffsetInFrame_) {
583       handler.SignalEnd();
584     } else {
585       error = "Unformatted variable-length sequential file input failed at "
586               "record #%jd (file offset %jd): truncated record header";
587     }
588   } else {
589     std::memcpy(&header, Frame() + recordOffsetInFrame_, sizeof header);
590     recordLength = sizeof header + header; // does not include footer
591     need = recordOffsetInFrame_ + *recordLength + sizeof footer;
592     got = ReadFrame(frameOffsetInFile_, need, handler);
593     if (got < need) {
594       error = "Unformatted variable-length sequential file input failed at "
595               "record #%jd (file offset %jd): hit EOF reading record with "
596               "length %jd bytes";
597     } else {
598       std::memcpy(&footer, Frame() + recordOffsetInFrame_ + *recordLength,
599           sizeof footer);
600       if (footer != header) {
601         error = "Unformatted variable-length sequential file input failed at "
602                 "record #%jd (file offset %jd): record header has length %jd "
603                 "that does not match record footer (%jd)";
604       }
605     }
606   }
607   if (error) {
608     handler.SignalError(error, static_cast<std::intmax_t>(currentRecordNumber),
609         static_cast<std::intmax_t>(frameOffsetInFile_),
610         static_cast<std::intmax_t>(header), static_cast<std::intmax_t>(footer));
611     // TODO: error recovery
612   }
613   positionInRecord = sizeof header;
614 }
615 
616 void ExternalFileUnit::BeginSequentialVariableFormattedInputRecord(
617     IoErrorHandler &handler) {
618   if (this == defaultInput && defaultOutput) {
619     defaultOutput->FlushOutput(handler);
620   }
621   std::size_t length{0};
622   do {
623     std::size_t need{length + 1};
624     length =
625         ReadFrame(frameOffsetInFile_, recordOffsetInFrame_ + need, handler) -
626         recordOffsetInFrame_;
627     if (length < need) {
628       if (length > 0) {
629         // final record w/o \n
630         recordLength = length;
631       } else {
632         handler.SignalEnd();
633       }
634       break;
635     }
636   } while (!SetSequentialVariableFormattedRecordLength());
637 }
638 
639 void ExternalFileUnit::BackspaceFixedRecord(IoErrorHandler &handler) {
640   RUNTIME_CHECK(handler, recordLength.has_value());
641   if (frameOffsetInFile_ < *recordLength) {
642     handler.SignalError(IostatBackspaceAtFirstRecord);
643   } else {
644     frameOffsetInFile_ -= *recordLength;
645   }
646 }
647 
648 void ExternalFileUnit::BackspaceVariableUnformattedRecord(
649     IoErrorHandler &handler) {
650   std::int32_t header{0}, footer{0};
651   auto headerBytes{static_cast<std::int64_t>(sizeof header)};
652   frameOffsetInFile_ += recordOffsetInFrame_;
653   recordOffsetInFrame_ = 0;
654   if (frameOffsetInFile_ <= headerBytes) {
655     handler.SignalError(IostatBackspaceAtFirstRecord);
656     return;
657   }
658   // Error conditions here cause crashes, not file format errors, because the
659   // validity of the file structure before the current record will have been
660   // checked informatively in NextSequentialVariableUnformattedInputRecord().
661   std::size_t got{
662       ReadFrame(frameOffsetInFile_ - headerBytes, headerBytes, handler)};
663   RUNTIME_CHECK(handler, got >= sizeof footer);
664   std::memcpy(&footer, Frame(), sizeof footer);
665   recordLength = footer;
666   RUNTIME_CHECK(handler, frameOffsetInFile_ >= *recordLength + 2 * headerBytes);
667   frameOffsetInFile_ -= *recordLength + 2 * headerBytes;
668   if (frameOffsetInFile_ >= headerBytes) {
669     frameOffsetInFile_ -= headerBytes;
670     recordOffsetInFrame_ = headerBytes;
671   }
672   auto need{static_cast<std::size_t>(
673       recordOffsetInFrame_ + sizeof header + *recordLength)};
674   got = ReadFrame(frameOffsetInFile_, need, handler);
675   RUNTIME_CHECK(handler, got >= need);
676   std::memcpy(&header, Frame() + recordOffsetInFrame_, sizeof header);
677   RUNTIME_CHECK(handler, header == *recordLength);
678 }
679 
680 // There's no portable memrchr(), unfortunately, and strrchr() would
681 // fail on a record with a NUL, so we have to do it the hard way.
682 static const char *FindLastNewline(const char *str, std::size_t length) {
683   for (const char *p{str + length}; p-- > str;) {
684     if (*p == '\n') {
685       return p;
686     }
687   }
688   return nullptr;
689 }
690 
691 void ExternalFileUnit::BackspaceVariableFormattedRecord(
692     IoErrorHandler &handler) {
693   // File offset of previous record's newline
694   auto prevNL{
695       frameOffsetInFile_ + static_cast<std::int64_t>(recordOffsetInFrame_) - 1};
696   if (prevNL < 0) {
697     handler.SignalError(IostatBackspaceAtFirstRecord);
698     return;
699   }
700   while (true) {
701     if (frameOffsetInFile_ < prevNL) {
702       if (const char *p{
703               FindLastNewline(Frame(), prevNL - 1 - frameOffsetInFile_)}) {
704         recordOffsetInFrame_ = p - Frame() + 1;
705         recordLength = prevNL - (frameOffsetInFile_ + recordOffsetInFrame_);
706         break;
707       }
708     }
709     if (frameOffsetInFile_ == 0) {
710       recordOffsetInFrame_ = 0;
711       recordLength = prevNL;
712       break;
713     }
714     frameOffsetInFile_ -= std::min<std::int64_t>(frameOffsetInFile_, 1024);
715     auto need{static_cast<std::size_t>(prevNL + 1 - frameOffsetInFile_)};
716     auto got{ReadFrame(frameOffsetInFile_, need, handler)};
717     RUNTIME_CHECK(handler, got >= need);
718   }
719   RUNTIME_CHECK(handler, Frame()[recordOffsetInFrame_ + *recordLength] == '\n');
720   if (*recordLength > 0 &&
721       Frame()[recordOffsetInFrame_ + *recordLength - 1] == '\r') {
722     --*recordLength;
723   }
724 }
725 
726 void ExternalFileUnit::DoImpliedEndfile(IoErrorHandler &handler) {
727   if (impliedEndfile_) {
728     impliedEndfile_ = false;
729     if (access == Access::Sequential && mayPosition()) {
730       DoEndfile(handler);
731     }
732   }
733 }
734 
735 void ExternalFileUnit::DoEndfile(IoErrorHandler &handler) {
736   endfileRecordNumber = currentRecordNumber;
737   Truncate(frameOffsetInFile_ + recordOffsetInFrame_, handler);
738   BeginRecord();
739   impliedEndfile_ = false;
740 }
741 
742 void ExternalFileUnit::CommitWrites() {
743   frameOffsetInFile_ +=
744       recordOffsetInFrame_ + recordLength.value_or(furthestPositionInRecord);
745   recordOffsetInFrame_ = 0;
746   BeginRecord();
747 }
748 
749 ChildIo &ExternalFileUnit::PushChildIo(IoStatementState &parent) {
750   OwningPtr<ChildIo> current{std::move(child_)};
751   Terminator &terminator{parent.GetIoErrorHandler()};
752   OwningPtr<ChildIo> next{New<ChildIo>{terminator}(parent, std::move(current))};
753   child_.reset(next.release());
754   return *child_;
755 }
756 
757 void ExternalFileUnit::PopChildIo(ChildIo &child) {
758   if (child_.get() != &child) {
759     child.parent().GetIoErrorHandler().Crash(
760         "ChildIo being popped is not top of stack");
761   }
762   child_.reset(child.AcquirePrevious().release()); // deletes top child
763 }
764 
765 void ChildIo::EndIoStatement() {
766   io_.reset();
767   u_.emplace<std::monostate>();
768 }
769 
770 bool ChildIo::CheckFormattingAndDirection(Terminator &terminator,
771     const char *what, bool unformatted, Direction direction) {
772   bool parentIsInput{!parent_.get_if<IoDirectionState<Direction::Output>>()};
773   bool parentIsFormatted{parentIsInput
774           ? parent_.get_if<FormattedIoStatementState<Direction::Input>>() !=
775               nullptr
776           : parent_.get_if<FormattedIoStatementState<Direction::Output>>() !=
777               nullptr};
778   bool parentIsUnformatted{!parentIsFormatted};
779   if (unformatted != parentIsUnformatted) {
780     terminator.Crash("Child %s attempted on %s parent I/O unit", what,
781         parentIsUnformatted ? "unformatted" : "formatted");
782     return false;
783   } else if (parentIsInput != (direction == Direction::Input)) {
784     terminator.Crash("Child %s attempted on %s parent I/O unit", what,
785         parentIsInput ? "input" : "output");
786     return false;
787   } else {
788     return true;
789   }
790 }
791 
792 } // namespace Fortran::runtime::io
793