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