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