1 //===-- File.cpp ------------------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "lldb/Host/File.h"
19 #include "lldb/Host/windows/windows.h"
21 #include <sys/ioctl.h>
27 #include "llvm/Support/ConvertUTF.h"
28 #include "llvm/Support/Errno.h"
29 #include "llvm/Support/FileSystem.h"
30 #include "llvm/Support/Process.h"
32 #include "lldb/Host/Config.h"
33 #include "lldb/Host/FileSystem.h"
34 #include "lldb/Host/Host.h"
35 #include "lldb/Utility/DataBufferHeap.h"
36 #include "lldb/Utility/FileSpec.h"
37 #include "lldb/Utility/Log.h"
40 using namespace lldb_private;
42 static const char *GetStreamOpenModeFromOptions(uint32_t options) {
43 if (options & File::eOpenOptionAppend) {
44 if (options & File::eOpenOptionRead) {
45 if (options & File::eOpenOptionCanCreateNewOnly)
49 } else if (options & File::eOpenOptionWrite) {
50 if (options & File::eOpenOptionCanCreateNewOnly)
55 } else if (options & File::eOpenOptionRead &&
56 options & File::eOpenOptionWrite) {
57 if (options & File::eOpenOptionCanCreate) {
58 if (options & File::eOpenOptionCanCreateNewOnly)
64 } else if (options & File::eOpenOptionRead) {
66 } else if (options & File::eOpenOptionWrite) {
72 int File::kInvalidDescriptor = -1;
73 FILE *File::kInvalidStream = NULL;
75 File::~File() { Close(); }
77 int File::GetDescriptor() const {
78 if (DescriptorIsValid())
81 // Don't open the file descriptor if we don't need to, just get it from the
82 // stream if we have one.
83 if (StreamIsValid()) {
85 return _fileno(m_stream);
87 return fileno(m_stream);
91 // Invalid descriptor and invalid stream, return invalid descriptor.
92 return kInvalidDescriptor;
95 IOObject::WaitableHandle File::GetWaitableHandle() { return m_descriptor; }
97 void File::SetDescriptor(int fd, bool transfer_ownership) {
101 m_should_close_fd = transfer_ownership;
104 FILE *File::GetStream() {
105 if (!StreamIsValid()) {
106 if (DescriptorIsValid()) {
107 const char *mode = GetStreamOpenModeFromOptions(m_options);
109 if (!m_should_close_fd) {
110 // We must duplicate the file descriptor if we don't own it because when you
111 // call fdopen, the stream will own the fd
113 m_descriptor = ::_dup(GetDescriptor());
115 m_descriptor = dup(GetDescriptor());
117 m_should_close_fd = true;
121 llvm::sys::RetryAfterSignal(nullptr, ::fdopen, m_descriptor, mode);
123 // If we got a stream, then we own the stream and should no longer own
124 // the descriptor because fclose() will close it for us
128 m_should_close_fd = false;
136 void File::SetStream(FILE *fh, bool transfer_ownership) {
140 m_own_stream = transfer_ownership;
143 uint32_t File::GetPermissions(Status &error) const {
144 int fd = GetDescriptor();
145 if (fd != kInvalidDescriptor) {
146 struct stat file_stats;
147 if (::fstat(fd, &file_stats) == -1)
148 error.SetErrorToErrno();
151 return file_stats.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO);
154 error.SetErrorString("invalid file descriptor");
159 Status File::Close() {
161 if (StreamIsValid() && m_own_stream) {
162 if (::fclose(m_stream) == EOF)
163 error.SetErrorToErrno();
166 if (DescriptorIsValid() && m_should_close_fd) {
167 if (::close(m_descriptor) != 0)
168 error.SetErrorToErrno();
170 m_descriptor = kInvalidDescriptor;
171 m_stream = kInvalidStream;
173 m_own_stream = false;
174 m_should_close_fd = false;
175 m_is_interactive = eLazyBoolCalculate;
176 m_is_real_terminal = eLazyBoolCalculate;
184 m_own_stream = false;
185 m_is_interactive = m_supports_colors = m_is_real_terminal =
189 Status File::GetFileSpec(FileSpec &file_spec) const {
194 if (::fcntl(GetDescriptor(), F_GETPATH, path) == -1)
195 error.SetErrorToErrno();
197 file_spec.SetFile(path, FileSpec::Style::native);
199 error.SetErrorString("invalid file handle");
201 #elif defined(__linux__)
204 if (::snprintf(proc, sizeof(proc), "/proc/self/fd/%d", GetDescriptor()) < 0)
205 error.SetErrorString("cannot resolve file descriptor");
208 if ((len = ::readlink(proc, path, sizeof(path) - 1)) == -1)
209 error.SetErrorToErrno();
212 file_spec.SetFile(path, FileSpec::Style::native);
216 error.SetErrorString("File::GetFileSpec is not supported on this platform");
224 off_t File::SeekFromStart(off_t offset, Status *error_ptr) {
226 if (DescriptorIsValid()) {
227 result = ::lseek(m_descriptor, offset, SEEK_SET);
231 error_ptr->SetErrorToErrno();
235 } else if (StreamIsValid()) {
236 result = ::fseek(m_stream, offset, SEEK_SET);
240 error_ptr->SetErrorToErrno();
244 } else if (error_ptr) {
245 error_ptr->SetErrorString("invalid file handle");
250 off_t File::SeekFromCurrent(off_t offset, Status *error_ptr) {
252 if (DescriptorIsValid()) {
253 result = ::lseek(m_descriptor, offset, SEEK_CUR);
257 error_ptr->SetErrorToErrno();
261 } else if (StreamIsValid()) {
262 result = ::fseek(m_stream, offset, SEEK_CUR);
266 error_ptr->SetErrorToErrno();
270 } else if (error_ptr) {
271 error_ptr->SetErrorString("invalid file handle");
276 off_t File::SeekFromEnd(off_t offset, Status *error_ptr) {
278 if (DescriptorIsValid()) {
279 result = ::lseek(m_descriptor, offset, SEEK_END);
283 error_ptr->SetErrorToErrno();
287 } else if (StreamIsValid()) {
288 result = ::fseek(m_stream, offset, SEEK_END);
292 error_ptr->SetErrorToErrno();
296 } else if (error_ptr) {
297 error_ptr->SetErrorString("invalid file handle");
302 Status File::Flush() {
304 if (StreamIsValid()) {
305 if (llvm::sys::RetryAfterSignal(EOF, ::fflush, m_stream) == EOF)
306 error.SetErrorToErrno();
307 } else if (!DescriptorIsValid()) {
308 error.SetErrorString("invalid file handle");
313 Status File::Sync() {
315 if (DescriptorIsValid()) {
317 int err = FlushFileBuffers((HANDLE)_get_osfhandle(m_descriptor));
319 error.SetErrorToGenericError();
321 if (llvm::sys::RetryAfterSignal(-1, ::fsync, m_descriptor) == -1)
322 error.SetErrorToErrno();
325 error.SetErrorString("invalid file handle");
330 #if defined(__APPLE__)
331 // Darwin kernels only can read/write <= INT_MAX bytes
332 #define MAX_READ_SIZE INT_MAX
333 #define MAX_WRITE_SIZE INT_MAX
336 Status File::Read(void *buf, size_t &num_bytes) {
339 #if defined(MAX_READ_SIZE)
340 if (num_bytes > MAX_READ_SIZE) {
341 uint8_t *p = (uint8_t *)buf;
342 size_t bytes_left = num_bytes;
343 // Init the num_bytes read to zero
346 while (bytes_left > 0) {
347 size_t curr_num_bytes;
348 if (bytes_left > MAX_READ_SIZE)
349 curr_num_bytes = MAX_READ_SIZE;
351 curr_num_bytes = bytes_left;
353 error = Read(p + num_bytes, curr_num_bytes);
355 // Update how many bytes were read
356 num_bytes += curr_num_bytes;
357 if (bytes_left < curr_num_bytes)
360 bytes_left -= curr_num_bytes;
369 ssize_t bytes_read = -1;
370 if (DescriptorIsValid()) {
371 bytes_read = llvm::sys::RetryAfterSignal(-1, ::read, m_descriptor, buf, num_bytes);
372 if (bytes_read == -1) {
373 error.SetErrorToErrno();
376 num_bytes = bytes_read;
377 } else if (StreamIsValid()) {
378 bytes_read = ::fread(buf, 1, num_bytes, m_stream);
380 if (bytes_read == 0) {
381 if (::feof(m_stream))
382 error.SetErrorString("feof");
383 else if (::ferror(m_stream))
384 error.SetErrorString("ferror");
387 num_bytes = bytes_read;
390 error.SetErrorString("invalid file handle");
395 Status File::Write(const void *buf, size_t &num_bytes) {
398 #if defined(MAX_WRITE_SIZE)
399 if (num_bytes > MAX_WRITE_SIZE) {
400 const uint8_t *p = (const uint8_t *)buf;
401 size_t bytes_left = num_bytes;
402 // Init the num_bytes written to zero
405 while (bytes_left > 0) {
406 size_t curr_num_bytes;
407 if (bytes_left > MAX_WRITE_SIZE)
408 curr_num_bytes = MAX_WRITE_SIZE;
410 curr_num_bytes = bytes_left;
412 error = Write(p + num_bytes, curr_num_bytes);
414 // Update how many bytes were read
415 num_bytes += curr_num_bytes;
416 if (bytes_left < curr_num_bytes)
419 bytes_left -= curr_num_bytes;
428 ssize_t bytes_written = -1;
429 if (DescriptorIsValid()) {
431 llvm::sys::RetryAfterSignal(-1, ::write, m_descriptor, buf, num_bytes);
432 if (bytes_written == -1) {
433 error.SetErrorToErrno();
436 num_bytes = bytes_written;
437 } else if (StreamIsValid()) {
438 bytes_written = ::fwrite(buf, 1, num_bytes, m_stream);
440 if (bytes_written == 0) {
441 if (::feof(m_stream))
442 error.SetErrorString("feof");
443 else if (::ferror(m_stream))
444 error.SetErrorString("ferror");
447 num_bytes = bytes_written;
451 error.SetErrorString("invalid file handle");
457 Status File::Read(void *buf, size_t &num_bytes, off_t &offset) {
460 #if defined(MAX_READ_SIZE)
461 if (num_bytes > MAX_READ_SIZE) {
462 uint8_t *p = (uint8_t *)buf;
463 size_t bytes_left = num_bytes;
464 // Init the num_bytes read to zero
467 while (bytes_left > 0) {
468 size_t curr_num_bytes;
469 if (bytes_left > MAX_READ_SIZE)
470 curr_num_bytes = MAX_READ_SIZE;
472 curr_num_bytes = bytes_left;
474 error = Read(p + num_bytes, curr_num_bytes, offset);
476 // Update how many bytes were read
477 num_bytes += curr_num_bytes;
478 if (bytes_left < curr_num_bytes)
481 bytes_left -= curr_num_bytes;
491 int fd = GetDescriptor();
492 if (fd != kInvalidDescriptor) {
494 llvm::sys::RetryAfterSignal(-1, ::pread, fd, buf, num_bytes, offset);
495 if (bytes_read < 0) {
497 error.SetErrorToErrno();
499 offset += bytes_read;
500 num_bytes = bytes_read;
504 error.SetErrorString("invalid file handle");
507 long cur = ::lseek(m_descriptor, 0, SEEK_CUR);
508 SeekFromStart(offset);
509 error = Read(buf, num_bytes);
516 Status File::Read(size_t &num_bytes, off_t &offset, bool null_terminate,
517 DataBufferSP &data_buffer_sp) {
521 int fd = GetDescriptor();
522 if (fd != kInvalidDescriptor) {
523 struct stat file_stats;
524 if (::fstat(fd, &file_stats) == 0) {
525 if (file_stats.st_size > offset) {
526 const size_t bytes_left = file_stats.st_size - offset;
527 if (num_bytes > bytes_left)
528 num_bytes = bytes_left;
530 size_t num_bytes_plus_nul_char = num_bytes + (null_terminate ? 1 : 0);
531 std::unique_ptr<DataBufferHeap> data_heap_ap;
532 data_heap_ap.reset(new DataBufferHeap());
533 data_heap_ap->SetByteSize(num_bytes_plus_nul_char);
535 if (data_heap_ap.get()) {
536 error = Read(data_heap_ap->GetBytes(), num_bytes, offset);
537 if (error.Success()) {
538 // Make sure we read exactly what we asked for and if we got
539 // less, adjust the array
540 if (num_bytes_plus_nul_char < data_heap_ap->GetByteSize())
541 data_heap_ap->SetByteSize(num_bytes_plus_nul_char);
542 data_buffer_sp.reset(data_heap_ap.release());
547 error.SetErrorString("file is empty");
549 error.SetErrorToErrno();
551 error.SetErrorString("invalid file handle");
553 error.SetErrorString("invalid file handle");
556 data_buffer_sp.reset();
560 Status File::Write(const void *buf, size_t &num_bytes, off_t &offset) {
563 #if defined(MAX_WRITE_SIZE)
564 if (num_bytes > MAX_WRITE_SIZE) {
565 const uint8_t *p = (const uint8_t *)buf;
566 size_t bytes_left = num_bytes;
567 // Init the num_bytes written to zero
570 while (bytes_left > 0) {
571 size_t curr_num_bytes;
572 if (bytes_left > MAX_WRITE_SIZE)
573 curr_num_bytes = MAX_WRITE_SIZE;
575 curr_num_bytes = bytes_left;
577 error = Write(p + num_bytes, curr_num_bytes, offset);
579 // Update how many bytes were read
580 num_bytes += curr_num_bytes;
581 if (bytes_left < curr_num_bytes)
584 bytes_left -= curr_num_bytes;
593 int fd = GetDescriptor();
594 if (fd != kInvalidDescriptor) {
596 ssize_t bytes_written =
597 llvm::sys::RetryAfterSignal(-1, ::pwrite, m_descriptor, buf, num_bytes, offset);
598 if (bytes_written < 0) {
600 error.SetErrorToErrno();
602 offset += bytes_written;
603 num_bytes = bytes_written;
606 long cur = ::lseek(m_descriptor, 0, SEEK_CUR);
607 error = Write(buf, num_bytes);
608 long after = ::lseek(m_descriptor, 0, SEEK_CUR);
617 error.SetErrorString("invalid file handle");
622 //------------------------------------------------------------------
623 // Print some formatted output to the stream.
624 //------------------------------------------------------------------
625 size_t File::Printf(const char *format, ...) {
627 va_start(args, format);
628 size_t result = PrintfVarArg(format, args);
633 //------------------------------------------------------------------
634 // Print some formatted output to the stream.
635 //------------------------------------------------------------------
636 size_t File::PrintfVarArg(const char *format, va_list args) {
638 if (DescriptorIsValid()) {
640 result = vasprintf(&s, format, args);
643 size_t s_len = result;
649 } else if (StreamIsValid()) {
650 result = ::vfprintf(m_stream, format, args);
655 mode_t File::ConvertOpenOptionsForPOSIXOpen(uint32_t open_options) {
657 if (open_options & eOpenOptionRead && open_options & eOpenOptionWrite)
659 else if (open_options & eOpenOptionWrite)
662 if (open_options & eOpenOptionAppend)
665 if (open_options & eOpenOptionTruncate)
668 if (open_options & eOpenOptionNonBlocking)
671 if (open_options & eOpenOptionCanCreateNewOnly)
672 mode |= O_CREAT | O_EXCL;
673 else if (open_options & eOpenOptionCanCreate)
679 void File::CalculateInteractiveAndTerminal() {
680 const int fd = GetDescriptor();
682 m_is_interactive = eLazyBoolNo;
683 m_is_real_terminal = eLazyBoolNo;
686 m_is_interactive = eLazyBoolYes;
687 m_is_real_terminal = eLazyBoolYes;
688 #if defined(ENABLE_VIRTUAL_TERMINAL_PROCESSING)
689 m_supports_colors = eLazyBoolYes;
694 m_is_interactive = eLazyBoolYes;
695 struct winsize window_size;
696 if (::ioctl(fd, TIOCGWINSZ, &window_size) == 0) {
697 if (window_size.ws_col > 0) {
698 m_is_real_terminal = eLazyBoolYes;
699 if (llvm::sys::Process::FileDescriptorHasColors(fd))
700 m_supports_colors = eLazyBoolYes;
708 bool File::GetIsInteractive() {
709 if (m_is_interactive == eLazyBoolCalculate)
710 CalculateInteractiveAndTerminal();
711 return m_is_interactive == eLazyBoolYes;
714 bool File::GetIsRealTerminal() {
715 if (m_is_real_terminal == eLazyBoolCalculate)
716 CalculateInteractiveAndTerminal();
717 return m_is_real_terminal == eLazyBoolYes;
720 bool File::GetIsTerminalWithColors() {
721 if (m_supports_colors == eLazyBoolCalculate)
722 CalculateInteractiveAndTerminal();
723 return m_supports_colors == eLazyBoolYes;