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"
39#include "llvm/Support/raw_ostream.h"
76 return llvm::createStringError(
77 llvm::inconvertibleErrorCode(),
78 "invalid options, cannot convert to mode string");
83 llvm::StringSwitch<OpenOptions>(mode)
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) {
258 int fd = _fileno(fh);
260 ::GetFileType((HANDLE)::_get_osfhandle(fd)) == FILE_TYPE_CHAR;
266 int mode = fcntl(fd, F_GETFL);
273 (required_mode == O_RDWR && mode == O_RDWR) ||
274 (required_mode == O_RDONLY && (mode == O_RDWR || mode == O_RDONLY) ||
275 (required_mode == O_WRONLY &&
276 (mode == O_RDWR || mode == O_WRONLY))) &&
277 "invalid file access mode");
292 ::GetFileType((HANDLE)::_get_osfhandle(fd)) == FILE_TYPE_CHAR;
337 llvm::consumeError(mode.takeError());
411 file_spec.
SetFile(path, FileSpec::Style::native);
415#elif defined(__linux__)
418 if (::snprintf(proc,
sizeof(proc),
"/proc/self/fd/%d",
GetDescriptor()) < 0)
422 if ((len = ::readlink(proc, path,
sizeof(path) - 1)) == -1)
426 file_spec.
SetFile(path, FileSpec::Style::native);
431 "NativeFile::GetFileSpec is not supported on this platform");
454 result = ::fseek(
m_stream, offset, SEEK_SET);
485 result = ::fseek(
m_stream, offset, SEEK_CUR);
516 result = ::fseek(
m_stream, offset, SEEK_END);
534 if (llvm::sys::RetryAfterSignal(EOF, ::fflush,
m_stream) == EOF)
541 if (!descriptor_guard)
551 int err = FlushFileBuffers((HANDLE)_get_osfhandle(
m_descriptor));
555 if (llvm::sys::RetryAfterSignal(-1, ::fsync,
m_descriptor) == -1)
564#if defined(__APPLE__)
566#define MAX_READ_SIZE INT_MAX
567#define MAX_WRITE_SIZE INT_MAX
575 return Status(std::make_error_code(std::errc::bad_file_descriptor));
577#if defined(MAX_READ_SIZE)
578 if (num_bytes > MAX_READ_SIZE) {
579 uint8_t *p = (uint8_t *)buf;
580 size_t bytes_left = num_bytes;
584 while (bytes_left > 0) {
585 size_t curr_num_bytes;
586 if (bytes_left > MAX_READ_SIZE)
587 curr_num_bytes = MAX_READ_SIZE;
589 curr_num_bytes = bytes_left;
591 error =
Read(p + num_bytes, curr_num_bytes);
594 num_bytes += curr_num_bytes;
595 if (bytes_left < curr_num_bytes)
598 bytes_left -= curr_num_bytes;
607 ssize_t bytes_read = -1;
610 llvm::sys::RetryAfterSignal(-1, ::read,
m_descriptor, buf, num_bytes);
611 if (bytes_read == -1) {
615 num_bytes = bytes_read;
620 bytes_read = ::fread(buf, 1, num_bytes,
m_stream);
622 if (bytes_read == 0) {
629 num_bytes = bytes_read;
643 return Status(std::make_error_code(std::errc::bad_file_descriptor));
645#if defined(MAX_WRITE_SIZE)
646 if (num_bytes > MAX_WRITE_SIZE) {
647 const uint8_t *p = (
const uint8_t *)buf;
648 size_t bytes_left = num_bytes;
652 while (bytes_left > 0) {
653 size_t curr_num_bytes;
654 if (bytes_left > MAX_WRITE_SIZE)
655 curr_num_bytes = MAX_WRITE_SIZE;
657 curr_num_bytes = bytes_left;
662 num_bytes += curr_num_bytes;
663 if (bytes_left < curr_num_bytes)
666 bytes_left -= curr_num_bytes;
675 ssize_t bytes_written = -1;
678 llvm::sys::RetryAfterSignal(-1, ::write,
m_descriptor, buf, num_bytes);
679 if (bytes_written == -1) {
683 num_bytes = bytes_written;
690 llvm::raw_fd_ostream(_fileno(
m_stream),
false)
691 .write((
const char *)buf, num_bytes);
695 bytes_written = ::fwrite(buf, 1, num_bytes,
m_stream);
697 if (bytes_written == 0) {
704 num_bytes = bytes_written;
716#if defined(MAX_READ_SIZE)
717 if (num_bytes > MAX_READ_SIZE) {
718 uint8_t *p = (uint8_t *)buf;
719 size_t bytes_left = num_bytes;
723 while (bytes_left > 0) {
724 size_t curr_num_bytes;
725 if (bytes_left > MAX_READ_SIZE)
726 curr_num_bytes = MAX_READ_SIZE;
728 curr_num_bytes = bytes_left;
730 error =
Read(p + num_bytes, curr_num_bytes, offset);
733 num_bytes += curr_num_bytes;
734 if (bytes_left < curr_num_bytes)
737 bytes_left -= curr_num_bytes;
750 llvm::sys::RetryAfterSignal(-1, ::pread, fd, buf, num_bytes, offset);
751 if (bytes_read < 0) {
755 offset += bytes_read;
756 num_bytes = bytes_read;
776#if defined(MAX_WRITE_SIZE)
777 if (num_bytes > MAX_WRITE_SIZE) {
778 const uint8_t *p = (
const uint8_t *)buf;
779 size_t bytes_left = num_bytes;
783 while (bytes_left > 0) {
784 size_t curr_num_bytes;
785 if (bytes_left > MAX_WRITE_SIZE)
786 curr_num_bytes = MAX_WRITE_SIZE;
788 curr_num_bytes = bytes_left;
790 error =
Write(p + num_bytes, curr_num_bytes, offset);
793 num_bytes += curr_num_bytes;
794 if (bytes_left < curr_num_bytes)
797 bytes_left -= curr_num_bytes;
809 ssize_t bytes_written = llvm::sys::RetryAfterSignal(
811 if (bytes_written < 0) {
815 offset += bytes_written;
816 num_bytes = bytes_written;
839 return ::vfprintf(
m_stream, format, args);
867 mode |= O_CREAT | O_EXCL;
874llvm::Expected<SerialPort::Options>
877 for (llvm::StringRef x : llvm::split(urlqs,
'&')) {
878 if (x.consume_front(
"baud=")) {
879 unsigned int baud_rate;
880 if (!llvm::to_integer(x, baud_rate, 10))
881 return llvm::createStringError(llvm::inconvertibleErrorCode(),
882 "Invalid baud rate: %s",
884 serial_options.
BaudRate = baud_rate;
885 }
else if (x.consume_front(
"parity=")) {
887 llvm::StringSwitch<std::optional<Terminal::Parity>>(x)
893 .Default(std::nullopt);
894 if (!serial_options.
Parity)
895 return llvm::createStringError(
896 llvm::inconvertibleErrorCode(),
897 "Invalid parity (must be no, even, odd, mark or space): %s",
899 }
else if (x.consume_front(
"parity-check=")) {
901 llvm::StringSwitch<std::optional<Terminal::ParityCheck>>(x)
908 .Default(std::nullopt);
910 return llvm::createStringError(
911 llvm::inconvertibleErrorCode(),
912 "Invalid parity-check (must be no, replace, ignore or mark): %s",
914 }
else if (x.consume_front(
"stop-bits=")) {
915 unsigned int stop_bits;
916 if (!llvm::to_integer(x, stop_bits, 10) ||
917 (stop_bits != 1 && stop_bits != 2))
918 return llvm::createStringError(
919 llvm::inconvertibleErrorCode(),
920 "Invalid stop bit number (must be 1 or 2): %s", x.str().c_str());
921 serial_options.
StopBits = stop_bits;
923 return llvm::createStringError(llvm::inconvertibleErrorCode(),
924 "Unknown parameter: %s", x.str().c_str());
926 return serial_options;
929llvm::Expected<std::unique_ptr<SerialPort>>
931 bool transfer_ownership) {
932 std::unique_ptr<SerialPort> out{
933 new SerialPort(fd, options, serial_options, transfer_ownership)};
935 if (!out->GetIsInteractive())
936 return llvm::createStringError(llvm::inconvertibleErrorCode(),
937 "the specified file is not a teletype");
941 return std::move(
error);
944 return std::move(
error);
946 if (serial_options.
Parity) {
948 return std::move(
error);
952 return std::move(
error);
956 return std::move(
error);
959 return std::move(out);
964 bool transfer_ownership)
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.
static constexpr OpenOptions OpenOptionsModeMask
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
lldb::file_t WaitableHandle
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.
static Status FromErrno()
Set the current error to errno.
static Status FromErrorString(const char *str)
llvm::Error SetParityCheck(ParityCheck parity_check)
llvm::Error SetBaudRate(unsigned int baud_rate)
llvm::Error SetParity(Parity parity)
llvm::Error SetStopBits(unsigned int stop_bits)
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