1 //===-- runtime/file.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 "file.h" 10 #include "flang/Runtime/magic-numbers.h" 11 #include "flang/Runtime/memory.h" 12 #include <algorithm> 13 #include <cerrno> 14 #include <cstring> 15 #include <fcntl.h> 16 #include <stdlib.h> 17 #include <sys/stat.h> 18 #ifdef _WIN32 19 #define NOMINMAX 20 #include <io.h> 21 #include <windows.h> 22 #else 23 #include <unistd.h> 24 #endif 25 26 namespace Fortran::runtime::io { 27 28 void OpenFile::set_path(OwningPtr<char> &&path, std::size_t bytes) { 29 path_ = std::move(path); 30 pathLength_ = bytes; 31 } 32 33 static int openfile_mkstemp(IoErrorHandler &handler) { 34 #ifdef _WIN32 35 const unsigned int uUnique{0}; 36 // GetTempFileNameA needs a directory name < MAX_PATH-14 characters in length. 37 // https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-gettempfilenamea 38 char tempDirName[MAX_PATH - 14]; 39 char tempFileName[MAX_PATH]; 40 unsigned long nBufferLength{sizeof(tempDirName)}; 41 nBufferLength = ::GetTempPathA(nBufferLength, tempDirName); 42 if (nBufferLength > sizeof(tempDirName) || nBufferLength == 0) { 43 return -1; 44 } 45 if (::GetTempFileNameA(tempDirName, "Fortran", uUnique, tempFileName) == 0) { 46 return -1; 47 } 48 int fd{::_open( 49 tempFileName, _O_CREAT | _O_TEMPORARY | _O_RDWR, _S_IREAD | _S_IWRITE)}; 50 #else 51 char path[]{"/tmp/Fortran-Scratch-XXXXXX"}; 52 int fd{::mkstemp(path)}; 53 #endif 54 if (fd < 0) { 55 handler.SignalErrno(); 56 } 57 #ifndef _WIN32 58 ::unlink(path); 59 #endif 60 return fd; 61 } 62 63 void OpenFile::Open(OpenStatus status, std::optional<Action> action, 64 Position position, IoErrorHandler &handler) { 65 if (fd_ >= 0 && 66 (status == OpenStatus::Old || status == OpenStatus::Unknown)) { 67 return; 68 } 69 CloseFd(handler); 70 if (status == OpenStatus::Scratch) { 71 if (path_.get()) { 72 handler.SignalError("FILE= must not appear with STATUS='SCRATCH'"); 73 path_.reset(); 74 } 75 if (!action) { 76 action = Action::ReadWrite; 77 } 78 fd_ = openfile_mkstemp(handler); 79 } else { 80 if (!path_.get()) { 81 handler.SignalError("FILE= is required"); 82 return; 83 } 84 int flags{0}; 85 if (status != OpenStatus::Old) { 86 flags |= O_CREAT; 87 } 88 if (status == OpenStatus::New) { 89 flags |= O_EXCL; 90 } else if (status == OpenStatus::Replace) { 91 flags |= O_TRUNC; 92 } 93 if (!action) { 94 // Try to open read/write, back off to read-only on failure 95 fd_ = ::open(path_.get(), flags | O_RDWR, 0600); 96 if (fd_ >= 0) { 97 action = Action::ReadWrite; 98 } else { 99 action = Action::Read; 100 } 101 } 102 if (fd_ < 0) { 103 switch (*action) { 104 case Action::Read: 105 flags |= O_RDONLY; 106 break; 107 case Action::Write: 108 flags |= O_WRONLY; 109 break; 110 case Action::ReadWrite: 111 flags |= O_RDWR; 112 break; 113 } 114 fd_ = ::open(path_.get(), flags, 0600); 115 if (fd_ < 0) { 116 handler.SignalErrno(); 117 } 118 } 119 } 120 RUNTIME_CHECK(handler, action.has_value()); 121 pending_.reset(); 122 if (position == Position::Append && !RawSeekToEnd()) { 123 handler.SignalErrno(); 124 } 125 isTerminal_ = ::isatty(fd_) == 1; 126 mayRead_ = *action != Action::Write; 127 mayWrite_ = *action != Action::Read; 128 if (status == OpenStatus::Old || status == OpenStatus::Unknown) { 129 knownSize_.reset(); 130 #ifndef _WIN32 131 struct stat buf; 132 if (::fstat(fd_, &buf) == 0) { 133 mayPosition_ = S_ISREG(buf.st_mode); 134 knownSize_ = buf.st_size; 135 } 136 #else // TODO: _WIN32 137 mayPosition_ = true; 138 #endif 139 } else { 140 knownSize_ = 0; 141 mayPosition_ = true; 142 } 143 openPosition_ = position; // for INQUIRE(POSITION=) 144 } 145 146 void OpenFile::Predefine(int fd) { 147 fd_ = fd; 148 path_.reset(); 149 pathLength_ = 0; 150 position_ = 0; 151 knownSize_.reset(); 152 nextId_ = 0; 153 pending_.reset(); 154 mayRead_ = fd == 0; 155 mayWrite_ = fd != 0; 156 mayPosition_ = false; 157 } 158 159 void OpenFile::Close(CloseStatus status, IoErrorHandler &handler) { 160 pending_.reset(); 161 knownSize_.reset(); 162 switch (status) { 163 case CloseStatus::Keep: 164 break; 165 case CloseStatus::Delete: 166 if (path_.get()) { 167 ::unlink(path_.get()); 168 } 169 break; 170 } 171 path_.reset(); 172 CloseFd(handler); 173 } 174 175 std::size_t OpenFile::Read(FileOffset at, char *buffer, std::size_t minBytes, 176 std::size_t maxBytes, IoErrorHandler &handler) { 177 if (maxBytes == 0) { 178 return 0; 179 } 180 CheckOpen(handler); 181 if (!Seek(at, handler)) { 182 return 0; 183 } 184 minBytes = std::min(minBytes, maxBytes); 185 std::size_t got{0}; 186 while (got < minBytes) { 187 auto chunk{::read(fd_, buffer + got, maxBytes - got)}; 188 if (chunk == 0) { 189 break; 190 } else if (chunk < 0) { 191 auto err{errno}; 192 if (err != EAGAIN && err != EWOULDBLOCK && err != EINTR) { 193 handler.SignalError(err); 194 break; 195 } 196 } else { 197 SetPosition(position_ + chunk); 198 got += chunk; 199 } 200 } 201 return got; 202 } 203 204 std::size_t OpenFile::Write(FileOffset at, const char *buffer, 205 std::size_t bytes, IoErrorHandler &handler) { 206 if (bytes == 0) { 207 return 0; 208 } 209 CheckOpen(handler); 210 if (!Seek(at, handler)) { 211 return 0; 212 } 213 std::size_t put{0}; 214 while (put < bytes) { 215 auto chunk{::write(fd_, buffer + put, bytes - put)}; 216 if (chunk >= 0) { 217 SetPosition(position_ + chunk); 218 put += chunk; 219 } else { 220 auto err{errno}; 221 if (err != EAGAIN && err != EWOULDBLOCK && err != EINTR) { 222 handler.SignalError(err); 223 break; 224 } 225 } 226 } 227 if (knownSize_ && position_ > *knownSize_) { 228 knownSize_ = position_; 229 } 230 return put; 231 } 232 233 inline static int openfile_ftruncate(int fd, OpenFile::FileOffset at) { 234 #ifdef _WIN32 235 return ::_chsize(fd, at); 236 #else 237 return ::ftruncate(fd, at); 238 #endif 239 } 240 241 void OpenFile::Truncate(FileOffset at, IoErrorHandler &handler) { 242 CheckOpen(handler); 243 if (!knownSize_ || *knownSize_ != at) { 244 if (openfile_ftruncate(fd_, at) != 0) { 245 handler.SignalErrno(); 246 } 247 knownSize_ = at; 248 } 249 } 250 251 // The operation is performed immediately; the results are saved 252 // to be claimed by a later WAIT statement. 253 // TODO: True asynchronicity 254 int OpenFile::ReadAsynchronously( 255 FileOffset at, char *buffer, std::size_t bytes, IoErrorHandler &handler) { 256 CheckOpen(handler); 257 int iostat{0}; 258 for (std::size_t got{0}; got < bytes;) { 259 #if _XOPEN_SOURCE >= 500 || _POSIX_C_SOURCE >= 200809L 260 auto chunk{::pread(fd_, buffer + got, bytes - got, at)}; 261 #else 262 auto chunk{Seek(at, handler) ? ::read(fd_, buffer + got, bytes - got) : -1}; 263 #endif 264 if (chunk == 0) { 265 iostat = FORTRAN_RUNTIME_IOSTAT_END; 266 break; 267 } 268 if (chunk < 0) { 269 auto err{errno}; 270 if (err != EAGAIN && err != EWOULDBLOCK && err != EINTR) { 271 iostat = err; 272 break; 273 } 274 } else { 275 at += chunk; 276 got += chunk; 277 } 278 } 279 return PendingResult(handler, iostat); 280 } 281 282 // TODO: True asynchronicity 283 int OpenFile::WriteAsynchronously(FileOffset at, const char *buffer, 284 std::size_t bytes, IoErrorHandler &handler) { 285 CheckOpen(handler); 286 int iostat{0}; 287 for (std::size_t put{0}; put < bytes;) { 288 #if _XOPEN_SOURCE >= 500 || _POSIX_C_SOURCE >= 200809L 289 auto chunk{::pwrite(fd_, buffer + put, bytes - put, at)}; 290 #else 291 auto chunk{ 292 Seek(at, handler) ? ::write(fd_, buffer + put, bytes - put) : -1}; 293 #endif 294 if (chunk >= 0) { 295 at += chunk; 296 put += chunk; 297 } else { 298 auto err{errno}; 299 if (err != EAGAIN && err != EWOULDBLOCK && err != EINTR) { 300 iostat = err; 301 break; 302 } 303 } 304 } 305 return PendingResult(handler, iostat); 306 } 307 308 void OpenFile::Wait(int id, IoErrorHandler &handler) { 309 std::optional<int> ioStat; 310 Pending *prev{nullptr}; 311 for (Pending *p{pending_.get()}; p; p = (prev = p)->next.get()) { 312 if (p->id == id) { 313 ioStat = p->ioStat; 314 if (prev) { 315 prev->next.reset(p->next.release()); 316 } else { 317 pending_.reset(p->next.release()); 318 } 319 break; 320 } 321 } 322 if (ioStat) { 323 handler.SignalError(*ioStat); 324 } 325 } 326 327 void OpenFile::WaitAll(IoErrorHandler &handler) { 328 while (true) { 329 int ioStat; 330 if (pending_) { 331 ioStat = pending_->ioStat; 332 pending_.reset(pending_->next.release()); 333 } else { 334 return; 335 } 336 handler.SignalError(ioStat); 337 } 338 } 339 340 Position OpenFile::InquirePosition() const { 341 if (openPosition_) { // from OPEN statement 342 return *openPosition_; 343 } else { // unit has been repositioned since opening 344 if (position_ == knownSize_.value_or(position_ + 1)) { 345 return Position::Append; 346 } else if (position_ == 0 && mayPosition_) { 347 return Position::Rewind; 348 } else { 349 return Position::AsIs; // processor-dependent & no common behavior 350 } 351 } 352 } 353 354 void OpenFile::CheckOpen(const Terminator &terminator) { 355 RUNTIME_CHECK(terminator, fd_ >= 0); 356 } 357 358 bool OpenFile::Seek(FileOffset at, IoErrorHandler &handler) { 359 if (at == position_) { 360 return true; 361 } else if (RawSeek(at)) { 362 SetPosition(at); 363 return true; 364 } else { 365 handler.SignalErrno(); 366 return false; 367 } 368 } 369 370 bool OpenFile::RawSeek(FileOffset at) { 371 #ifdef _LARGEFILE64_SOURCE 372 return ::lseek64(fd_, at, SEEK_SET) == at; 373 #else 374 return ::lseek(fd_, at, SEEK_SET) == at; 375 #endif 376 } 377 378 bool OpenFile::RawSeekToEnd() { 379 #ifdef _LARGEFILE64_SOURCE 380 std::int64_t at{::lseek64(fd_, 0, SEEK_END)}; 381 #else 382 std::int64_t at{::lseek(fd_, 0, SEEK_END)}; 383 #endif 384 if (at >= 0) { 385 knownSize_ = at; 386 return true; 387 } else { 388 return false; 389 } 390 } 391 392 int OpenFile::PendingResult(const Terminator &terminator, int iostat) { 393 int id{nextId_++}; 394 pending_ = New<Pending>{terminator}(id, iostat, std::move(pending_)); 395 return id; 396 } 397 398 void OpenFile::CloseFd(IoErrorHandler &handler) { 399 if (fd_ >= 0) { 400 if (fd_ <= 2) { 401 // don't actually close a standard file descriptor, we might need it 402 } else { 403 if (::close(fd_) != 0) { 404 handler.SignalErrno(); 405 } 406 } 407 fd_ = -1; 408 } 409 } 410 411 bool IsATerminal(int fd) { return ::isatty(fd); } 412 413 #ifdef WIN32 414 // Access flags are normally defined in unistd.h, which unavailable under 415 // Windows. Instead, define the flags as documented at 416 // https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/access-waccess 417 #define F_OK 00 418 #define W_OK 02 419 #define R_OK 04 420 #endif 421 422 bool IsExtant(const char *path) { return ::access(path, F_OK) == 0; } 423 bool MayRead(const char *path) { return ::access(path, R_OK) == 0; } 424 bool MayWrite(const char *path) { return ::access(path, W_OK) == 0; } 425 bool MayReadAndWrite(const char *path) { 426 return ::access(path, R_OK | W_OK) == 0; 427 } 428 } // namespace Fortran::runtime::io 429