1 //===-- runtime/unit.cpp --------------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "unit.h" 10 #include "environment.h" 11 #include "io-error.h" 12 #include "lock.h" 13 #include "unit-map.h" 14 #include <cstdio> 15 #include <limits> 16 #include <utility> 17 18 namespace Fortran::runtime::io { 19 20 // The per-unit data structures are created on demand so that Fortran I/O 21 // should work without a Fortran main program. 22 static Lock unitMapLock; 23 static UnitMap *unitMap{nullptr}; 24 static ExternalFileUnit *defaultInput{nullptr}; 25 static ExternalFileUnit *defaultOutput{nullptr}; 26 27 void FlushOutputOnCrash(const Terminator &terminator) { 28 if (!defaultOutput) { 29 return; 30 } 31 CriticalSection critical{unitMapLock}; 32 if (defaultOutput) { 33 IoErrorHandler handler{terminator}; 34 handler.HasIoStat(); // prevent nested crash if flush has error 35 defaultOutput->FlushOutput(handler); 36 } 37 } 38 39 ExternalFileUnit *ExternalFileUnit::LookUp(int unit) { 40 return GetUnitMap().LookUp(unit); 41 } 42 43 ExternalFileUnit &ExternalFileUnit::LookUpOrCrash( 44 int unit, const Terminator &terminator) { 45 ExternalFileUnit *file{LookUp(unit)}; 46 if (!file) { 47 terminator.Crash("Not an open I/O unit number: %d", unit); 48 } 49 return *file; 50 } 51 52 ExternalFileUnit &ExternalFileUnit::LookUpOrCreate( 53 int unit, const Terminator &terminator, bool &wasExtant) { 54 return GetUnitMap().LookUpOrCreate(unit, terminator, wasExtant); 55 } 56 57 ExternalFileUnit &ExternalFileUnit::LookUpOrCreateAnonymous(int unit, 58 Direction dir, std::optional<bool> isUnformatted, 59 const Terminator &terminator) { 60 bool exists{false}; 61 ExternalFileUnit &result{ 62 GetUnitMap().LookUpOrCreate(unit, terminator, exists)}; 63 if (!exists) { 64 IoErrorHandler handler{terminator}; 65 result.OpenAnonymousUnit( 66 dir == Direction::Input ? OpenStatus::Unknown : OpenStatus::Replace, 67 Action::ReadWrite, Position::Rewind, Convert::Native, handler); 68 result.isUnformatted = isUnformatted; 69 } 70 return result; 71 } 72 73 ExternalFileUnit *ExternalFileUnit::LookUp(const char *path) { 74 return GetUnitMap().LookUp(path); 75 } 76 77 ExternalFileUnit &ExternalFileUnit::CreateNew( 78 int unit, const Terminator &terminator) { 79 bool wasExtant{false}; 80 ExternalFileUnit &result{ 81 GetUnitMap().LookUpOrCreate(unit, terminator, wasExtant)}; 82 RUNTIME_CHECK(terminator, !wasExtant); 83 return result; 84 } 85 86 ExternalFileUnit *ExternalFileUnit::LookUpForClose(int unit) { 87 return GetUnitMap().LookUpForClose(unit); 88 } 89 90 ExternalFileUnit &ExternalFileUnit::NewUnit( 91 const Terminator &terminator, bool forChildIo) { 92 ExternalFileUnit &unit{GetUnitMap().NewUnit(terminator)}; 93 unit.createdForInternalChildIo_ = forChildIo; 94 return unit; 95 } 96 97 void ExternalFileUnit::OpenUnit(std::optional<OpenStatus> status, 98 std::optional<Action> action, Position position, OwningPtr<char> &&newPath, 99 std::size_t newPathLength, Convert convert, IoErrorHandler &handler) { 100 if (executionEnvironment.conversion != Convert::Unknown) { 101 convert = executionEnvironment.conversion; 102 } 103 swapEndianness_ = convert == Convert::Swap || 104 (convert == Convert::LittleEndian && !isHostLittleEndian) || 105 (convert == Convert::BigEndian && isHostLittleEndian); 106 if (IsOpen()) { 107 bool isSamePath{newPath.get() && path() && pathLength() == newPathLength && 108 std::memcmp(path(), newPath.get(), newPathLength) == 0}; 109 if (status && *status != OpenStatus::Old && isSamePath) { 110 handler.SignalError("OPEN statement for connected unit may not have " 111 "explicit STATUS= other than 'OLD'"); 112 return; 113 } 114 if (!newPath.get() || isSamePath) { 115 // OPEN of existing unit, STATUS='OLD' or unspecified, not new FILE= 116 newPath.reset(); 117 return; 118 } 119 // Otherwise, OPEN on open unit with new FILE= implies CLOSE 120 DoImpliedEndfile(handler); 121 FlushOutput(handler); 122 Close(CloseStatus::Keep, handler); 123 } 124 set_path(std::move(newPath), newPathLength); 125 Open(status.value_or(OpenStatus::Unknown), action, position, handler); 126 auto totalBytes{knownSize()}; 127 if (access == Access::Direct) { 128 if (!isFixedRecordLength || !recordLength) { 129 handler.SignalError(IostatOpenBadRecl, 130 "OPEN(UNIT=%d,ACCESS='DIRECT'): record length is not known", 131 unitNumber()); 132 } else if (*recordLength <= 0) { 133 handler.SignalError(IostatOpenBadRecl, 134 "OPEN(UNIT=%d,ACCESS='DIRECT',RECL=%jd): record length is invalid", 135 unitNumber(), static_cast<std::intmax_t>(*recordLength)); 136 } else if (totalBytes && (*totalBytes % *recordLength != 0)) { 137 handler.SignalError(IostatOpenBadAppend, 138 "OPEN(UNIT=%d,ACCESS='DIRECT',RECL=%jd): record length is not an " 139 "even divisor of the file size %jd", 140 unitNumber(), static_cast<std::intmax_t>(*recordLength), 141 static_cast<std::intmax_t>(*totalBytes)); 142 } 143 } 144 endfileRecordNumber.reset(); 145 currentRecordNumber = 1; 146 if (totalBytes && recordLength && *recordLength) { 147 endfileRecordNumber = 1 + (*totalBytes / *recordLength); 148 } 149 if (position == Position::Append) { 150 if (!endfileRecordNumber) { 151 // Fake it so that we can backspace relative from the end 152 endfileRecordNumber = std::numeric_limits<std::int64_t>::max() - 2; 153 } 154 currentRecordNumber = *endfileRecordNumber; 155 } 156 } 157 158 void ExternalFileUnit::OpenAnonymousUnit(std::optional<OpenStatus> status, 159 std::optional<Action> action, Position position, Convert convert, 160 IoErrorHandler &handler) { 161 // I/O to an unconnected unit reads/creates a local file, e.g. fort.7 162 std::size_t pathMaxLen{32}; 163 auto path{SizedNew<char>{handler}(pathMaxLen)}; 164 std::snprintf(path.get(), pathMaxLen, "fort.%d", unitNumber_); 165 OpenUnit(status, action, position, std::move(path), std::strlen(path.get()), 166 convert, handler); 167 } 168 169 void ExternalFileUnit::CloseUnit(CloseStatus status, IoErrorHandler &handler) { 170 DoImpliedEndfile(handler); 171 FlushOutput(handler); 172 Close(status, handler); 173 } 174 175 void ExternalFileUnit::DestroyClosed() { 176 GetUnitMap().DestroyClosed(*this); // destroys *this 177 } 178 179 bool ExternalFileUnit::SetDirection( 180 Direction direction, IoErrorHandler &handler) { 181 if (direction == Direction::Input) { 182 if (mayRead()) { 183 direction_ = Direction::Input; 184 return true; 185 } else { 186 handler.SignalError(IostatReadFromWriteOnly, 187 "READ(UNIT=%d) with ACTION='WRITE'", unitNumber()); 188 return false; 189 } 190 } else { 191 if (mayWrite()) { 192 direction_ = Direction::Output; 193 return true; 194 } else { 195 handler.SignalError(IostatWriteToReadOnly, 196 "WRITE(UNIT=%d) with ACTION='READ'", unitNumber()); 197 return false; 198 } 199 } 200 } 201 202 UnitMap &ExternalFileUnit::GetUnitMap() { 203 if (unitMap) { 204 return *unitMap; 205 } 206 CriticalSection critical{unitMapLock}; 207 if (unitMap) { 208 return *unitMap; 209 } 210 Terminator terminator{__FILE__, __LINE__}; 211 IoErrorHandler handler{terminator}; 212 UnitMap *newUnitMap{New<UnitMap>{terminator}().release()}; 213 bool wasExtant{false}; 214 ExternalFileUnit &out{newUnitMap->LookUpOrCreate(6, terminator, wasExtant)}; 215 RUNTIME_CHECK(terminator, !wasExtant); 216 out.Predefine(1); 217 out.SetDirection(Direction::Output, handler); 218 defaultOutput = &out; 219 ExternalFileUnit &in{newUnitMap->LookUpOrCreate(5, terminator, wasExtant)}; 220 RUNTIME_CHECK(terminator, !wasExtant); 221 in.Predefine(0); 222 in.SetDirection(Direction::Input, handler); 223 defaultInput = ∈ 224 // TODO: Set UTF-8 mode from the environment 225 unitMap = newUnitMap; 226 return *unitMap; 227 } 228 229 void ExternalFileUnit::CloseAll(IoErrorHandler &handler) { 230 CriticalSection critical{unitMapLock}; 231 if (unitMap) { 232 unitMap->CloseAll(handler); 233 FreeMemoryAndNullify(unitMap); 234 } 235 defaultOutput = nullptr; 236 } 237 238 void ExternalFileUnit::FlushAll(IoErrorHandler &handler) { 239 CriticalSection critical{unitMapLock}; 240 if (unitMap) { 241 unitMap->FlushAll(handler); 242 } 243 } 244 245 static void SwapEndianness( 246 char *data, std::size_t bytes, std::size_t elementBytes) { 247 if (elementBytes > 1) { 248 auto half{elementBytes >> 1}; 249 for (std::size_t j{0}; j + elementBytes <= bytes; j += elementBytes) { 250 for (std::size_t k{0}; k < half; ++k) { 251 std::swap(data[j + k], data[j + elementBytes - 1 - k]); 252 } 253 } 254 } 255 } 256 257 bool ExternalFileUnit::Emit(const char *data, std::size_t bytes, 258 std::size_t elementBytes, IoErrorHandler &handler) { 259 auto furthestAfter{std::max(furthestPositionInRecord, 260 positionInRecord + static_cast<std::int64_t>(bytes))}; 261 if (recordLength) { 262 // It is possible for recordLength to have a value now for a 263 // variable-length output record if the previous operation 264 // was a BACKSPACE. 265 if (!isFixedRecordLength) { 266 recordLength.reset(); 267 } else if (furthestAfter > *recordLength) { 268 handler.SignalError(IostatRecordWriteOverrun, 269 "Attempt to write %zd bytes to position %jd in a fixed-size record " 270 "of %jd bytes", 271 bytes, static_cast<std::intmax_t>(positionInRecord), 272 static_cast<std::intmax_t>(*recordLength)); 273 return false; 274 } 275 } 276 WriteFrame(frameOffsetInFile_, recordOffsetInFrame_ + furthestAfter, handler); 277 if (positionInRecord > furthestPositionInRecord) { 278 std::memset(Frame() + recordOffsetInFrame_ + furthestPositionInRecord, ' ', 279 positionInRecord - furthestPositionInRecord); 280 } 281 char *to{Frame() + recordOffsetInFrame_ + positionInRecord}; 282 std::memcpy(to, data, bytes); 283 if (swapEndianness_) { 284 SwapEndianness(to, bytes, elementBytes); 285 } 286 positionInRecord += bytes; 287 furthestPositionInRecord = furthestAfter; 288 return true; 289 } 290 291 bool ExternalFileUnit::Receive(char *data, std::size_t bytes, 292 std::size_t elementBytes, IoErrorHandler &handler) { 293 RUNTIME_CHECK(handler, direction_ == Direction::Input); 294 auto furthestAfter{std::max(furthestPositionInRecord, 295 positionInRecord + static_cast<std::int64_t>(bytes))}; 296 if (furthestAfter > recordLength.value_or(furthestAfter)) { 297 handler.SignalError(IostatRecordReadOverrun, 298 "Attempt to read %zd bytes at position %jd in a record of %jd bytes", 299 bytes, static_cast<std::intmax_t>(positionInRecord), 300 static_cast<std::intmax_t>(*recordLength)); 301 return false; 302 } 303 auto need{recordOffsetInFrame_ + furthestAfter}; 304 auto got{ReadFrame(frameOffsetInFile_, need, handler)}; 305 if (got >= need) { 306 std::memcpy(data, Frame() + recordOffsetInFrame_ + positionInRecord, bytes); 307 if (swapEndianness_) { 308 SwapEndianness(data, bytes, elementBytes); 309 } 310 positionInRecord += bytes; 311 furthestPositionInRecord = furthestAfter; 312 return true; 313 } else { 314 // EOF or error: can be handled & has been signaled 315 endfileRecordNumber = currentRecordNumber; 316 return false; 317 } 318 } 319 320 std::optional<char32_t> ExternalFileUnit::GetCurrentChar( 321 IoErrorHandler &handler) { 322 RUNTIME_CHECK(handler, direction_ == Direction::Input); 323 if (const char *p{FrameNextInput(handler, 1)}) { 324 // TODO: UTF-8 decoding; may have to get more bytes in a loop 325 return *p; 326 } 327 return std::nullopt; 328 } 329 330 const char *ExternalFileUnit::FrameNextInput( 331 IoErrorHandler &handler, std::size_t bytes) { 332 RUNTIME_CHECK(handler, isUnformatted.has_value() && !*isUnformatted); 333 if (static_cast<std::int64_t>(positionInRecord + bytes) <= 334 recordLength.value_or(positionInRecord + bytes)) { 335 auto at{recordOffsetInFrame_ + positionInRecord}; 336 auto need{static_cast<std::size_t>(at + bytes)}; 337 auto got{ReadFrame(frameOffsetInFile_, need, handler)}; 338 SetSequentialVariableFormattedRecordLength(); 339 if (got >= need) { 340 return Frame() + at; 341 } 342 handler.SignalEnd(); 343 endfileRecordNumber = currentRecordNumber; 344 } 345 return nullptr; 346 } 347 348 bool ExternalFileUnit::SetSequentialVariableFormattedRecordLength() { 349 if (recordLength || access != Access::Sequential) { 350 return true; 351 } else if (FrameLength() > recordOffsetInFrame_) { 352 const char *record{Frame() + recordOffsetInFrame_}; 353 std::size_t bytes{FrameLength() - recordOffsetInFrame_}; 354 if (const char *nl{ 355 reinterpret_cast<const char *>(std::memchr(record, '\n', bytes))}) { 356 recordLength = nl - record; 357 if (*recordLength > 0 && record[*recordLength - 1] == '\r') { 358 --*recordLength; 359 } 360 return true; 361 } 362 } 363 return false; 364 } 365 366 void ExternalFileUnit::SetLeftTabLimit() { 367 leftTabLimit = furthestPositionInRecord; 368 positionInRecord = furthestPositionInRecord; 369 } 370 371 bool ExternalFileUnit::BeginReadingRecord(IoErrorHandler &handler) { 372 RUNTIME_CHECK(handler, direction_ == Direction::Input); 373 if (!beganReadingRecord_) { 374 beganReadingRecord_ = true; 375 if (access == Access::Sequential) { 376 if (endfileRecordNumber && currentRecordNumber >= *endfileRecordNumber) { 377 handler.SignalEnd(); 378 } else if (isFixedRecordLength) { 379 RUNTIME_CHECK(handler, recordLength.has_value()); 380 auto need{ 381 static_cast<std::size_t>(recordOffsetInFrame_ + *recordLength)}; 382 auto got{ReadFrame(frameOffsetInFile_, need, handler)}; 383 if (got < need) { 384 handler.SignalEnd(); 385 } 386 } else { 387 RUNTIME_CHECK(handler, isUnformatted.has_value()); 388 if (isUnformatted.value_or(false)) { 389 BeginSequentialVariableUnformattedInputRecord(handler); 390 } else { // formatted 391 BeginSequentialVariableFormattedInputRecord(handler); 392 } 393 } 394 } 395 } 396 RUNTIME_CHECK(handler, 397 access != Access::Sequential || recordLength.has_value() || 398 handler.InError()); 399 return !handler.InError(); 400 } 401 402 void ExternalFileUnit::FinishReadingRecord(IoErrorHandler &handler) { 403 RUNTIME_CHECK(handler, direction_ == Direction::Input && beganReadingRecord_); 404 beganReadingRecord_ = false; 405 if (handler.InError()) { 406 // avoid bogus crashes in END/ERR circumstances 407 } else if (access == Access::Sequential) { 408 RUNTIME_CHECK(handler, recordLength.has_value()); 409 if (isFixedRecordLength) { 410 frameOffsetInFile_ += recordOffsetInFrame_ + *recordLength; 411 recordOffsetInFrame_ = 0; 412 } else { 413 RUNTIME_CHECK(handler, isUnformatted.has_value()); 414 if (isUnformatted.value_or(false)) { 415 // Retain footer in frame for more efficient BACKSPACE 416 frameOffsetInFile_ += recordOffsetInFrame_ + *recordLength; 417 recordOffsetInFrame_ = sizeof(std::uint32_t); 418 recordLength.reset(); 419 } else { // formatted 420 if (FrameLength() > recordOffsetInFrame_ + *recordLength && 421 Frame()[recordOffsetInFrame_ + *recordLength] == '\r') { 422 ++recordOffsetInFrame_; 423 } 424 if (FrameLength() >= recordOffsetInFrame_ && 425 Frame()[recordOffsetInFrame_ + *recordLength] == '\n') { 426 ++recordOffsetInFrame_; 427 } 428 if (!resumptionRecordNumber || mayPosition()) { 429 frameOffsetInFile_ += recordOffsetInFrame_ + *recordLength; 430 recordOffsetInFrame_ = 0; 431 } 432 recordLength.reset(); 433 } 434 } 435 } 436 ++currentRecordNumber; 437 BeginRecord(); 438 } 439 440 bool ExternalFileUnit::AdvanceRecord(IoErrorHandler &handler) { 441 if (direction_ == Direction::Input) { 442 FinishReadingRecord(handler); 443 return BeginReadingRecord(handler); 444 } else { // Direction::Output 445 bool ok{true}; 446 RUNTIME_CHECK(handler, isUnformatted.has_value()); 447 if (isFixedRecordLength && recordLength) { 448 // Pad remainder of fixed length record 449 if (furthestPositionInRecord < *recordLength) { 450 WriteFrame( 451 frameOffsetInFile_, recordOffsetInFrame_ + *recordLength, handler); 452 std::memset(Frame() + recordOffsetInFrame_ + furthestPositionInRecord, 453 isUnformatted.value_or(false) ? 0 : ' ', 454 *recordLength - furthestPositionInRecord); 455 } 456 } else { 457 positionInRecord = furthestPositionInRecord; 458 if (isUnformatted.value_or(false)) { 459 // Append the length of a sequential unformatted variable-length record 460 // as its footer, then overwrite the reserved first four bytes of the 461 // record with its length as its header. These four bytes were skipped 462 // over in BeginUnformattedIO<Output>(). 463 // TODO: Break very large records up into subrecords with negative 464 // headers &/or footers 465 std::uint32_t length; 466 length = furthestPositionInRecord - sizeof length; 467 ok = ok && 468 Emit(reinterpret_cast<const char *>(&length), sizeof length, 469 sizeof length, handler); 470 positionInRecord = 0; 471 ok = ok && 472 Emit(reinterpret_cast<const char *>(&length), sizeof length, 473 sizeof length, handler); 474 } else { 475 // Terminate formatted variable length record 476 ok = ok && Emit("\n", 1, 1, handler); // TODO: Windows CR+LF 477 } 478 } 479 CommitWrites(); 480 impliedEndfile_ = true; 481 ++currentRecordNumber; 482 if (endfileRecordNumber && currentRecordNumber >= *endfileRecordNumber) { 483 endfileRecordNumber.reset(); 484 } 485 return ok; 486 } 487 } 488 489 void ExternalFileUnit::BackspaceRecord(IoErrorHandler &handler) { 490 if (access != Access::Sequential) { 491 handler.SignalError(IostatBackspaceNonSequential, 492 "BACKSPACE(UNIT=%d) on non-sequential file", unitNumber()); 493 } else { 494 if (endfileRecordNumber && currentRecordNumber > *endfileRecordNumber) { 495 // BACKSPACE after explicit ENDFILE 496 currentRecordNumber = *endfileRecordNumber; 497 } else { 498 DoImpliedEndfile(handler); 499 if (frameOffsetInFile_ + recordOffsetInFrame_ > 0) { 500 --currentRecordNumber; 501 if (isFixedRecordLength) { 502 BackspaceFixedRecord(handler); 503 } else { 504 RUNTIME_CHECK(handler, isUnformatted.has_value()); 505 if (isUnformatted.value_or(false)) { 506 BackspaceVariableUnformattedRecord(handler); 507 } else { 508 BackspaceVariableFormattedRecord(handler); 509 } 510 } 511 } 512 } 513 BeginRecord(); 514 } 515 } 516 517 void ExternalFileUnit::FlushOutput(IoErrorHandler &handler) { 518 if (!mayPosition()) { 519 auto frameAt{FrameAt()}; 520 if (frameOffsetInFile_ >= frameAt && 521 frameOffsetInFile_ < 522 static_cast<std::int64_t>(frameAt + FrameLength())) { 523 // A Flush() that's about to happen to a non-positionable file 524 // needs to advance frameOffsetInFile_ to prevent attempts at 525 // impossible seeks 526 CommitWrites(); 527 } 528 } 529 Flush(handler); 530 } 531 532 void ExternalFileUnit::FlushIfTerminal(IoErrorHandler &handler) { 533 if (isTerminal()) { 534 FlushOutput(handler); 535 } 536 } 537 538 void ExternalFileUnit::Endfile(IoErrorHandler &handler) { 539 if (access != Access::Sequential) { 540 handler.SignalError(IostatEndfileNonSequential, 541 "ENDFILE(UNIT=%d) on non-sequential file", unitNumber()); 542 } else if (!mayWrite()) { 543 handler.SignalError(IostatEndfileUnwritable, 544 "ENDFILE(UNIT=%d) on read-only file", unitNumber()); 545 } else if (endfileRecordNumber && 546 currentRecordNumber > *endfileRecordNumber) { 547 // ENDFILE after ENDFILE 548 } else { 549 DoEndfile(handler); 550 // Explicit ENDFILE leaves position *after* the endfile record 551 RUNTIME_CHECK(handler, endfileRecordNumber.has_value()); 552 currentRecordNumber = *endfileRecordNumber + 1; 553 } 554 } 555 556 void ExternalFileUnit::Rewind(IoErrorHandler &handler) { 557 if (access == Access::Direct) { 558 handler.SignalError(IostatRewindNonSequential, 559 "REWIND(UNIT=%d) on non-sequential file", unitNumber()); 560 } else { 561 DoImpliedEndfile(handler); 562 SetPosition(0); 563 currentRecordNumber = 1; 564 } 565 } 566 567 void ExternalFileUnit::EndIoStatement() { 568 io_.reset(); 569 u_.emplace<std::monostate>(); 570 lock_.Drop(); 571 } 572 573 void ExternalFileUnit::BeginSequentialVariableUnformattedInputRecord( 574 IoErrorHandler &handler) { 575 std::int32_t header{0}, footer{0}; 576 std::size_t need{recordOffsetInFrame_ + sizeof header}; 577 std::size_t got{ReadFrame(frameOffsetInFile_, need, handler)}; 578 // Try to emit informative errors to help debug corrupted files. 579 const char *error{nullptr}; 580 if (got < need) { 581 if (got == recordOffsetInFrame_) { 582 handler.SignalEnd(); 583 } else { 584 error = "Unformatted variable-length sequential file input failed at " 585 "record #%jd (file offset %jd): truncated record header"; 586 } 587 } else { 588 std::memcpy(&header, Frame() + recordOffsetInFrame_, sizeof header); 589 recordLength = sizeof header + header; // does not include footer 590 need = recordOffsetInFrame_ + *recordLength + sizeof footer; 591 got = ReadFrame(frameOffsetInFile_, need, handler); 592 if (got < need) { 593 error = "Unformatted variable-length sequential file input failed at " 594 "record #%jd (file offset %jd): hit EOF reading record with " 595 "length %jd bytes"; 596 } else { 597 std::memcpy(&footer, Frame() + recordOffsetInFrame_ + *recordLength, 598 sizeof footer); 599 if (footer != header) { 600 error = "Unformatted variable-length sequential file input failed at " 601 "record #%jd (file offset %jd): record header has length %jd " 602 "that does not match record footer (%jd)"; 603 } 604 } 605 } 606 if (error) { 607 handler.SignalError(error, static_cast<std::intmax_t>(currentRecordNumber), 608 static_cast<std::intmax_t>(frameOffsetInFile_), 609 static_cast<std::intmax_t>(header), static_cast<std::intmax_t>(footer)); 610 // TODO: error recovery 611 } 612 positionInRecord = sizeof header; 613 } 614 615 void ExternalFileUnit::BeginSequentialVariableFormattedInputRecord( 616 IoErrorHandler &handler) { 617 if (this == defaultInput && defaultOutput) { 618 defaultOutput->FlushOutput(handler); 619 } 620 std::size_t length{0}; 621 do { 622 std::size_t need{length + 1}; 623 length = 624 ReadFrame(frameOffsetInFile_, recordOffsetInFrame_ + need, handler) - 625 recordOffsetInFrame_; 626 if (length < need) { 627 if (length > 0) { 628 // final record w/o \n 629 recordLength = length; 630 } else { 631 handler.SignalEnd(); 632 } 633 break; 634 } 635 } while (!SetSequentialVariableFormattedRecordLength()); 636 } 637 638 void ExternalFileUnit::BackspaceFixedRecord(IoErrorHandler &handler) { 639 RUNTIME_CHECK(handler, recordLength.has_value()); 640 if (frameOffsetInFile_ < *recordLength) { 641 handler.SignalError(IostatBackspaceAtFirstRecord); 642 } else { 643 frameOffsetInFile_ -= *recordLength; 644 } 645 } 646 647 void ExternalFileUnit::BackspaceVariableUnformattedRecord( 648 IoErrorHandler &handler) { 649 std::int32_t header{0}, footer{0}; 650 auto headerBytes{static_cast<std::int64_t>(sizeof header)}; 651 frameOffsetInFile_ += recordOffsetInFrame_; 652 recordOffsetInFrame_ = 0; 653 if (frameOffsetInFile_ <= headerBytes) { 654 handler.SignalError(IostatBackspaceAtFirstRecord); 655 return; 656 } 657 // Error conditions here cause crashes, not file format errors, because the 658 // validity of the file structure before the current record will have been 659 // checked informatively in NextSequentialVariableUnformattedInputRecord(). 660 std::size_t got{ 661 ReadFrame(frameOffsetInFile_ - headerBytes, headerBytes, handler)}; 662 RUNTIME_CHECK(handler, got >= sizeof footer); 663 std::memcpy(&footer, Frame(), sizeof footer); 664 recordLength = footer; 665 RUNTIME_CHECK(handler, frameOffsetInFile_ >= *recordLength + 2 * headerBytes); 666 frameOffsetInFile_ -= *recordLength + 2 * headerBytes; 667 if (frameOffsetInFile_ >= headerBytes) { 668 frameOffsetInFile_ -= headerBytes; 669 recordOffsetInFrame_ = headerBytes; 670 } 671 auto need{static_cast<std::size_t>( 672 recordOffsetInFrame_ + sizeof header + *recordLength)}; 673 got = ReadFrame(frameOffsetInFile_, need, handler); 674 RUNTIME_CHECK(handler, got >= need); 675 std::memcpy(&header, Frame() + recordOffsetInFrame_, sizeof header); 676 RUNTIME_CHECK(handler, header == *recordLength); 677 } 678 679 // There's no portable memrchr(), unfortunately, and strrchr() would 680 // fail on a record with a NUL, so we have to do it the hard way. 681 static const char *FindLastNewline(const char *str, std::size_t length) { 682 for (const char *p{str + length}; p-- > str;) { 683 if (*p == '\n') { 684 return p; 685 } 686 } 687 return nullptr; 688 } 689 690 void ExternalFileUnit::BackspaceVariableFormattedRecord( 691 IoErrorHandler &handler) { 692 // File offset of previous record's newline 693 auto prevNL{ 694 frameOffsetInFile_ + static_cast<std::int64_t>(recordOffsetInFrame_) - 1}; 695 if (prevNL < 0) { 696 handler.SignalError(IostatBackspaceAtFirstRecord); 697 return; 698 } 699 while (true) { 700 if (frameOffsetInFile_ < prevNL) { 701 if (const char *p{ 702 FindLastNewline(Frame(), prevNL - 1 - frameOffsetInFile_)}) { 703 recordOffsetInFrame_ = p - Frame() + 1; 704 recordLength = prevNL - (frameOffsetInFile_ + recordOffsetInFrame_); 705 break; 706 } 707 } 708 if (frameOffsetInFile_ == 0) { 709 recordOffsetInFrame_ = 0; 710 recordLength = prevNL; 711 break; 712 } 713 frameOffsetInFile_ -= std::min<std::int64_t>(frameOffsetInFile_, 1024); 714 auto need{static_cast<std::size_t>(prevNL + 1 - frameOffsetInFile_)}; 715 auto got{ReadFrame(frameOffsetInFile_, need, handler)}; 716 RUNTIME_CHECK(handler, got >= need); 717 } 718 RUNTIME_CHECK(handler, Frame()[recordOffsetInFrame_ + *recordLength] == '\n'); 719 if (*recordLength > 0 && 720 Frame()[recordOffsetInFrame_ + *recordLength - 1] == '\r') { 721 --*recordLength; 722 } 723 } 724 725 void ExternalFileUnit::DoImpliedEndfile(IoErrorHandler &handler) { 726 if (impliedEndfile_) { 727 impliedEndfile_ = false; 728 if (access == Access::Sequential && mayPosition()) { 729 DoEndfile(handler); 730 } 731 } 732 } 733 734 void ExternalFileUnit::DoEndfile(IoErrorHandler &handler) { 735 endfileRecordNumber = currentRecordNumber; 736 Truncate(frameOffsetInFile_ + recordOffsetInFrame_, handler); 737 BeginRecord(); 738 impliedEndfile_ = false; 739 } 740 741 void ExternalFileUnit::CommitWrites() { 742 frameOffsetInFile_ += 743 recordOffsetInFrame_ + recordLength.value_or(furthestPositionInRecord); 744 recordOffsetInFrame_ = 0; 745 BeginRecord(); 746 } 747 748 ChildIo &ExternalFileUnit::PushChildIo(IoStatementState &parent) { 749 OwningPtr<ChildIo> current{std::move(child_)}; 750 Terminator &terminator{parent.GetIoErrorHandler()}; 751 OwningPtr<ChildIo> next{New<ChildIo>{terminator}(parent, std::move(current))}; 752 child_.reset(next.release()); 753 return *child_; 754 } 755 756 void ExternalFileUnit::PopChildIo(ChildIo &child) { 757 if (child_.get() != &child) { 758 child.parent().GetIoErrorHandler().Crash( 759 "ChildIo being popped is not top of stack"); 760 } 761 child_.reset(child.AcquirePrevious().release()); // deletes top child 762 } 763 764 void ChildIo::EndIoStatement() { 765 io_.reset(); 766 u_.emplace<std::monostate>(); 767 } 768 769 bool ChildIo::CheckFormattingAndDirection(Terminator &terminator, 770 const char *what, bool unformatted, Direction direction) { 771 bool parentIsUnformatted{!parent_.get_if<FormattedIoStatementState>()}; 772 bool parentIsInput{!parent_.get_if<IoDirectionState<Direction::Output>>()}; 773 if (unformatted != parentIsUnformatted) { 774 terminator.Crash("Child %s attempted on %s parent I/O unit", what, 775 parentIsUnformatted ? "unformatted" : "formatted"); 776 return false; 777 } else if (parentIsInput != (direction == Direction::Input)) { 778 terminator.Crash("Child %s attempted on %s parent I/O unit", what, 779 parentIsInput ? "input" : "output"); 780 return false; 781 } else { 782 return true; 783 } 784 } 785 786 } // namespace Fortran::runtime::io 787