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