diff options
Diffstat (limited to 'source/Host/posix')
-rw-r--r-- | source/Host/posix/ConnectionFileDescriptorPosix.cpp | 797 | ||||
-rw-r--r-- | source/Host/posix/HostInfoPosix.cpp | 14 | ||||
-rw-r--r-- | source/Host/posix/HostProcessPosix.cpp | 47 | ||||
-rw-r--r-- | source/Host/posix/HostThreadPosix.cpp | 74 | ||||
-rw-r--r-- | source/Host/posix/PipePosix.cpp | 378 | ||||
-rw-r--r-- | source/Host/posix/ProcessLauncherPosix.cpp | 33 |
6 files changed, 1326 insertions, 17 deletions
diff --git a/source/Host/posix/ConnectionFileDescriptorPosix.cpp b/source/Host/posix/ConnectionFileDescriptorPosix.cpp new file mode 100644 index 000000000000..38ddc0a49220 --- /dev/null +++ b/source/Host/posix/ConnectionFileDescriptorPosix.cpp @@ -0,0 +1,797 @@ +//===-- ConnectionFileDescriptorPosix.cpp -----------------------*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#if defined(__APPLE__) +// Enable this special support for Apple builds where we can have unlimited +// select bounds. We tried switching to poll() and kqueue and we were panicing +// the kernel, so we have to stick with select for now. +#define _DARWIN_UNLIMITED_SELECT +#endif + +#include "lldb/Host/posix/ConnectionFileDescriptorPosix.h" +#include "lldb/Host/Config.h" +#include "lldb/Host/IOObject.h" +#include "lldb/Host/SocketAddress.h" +#include "lldb/Host/Socket.h" + +// C Includes +#include <errno.h> +#include <fcntl.h> +#include <string.h> +#include <stdlib.h> +#include <sys/types.h> + +#ifndef LLDB_DISABLE_POSIX +#include <termios.h> +#endif + +// C++ Includes +// Other libraries and framework includes +#include "llvm/Support/ErrorHandling.h" +#if defined(__APPLE__) +#include "llvm/ADT/SmallVector.h" +#endif +// Project includes +#include "lldb/lldb-private-log.h" +#include "lldb/Core/Communication.h" +#include "lldb/Core/Log.h" +#include "lldb/Core/Timer.h" +#include "lldb/Host/Host.h" +#include "lldb/Host/Socket.h" +#include "lldb/Interpreter/Args.h" + +using namespace lldb; +using namespace lldb_private; + +ConnectionFileDescriptor::ConnectionFileDescriptor(bool child_processes_inherit) + : Connection() + , m_pipe() + , m_mutex(Mutex::eMutexTypeRecursive) + , m_shutting_down(false) + , m_waiting_for_accept(false) + , m_child_processes_inherit(child_processes_inherit) +{ + Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION | LIBLLDB_LOG_OBJECT)); + if (log) + log->Printf("%p ConnectionFileDescriptor::ConnectionFileDescriptor ()", static_cast<void *>(this)); +} + +ConnectionFileDescriptor::ConnectionFileDescriptor(int fd, bool owns_fd) + : Connection() + , m_pipe() + , m_mutex(Mutex::eMutexTypeRecursive) + , m_shutting_down(false) + , m_waiting_for_accept(false) + , m_child_processes_inherit(false) +{ + m_write_sp.reset(new File(fd, owns_fd)); + m_read_sp.reset(new File(fd, false)); + + Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION | LIBLLDB_LOG_OBJECT)); + if (log) + log->Printf("%p ConnectionFileDescriptor::ConnectionFileDescriptor (fd = %i, owns_fd = %i)", static_cast<void *>(this), fd, + owns_fd); + OpenCommandPipe(); +} + +ConnectionFileDescriptor::~ConnectionFileDescriptor() +{ + Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION | LIBLLDB_LOG_OBJECT)); + if (log) + log->Printf("%p ConnectionFileDescriptor::~ConnectionFileDescriptor ()", static_cast<void *>(this)); + Disconnect(NULL); + CloseCommandPipe(); +} + +void +ConnectionFileDescriptor::OpenCommandPipe() +{ + CloseCommandPipe(); + + Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION)); + // Make the command file descriptor here: + Error result = m_pipe.CreateNew(m_child_processes_inherit); + if (!result.Success()) + { + if (log) + log->Printf("%p ConnectionFileDescriptor::OpenCommandPipe () - could not make pipe: %s", static_cast<void *>(this), + result.AsCString()); + } + else + { + if (log) + log->Printf("%p ConnectionFileDescriptor::OpenCommandPipe() - success readfd=%d writefd=%d", static_cast<void *>(this), + m_pipe.GetReadFileDescriptor(), m_pipe.GetWriteFileDescriptor()); + } +} + +void +ConnectionFileDescriptor::CloseCommandPipe() +{ + Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION)); + if (log) + log->Printf("%p ConnectionFileDescriptor::CloseCommandPipe()", static_cast<void *>(this)); + + m_pipe.Close(); +} + +bool +ConnectionFileDescriptor::IsConnected() const +{ + return (m_read_sp && m_read_sp->IsValid()) || (m_write_sp && m_write_sp->IsValid()); +} + +ConnectionStatus +ConnectionFileDescriptor::Connect(const char *s, Error *error_ptr) +{ + Mutex::Locker locker(m_mutex); + Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION)); + if (log) + log->Printf("%p ConnectionFileDescriptor::Connect (url = '%s')", static_cast<void *>(this), s); + + OpenCommandPipe(); + + if (s && s[0]) + { + if (strstr(s, "listen://") == s) + { + // listen://HOST:PORT + return SocketListen(s + strlen("listen://"), error_ptr); + } + else if (strstr(s, "accept://") == s) + { + // unix://SOCKNAME + return NamedSocketAccept(s + strlen("accept://"), error_ptr); + } + else if (strstr(s, "unix-accept://") == s) + { + // unix://SOCKNAME + return NamedSocketAccept(s + strlen("unix-accept://"), error_ptr); + } + else if (strstr(s, "connect://") == s) + { + return ConnectTCP(s + strlen("connect://"), error_ptr); + } + else if (strstr(s, "tcp-connect://") == s) + { + return ConnectTCP(s + strlen("tcp-connect://"), error_ptr); + } + else if (strstr(s, "udp://") == s) + { + return ConnectUDP(s + strlen("udp://"), error_ptr); + } +#ifndef LLDB_DISABLE_POSIX + else if (strstr(s, "fd://") == s) + { + // Just passing a native file descriptor within this current process + // that is already opened (possibly from a service or other source). + s += strlen("fd://"); + bool success = false; + int fd = Args::StringToSInt32(s, -1, 0, &success); + + if (success) + { + // We have what looks to be a valid file descriptor, but we + // should make sure it is. We currently are doing this by trying to + // get the flags from the file descriptor and making sure it + // isn't a bad fd. + errno = 0; + int flags = ::fcntl(fd, F_GETFL, 0); + if (flags == -1 || errno == EBADF) + { + if (error_ptr) + error_ptr->SetErrorStringWithFormat("stale file descriptor: %s", s); + m_read_sp.reset(); + m_write_sp.reset(); + return eConnectionStatusError; + } + else + { + // Don't take ownership of a file descriptor that gets passed + // to us since someone else opened the file descriptor and + // handed it to us. + // TODO: Since are using a URL to open connection we should + // eventually parse options using the web standard where we + // have "fd://123?opt1=value;opt2=value" and we can have an + // option be "owns=1" or "owns=0" or something like this to + // allow us to specify this. For now, we assume we must + // assume we don't own it. + + std::unique_ptr<Socket> tcp_socket; + tcp_socket.reset(new Socket(fd, Socket::ProtocolTcp, false)); + // Try and get a socket option from this file descriptor to + // see if this is a socket and set m_is_socket accordingly. + int resuse; + bool is_socket = !!tcp_socket->GetOption(SOL_SOCKET, SO_REUSEADDR, resuse); + if (is_socket) + { + m_read_sp = std::move(tcp_socket); + m_write_sp = m_read_sp; + } + else + { + m_read_sp.reset(new File(fd, false)); + m_write_sp.reset(new File(fd, false)); + } + return eConnectionStatusSuccess; + } + } + + if (error_ptr) + error_ptr->SetErrorStringWithFormat("invalid file descriptor: \"fd://%s\"", s); + m_read_sp.reset(); + m_write_sp.reset(); + return eConnectionStatusError; + } + else if (strstr(s, "file://") == s) + { + // file:///PATH + const char *path = s + strlen("file://"); + int fd = -1; + do + { + fd = ::open(path, O_RDWR); + } while (fd == -1 && errno == EINTR); + + if (fd == -1) + { + if (error_ptr) + error_ptr->SetErrorToErrno(); + return eConnectionStatusError; + } + + if (::isatty(fd)) + { + // Set up serial terminal emulation + struct termios options; + ::tcgetattr(fd, &options); + + // Set port speed to maximum + ::cfsetospeed(&options, B115200); + ::cfsetispeed(&options, B115200); + + // Raw input, disable echo and signals + options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); + + // Make sure only one character is needed to return from a read + options.c_cc[VMIN] = 1; + options.c_cc[VTIME] = 0; + + ::tcsetattr(fd, TCSANOW, &options); + } + + int flags = ::fcntl(fd, F_GETFL, 0); + if (flags >= 0) + { + if ((flags & O_NONBLOCK) == 0) + { + flags |= O_NONBLOCK; + ::fcntl(fd, F_SETFL, flags); + } + } + m_read_sp.reset(new File(fd, true)); + m_write_sp.reset(new File(fd, false)); + return eConnectionStatusSuccess; + } +#endif + if (error_ptr) + error_ptr->SetErrorStringWithFormat("unsupported connection URL: '%s'", s); + return eConnectionStatusError; + } + if (error_ptr) + error_ptr->SetErrorString("invalid connect arguments"); + return eConnectionStatusError; +} + +bool +ConnectionFileDescriptor::InterruptRead() +{ + size_t bytes_written = 0; + Error result = m_pipe.Write("i", 1, bytes_written); + return result.Success(); +} + +ConnectionStatus +ConnectionFileDescriptor::Disconnect(Error *error_ptr) +{ + Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION)); + if (log) + log->Printf("%p ConnectionFileDescriptor::Disconnect ()", static_cast<void *>(this)); + + ConnectionStatus status = eConnectionStatusSuccess; + + if (!IsConnected()) + { + if (log) + log->Printf("%p ConnectionFileDescriptor::Disconnect(): Nothing to disconnect", static_cast<void *>(this)); + return eConnectionStatusSuccess; + } + + if (m_read_sp && m_read_sp->IsValid() && m_read_sp->GetFdType() == IOObject::eFDTypeSocket) + static_cast<Socket &>(*m_read_sp).PreDisconnect(); + + // Try to get the ConnectionFileDescriptor's mutex. If we fail, that is quite likely + // because somebody is doing a blocking read on our file descriptor. If that's the case, + // then send the "q" char to the command file channel so the read will wake up and the connection + // will then know to shut down. + + m_shutting_down = true; + + Mutex::Locker locker; + bool got_lock = locker.TryLock(m_mutex); + + if (!got_lock) + { + if (m_pipe.CanWrite()) + { + size_t bytes_written = 0; + Error result = m_pipe.Write("q", 1, bytes_written); + if (log) + log->Printf("%p ConnectionFileDescriptor::Disconnect(): Couldn't get the lock, sent 'q' to %d, error = '%s'.", + static_cast<void *>(this), m_pipe.GetWriteFileDescriptor(), result.AsCString()); + } + else if (log) + { + log->Printf("%p ConnectionFileDescriptor::Disconnect(): Couldn't get the lock, but no command pipe is available.", + static_cast<void *>(this)); + } + locker.Lock(m_mutex); + } + + Error error = m_read_sp->Close(); + Error error2 = m_write_sp->Close(); + if (error.Fail() || error2.Fail()) + status = eConnectionStatusError; + if (error_ptr) + *error_ptr = error.Fail() ? error : error2; + + m_shutting_down = false; + return status; +} + +size_t +ConnectionFileDescriptor::Read(void *dst, size_t dst_len, uint32_t timeout_usec, ConnectionStatus &status, Error *error_ptr) +{ + Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION)); + + Mutex::Locker locker; + bool got_lock = locker.TryLock(m_mutex); + if (!got_lock) + { + if (log) + log->Printf("%p ConnectionFileDescriptor::Read () failed to get the connection lock.", static_cast<void *>(this)); + if (error_ptr) + error_ptr->SetErrorString("failed to get the connection lock for read."); + + status = eConnectionStatusTimedOut; + return 0; + } + else if (m_shutting_down) + return eConnectionStatusError; + + status = BytesAvailable(timeout_usec, error_ptr); + if (status != eConnectionStatusSuccess) + return 0; + + Error error; + size_t bytes_read = dst_len; + error = m_read_sp->Read(dst, bytes_read); + + if (log) + { + log->Printf("%p ConnectionFileDescriptor::Read() fd = %" PRIu64 ", dst = %p, dst_len = %" PRIu64 ") => %" PRIu64 ", error = %s", + static_cast<void *>(this), static_cast<uint64_t>(m_read_sp->GetWaitableHandle()), static_cast<void *>(dst), + static_cast<uint64_t>(dst_len), static_cast<uint64_t>(bytes_read), error.AsCString()); + } + + if (bytes_read == 0) + { + error.Clear(); // End-of-file. Do not automatically close; pass along for the end-of-file handlers. + status = eConnectionStatusEndOfFile; + } + + if (error_ptr) + *error_ptr = error; + + if (error.Fail()) + { + uint32_t error_value = error.GetError(); + switch (error_value) + { + case EAGAIN: // The file was marked for non-blocking I/O, and no data were ready to be read. + if (m_read_sp->GetFdType() == IOObject::eFDTypeSocket) + status = eConnectionStatusTimedOut; + else + status = eConnectionStatusSuccess; + return 0; + + case EFAULT: // Buf points outside the allocated address space. + case EINTR: // A read from a slow device was interrupted before any data arrived by the delivery of a signal. + case EINVAL: // The pointer associated with fildes was negative. + case EIO: // An I/O error occurred while reading from the file system. + // The process group is orphaned. + // The file is a regular file, nbyte is greater than 0, + // the starting position is before the end-of-file, and + // the starting position is greater than or equal to the + // offset maximum established for the open file + // descriptor associated with fildes. + case EISDIR: // An attempt is made to read a directory. + case ENOBUFS: // An attempt to allocate a memory buffer fails. + case ENOMEM: // Insufficient memory is available. + status = eConnectionStatusError; + break; // Break to close.... + + case ENOENT: // no such file or directory + case EBADF: // fildes is not a valid file or socket descriptor open for reading. + case ENXIO: // An action is requested of a device that does not exist.. + // A requested action cannot be performed by the device. + case ECONNRESET: // The connection is closed by the peer during a read attempt on a socket. + case ENOTCONN: // A read is attempted on an unconnected socket. + status = eConnectionStatusLostConnection; + break; // Break to close.... + + case ETIMEDOUT: // A transmission timeout occurs during a read attempt on a socket. + status = eConnectionStatusTimedOut; + return 0; + + default: + if (log) + log->Printf("%p ConnectionFileDescriptor::Read (), unexpected error: %s", static_cast<void *>(this), + strerror(error_value)); + status = eConnectionStatusError; + break; // Break to close.... + } + + return 0; + } + return bytes_read; +} + +size_t +ConnectionFileDescriptor::Write(const void *src, size_t src_len, ConnectionStatus &status, Error *error_ptr) +{ + Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION)); + if (log) + log->Printf("%p ConnectionFileDescriptor::Write (src = %p, src_len = %" PRIu64 ")", static_cast<void *>(this), + static_cast<const void *>(src), static_cast<uint64_t>(src_len)); + + if (!IsConnected()) + { + if (error_ptr) + error_ptr->SetErrorString("not connected"); + status = eConnectionStatusNoConnection; + return 0; + } + + Error error; + + size_t bytes_sent = src_len; + error = m_write_sp->Write(src, bytes_sent); + + if (log) + { + log->Printf("%p ConnectionFileDescriptor::Write(fd = %" PRIu64 ", src = %p, src_len = %" PRIu64 ") => %" PRIu64 " (error = %s)", + static_cast<void *>(this), static_cast<uint64_t>(m_write_sp->GetWaitableHandle()), static_cast<const void *>(src), + static_cast<uint64_t>(src_len), static_cast<uint64_t>(bytes_sent), error.AsCString()); + } + + if (error_ptr) + *error_ptr = error; + + if (error.Fail()) + { + switch (error.GetError()) + { + case EAGAIN: + case EINTR: + status = eConnectionStatusSuccess; + return 0; + + case ECONNRESET: // The connection is closed by the peer during a read attempt on a socket. + case ENOTCONN: // A read is attempted on an unconnected socket. + status = eConnectionStatusLostConnection; + break; // Break to close.... + + default: + status = eConnectionStatusError; + break; // Break to close.... + } + + return 0; + } + + status = eConnectionStatusSuccess; + return bytes_sent; +} + +// This ConnectionFileDescriptor::BytesAvailable() uses select(). +// +// PROS: +// - select is consistent across most unix platforms +// - The Apple specific version allows for unlimited fds in the fd_sets by +// setting the _DARWIN_UNLIMITED_SELECT define prior to including the +// required header files. +// CONS: +// - on non-Apple platforms, only supports file descriptors up to FD_SETSIZE. +// This implementation will assert if it runs into that hard limit to let +// users know that another ConnectionFileDescriptor::BytesAvailable() should +// be used or a new version of ConnectionFileDescriptor::BytesAvailable() +// should be written for the system that is running into the limitations. + +#if defined(__APPLE__) +#define FD_SET_DATA(fds) fds.data() +#else +#define FD_SET_DATA(fds) &fds +#endif + +ConnectionStatus +ConnectionFileDescriptor::BytesAvailable(uint32_t timeout_usec, Error *error_ptr) +{ + // Don't need to take the mutex here separately since we are only called from Read. If we + // ever get used more generally we will need to lock here as well. + + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_CONNECTION)); + if (log) + log->Printf("%p ConnectionFileDescriptor::BytesAvailable (timeout_usec = %u)", static_cast<void *>(this), timeout_usec); + + struct timeval *tv_ptr; + struct timeval tv; + if (timeout_usec == UINT32_MAX) + { + // Inifinite wait... + tv_ptr = nullptr; + } + else + { + TimeValue time_value; + time_value.OffsetWithMicroSeconds(timeout_usec); + tv.tv_sec = time_value.seconds(); + tv.tv_usec = time_value.microseconds(); + tv_ptr = &tv; + } + + // Make a copy of the file descriptors to make sure we don't + // have another thread change these values out from under us + // and cause problems in the loop below where like in FS_SET() + const IOObject::WaitableHandle handle = m_read_sp->GetWaitableHandle(); + const int pipe_fd = m_pipe.GetReadFileDescriptor(); + + if (handle != IOObject::kInvalidHandleValue) + { +#if defined(_MSC_VER) + // select() won't accept pipes on Windows. The entire Windows codepath needs to be + // converted over to using WaitForMultipleObjects and event HANDLEs, but for now at least + // this will allow ::select() to not return an error. + const bool have_pipe_fd = false; +#else + const bool have_pipe_fd = pipe_fd >= 0; +#if !defined(__APPLE__) + assert(handle < FD_SETSIZE); + if (have_pipe_fd) + assert(pipe_fd < FD_SETSIZE); +#endif +#endif + while (handle == m_read_sp->GetWaitableHandle()) + { + const int nfds = std::max<int>(handle, pipe_fd) + 1; +#if defined(__APPLE__) + llvm::SmallVector<fd_set, 1> read_fds; + read_fds.resize((nfds / FD_SETSIZE) + 1); + for (size_t i = 0; i < read_fds.size(); ++i) + FD_ZERO(&read_fds[i]); +// FD_SET doesn't bounds check, it just happily walks off the end +// but we have taken care of making the extra storage with our +// SmallVector of fd_set objects +#else + fd_set read_fds; + FD_ZERO(&read_fds); +#endif + FD_SET(handle, FD_SET_DATA(read_fds)); + if (have_pipe_fd) + FD_SET(pipe_fd, FD_SET_DATA(read_fds)); + + Error error; + + if (log) + { + if (have_pipe_fd) + log->Printf( + "%p ConnectionFileDescriptor::BytesAvailable() ::select (nfds=%i, fds={%i, %i}, NULL, NULL, timeout=%p)...", + static_cast<void *>(this), nfds, handle, pipe_fd, static_cast<void *>(tv_ptr)); + else + log->Printf("%p ConnectionFileDescriptor::BytesAvailable() ::select (nfds=%i, fds={%i}, NULL, NULL, timeout=%p)...", + static_cast<void *>(this), nfds, handle, static_cast<void *>(tv_ptr)); + } + + const int num_set_fds = ::select(nfds, FD_SET_DATA(read_fds), NULL, NULL, tv_ptr); + if (num_set_fds < 0) + error.SetErrorToErrno(); + else + error.Clear(); + + if (log) + { + if (have_pipe_fd) + log->Printf("%p ConnectionFileDescriptor::BytesAvailable() ::select (nfds=%i, fds={%i, %i}, NULL, NULL, timeout=%p) " + "=> %d, error = %s", + static_cast<void *>(this), nfds, handle, pipe_fd, static_cast<void *>(tv_ptr), num_set_fds, + error.AsCString()); + else + log->Printf("%p ConnectionFileDescriptor::BytesAvailable() ::select (nfds=%i, fds={%i}, NULL, NULL, timeout=%p) => " + "%d, error = %s", + static_cast<void *>(this), nfds, handle, static_cast<void *>(tv_ptr), num_set_fds, error.AsCString()); + } + + if (error_ptr) + *error_ptr = error; + + if (error.Fail()) + { + switch (error.GetError()) + { + case EBADF: // One of the descriptor sets specified an invalid descriptor. + return eConnectionStatusLostConnection; + + case EINVAL: // The specified time limit is invalid. One of its components is negative or too large. + default: // Other unknown error + return eConnectionStatusError; + + case EAGAIN: // The kernel was (perhaps temporarily) unable to + // allocate the requested number of file descriptors, + // or we have non-blocking IO + case EINTR: // A signal was delivered before the time limit + // expired and before any of the selected events + // occurred. + break; // Lets keep reading to until we timeout + } + } + else if (num_set_fds == 0) + { + return eConnectionStatusTimedOut; + } + else if (num_set_fds > 0) + { + if (FD_ISSET(handle, FD_SET_DATA(read_fds))) + return eConnectionStatusSuccess; + if (have_pipe_fd && FD_ISSET(pipe_fd, FD_SET_DATA(read_fds))) + { + // We got a command to exit. Read the data from that pipe: + char buffer[16]; + ssize_t bytes_read; + + do + { + bytes_read = ::read(pipe_fd, buffer, sizeof(buffer)); + } while (bytes_read < 0 && errno == EINTR); + + switch (buffer[0]) + { + case 'q': + if (log) + log->Printf("%p ConnectionFileDescriptor::BytesAvailable() got data: %*s from the command channel.", + static_cast<void *>(this), static_cast<int>(bytes_read), buffer); + return eConnectionStatusEndOfFile; + case 'i': + // Interrupt the current read + return eConnectionStatusInterrupted; + } + } + } + } + } + + if (error_ptr) + error_ptr->SetErrorString("not connected"); + return eConnectionStatusLostConnection; +} + +ConnectionStatus +ConnectionFileDescriptor::NamedSocketAccept(const char *socket_name, Error *error_ptr) +{ + Socket *socket = nullptr; + Error error = Socket::UnixDomainAccept(socket_name, m_child_processes_inherit, socket); + if (error_ptr) + *error_ptr = error; + m_write_sp.reset(socket); + m_read_sp = m_write_sp; + return (error.Success()) ? eConnectionStatusSuccess : eConnectionStatusError; +} + +ConnectionStatus +ConnectionFileDescriptor::NamedSocketConnect(const char *socket_name, Error *error_ptr) +{ + Socket *socket = nullptr; + Error error = Socket::UnixDomainConnect(socket_name, m_child_processes_inherit, socket); + if (error_ptr) + *error_ptr = error; + m_write_sp.reset(socket); + m_read_sp = m_write_sp; + return (error.Success()) ? eConnectionStatusSuccess : eConnectionStatusError; +} + +ConnectionStatus +ConnectionFileDescriptor::SocketListen(const char *s, Error *error_ptr) +{ + m_port_predicate.SetValue(0, eBroadcastNever); + + Socket *socket = nullptr; + m_waiting_for_accept = true; + Error error = Socket::TcpListen(s, m_child_processes_inherit, socket, &m_port_predicate); + if (error_ptr) + *error_ptr = error; + if (error.Fail()) + return eConnectionStatusError; + + std::unique_ptr<Socket> listening_socket_up; + + listening_socket_up.reset(socket); + socket = nullptr; + error = listening_socket_up->BlockingAccept(s, m_child_processes_inherit, socket); + listening_socket_up.reset(); + if (error_ptr) + *error_ptr = error; + if (error.Fail()) + return eConnectionStatusError; + + m_write_sp.reset(socket); + m_read_sp = m_write_sp; + return (error.Success()) ? eConnectionStatusSuccess : eConnectionStatusError; +} + +ConnectionStatus +ConnectionFileDescriptor::ConnectTCP(const char *s, Error *error_ptr) +{ + Socket *socket = nullptr; + Error error = Socket::TcpConnect(s, m_child_processes_inherit, socket); + if (error_ptr) + *error_ptr = error; + m_write_sp.reset(socket); + m_read_sp = m_write_sp; + return (error.Success()) ? eConnectionStatusSuccess : eConnectionStatusError; +} + +ConnectionStatus +ConnectionFileDescriptor::ConnectUDP(const char *s, Error *error_ptr) +{ + Socket *send_socket = nullptr; + Socket *recv_socket = nullptr; + Error error = Socket::UdpConnect(s, m_child_processes_inherit, send_socket, recv_socket); + if (error_ptr) + *error_ptr = error; + m_write_sp.reset(send_socket); + m_read_sp.reset(recv_socket); + return (error.Success()) ? eConnectionStatusSuccess : eConnectionStatusError; +} + +uint16_t +ConnectionFileDescriptor::GetListeningPort(uint32_t timeout_sec) +{ + uint16_t bound_port = 0; + if (timeout_sec == UINT32_MAX) + m_port_predicate.WaitForValueNotEqualTo(0, bound_port); + else + { + TimeValue timeout = TimeValue::Now(); + timeout.OffsetWithSeconds(timeout_sec); + m_port_predicate.WaitForValueNotEqualTo(0, bound_port, &timeout); + } + return bound_port; +} + +bool +ConnectionFileDescriptor::GetChildProcessesInherit() const +{ + return m_child_processes_inherit; +} + +void +ConnectionFileDescriptor::SetChildProcessesInherit(bool child_processes_inherit) +{ + m_child_processes_inherit = child_processes_inherit; +} diff --git a/source/Host/posix/HostInfoPosix.cpp b/source/Host/posix/HostInfoPosix.cpp index 77fdc2b61a31..018d423ee9d3 100644 --- a/source/Host/posix/HostInfoPosix.cpp +++ b/source/Host/posix/HostInfoPosix.cpp @@ -69,6 +69,7 @@ HostInfoPosix::LookupUserName(uint32_t uid, std::string &user_name) const char * HostInfoPosix::LookupGroupName(uint32_t gid, std::string &group_name) { +#ifndef __ANDROID__ char group_buffer[PATH_MAX]; size_t group_buffer_size = sizeof(group_buffer); struct group group_info; @@ -94,6 +95,9 @@ HostInfoPosix::LookupGroupName(uint32_t gid, std::string &group_name) } } group_name.clear(); +#else + assert(false && "getgrgid_r() not supported on Android"); +#endif return NULL; } @@ -121,6 +125,12 @@ HostInfoPosix::GetEffectiveGroupID() return getegid(); } +FileSpec +HostInfoPosix::GetDefaultShell() +{ + return FileSpec("/bin/sh", false); +} + bool HostInfoPosix::ComputeSupportExeDirectory(FileSpec &file_spec) { @@ -173,6 +183,7 @@ HostInfoPosix::ComputeHeaderDirectory(FileSpec &file_spec) bool HostInfoPosix::ComputePythonDirectory(FileSpec &file_spec) { +#ifndef LLDB_DISABLE_PYTHON FileSpec lldb_file_spec; if (!GetLLDBPath(lldb::ePathTypeLLDBShlibDir, lldb_file_spec)) return false; @@ -190,4 +201,7 @@ HostInfoPosix::ComputePythonDirectory(FileSpec &file_spec) file_spec.GetDirectory().SetCString(raw_path); return true; +#else + return false; +#endif } diff --git a/source/Host/posix/HostProcessPosix.cpp b/source/Host/posix/HostProcessPosix.cpp index 4618de4711de..8e19add048ee 100644 --- a/source/Host/posix/HostProcessPosix.cpp +++ b/source/Host/posix/HostProcessPosix.cpp @@ -1,4 +1,4 @@ -//===-- HostProcessWindows.cpp ----------------------------------*- C++ -*-===// +//===-- HostProcessPosix.cpp ------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // @@ -7,6 +7,7 @@ // //===----------------------------------------------------------------------===// +#include "lldb/Host/Host.h" #include "lldb/Host/posix/HostProcessPosix.h" #include "lldb/Host/FileSystem.h" @@ -16,49 +17,52 @@ using namespace lldb_private; -const lldb::pid_t HostProcessPosix::kInvalidProcessId = 0; +namespace +{ + const int kInvalidPosixProcess = 0; +} HostProcessPosix::HostProcessPosix() -: m_pid(kInvalidProcessId) + : HostNativeProcessBase(kInvalidPosixProcess) { } -HostProcessPosix::~HostProcessPosix() +HostProcessPosix::HostProcessPosix(lldb::process_t process) + : HostNativeProcessBase(process) { } -Error HostProcessPosix::Create(lldb::pid_t pid) +HostProcessPosix::~HostProcessPosix() { - Error error; - if (pid == kInvalidProcessId) - error.SetErrorString("Attempt to create an invalid process"); - - m_pid = pid; - return error; } Error HostProcessPosix::Signal(int signo) const { - if (m_pid <= 0) + if (m_process == kInvalidPosixProcess) { Error error; error.SetErrorString("HostProcessPosix refers to an invalid process"); return error; } - return HostProcessPosix::Signal(m_pid, signo); + return HostProcessPosix::Signal(m_process, signo); } -Error HostProcessPosix::Signal(lldb::pid_t pid, int signo) +Error HostProcessPosix::Signal(lldb::process_t process, int signo) { Error error; - if (-1 == ::kill(pid, signo)) + if (-1 == ::kill(process, signo)) error.SetErrorToErrno(); return error; } +Error HostProcessPosix::Terminate() +{ + return Signal(SIGKILL); +} + Error HostProcessPosix::GetMainModule(FileSpec &file_spec) const { Error error; @@ -66,7 +70,7 @@ Error HostProcessPosix::GetMainModule(FileSpec &file_spec) const // Use special code here because proc/[pid]/exe is a symbolic link. char link_path[PATH_MAX]; char exe_path[PATH_MAX] = ""; - if (snprintf (link_path, PATH_MAX, "/proc/%" PRIu64 "/exe", m_pid) <= 0) + if (snprintf (link_path, PATH_MAX, "/proc/%" PRIu64 "/exe", m_process) <= 0) { error.SetErrorString("Unable to build /proc/<pid>/exe string"); return error; @@ -92,12 +96,21 @@ Error HostProcessPosix::GetMainModule(FileSpec &file_spec) const lldb::pid_t HostProcessPosix::GetProcessId() const { - return m_pid; + return m_process; } bool HostProcessPosix::IsRunning() const { + if (m_process == kInvalidPosixProcess) + return false; + // Send this process the null signal. If it succeeds the process is running. Error error = Signal(0); return error.Success(); } + +HostThread +HostProcessPosix::StartMonitoring(HostProcess::MonitorCallback callback, void *callback_baton, bool monitor_signals) +{ + return Host::StartMonitoringChildProcess(callback, callback_baton, m_process, monitor_signals); +} diff --git a/source/Host/posix/HostThreadPosix.cpp b/source/Host/posix/HostThreadPosix.cpp new file mode 100644 index 000000000000..9c4892431938 --- /dev/null +++ b/source/Host/posix/HostThreadPosix.cpp @@ -0,0 +1,74 @@ +//===-- HostThreadPosix.cpp -------------------------------------*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#include "lldb/Core/Error.h" +#include "lldb/Host/posix/HostThreadPosix.h" + +#include <errno.h> +#include <pthread.h> + +using namespace lldb; +using namespace lldb_private; + +HostThreadPosix::HostThreadPosix() +{ +} + +HostThreadPosix::HostThreadPosix(lldb::thread_t thread) + : HostNativeThreadBase(thread) +{ +} + +HostThreadPosix::~HostThreadPosix() +{ +} + +Error +HostThreadPosix::Join(lldb::thread_result_t *result) +{ + Error error; + if (IsJoinable()) + { + int err = ::pthread_join(m_thread, result); + error.SetError(err, lldb::eErrorTypePOSIX); + } + else + { + if (result) + *result = NULL; + error.SetError(EINVAL, eErrorTypePOSIX); + } + + Reset(); + return error; +} + +Error +HostThreadPosix::Cancel() +{ + Error error; +#ifndef __ANDROID__ + int err = ::pthread_cancel(m_thread); + error.SetError(err, eErrorTypePOSIX); +#else + error.SetErrorString("HostThreadPosix::Cancel() not supported on Android"); +#endif + + return error; +} + +Error +HostThreadPosix::Detach() +{ + Error error; + int err = ::pthread_detach(m_thread); + error.SetError(err, eErrorTypePOSIX); + Reset(); + return error; +} diff --git a/source/Host/posix/PipePosix.cpp b/source/Host/posix/PipePosix.cpp new file mode 100644 index 000000000000..02838ec5124e --- /dev/null +++ b/source/Host/posix/PipePosix.cpp @@ -0,0 +1,378 @@ +//===-- PipePosix.cpp -------------------------------------------*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#include "lldb/Host/posix/PipePosix.h" +#include "lldb/Host/FileSystem.h" + +#include <functional> +#include <thread> + +#include <errno.h> +#include <fcntl.h> +#include <unistd.h> +#include <sys/types.h> +#include <sys/stat.h> + +using namespace lldb; +using namespace lldb_private; + +int PipePosix::kInvalidDescriptor = -1; + +enum PIPES { READ, WRITE }; // Constants 0 and 1 for READ and WRITE + +// pipe2 is supported by Linux, FreeBSD v10 and higher. +// TODO: Add more platforms that support pipe2. +#if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD__ >= 10) +#define PIPE2_SUPPORTED 1 +#else +#define PIPE2_SUPPORTED 0 +#endif + +namespace +{ + +constexpr auto OPEN_WRITER_SLEEP_TIMEOUT_MSECS = 100; + +#if defined(FD_CLOEXEC) && !PIPE2_SUPPORTED +bool SetCloexecFlag(int fd) +{ + int flags = ::fcntl(fd, F_GETFD); + if (flags == -1) + return false; + return (::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == 0); +} +#endif + +std::chrono::time_point<std::chrono::steady_clock> +Now() +{ + return std::chrono::steady_clock::now(); +} + +Error +SelectIO(int handle, bool is_read, const std::function<Error(bool&)> &io_handler, const std::chrono::microseconds &timeout) +{ + Error error; + fd_set fds; + bool done = false; + + using namespace std::chrono; + + const auto finish_time = Now() + timeout; + + while (!done) + { + struct timeval tv = {0, 0}; + if (timeout != microseconds::zero()) + { + const auto remaining_dur = duration_cast<microseconds>(finish_time - Now()); + if (remaining_dur.count() <= 0) + { + error.SetErrorString("timeout exceeded"); + break; + } + const auto dur_secs = duration_cast<seconds>(remaining_dur); + const auto dur_usecs = remaining_dur % seconds(1); + + tv.tv_sec = dur_secs.count(); + tv.tv_usec = dur_usecs.count(); + } + else + tv.tv_sec = 1; + + FD_ZERO(&fds); + FD_SET(handle, &fds); + + const auto retval = ::select(handle + 1, + (is_read) ? &fds : nullptr, + (is_read) ? nullptr : &fds, + nullptr, &tv); + if (retval == -1) + { + if (errno == EINTR) + continue; + error.SetErrorToErrno(); + break; + } + if (retval == 0) + { + error.SetErrorString("timeout exceeded"); + break; + } + if (!FD_ISSET(handle, &fds)) + { + error.SetErrorString("invalid state"); + break; + } + + error = io_handler(done); + if (error.Fail()) + { + if (error.GetError() == EINTR) + continue; + break; + } + } + return error; +} + +} + +PipePosix::PipePosix() +{ + m_fds[READ] = PipePosix::kInvalidDescriptor; + m_fds[WRITE] = PipePosix::kInvalidDescriptor; +} + +PipePosix::~PipePosix() +{ + Close(); +} + +Error +PipePosix::CreateNew(bool child_processes_inherit) +{ + if (CanRead() || CanWrite()) + return Error(EINVAL, eErrorTypePOSIX); + + Error error; +#if PIPE2_SUPPORTED + if (::pipe2(m_fds, (child_processes_inherit) ? 0 : O_CLOEXEC) == 0) + return error; +#else + if (::pipe(m_fds) == 0) + { +#ifdef FD_CLOEXEC + if (!child_processes_inherit) + { + if (!SetCloexecFlag(m_fds[0]) || !SetCloexecFlag(m_fds[1])) + { + error.SetErrorToErrno(); + Close(); + return error; + } + } +#endif + return error; + } +#endif + + error.SetErrorToErrno(); + m_fds[READ] = PipePosix::kInvalidDescriptor; + m_fds[WRITE] = PipePosix::kInvalidDescriptor; + return error; +} + +Error +PipePosix::CreateNew(llvm::StringRef name, bool child_process_inherit) +{ + if (CanRead() || CanWrite()) + return Error("Pipe is already opened"); + + Error error; + if (::mkfifo(name.data(), 0660) != 0) + error.SetErrorToErrno(); + + return error; +} + +Error +PipePosix::OpenAsReader(llvm::StringRef name, bool child_process_inherit) +{ + if (CanRead() || CanWrite()) + return Error("Pipe is already opened"); + + int flags = O_RDONLY | O_NONBLOCK; + if (!child_process_inherit) + flags |= O_CLOEXEC; + + Error error; + int fd = ::open(name.data(), flags); + if (fd != -1) + m_fds[READ] = fd; + else + error.SetErrorToErrno(); + + return error; +} + +Error +PipePosix::OpenAsWriterWithTimeout(llvm::StringRef name, bool child_process_inherit, const std::chrono::microseconds &timeout) +{ + if (CanRead() || CanWrite()) + return Error("Pipe is already opened"); + + int flags = O_WRONLY | O_NONBLOCK; + if (!child_process_inherit) + flags |= O_CLOEXEC; + + using namespace std::chrono; + const auto finish_time = Now() + timeout; + + while (!CanWrite()) + { + if (timeout != microseconds::zero()) + { + const auto dur = duration_cast<microseconds>(finish_time - Now()).count(); + if (dur <= 0) + return Error("timeout exceeded - reader hasn't opened so far"); + } + + errno = 0; + int fd = ::open(name.data(), flags); + if (fd == -1) + { + const auto errno_copy = errno; + // We may get ENXIO if a reader side of the pipe hasn't opened yet. + if (errno_copy != ENXIO) + return Error(errno_copy, eErrorTypePOSIX); + + std::this_thread::sleep_for(milliseconds(OPEN_WRITER_SLEEP_TIMEOUT_MSECS)); + } + else + { + m_fds[WRITE] = fd; + } + } + + return Error(); +} + +int +PipePosix::GetReadFileDescriptor() const +{ + return m_fds[READ]; +} + +int +PipePosix::GetWriteFileDescriptor() const +{ + return m_fds[WRITE]; +} + +int +PipePosix::ReleaseReadFileDescriptor() +{ + const int fd = m_fds[READ]; + m_fds[READ] = PipePosix::kInvalidDescriptor; + return fd; +} + +int +PipePosix::ReleaseWriteFileDescriptor() +{ + const int fd = m_fds[WRITE]; + m_fds[WRITE] = PipePosix::kInvalidDescriptor; + return fd; +} + +void +PipePosix::Close() +{ + CloseReadFileDescriptor(); + CloseWriteFileDescriptor(); +} + +Error +PipePosix::Delete(llvm::StringRef name) +{ + return FileSystem::Unlink(name.data()); +} + +bool +PipePosix::CanRead() const +{ + return m_fds[READ] != PipePosix::kInvalidDescriptor; +} + +bool +PipePosix::CanWrite() const +{ + return m_fds[WRITE] != PipePosix::kInvalidDescriptor; +} + +void +PipePosix::CloseReadFileDescriptor() +{ + if (CanRead()) + { + close(m_fds[READ]); + m_fds[READ] = PipePosix::kInvalidDescriptor; + } +} + +void +PipePosix::CloseWriteFileDescriptor() +{ + if (CanWrite()) + { + close(m_fds[WRITE]); + m_fds[WRITE] = PipePosix::kInvalidDescriptor; + } +} + +Error +PipePosix::ReadWithTimeout(void *buf, size_t size, const std::chrono::microseconds &timeout, size_t &bytes_read) +{ + bytes_read = 0; + if (!CanRead()) + return Error(EINVAL, eErrorTypePOSIX); + + auto handle = GetReadFileDescriptor(); + return SelectIO(handle, + true, + [=, &bytes_read](bool &done) + { + Error error; + auto result = ::read(handle, + reinterpret_cast<char*>(buf) + bytes_read, + size - bytes_read); + if (result != -1) + { + bytes_read += result; + if (bytes_read == size || result == 0) + done = true; + } + else + error.SetErrorToErrno(); + + return error; + }, + timeout); +} + +Error +PipePosix::Write(const void *buf, size_t size, size_t &bytes_written) +{ + bytes_written = 0; + if (!CanWrite()) + return Error(EINVAL, eErrorTypePOSIX); + + auto handle = GetWriteFileDescriptor(); + return SelectIO(handle, + false, + [=, &bytes_written](bool &done) + { + Error error; + auto result = ::write(handle, + reinterpret_cast<const char*>(buf) + bytes_written, + size - bytes_written); + if (result != -1) + { + bytes_written += result; + if (bytes_written == size) + done = true; + } + else + error.SetErrorToErrno(); + + return error; + }, + std::chrono::microseconds::zero()); +} diff --git a/source/Host/posix/ProcessLauncherPosix.cpp b/source/Host/posix/ProcessLauncherPosix.cpp new file mode 100644 index 000000000000..dd5c5121a97b --- /dev/null +++ b/source/Host/posix/ProcessLauncherPosix.cpp @@ -0,0 +1,33 @@ +//===-- ProcessLauncherPosix.cpp --------------------------------*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#include "lldb/Host/Host.h" +#include "lldb/Host/HostProcess.h" +#include "lldb/Host/posix/ProcessLauncherPosix.h" + +#include "lldb/Target/ProcessLaunchInfo.h" + +#include <limits.h> + +using namespace lldb; +using namespace lldb_private; + +HostProcess +ProcessLauncherPosix::LaunchProcess(const ProcessLaunchInfo &launch_info, Error &error) +{ + lldb::pid_t pid; + char exe_path[PATH_MAX]; + + launch_info.GetExecutableFile().GetPath(exe_path, sizeof(exe_path)); + + // TODO(zturner): Move the code from LaunchProcessPosixSpawn to here, and make MacOSX re-use this + // ProcessLauncher when it wants a posix_spawn launch. + error = Host::LaunchProcessPosixSpawn(exe_path, launch_info, pid); + return HostProcess(pid); +} |