brintos

brintos / llvm-project-archived public Read only

0
0
Text · 14.2 KiB · 406fa06 Raw
406 lines · cpp
1//===-- GDBRemoteClientBase.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-exception6//7//===----------------------------------------------------------------------===//8 9#include "GDBRemoteClientBase.h"10 11#include "llvm/ADT/StringExtras.h"12 13#include "lldb/Target/UnixSignals.h"14#include "lldb/Utility/LLDBAssert.h"15 16#include "ProcessGDBRemoteLog.h"17 18using namespace lldb;19using namespace lldb_private;20using namespace lldb_private::process_gdb_remote;21using namespace std::chrono;22 23// When we've sent a continue packet and are waiting for the target to stop,24// we wake up the wait with this interval to make sure the stub hasn't gone25// away while we were waiting.26static const seconds kWakeupInterval(5);27 28/////////////////////////29// GDBRemoteClientBase //30/////////////////////////31 32GDBRemoteClientBase::ContinueDelegate::~ContinueDelegate() = default;33 34GDBRemoteClientBase::GDBRemoteClientBase(const char *comm_name)35    : GDBRemoteCommunication(), Broadcaster(nullptr, comm_name),36      m_async_count(0), m_is_running(false), m_should_stop(false) {}37 38StateType GDBRemoteClientBase::SendContinuePacketAndWaitForResponse(39    ContinueDelegate &delegate, const UnixSignals &signals,40    llvm::StringRef payload, std::chrono::seconds interrupt_timeout,41    StringExtractorGDBRemote &response) {42  Log *log = GetLog(GDBRLog::Process);43  response.Clear();44 45  {46    std::lock_guard<std::mutex> lock(m_mutex);47    m_continue_packet = std::string(payload);48    m_should_stop = false;49  }50  ContinueLock cont_lock(*this);51  if (!cont_lock)52    return eStateInvalid;53  OnRunPacketSent(true);54  // The main ReadPacket loop wakes up at computed_timeout intervals, just to 55  // check that the connection hasn't dropped.  When we wake up we also check56  // whether there is an interrupt request that has reached its endpoint.57  // If we want a shorter interrupt timeout that kWakeupInterval, we need to 58  // choose the shorter interval for the wake up as well.59  std::chrono::seconds computed_timeout = std::min(interrupt_timeout, 60                                                   kWakeupInterval);61  for (;;) {62    PacketResult read_result = ReadPacket(response, computed_timeout, false);63    // Reset the computed_timeout to the default value in case we are going64    // round again.65    computed_timeout = std::min(interrupt_timeout, kWakeupInterval);66    switch (read_result) {67    case PacketResult::ErrorReplyTimeout: {68      std::lock_guard<std::mutex> lock(m_mutex);69      if (m_async_count == 0) {70        continue;71      }72      auto cur_time = steady_clock::now();73      if (cur_time >= m_interrupt_endpoint)74        return eStateInvalid;75      else {76        // We woke up and found an interrupt is in flight, but we haven't77        // exceeded the interrupt wait time.  So reset the wait time to the78        // time left till the interrupt timeout.  But don't wait longer79        // than our wakeup timeout.80        auto new_wait = m_interrupt_endpoint - cur_time;81        computed_timeout = std::min(kWakeupInterval,82            std::chrono::duration_cast<std::chrono::seconds>(new_wait));83        continue;84      }85      break;86    }87    case PacketResult::Success:88      break;89    default:90      LLDB_LOGF(log, "GDBRemoteClientBase::%s () ReadPacket(...) => false",91                __FUNCTION__);92      return eStateInvalid;93    }94    if (response.Empty())95      return eStateInvalid;96 97    const char stop_type = response.GetChar();98    LLDB_LOGF(log, "GDBRemoteClientBase::%s () got packet: %s", __FUNCTION__,99              response.GetStringRef().data());100 101    switch (stop_type) {102    case 'W':103    case 'X':104      return eStateExited;105    case 'E':106      // ERROR107      return eStateInvalid;108    default:109      LLDB_LOGF(log, "GDBRemoteClientBase::%s () unrecognized async packet",110                __FUNCTION__);111      return eStateInvalid;112    case 'O': {113      std::string inferior_stdout;114      response.GetHexByteString(inferior_stdout);115      delegate.HandleAsyncStdout(inferior_stdout);116      break;117    }118    case 'A':119      delegate.HandleAsyncMisc(120          llvm::StringRef(response.GetStringRef()).substr(1));121      break;122    case 'J':123      delegate.HandleAsyncStructuredDataPacket(response.GetStringRef());124      break;125    case 'T':126    case 'S':127      // Do this with the continue lock held.128      const bool should_stop = ShouldStop(signals, response);129      response.SetFilePos(0);130 131      // The packet we should resume with. In the future we should check our132      // thread list and "do the right thing" for new threads that show up133      // while we stop and run async packets. Setting the packet to 'c' to134      // continue all threads is the right thing to do 99.99% of the time135      // because if a thread was single stepping, and we sent an interrupt, we136      // will notice above that we didn't stop due to an interrupt but stopped137      // due to stepping and we would _not_ continue. This packet may get138      // modified by the async actions (e.g. to send a signal).139      m_continue_packet = 'c';140      cont_lock.unlock();141 142      delegate.HandleStopReply();143      if (should_stop)144        return eStateStopped;145 146      switch (cont_lock.lock()) {147      case ContinueLock::LockResult::Success:148        break;149      case ContinueLock::LockResult::Failed:150        return eStateInvalid;151      case ContinueLock::LockResult::Cancelled:152        return eStateStopped;153      }154      OnRunPacketSent(false);155      break;156    }157  }158}159 160bool GDBRemoteClientBase::SendAsyncSignal(161    int signo, std::chrono::seconds interrupt_timeout) {162  Lock lock(*this, interrupt_timeout);163  if (!lock || !lock.DidInterrupt())164    return false;165 166  m_continue_packet = 'C';167  m_continue_packet += llvm::hexdigit((signo / 16) % 16);168  m_continue_packet += llvm::hexdigit(signo % 16);169  return true;170}171 172bool GDBRemoteClientBase::Interrupt(std::chrono::seconds interrupt_timeout) {173  Lock lock(*this, interrupt_timeout);174  if (!lock.DidInterrupt())175    return false;176  m_should_stop = true;177  return true;178}179 180GDBRemoteCommunication::PacketResult181GDBRemoteClientBase::SendPacketAndWaitForResponse(182    llvm::StringRef payload, StringExtractorGDBRemote &response,183    std::chrono::seconds interrupt_timeout, bool sync_on_timeout) {184  Lock lock(*this, interrupt_timeout);185  if (!lock) {186    if (Log *log = GetLog(GDBRLog::Process))187      LLDB_LOGF(log,188                "GDBRemoteClientBase::%s failed to get mutex, not sending "189                "packet '%.*s'",190                __FUNCTION__, int(payload.size()), payload.data());191    return PacketResult::ErrorSendFailed;192  }193 194  return SendPacketAndWaitForResponseNoLock(payload, response, sync_on_timeout);195}196 197GDBRemoteCommunication::PacketResult198GDBRemoteClientBase::ReadPacketWithOutputSupport(199    StringExtractorGDBRemote &response, Timeout<std::micro> timeout,200    bool sync_on_timeout,201    llvm::function_ref<void(llvm::StringRef)> output_callback) {202  auto result = ReadPacket(response, timeout, sync_on_timeout);203  while (result == PacketResult::Success && response.IsNormalResponse() &&204         response.PeekChar() == 'O') {205    response.GetChar();206    std::string output;207    if (response.GetHexByteString(output))208      output_callback(output);209    result = ReadPacket(response, timeout, sync_on_timeout);210  }211  return result;212}213 214GDBRemoteCommunication::PacketResult215GDBRemoteClientBase::SendPacketAndReceiveResponseWithOutputSupport(216    llvm::StringRef payload, StringExtractorGDBRemote &response,217    std::chrono::seconds interrupt_timeout,218    llvm::function_ref<void(llvm::StringRef)> output_callback) {219  Lock lock(*this, interrupt_timeout);220  if (!lock) {221    if (Log *log = GetLog(GDBRLog::Process))222      LLDB_LOGF(log,223                "GDBRemoteClientBase::%s failed to get mutex, not sending "224                "packet '%.*s'",225                __FUNCTION__, int(payload.size()), payload.data());226    return PacketResult::ErrorSendFailed;227  }228 229  PacketResult packet_result = SendPacketNoLock(payload);230  if (packet_result != PacketResult::Success)231    return packet_result;232 233  return ReadPacketWithOutputSupport(response, GetPacketTimeout(), true,234                                     output_callback);235}236 237GDBRemoteCommunication::PacketResult238GDBRemoteClientBase::SendPacketAndWaitForResponseNoLock(239    llvm::StringRef payload, StringExtractorGDBRemote &response,240    bool sync_on_timeout) {241  PacketResult packet_result = SendPacketNoLock(payload);242  if (packet_result != PacketResult::Success)243    return packet_result;244 245  const size_t max_response_retries = 3;246  for (size_t i = 0; i < max_response_retries; ++i) {247    packet_result = ReadPacket(response, GetPacketTimeout(), sync_on_timeout);248    // Make sure we received a response249    if (packet_result != PacketResult::Success)250      return packet_result;251    // Make sure our response is valid for the payload that was sent252    if (response.ValidateResponse())253      return packet_result;254    // Response says it wasn't valid255    Log *log = GetLog(GDBRLog::Packets);256    LLDB_LOGF(257        log,258        "error: packet with payload \"%.*s\" got invalid response \"%s\": %s",259        int(payload.size()), payload.data(), response.GetStringRef().data(),260        (i == (max_response_retries - 1))261            ? "using invalid response and giving up"262            : "ignoring response and waiting for another");263  }264  return packet_result;265}266 267bool GDBRemoteClientBase::ShouldStop(const UnixSignals &signals,268                                     StringExtractorGDBRemote &response) {269  std::lock_guard<std::mutex> lock(m_mutex);270 271  if (m_async_count == 0)272    return true; // We were not interrupted. The process stopped on its own.273 274  // Older debugserver stubs (before April 2016) can return two stop-reply275  // packets in response to a ^C packet. Additionally, all debugservers still276  // return two stop replies if the inferior stops due to some other reason277  // before the remote stub manages to interrupt it. We need to wait for this278  // additional packet to make sure the packet sequence does not get skewed.279  StringExtractorGDBRemote extra_stop_reply_packet;280  ReadPacket(extra_stop_reply_packet, milliseconds(100), false);281 282  // Interrupting is typically done using SIGSTOP or SIGINT, so if the process283  // stops with some other signal, we definitely want to stop.284  const uint8_t signo = response.GetHexU8(UINT8_MAX);285  if (signo != signals.GetSignalNumberFromName("SIGSTOP") &&286      signo != signals.GetSignalNumberFromName("SIGINT"))287    return true;288 289  // We probably only stopped to perform some async processing, so continue290  // after that is done.291  // TODO: This is not 100% correct, as the process may have been stopped with292  // SIGINT or SIGSTOP that was not caused by us (e.g. raise(SIGINT)). This will293  // normally cause a stop, but if it's done concurrently with a async294  // interrupt, that stop will get eaten (llvm.org/pr20231).295  return false;296}297 298void GDBRemoteClientBase::OnRunPacketSent(bool first) {299  if (first)300    BroadcastEvent(eBroadcastBitRunPacketSent, nullptr);301}302 303///////////////////////////////////////304// GDBRemoteClientBase::ContinueLock //305///////////////////////////////////////306 307GDBRemoteClientBase::ContinueLock::ContinueLock(GDBRemoteClientBase &comm)308    : m_comm(comm), m_acquired(false) {309  lock();310}311 312GDBRemoteClientBase::ContinueLock::~ContinueLock() {313  if (m_acquired)314    unlock();315}316 317void GDBRemoteClientBase::ContinueLock::unlock() {318  lldbassert(m_acquired);319  {320    std::unique_lock<std::mutex> lock(m_comm.m_mutex);321    m_comm.m_is_running = false;322  }323  m_comm.m_cv.notify_all();324  m_acquired = false;325}326 327GDBRemoteClientBase::ContinueLock::LockResult328GDBRemoteClientBase::ContinueLock::lock() {329  Log *log = GetLog(GDBRLog::Process);330  LLDB_LOGF(log, "GDBRemoteClientBase::ContinueLock::%s() resuming with %s",331            __FUNCTION__, m_comm.m_continue_packet.c_str());332 333  lldbassert(!m_acquired);334  std::unique_lock<std::mutex> lock(m_comm.m_mutex);335  m_comm.m_cv.wait(lock, [this] { return m_comm.m_async_count == 0; });336  if (m_comm.m_should_stop) {337    m_comm.m_should_stop = false;338    LLDB_LOGF(log, "GDBRemoteClientBase::ContinueLock::%s() cancelled",339              __FUNCTION__);340    return LockResult::Cancelled;341  }342  if (m_comm.SendPacketNoLock(m_comm.m_continue_packet) !=343      PacketResult::Success)344    return LockResult::Failed;345 346  lldbassert(!m_comm.m_is_running);347  m_comm.m_is_running = true;348  m_acquired = true;349  return LockResult::Success;350}351 352///////////////////////////////353// GDBRemoteClientBase::Lock //354///////////////////////////////355 356GDBRemoteClientBase::Lock::Lock(GDBRemoteClientBase &comm,357                                std::chrono::seconds interrupt_timeout)358    : m_async_lock(comm.m_async_mutex, std::defer_lock), m_comm(comm),359      m_interrupt_timeout(interrupt_timeout), m_acquired(false),360      m_did_interrupt(false) {361  SyncWithContinueThread();362  if (m_acquired)363    m_async_lock.lock();364}365 366void GDBRemoteClientBase::Lock::SyncWithContinueThread() {367  Log *log = GetLog(GDBRLog::Process|GDBRLog::Packets);368  std::unique_lock<std::mutex> lock(m_comm.m_mutex);369  if (m_comm.m_is_running && m_interrupt_timeout == std::chrono::seconds(0))370    return; // We were asked to avoid interrupting the sender. Lock is not371            // acquired.372 373  ++m_comm.m_async_count;374  if (m_comm.m_is_running) {375    if (m_comm.m_async_count == 1) {376      // The sender has sent the continue packet and we are the first async377      // packet. Let's interrupt it.378      const char ctrl_c = '\x03';379      ConnectionStatus status = eConnectionStatusSuccess;380      size_t bytes_written = m_comm.Write(&ctrl_c, 1, status, nullptr);381      if (bytes_written == 0) {382        --m_comm.m_async_count;383        LLDB_LOGF(log, "GDBRemoteClientBase::Lock::Lock failed to send "384                       "interrupt packet");385        return;386      }387      m_comm.m_interrupt_endpoint = steady_clock::now() + m_interrupt_timeout;388      if (log)389        log->PutCString("GDBRemoteClientBase::Lock::Lock sent packet: \\x03");390    }391    m_comm.m_cv.wait(lock, [this] { return !m_comm.m_is_running; });392    m_did_interrupt = true;393  }394  m_acquired = true;395}396 397GDBRemoteClientBase::Lock::~Lock() {398  if (!m_acquired)399    return;400  {401    std::unique_lock<std::mutex> lock(m_comm.m_mutex);402    --m_comm.m_async_count;403  }404  m_comm.m_cv.notify_one();405}406