27#include "lldb/Host/Config.h"
34#include "llvm/ADT/StringExtras.h"
35#include "llvm/Support/ConvertUTF.h"
36#include "llvm/Support/Errno.h"
37#include "llvm/Support/FileSystem.h"
38#include "llvm/Support/Process.h"
75 return llvm::createStringError(
76 llvm::inconvertibleErrorCode(),
77 "invalid options, cannot convert to mode string");
82 llvm::StringSwitch<OpenOptions>(mode)
89 .Cases(
"w+",
"wb+",
"w+b",
92 .Cases(
"a+",
"ab+",
"a+b",
98 return llvm::createStringError(
99 llvm::inconvertibleErrorCode(),
100 "invalid mode, cannot convert to File::OpenOptions");
107 return std::error_code(ENOTSUP, std::system_category());
110 return std::error_code(ENOTSUP, std::system_category());
123 return std::error_code(ENOTSUP, std::system_category());
132 *error_ptr = std::error_code(ENOTSUP, std::system_category());
138 *error_ptr = std::error_code(ENOTSUP, std::system_category());
144 *error_ptr = std::error_code(ENOTSUP, std::system_category());
149 return std::error_code(ENOTSUP, std::system_category());
153 return std::error_code(ENOTSUP, std::system_category());
174#if defined(ENABLE_VIRTUAL_TERMINAL_PROCESSING)
181 struct winsize window_size;
182 if (::ioctl(fd, TIOCGWINSZ, &window_size) == 0) {
183 if (window_size.ws_col > 0) {
185 if (llvm::sys::Process::FileDescriptorHasColors(fd))
213 va_start(args, format);
220 llvm::SmallString<0> s;
222 size_t written = s.size();
223 Write(s.data(), written);
230 return llvm::createStringError(
231 llvm::inconvertibleErrorCode(),
232 "GetOptions() not implemented for this File class");
238 error = std::error_code(ENOTSUP, std::system_category());
241 struct stat file_stats;
242 if (::fstat(fd, &file_stats) == -1) {
243 error.SetErrorToErrno();
286 llvm::consumeError(mode.takeError());
323 error.SetErrorToErrno();
331 error.SetErrorToErrno();
338 error.SetErrorToErrno();
357 error.SetErrorToErrno();
359 file_spec.
SetFile(path, FileSpec::Style::native);
361 error.SetErrorString(
"invalid file handle");
363#elif defined(__linux__)
366 if (::snprintf(proc,
sizeof(proc),
"/proc/self/fd/%d",
GetDescriptor()) < 0)
367 error.SetErrorString(
"cannot resolve file descriptor");
370 if ((len = ::readlink(proc, path,
sizeof(path) - 1)) == -1)
371 error.SetErrorToErrno();
374 file_spec.
SetFile(path, FileSpec::Style::native);
378 error.SetErrorString(
379 "NativeFile::GetFileSpec is not supported on this platform");
402 result = ::fseek(
m_stream, offset, SEEK_SET);
433 result = ::fseek(
m_stream, offset, SEEK_CUR);
464 result = ::fseek(
m_stream, offset, SEEK_END);
482 if (llvm::sys::RetryAfterSignal(EOF, ::fflush,
m_stream) == EOF)
483 error.SetErrorToErrno();
489 if (!descriptor_guard)
490 error.SetErrorString(
"invalid file handle");
499 int err = FlushFileBuffers((HANDLE)_get_osfhandle(
m_descriptor));
501 error.SetErrorToGenericError();
503 if (llvm::sys::RetryAfterSignal(-1, ::fsync,
m_descriptor) == -1)
504 error.SetErrorToErrno();
507 error.SetErrorString(
"invalid file handle");
512#if defined(__APPLE__)
514#define MAX_READ_SIZE INT_MAX
515#define MAX_WRITE_SIZE INT_MAX
521#if defined(MAX_READ_SIZE)
522 if (num_bytes > MAX_READ_SIZE) {
523 uint8_t *p = (uint8_t *)buf;
524 size_t bytes_left = num_bytes;
528 while (bytes_left > 0) {
529 size_t curr_num_bytes;
530 if (bytes_left > MAX_READ_SIZE)
531 curr_num_bytes = MAX_READ_SIZE;
533 curr_num_bytes = bytes_left;
535 error =
Read(p + num_bytes, curr_num_bytes);
538 num_bytes += curr_num_bytes;
539 if (bytes_left < curr_num_bytes)
542 bytes_left -= curr_num_bytes;
551 ssize_t bytes_read = -1;
554 llvm::sys::RetryAfterSignal(-1, ::read,
m_descriptor, buf, num_bytes);
555 if (bytes_read == -1) {
556 error.SetErrorToErrno();
559 num_bytes = bytes_read;
564 bytes_read = ::fread(buf, 1, num_bytes,
m_stream);
566 if (bytes_read == 0) {
568 error.SetErrorString(
"feof");
570 error.SetErrorString(
"ferror");
573 num_bytes = bytes_read;
578 error.SetErrorString(
"invalid file handle");
585#if defined(MAX_WRITE_SIZE)
586 if (num_bytes > MAX_WRITE_SIZE) {
587 const uint8_t *p = (
const uint8_t *)buf;
588 size_t bytes_left = num_bytes;
592 while (bytes_left > 0) {
593 size_t curr_num_bytes;
594 if (bytes_left > MAX_WRITE_SIZE)
595 curr_num_bytes = MAX_WRITE_SIZE;
597 curr_num_bytes = bytes_left;
602 num_bytes += curr_num_bytes;
603 if (bytes_left < curr_num_bytes)
606 bytes_left -= curr_num_bytes;
615 ssize_t bytes_written = -1;
618 llvm::sys::RetryAfterSignal(-1, ::write,
m_descriptor, buf, num_bytes);
619 if (bytes_written == -1) {
620 error.SetErrorToErrno();
623 num_bytes = bytes_written;
628 bytes_written = ::fwrite(buf, 1, num_bytes,
m_stream);
630 if (bytes_written == 0) {
632 error.SetErrorString(
"feof");
634 error.SetErrorString(
"ferror");
637 num_bytes = bytes_written;
642 error.SetErrorString(
"invalid file handle");
649#if defined(MAX_READ_SIZE)
650 if (num_bytes > MAX_READ_SIZE) {
651 uint8_t *p = (uint8_t *)buf;
652 size_t bytes_left = num_bytes;
656 while (bytes_left > 0) {
657 size_t curr_num_bytes;
658 if (bytes_left > MAX_READ_SIZE)
659 curr_num_bytes = MAX_READ_SIZE;
661 curr_num_bytes = bytes_left;
663 error =
Read(p + num_bytes, curr_num_bytes, offset);
666 num_bytes += curr_num_bytes;
667 if (bytes_left < curr_num_bytes)
670 bytes_left -= curr_num_bytes;
683 llvm::sys::RetryAfterSignal(-1, ::pread, fd, buf, num_bytes, offset);
684 if (bytes_read < 0) {
686 error.SetErrorToErrno();
688 offset += bytes_read;
689 num_bytes = bytes_read;
693 error.SetErrorString(
"invalid file handle");
709#if defined(MAX_WRITE_SIZE)
710 if (num_bytes > MAX_WRITE_SIZE) {
711 const uint8_t *p = (
const uint8_t *)buf;
712 size_t bytes_left = num_bytes;
716 while (bytes_left > 0) {
717 size_t curr_num_bytes;
718 if (bytes_left > MAX_WRITE_SIZE)
719 curr_num_bytes = MAX_WRITE_SIZE;
721 curr_num_bytes = bytes_left;
723 error =
Write(p + num_bytes, curr_num_bytes, offset);
726 num_bytes += curr_num_bytes;
727 if (bytes_left < curr_num_bytes)
730 bytes_left -= curr_num_bytes;
742 ssize_t bytes_written =
743 llvm::sys::RetryAfterSignal(-1, ::pwrite,
m_descriptor, buf, num_bytes, offset);
744 if (bytes_written < 0) {
746 error.SetErrorToErrno();
748 offset += bytes_written;
749 num_bytes = bytes_written;
765 error.SetErrorString(
"invalid file handle");
772 return ::vfprintf(
m_stream, format, args);
800 mode |= O_CREAT | O_EXCL;
807llvm::Expected<SerialPort::Options>
810 for (llvm::StringRef x : llvm::split(urlqs,
'&')) {
811 if (x.consume_front(
"baud=")) {
812 unsigned int baud_rate;
813 if (!llvm::to_integer(x, baud_rate, 10))
814 return llvm::createStringError(llvm::inconvertibleErrorCode(),
815 "Invalid baud rate: %s",
817 serial_options.
BaudRate = baud_rate;
818 }
else if (x.consume_front(
"parity=")) {
820 llvm::StringSwitch<std::optional<Terminal::Parity>>(x)
826 .Default(std::nullopt);
827 if (!serial_options.
Parity)
828 return llvm::createStringError(
829 llvm::inconvertibleErrorCode(),
830 "Invalid parity (must be no, even, odd, mark or space): %s",
832 }
else if (x.consume_front(
"parity-check=")) {
834 llvm::StringSwitch<std::optional<Terminal::ParityCheck>>(x)
841 .Default(std::nullopt);
843 return llvm::createStringError(
844 llvm::inconvertibleErrorCode(),
845 "Invalid parity-check (must be no, replace, ignore or mark): %s",
847 }
else if (x.consume_front(
"stop-bits=")) {
848 unsigned int stop_bits;
849 if (!llvm::to_integer(x, stop_bits, 10) ||
850 (stop_bits != 1 && stop_bits != 2))
851 return llvm::createStringError(
852 llvm::inconvertibleErrorCode(),
853 "Invalid stop bit number (must be 1 or 2): %s", x.str().c_str());
854 serial_options.
StopBits = stop_bits;
856 return llvm::createStringError(llvm::inconvertibleErrorCode(),
857 "Unknown parameter: %s", x.str().c_str());
859 return serial_options;
862llvm::Expected<std::unique_ptr<SerialPort>>
864 bool transfer_ownership) {
865 std::unique_ptr<SerialPort> out{
866 new SerialPort(fd, options, serial_options, transfer_ownership)};
868 if (!out->GetIsInteractive())
869 return llvm::createStringError(llvm::inconvertibleErrorCode(),
870 "the specified file is not a teletype");
873 if (llvm::Error
error = term.SetRaw())
874 return std::move(
error);
876 if (llvm::Error
error = term.SetBaudRate(*serial_options.
BaudRate))
877 return std::move(
error);
879 if (serial_options.
Parity) {
880 if (llvm::Error
error = term.SetParity(*serial_options.
Parity))
881 return std::move(
error);
885 return std::move(
error);
888 if (llvm::Error
error = term.SetStopBits(*serial_options.
StopBits))
889 return std::move(
error);
892 return std::move(out);
897 bool transfer_ownership)
898 :
NativeFile(fd, options, transfer_ownership), m_state(fd) {}
static llvm::raw_ostream & error(Stream &strm)
void SetFile(llvm::StringRef path, Style style)
Change the file specified with a new path.
void Clear()
Clears the object state.
virtual llvm::Expected< OpenOptions > GetOptions() const
Return the OpenOptions for this file.
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
WaitableHandle GetWaitableHandle() override
Get a handle that can be used for OS polling interfaces, such as WaitForMultipleObjects,...
bool GetIsRealTerminal()
Return true if this file from a real terminal.
virtual FILE * GetStream()
Get the underlying libc stream for this file, or NULL.
Status Read(void *buf, size_t &num_bytes) override
Read bytes from a file from the current file position into buf.
virtual off_t SeekFromStart(off_t offset, Status *error_ptr=nullptr)
Seek to an offset relative to the beginning of the file.
static int kInvalidDescriptor
static FILE * kInvalidStream
virtual Status GetFileSpec(FileSpec &file_spec) const
Get the file specification for this file, if possible.
LazyBool m_is_real_terminal
virtual off_t SeekFromCurrent(off_t offset, Status *error_ptr=nullptr)
Seek to an offset relative to the current file position.
LazyBool m_is_interactive
static bool DescriptorIsValid(int descriptor)
static mode_t ConvertOpenOptionsForPOSIXOpen(OpenOptions open_options)
virtual int GetDescriptor() const
Get underlying OS file descriptor for this file, or kInvalidDescriptor.
static llvm::Expected< const char * > GetStreamOpenModeFromOptions(OpenOptions options)
bool GetIsTerminalWithColors()
Return true if this file is a terminal which supports colors.
Status Close() override
Flush any buffers and release any resources owned by the file.
Status Write(const void *buf, size_t &num_bytes) override
Write bytes from buf to a file at the current file position.
@ eOpenOptionCanCreateNewOnly
uint32_t GetPermissions(Status &error) const
Get the permissions for a this file.
bool IsValid() const override
IsValid.
virtual Status Flush()
Flush the current stream.
static llvm::Expected< OpenOptions > GetOptionsFromMode(llvm::StringRef mode)
size_t virtual size_t PrintfVarArg(const char *format, va_list args)
Output printf formatted output to the stream.
virtual Status Sync()
Sync to disk.
LazyBool m_supports_colors
bool GetIsInteractive()
Return true if this file is interactive.
void CalculateInteractiveAndTerminal()
virtual off_t SeekFromEnd(off_t offset, Status *error_ptr=nullptr)
Seek to an offset relative to the end of the file.
static const WaitableHandle kInvalidHandleValue
bool DescriptorIsValidUnlocked() const
off_t SeekFromStart(off_t offset, Status *error_ptr=nullptr) override
Seek to an offset relative to the beginning of the file.
Status GetFileSpec(FileSpec &file_spec) const override
Get the file specification for this file, if possible.
FILE * GetStream() override
Get the underlying libc stream for this file, or NULL.
Status Sync() override
Sync to disk.
std::mutex offset_access_mutex
Status Close() override
Flush any buffers and release any resources owned by the file.
WaitableHandle GetWaitableHandle() override
Get a handle that can be used for OS polling interfaces, such as WaitForMultipleObjects,...
Status Flush() override
Flush the current stream.
bool StreamIsValidUnlocked() const
ValueGuard DescriptorIsValid() const
llvm::Expected< OpenOptions > GetOptions() const override
Return the OpenOptions for this file.
off_t SeekFromCurrent(off_t offset, Status *error_ptr=nullptr) override
Seek to an offset relative to the current file position.
size_t PrintfVarArg(const char *format, va_list args) override
Output printf formatted output to the stream.
Status Write(const void *buf, size_t &num_bytes) override
Write bytes from buf to a file at the current file position.
int GetDescriptor() const override
Get underlying OS file descriptor for this file, or kInvalidDescriptor.
Status Read(void *buf, size_t &num_bytes) override
Read bytes from a file from the current file position into buf.
bool IsValid() const override
IsValid.
std::mutex m_descriptor_mutex
std::mutex m_stream_mutex
ValueGuard StreamIsValid() const
off_t SeekFromEnd(off_t offset, Status *error_ptr=nullptr) override
Seek to an offset relative to the end of the file.
static llvm::Expected< std::unique_ptr< SerialPort > > Create(int fd, OpenOptions options, Options serial_options, bool transfer_ownership)
SerialPort(int fd, OpenOptions options, Options serial_options, bool transfer_ownership)
Status Close() override
Flush any buffers and release any resources owned by the file.
static llvm::Expected< Options > OptionsFromURL(llvm::StringRef urlqs)
void Clear()
Clear the object state.
void SetErrorToErrno()
Set the current error to errno.
void SetErrorString(llvm::StringRef err_str)
Set the current error string to err_str.
bool Restore() const
Restore the TTY state to the cached state.
A class that represents a running process on the host machine.
bool VASprintf(llvm::SmallVectorImpl< char > &buf, const char *fmt, va_list args)
std::optional< Terminal::ParityCheck > ParityCheck
std::optional< unsigned int > StopBits
std::optional< Terminal::Parity > Parity
std::optional< unsigned int > BaudRate