Debian Codegraph @

flang/runtime/unit.cpp

raw
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 // Implementation of ExternalFileUnit common for both
10 // RT_USE_PSEUDO_FILE_UNIT=0 and RT_USE_PSEUDO_FILE_UNIT=1.
11 //
12 //===----------------------------------------------------------------------===//
13 #include "unit.h"
14 #include "io-error.h"
15 #include "lock.h"
16 #include "tools.h"
17 #include <limits>
18 #include <utility>
19
20 namespace Fortran::runtime::io {
21
22 #ifndef FLANG_RUNTIME_NO_GLOBAL_VAR_DEFS
23 RT_OFFLOAD_VAR_GROUP_BEGIN
24 RT_VAR_ATTRS ExternalFileUnit *defaultInput{nullptr}; // unit 5
25 RT_VAR_ATTRS ExternalFileUnit *defaultOutput{nullptr}; // unit 6
26 RT_VAR_ATTRS ExternalFileUnit *errorOutput{nullptr}; // unit 0 extension
27 RT_OFFLOAD_VAR_GROUP_END
28 #endif // FLANG_RUNTIME_NO_GLOBAL_VAR_DEFS
29
30 RT_OFFLOAD_API_GROUP_BEGIN
31
32 static inline RT_API_ATTRS void SwapEndianness(
33 char *data, std::size_t bytes, std::size_t elementBytes) {
34 if (elementBytes > 1) {
35 auto half{elementBytes >> 1};
36 for (std::size_t j{0}; j + elementBytes <= bytes; j += elementBytes) {
37 for (std::size_t k{0}; k < half; ++k) {
38 RT_DIAG_PUSH
39 RT_DIAG_DISABLE_CALL_HOST_FROM_DEVICE_WARN
40 std::swap(data[j + k], data[j + elementBytes - 1 - k]);
41 RT_DIAG_POP
42 }
43 }
44 }
45 }
46
47 bool ExternalFileUnit::Emit(const char *data, std::size_t bytes,
48 std::size_t elementBytes, IoErrorHandler &handler) {
49 auto furthestAfter{std::max(furthestPositionInRecord,
50 positionInRecord + static_cast<std::int64_t>(bytes))};
51 if (openRecl) {
52 // Check for fixed-length record overrun, but allow for
53 // sequential record termination.
54 int extra{0};
55 int header{0};
56 if (access == Access::Sequential) {
57 if (isUnformatted.value_or(false)) {
58 // record header + footer
59 header = static_cast<int>(sizeof(std::uint32_t));
60 extra = 2 * header;
61 } else {
62 #ifdef _WIN32
63 if (!isWindowsTextFile()) {
64 ++extra; // carriage return (CR)
65 }
66 #endif
67 ++extra; // newline (LF)
68 }
69 }
70 if (furthestAfter > extra + *openRecl) {
71 handler.SignalError(IostatRecordWriteOverrun,
72 "Attempt to write %zd bytes to position %jd in a fixed-size record "
73 "of %jd bytes",
74 bytes, static_cast<std::intmax_t>(positionInRecord - header),
75 static_cast<std::intmax_t>(*openRecl));
76 return false;
77 }
78 }
79 if (recordLength) {
80 // It is possible for recordLength to have a value now for a
81 // variable-length output record if the previous operation
82 // was a BACKSPACE or non advancing input statement.
83 recordLength.reset();
84 beganReadingRecord_ = false;
85 }
86 if (IsAfterEndfile()) {
87 handler.SignalError(IostatWriteAfterEndfile);
88 return false;
89 }
90 CheckDirectAccess(handler);
91 WriteFrame(frameOffsetInFile_, recordOffsetInFrame_ + furthestAfter, handler);
92 if (positionInRecord > furthestPositionInRecord) {
93 std::memset(Frame() + recordOffsetInFrame_ + furthestPositionInRecord, ' ',
94 positionInRecord - furthestPositionInRecord);
95 }
96 char *to{Frame() + recordOffsetInFrame_ + positionInRecord};
97 std::memcpy(to, data, bytes);
98 if (swapEndianness_) {
99 SwapEndianness(to, bytes, elementBytes);
100 }
101 positionInRecord += bytes;
102 furthestPositionInRecord = furthestAfter;
103 anyWriteSinceLastPositioning_ = true;
104 return true;
105 }
106
107 bool ExternalFileUnit::Receive(char *data, std::size_t bytes,
108 std::size_t elementBytes, IoErrorHandler &handler) {
109 RUNTIME_CHECK(handler, direction_ == Direction::Input);
110 auto furthestAfter{std::max(furthestPositionInRecord,
111 positionInRecord + static_cast<std::int64_t>(bytes))};
112 if (furthestAfter > recordLength.value_or(furthestAfter)) {
113 handler.SignalError(IostatRecordReadOverrun,
114 "Attempt to read %zd bytes at position %jd in a record of %jd bytes",
115 bytes, static_cast<std::intmax_t>(positionInRecord),
116 static_cast<std::intmax_t>(*recordLength));
117 return false;
118 }
119 auto need{recordOffsetInFrame_ + furthestAfter};
120 auto got{ReadFrame(frameOffsetInFile_, need, handler)};
121 if (got >= need) {
122 std::memcpy(data, Frame() + recordOffsetInFrame_ + positionInRecord, bytes);
123 if (swapEndianness_) {
124 SwapEndianness(data, bytes, elementBytes);
125 }
126 positionInRecord += bytes;
127 furthestPositionInRecord = furthestAfter;
128 return true;
129 } else {
130 HitEndOnRead(handler);
131 return false;
132 }
133 }
134
135 std::size_t ExternalFileUnit::GetNextInputBytes(
136 const char *&p, IoErrorHandler &handler) {
137 RUNTIME_CHECK(handler, direction_ == Direction::Input);
138 std::size_t length{1};
139 if (auto recl{EffectiveRecordLength()}) {
140 if (positionInRecord < *recl) {
141 length = *recl - positionInRecord;
142 } else {
143 p = nullptr;
144 return 0;
145 }
146 }
147 p = FrameNextInput(handler, length);
148 return p ? length : 0;
149 }
150
151 const char *ExternalFileUnit::FrameNextInput(
152 IoErrorHandler &handler, std::size_t bytes) {
153 RUNTIME_CHECK(handler, isUnformatted.has_value() && !*isUnformatted);
154 if (static_cast<std::int64_t>(positionInRecord + bytes) <=
155 recordLength.value_or(positionInRecord + bytes)) {
156 auto at{recordOffsetInFrame_ + positionInRecord};
157 auto need{static_cast<std::size_t>(at + bytes)};
158 auto got{ReadFrame(frameOffsetInFile_, need, handler)};
159 SetVariableFormattedRecordLength();
160 if (got >= need) {
161 return Frame() + at;
162 }
163 HitEndOnRead(handler);
164 }
165 return nullptr;
166 }
167
168 bool ExternalFileUnit::SetVariableFormattedRecordLength() {
169 if (recordLength || access == Access::Direct) {
170 return true;
171 } else if (FrameLength() > recordOffsetInFrame_) {
172 const char *record{Frame() + recordOffsetInFrame_};
173 std::size_t bytes{FrameLength() - recordOffsetInFrame_};
174 if (const char *nl{FindCharacter(record, '\n', bytes)}) {
175 recordLength = nl - record;
176 if (*recordLength > 0 && record[*recordLength - 1] == '\r') {
177 --*recordLength;
178 }
179 return true;
180 }
181 }
182 return false;
183 }
184
185 bool ExternalFileUnit::BeginReadingRecord(IoErrorHandler &handler) {
186 RUNTIME_CHECK(handler, direction_ == Direction::Input);
187 if (!beganReadingRecord_) {
188 beganReadingRecord_ = true;
189 // Don't use IsAtEOF() to check for an EOF condition here, just detect
190 // it from a failed or short read from the file. IsAtEOF() could be
191 // wrong for formatted input if actual newline characters had been
192 // written in-band by previous WRITEs before a REWIND. In fact,
193 // now that we know that the unit is being used for input (again),
194 // it's best to reset endfileRecordNumber and ensure IsAtEOF() will
195 // now be true on return only if it gets set by HitEndOnRead().
196 endfileRecordNumber.reset();
197 if (access == Access::Direct) {
198 CheckDirectAccess(handler);
199 auto need{static_cast<std::size_t>(recordOffsetInFrame_ + *openRecl)};
200 auto got{ReadFrame(frameOffsetInFile_, need, handler)};
201 if (got >= need) {
202 recordLength = openRecl;
203 } else {
204 recordLength.reset();
205 HitEndOnRead(handler);
206 }
207 } else {
208 if (anyWriteSinceLastPositioning_ && access == Access::Sequential) {
209 // Most Fortran implementations allow a READ after a WRITE;
210 // the read then just hits an EOF.
211 DoEndfile<false, Direction::Input>(handler);
212 }
213 recordLength.reset();
214 RUNTIME_CHECK(handler, isUnformatted.has_value());
215 if (*isUnformatted) {
216 if (access == Access::Sequential) {
217 BeginSequentialVariableUnformattedInputRecord(handler);
218 }
219 } else { // formatted sequential or stream
220 BeginVariableFormattedInputRecord(handler);
221 }
222 }
223 }
224 RUNTIME_CHECK(handler,
225 recordLength.has_value() || !IsRecordFile() || handler.InError());
226 return !handler.InError();
227 }
228
229 void ExternalFileUnit::FinishReadingRecord(IoErrorHandler &handler) {
230 RUNTIME_CHECK(handler, direction_ == Direction::Input && beganReadingRecord_);
231 beganReadingRecord_ = false;
232 if (handler.GetIoStat() == IostatEnd ||
233 (IsRecordFile() && !recordLength.has_value())) {
234 // Avoid bogus crashes in END/ERR circumstances; but
235 // still increment the current record number so that
236 // an attempted read of an endfile record, followed by
237 // a BACKSPACE, will still be at EOF.
238 ++currentRecordNumber;
239 } else if (IsRecordFile()) {
240 recordOffsetInFrame_ += *recordLength;
241 if (access != Access::Direct) {
242 RUNTIME_CHECK(handler, isUnformatted.has_value());
243 recordLength.reset();
244 if (isUnformatted.value_or(false)) {
245 // Retain footer in frame for more efficient BACKSPACE
246 frameOffsetInFile_ += recordOffsetInFrame_;
247 recordOffsetInFrame_ = sizeof(std::uint32_t);
248 } else { // formatted
249 if (FrameLength() > recordOffsetInFrame_ &&
250 Frame()[recordOffsetInFrame_] == '\r') {
251 ++recordOffsetInFrame_;
252 }
253 if (FrameLength() > recordOffsetInFrame_ &&
254 Frame()[recordOffsetInFrame_] == '\n') {
255 ++recordOffsetInFrame_;
256 }
257 if (!pinnedFrame || mayPosition()) {
258 frameOffsetInFile_ += recordOffsetInFrame_;
259 recordOffsetInFrame_ = 0;
260 }
261 }
262 }
263 ++currentRecordNumber;
264 } else { // unformatted stream
265 furthestPositionInRecord =
266 std::max(furthestPositionInRecord, positionInRecord);
267 frameOffsetInFile_ += recordOffsetInFrame_ + furthestPositionInRecord;
268 recordOffsetInFrame_ = 0;
269 }
270 BeginRecord();
271 leftTabLimit.reset();
272 }
273
274 bool ExternalFileUnit::AdvanceRecord(IoErrorHandler &handler) {
275 if (direction_ == Direction::Input) {
276 FinishReadingRecord(handler);
277 return BeginReadingRecord(handler);
278 } else { // Direction::Output
279 bool ok{true};
280 RUNTIME_CHECK(handler, isUnformatted.has_value());
281 positionInRecord = furthestPositionInRecord;
282 if (access == Access::Direct) {
283 if (furthestPositionInRecord <
284 openRecl.value_or(furthestPositionInRecord)) {
285 // Pad remainder of fixed length record
286 WriteFrame(
287 frameOffsetInFile_, recordOffsetInFrame_ + *openRecl, handler);
288 std::memset(Frame() + recordOffsetInFrame_ + furthestPositionInRecord,
289 isUnformatted.value_or(false) ? 0 : ' ',
290 *openRecl - furthestPositionInRecord);
291 furthestPositionInRecord = *openRecl;
292 }
293 } else if (*isUnformatted) {
294 if (access == Access::Sequential) {
295 // Append the length of a sequential unformatted variable-length record
296 // as its footer, then overwrite the reserved first four bytes of the
297 // record with its length as its header. These four bytes were skipped
298 // over in BeginUnformattedIO<Output>().
299 // TODO: Break very large records up into subrecords with negative
300 // headers &/or footers
301 std::uint32_t length;
302 length = furthestPositionInRecord - sizeof length;
303 ok = ok &&
304 Emit(reinterpret_cast<const char *>(&length), sizeof length,
305 sizeof length, handler);
306 positionInRecord = 0;
307 ok = ok &&
308 Emit(reinterpret_cast<const char *>(&length), sizeof length,
309 sizeof length, handler);
310 } else {
311 // Unformatted stream: nothing to do
312 }
313 } else if (handler.GetIoStat() != IostatOk &&
314 furthestPositionInRecord == 0) {
315 // Error in formatted variable length record, and no output yet; do
316 // nothing, like most other Fortran compilers do.
317 return true;
318 } else {
319 // Terminate formatted variable length record
320 const char *lineEnding{"\n"};
321 std::size_t lineEndingBytes{1};
322 #ifdef _WIN32
323 if (!isWindowsTextFile()) {
324 lineEnding = "\r\n";
325 lineEndingBytes = 2;
326 }
327 #endif
328 ok = ok && Emit(lineEnding, lineEndingBytes, 1, handler);
329 }
330 leftTabLimit.reset();
331 if (IsAfterEndfile()) {
332 return false;
333 }
334 CommitWrites();
335 ++currentRecordNumber;
336 if (access != Access::Direct) {
337 impliedEndfile_ = IsRecordFile();
338 if (IsAtEOF()) {
339 endfileRecordNumber.reset();
340 }
341 }
342 return ok;
343 }
344 }
345
346 void ExternalFileUnit::BackspaceRecord(IoErrorHandler &handler) {
347 if (access == Access::Direct || !IsRecordFile()) {
348 handler.SignalError(IostatBackspaceNonSequential,
349 "BACKSPACE(UNIT=%d) on direct-access file or unformatted stream",
350 unitNumber());
351 } else {
352 if (IsAfterEndfile()) {
353 // BACKSPACE after explicit ENDFILE
354 currentRecordNumber = *endfileRecordNumber;
355 } else if (leftTabLimit && direction_ == Direction::Input) {
356 // BACKSPACE after non-advancing input
357 leftTabLimit.reset();
358 } else {
359 DoImpliedEndfile(handler);
360 if (frameOffsetInFile_ + recordOffsetInFrame_ > 0) {
361 --currentRecordNumber;
362 if (openRecl && access == Access::Direct) {
363 BackspaceFixedRecord(handler);
364 } else {
365 RUNTIME_CHECK(handler, isUnformatted.has_value());
366 if (isUnformatted.value_or(false)) {
367 BackspaceVariableUnformattedRecord(handler);
368 } else {
369 BackspaceVariableFormattedRecord(handler);
370 }
371 }
372 }
373 }
374 BeginRecord();
375 anyWriteSinceLastPositioning_ = false;
376 }
377 }
378
379 void ExternalFileUnit::FlushOutput(IoErrorHandler &handler) {
380 if (!mayPosition()) {
381 auto frameAt{FrameAt()};
382 if (frameOffsetInFile_ >= frameAt &&
383 frameOffsetInFile_ <
384 static_cast<std::int64_t>(frameAt + FrameLength())) {
385 // A Flush() that's about to happen to a non-positionable file
386 // needs to advance frameOffsetInFile_ to prevent attempts at
387 // impossible seeks
388 CommitWrites();
389 leftTabLimit.reset();
390 }
391 }
392 Flush(handler);
393 }
394
395 void ExternalFileUnit::FlushIfTerminal(IoErrorHandler &handler) {
396 if (isTerminal()) {
397 FlushOutput(handler);
398 }
399 }
400
401 void ExternalFileUnit::Endfile(IoErrorHandler &handler) {
402 if (access == Access::Direct) {
403 handler.SignalError(IostatEndfileDirect,
404 "ENDFILE(UNIT=%d) on direct-access file", unitNumber());
405 } else if (!mayWrite()) {
406 handler.SignalError(IostatEndfileUnwritable,
407 "ENDFILE(UNIT=%d) on read-only file", unitNumber());
408 } else if (IsAfterEndfile()) {
409 // ENDFILE after ENDFILE
410 } else {
411 DoEndfile(handler);
412 if (IsRecordFile() && access != Access::Direct) {
413 // Explicit ENDFILE leaves position *after* the endfile record
414 RUNTIME_CHECK(handler, endfileRecordNumber.has_value());
415 currentRecordNumber = *endfileRecordNumber + 1;
416 }
417 }
418 }
419
420 void ExternalFileUnit::Rewind(IoErrorHandler &handler) {
421 if (access == Access::Direct) {
422 handler.SignalError(IostatRewindNonSequential,
423 "REWIND(UNIT=%d) on non-sequential file", unitNumber());
424 } else {
425 DoImpliedEndfile(handler);
426 SetPosition(0, handler);
427 currentRecordNumber = 1;
428 leftTabLimit.reset();
429 anyWriteSinceLastPositioning_ = false;
430 }
431 }
432
433 void ExternalFileUnit::SetPosition(std::int64_t pos, IoErrorHandler &handler) {
434 frameOffsetInFile_ = pos;
435 recordOffsetInFrame_ = 0;
436 if (access == Access::Direct) {
437 directAccessRecWasSet_ = true;
438 }
439 BeginRecord();
440 }
441
442 bool ExternalFileUnit::SetStreamPos(
443 std::int64_t oneBasedPos, IoErrorHandler &handler) {
444 if (access != Access::Stream) {
445 handler.SignalError("POS= may not appear unless ACCESS='STREAM'");
446 return false;
447 }
448 if (oneBasedPos < 1) { // POS=1 is beginning of file (12.6.2.11)
449 handler.SignalError(
450 "POS=%zd is invalid", static_cast<std::intmax_t>(oneBasedPos));
451 return false;
452 }
453 // A backwards POS= implies truncation after writing, at least in
454 // Intel and NAG.
455 if (static_cast<std::size_t>(oneBasedPos - 1) <
456 frameOffsetInFile_ + recordOffsetInFrame_) {
457 DoImpliedEndfile(handler);
458 }
459 SetPosition(oneBasedPos - 1, handler);
460 // We no longer know which record we're in. Set currentRecordNumber to
461 // a large value from whence we can both advance and backspace.
462 currentRecordNumber = std::numeric_limits<std::int64_t>::max() / 2;
463 endfileRecordNumber.reset();
464 return true;
465 }
466
467 bool ExternalFileUnit::SetDirectRec(
468 std::int64_t oneBasedRec, IoErrorHandler &handler) {
469 if (access != Access::Direct) {
470 handler.SignalError("REC= may not appear unless ACCESS='DIRECT'");
471 return false;
472 }
473 if (!openRecl) {
474 handler.SignalError("RECL= was not specified");
475 return false;
476 }
477 if (oneBasedRec < 1) {
478 handler.SignalError(
479 "REC=%zd is invalid", static_cast<std::intmax_t>(oneBasedRec));
480 return false;
481 }
482 currentRecordNumber = oneBasedRec;
483 SetPosition((oneBasedRec - 1) * *openRecl, handler);
484 return true;
485 }
486
487 void ExternalFileUnit::EndIoStatement() {
488 io_.reset();
489 u_.emplace<std::monostate>();
490 lock_.Drop();
491 }
492
493 void ExternalFileUnit::BeginSequentialVariableUnformattedInputRecord(
494 IoErrorHandler &handler) {
495 RUNTIME_CHECK(handler, access == Access::Sequential);
496 std::int32_t header{0}, footer{0};
497 std::size_t need{recordOffsetInFrame_ + sizeof header};
498 std::size_t got{ReadFrame(frameOffsetInFile_, need, handler)};
499 // Try to emit informative errors to help debug corrupted files.
500 const char *error{nullptr};
501 if (got < need) {
502 if (got == recordOffsetInFrame_) {
503 HitEndOnRead(handler);
504 } else {
505 error = "Unformatted variable-length sequential file input failed at "
506 "record #%jd (file offset %jd): truncated record header";
507 }
508 } else {
509 header = ReadHeaderOrFooter(recordOffsetInFrame_);
510 recordLength = sizeof header + header; // does not include footer
511 need = recordOffsetInFrame_ + *recordLength + sizeof footer;
512 got = ReadFrame(frameOffsetInFile_, need, handler);
513 if (got < need) {
514 error = "Unformatted variable-length sequential file input failed at "
515 "record #%jd (file offset %jd): hit EOF reading record with "
516 "length %jd bytes";
517 } else {
518 footer = ReadHeaderOrFooter(recordOffsetInFrame_ + *recordLength);
519 if (footer != header) {
520 error = "Unformatted variable-length sequential file input failed at "
521 "record #%jd (file offset %jd): record header has length %jd "
522 "that does not match record footer (%jd)";
523 }
524 }
525 }
526 if (error) {
527 handler.SignalError(error, static_cast<std::intmax_t>(currentRecordNumber),
528 static_cast<std::intmax_t>(frameOffsetInFile_),
529 static_cast<std::intmax_t>(header), static_cast<std::intmax_t>(footer));
530 // TODO: error recovery
531 }
532 positionInRecord = sizeof header;
533 }
534
535 void ExternalFileUnit::BeginVariableFormattedInputRecord(
536 IoErrorHandler &handler) {
537 if (this == defaultInput) {
538 if (defaultOutput) {
539 defaultOutput->FlushOutput(handler);
540 }
541 if (errorOutput) {
542 errorOutput->FlushOutput(handler);
543 }
544 }
545 std::size_t length{0};
546 do {
547 std::size_t need{length + 1};
548 length =
549 ReadFrame(frameOffsetInFile_, recordOffsetInFrame_ + need, handler) -
550 recordOffsetInFrame_;
551 if (length < need) {
552 if (length > 0) {
553 // final record w/o \n
554 recordLength = length;
555 unterminatedRecord = true;
556 } else {
557 HitEndOnRead(handler);
558 }
559 break;
560 }
561 } while (!SetVariableFormattedRecordLength());
562 }
563
564 void ExternalFileUnit::BackspaceFixedRecord(IoErrorHandler &handler) {
565 RUNTIME_CHECK(handler, openRecl.has_value());
566 if (frameOffsetInFile_ < *openRecl) {
567 handler.SignalError(IostatBackspaceAtFirstRecord);
568 } else {
569 frameOffsetInFile_ -= *openRecl;
570 }
571 }
572
573 void ExternalFileUnit::BackspaceVariableUnformattedRecord(
574 IoErrorHandler &handler) {
575 std::int32_t header{0};
576 auto headerBytes{static_cast<std::int64_t>(sizeof header)};
577 frameOffsetInFile_ += recordOffsetInFrame_;
578 recordOffsetInFrame_ = 0;
579 if (frameOffsetInFile_ <= headerBytes) {
580 handler.SignalError(IostatBackspaceAtFirstRecord);
581 return;
582 }
583 // Error conditions here cause crashes, not file format errors, because the
584 // validity of the file structure before the current record will have been
585 // checked informatively in NextSequentialVariableUnformattedInputRecord().
586 std::size_t got{
587 ReadFrame(frameOffsetInFile_ - headerBytes, headerBytes, handler)};
588 if (static_cast<std::int64_t>(got) < headerBytes) {
589 handler.SignalError(IostatShortRead);
590 return;
591 }
592 recordLength = ReadHeaderOrFooter(0);
593 if (frameOffsetInFile_ < *recordLength + 2 * headerBytes) {
594 handler.SignalError(IostatBadUnformattedRecord);
595 return;
596 }
597 frameOffsetInFile_ -= *recordLength + 2 * headerBytes;
598 auto need{static_cast<std::size_t>(
599 recordOffsetInFrame_ + sizeof header + *recordLength)};
600 got = ReadFrame(frameOffsetInFile_, need, handler);
601 if (got < need) {
602 handler.SignalError(IostatShortRead);
603 return;
604 }
605 header = ReadHeaderOrFooter(recordOffsetInFrame_);
606 if (header != *recordLength) {
607 handler.SignalError(IostatBadUnformattedRecord);
608 return;
609 }
610 }
611
612 // There's no portable memrchr(), unfortunately, and strrchr() would
613 // fail on a record with a NUL, so we have to do it the hard way.
614 static RT_API_ATTRS const char *FindLastNewline(
615 const char *str, std::size_t length) {
616 for (const char *p{str + length}; p >= str; p--) {
617 if (*p == '\n') {
618 return p;
619 }
620 }
621 return nullptr;
622 }
623
624 void ExternalFileUnit::BackspaceVariableFormattedRecord(
625 IoErrorHandler &handler) {
626 // File offset of previous record's newline
627 auto prevNL{
628 frameOffsetInFile_ + static_cast<std::int64_t>(recordOffsetInFrame_) - 1};
629 if (prevNL < 0) {
630 handler.SignalError(IostatBackspaceAtFirstRecord);
631 return;
632 }
633 while (true) {
634 if (frameOffsetInFile_ < prevNL) {
635 if (const char *p{
636 FindLastNewline(Frame(), prevNL - 1 - frameOffsetInFile_)}) {
637 recordOffsetInFrame_ = p - Frame() + 1;
638 recordLength = prevNL - (frameOffsetInFile_ + recordOffsetInFrame_);
639 break;
640 }
641 }
642 if (frameOffsetInFile_ == 0) {
643 recordOffsetInFrame_ = 0;
644 recordLength = prevNL;
645 break;
646 }
647 frameOffsetInFile_ -= std::min<std::int64_t>(frameOffsetInFile_, 1024);
648 auto need{static_cast<std::size_t>(prevNL + 1 - frameOffsetInFile_)};
649 auto got{ReadFrame(frameOffsetInFile_, need, handler)};
650 if (got < need) {
651 handler.SignalError(IostatShortRead);
652 return;
653 }
654 }
655 if (Frame()[recordOffsetInFrame_ + *recordLength] != '\n') {
656 handler.SignalError(IostatMissingTerminator);
657 return;
658 }
659 if (*recordLength > 0 &&
660 Frame()[recordOffsetInFrame_ + *recordLength - 1] == '\r') {
661 --*recordLength;
662 }
663 }
664
665 void ExternalFileUnit::DoImpliedEndfile(IoErrorHandler &handler) {
666 if (access != Access::Direct) {
667 if (!impliedEndfile_ && leftTabLimit && direction_ == Direction::Output) {
668 // Flush a partial record after non-advancing output
669 impliedEndfile_ = true;
670 }
671 if (impliedEndfile_ && mayPosition()) {
672 DoEndfile(handler);
673 }
674 }
675 impliedEndfile_ = false;
676 }
677
678 template <bool ANY_DIR, Direction DIR>
679 void ExternalFileUnit::DoEndfile(IoErrorHandler &handler) {
680 if (IsRecordFile() && access != Access::Direct) {
681 furthestPositionInRecord =
682 std::max(positionInRecord, furthestPositionInRecord);
683 if (leftTabLimit) { // last I/O was non-advancing
684 if (access == Access::Sequential && direction_ == Direction::Output) {
685 if constexpr (ANY_DIR || DIR == Direction::Output) {
686 // When DoEndfile() is called from BeginReadingRecord(),
687 // this call to AdvanceRecord() may appear as a recursion
688 // though it may never happen. Expose the call only
689 // under the constexpr direction check.
690 AdvanceRecord(handler);
691 } else {
692 // This check always fails if we are here.
693 RUNTIME_CHECK(handler, direction_ != Direction::Output);
694 }
695 } else { // Access::Stream or input
696 leftTabLimit.reset();
697 ++currentRecordNumber;
698 }
699 }
700 endfileRecordNumber = currentRecordNumber;
701 }
702 frameOffsetInFile_ += recordOffsetInFrame_ + furthestPositionInRecord;
703 recordOffsetInFrame_ = 0;
704 FlushOutput(handler);
705 Truncate(frameOffsetInFile_, handler);
706 TruncateFrame(frameOffsetInFile_, handler);
707 BeginRecord();
708 impliedEndfile_ = false;
709 anyWriteSinceLastPositioning_ = false;
710 }
711
712 template void ExternalFileUnit::DoEndfile(IoErrorHandler &handler);
713 template void ExternalFileUnit::DoEndfile<false, Direction::Output>(
714 IoErrorHandler &handler);
715 template void ExternalFileUnit::DoEndfile<false, Direction::Input>(
716 IoErrorHandler &handler);
717
718 void ExternalFileUnit::CommitWrites() {
719 frameOffsetInFile_ +=
720 recordOffsetInFrame_ + recordLength.value_or(furthestPositionInRecord);
721 recordOffsetInFrame_ = 0;
722 BeginRecord();
723 }
724
725 bool ExternalFileUnit::CheckDirectAccess(IoErrorHandler &handler) {
726 if (access == Access::Direct) {
727 RUNTIME_CHECK(handler, openRecl);
728 if (!directAccessRecWasSet_) {
729 handler.SignalError(
730 "No REC= was specified for a data transfer with ACCESS='DIRECT'");
731 return false;
732 }
733 }
734 return true;
735 }
736
737 void ExternalFileUnit::HitEndOnRead(IoErrorHandler &handler) {
738 handler.SignalEnd();
739 if (IsRecordFile() && access != Access::Direct) {
740 endfileRecordNumber = currentRecordNumber;
741 }
742 }
743
744 ChildIo &ExternalFileUnit::PushChildIo(IoStatementState &parent) {
745 OwningPtr<ChildIo> current{std::move(child_)};
746 Terminator &terminator{parent.GetIoErrorHandler()};
747 OwningPtr<ChildIo> next{New<ChildIo>{terminator}(parent, std::move(current))};
748 child_.reset(next.release());
749 return *child_;
750 }
751
752 void ExternalFileUnit::PopChildIo(ChildIo &child) {
753 if (child_.get() != &child) {
754 child.parent().GetIoErrorHandler().Crash(
755 "ChildIo being popped is not top of stack");
756 }
757 child_.reset(child.AcquirePrevious().release()); // deletes top child
758 }
759
760 std::int32_t ExternalFileUnit::ReadHeaderOrFooter(std::int64_t frameOffset) {
761 std::int32_t word;
762 char *wordPtr{reinterpret_cast<char *>(&word)};
763 std::memcpy(wordPtr, Frame() + frameOffset, sizeof word);
764 if (swapEndianness_) {
765 SwapEndianness(wordPtr, sizeof word, sizeof word);
766 }
767 return word;
768 }
769
770 void ChildIo::EndIoStatement() {
771 io_.reset();
772 u_.emplace<std::monostate>();
773 }
774
775 Iostat ChildIo::CheckFormattingAndDirection(
776 bool unformatted, Direction direction) {
777 bool parentIsInput{!parent_.get_if<IoDirectionState<Direction::Output>>()};
778 bool parentIsFormatted{parentIsInput
779 ? parent_.get_if<FormattedIoStatementState<Direction::Input>>() !=
780 nullptr
781 : parent_.get_if<FormattedIoStatementState<Direction::Output>>() !=
782 nullptr};
783 bool parentIsUnformatted{!parentIsFormatted};
784 if (unformatted != parentIsUnformatted) {
785 return unformatted ? IostatUnformattedChildOnFormattedParent
786 : IostatFormattedChildOnUnformattedParent;
787 } else if (parentIsInput != (direction == Direction::Input)) {
788 return parentIsInput ? IostatChildOutputToInputParent
789 : IostatChildInputFromOutputParent;
790 } else {
791 return IostatOk;
792 }
793 }
794
795 RT_OFFLOAD_API_GROUP_END
796 } // namespace Fortran::runtime::io