brintos

brintos / llvm-project-archived public Read only

0
0
Text · 69.6 KiB · 7ef50da Raw
2066 lines · cpp
1//===-- NativeProcessLinux.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 "NativeProcessLinux.h"10 11#include <cerrno>12#include <cstdint>13#include <cstring>14#include <unistd.h>15 16#include <fstream>17#include <mutex>18#include <optional>19#include <sstream>20#include <string>21#include <unordered_map>22 23#include "NativeThreadLinux.h"24#include "Plugins/Process/POSIX/ProcessPOSIXLog.h"25#include "Plugins/Process/Utility/LinuxProcMaps.h"26#include "Procfs.h"27#include "lldb/Core/ModuleSpec.h"28#include "lldb/Host/Host.h"29#include "lldb/Host/HostProcess.h"30#include "lldb/Host/ProcessLaunchInfo.h"31#include "lldb/Host/PseudoTerminal.h"32#include "lldb/Host/ThreadLauncher.h"33#include "lldb/Host/common/NativeRegisterContext.h"34#include "lldb/Host/linux/Host.h"35#include "lldb/Host/linux/Ptrace.h"36#include "lldb/Host/linux/Uio.h"37#include "lldb/Host/posix/ProcessLauncherPosixFork.h"38#include "lldb/Symbol/ObjectFile.h"39#include "lldb/Target/Process.h"40#include "lldb/Target/Target.h"41#include "lldb/Utility/LLDBAssert.h"42#include "lldb/Utility/LLDBLog.h"43#include "lldb/Utility/State.h"44#include "lldb/Utility/Status.h"45#include "lldb/Utility/StringExtractor.h"46#include "llvm/ADT/ScopeExit.h"47#include "llvm/Support/Errno.h"48#include "llvm/Support/Error.h"49#include "llvm/Support/FileSystem.h"50#include "llvm/Support/Threading.h"51 52#include <linux/unistd.h>53#include <sys/socket.h>54#include <sys/syscall.h>55#include <sys/types.h>56#include <sys/user.h>57#include <sys/wait.h>58 59#ifdef __aarch64__60#include <asm/hwcap.h>61#include <sys/auxv.h>62#endif63 64// Support hardware breakpoints in case it has not been defined65#ifndef TRAP_HWBKPT66#define TRAP_HWBKPT 467#endif68 69#ifndef HWCAP2_MTE70#define HWCAP2_MTE (1 << 18)71#endif72 73using namespace lldb;74using namespace lldb_private;75using namespace lldb_private::process_linux;76using namespace llvm;77 78// Private bits we only need internally.79 80static bool ProcessVmReadvSupported() {81  static bool is_supported;82  static llvm::once_flag flag;83 84  llvm::call_once(flag, [] {85    Log *log = GetLog(POSIXLog::Process);86 87    uint32_t source = 0x47424742;88    uint32_t dest = 0;89 90    struct iovec local, remote;91    remote.iov_base = &source;92    local.iov_base = &dest;93    remote.iov_len = local.iov_len = sizeof source;94 95    // We shall try if cross-process-memory reads work by attempting to read a96    // value from our own process.97    ssize_t res = process_vm_readv(getpid(), &local, 1, &remote, 1, 0);98    is_supported = (res == sizeof(source) && source == dest);99    if (is_supported)100      LLDB_LOG(log,101               "Detected kernel support for process_vm_readv syscall. "102               "Fast memory reads enabled.");103    else104      LLDB_LOG(log,105               "syscall process_vm_readv failed (error: {0}). Fast memory "106               "reads disabled.",107               llvm::sys::StrError());108  });109 110  return is_supported;111}112 113static void MaybeLogLaunchInfo(const ProcessLaunchInfo &info) {114  Log *log = GetLog(POSIXLog::Process);115  if (!log)116    return;117 118  if (const FileAction *action = info.GetFileActionForFD(STDIN_FILENO))119    LLDB_LOG(log, "setting STDIN to '{0}'", action->GetFileSpec());120  else121    LLDB_LOG(log, "leaving STDIN as is");122 123  if (const FileAction *action = info.GetFileActionForFD(STDOUT_FILENO))124    LLDB_LOG(log, "setting STDOUT to '{0}'", action->GetFileSpec());125  else126    LLDB_LOG(log, "leaving STDOUT as is");127 128  if (const FileAction *action = info.GetFileActionForFD(STDERR_FILENO))129    LLDB_LOG(log, "setting STDERR to '{0}'", action->GetFileSpec());130  else131    LLDB_LOG(log, "leaving STDERR as is");132 133  int i = 0;134  for (const char **args = info.GetArguments().GetConstArgumentVector(); *args;135       ++args, ++i)136    LLDB_LOG(log, "arg {0}: '{1}'", i, *args);137}138 139static void DisplayBytes(StreamString &s, void *bytes, uint32_t count) {140  uint8_t *ptr = (uint8_t *)bytes;141  const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count);142  for (uint32_t i = 0; i < loop_count; i++) {143    s.Printf("[%x]", *ptr);144    ptr++;145  }146}147 148static void PtraceDisplayBytes(int &req, void *data, size_t data_size) {149  Log *log = GetLog(POSIXLog::Ptrace);150  if (!log)151    return;152  StreamString buf;153 154  switch (req) {155  case PTRACE_POKETEXT: {156    DisplayBytes(buf, &data, 8);157    LLDB_LOGV(log, "PTRACE_POKETEXT {0}", buf.GetData());158    break;159  }160  case PTRACE_POKEDATA: {161    DisplayBytes(buf, &data, 8);162    LLDB_LOGV(log, "PTRACE_POKEDATA {0}", buf.GetData());163    break;164  }165  case PTRACE_POKEUSER: {166    DisplayBytes(buf, &data, 8);167    LLDB_LOGV(log, "PTRACE_POKEUSER {0}", buf.GetData());168    break;169  }170  case PTRACE_SETREGS: {171    DisplayBytes(buf, data, data_size);172    LLDB_LOGV(log, "PTRACE_SETREGS {0}", buf.GetData());173    break;174  }175  case PTRACE_SETFPREGS: {176    DisplayBytes(buf, data, data_size);177    LLDB_LOGV(log, "PTRACE_SETFPREGS {0}", buf.GetData());178    break;179  }180  case PTRACE_SETSIGINFO: {181    DisplayBytes(buf, data, sizeof(siginfo_t));182    LLDB_LOGV(log, "PTRACE_SETSIGINFO {0}", buf.GetData());183    break;184  }185  case PTRACE_SETREGSET: {186    // Extract iov_base from data, which is a pointer to the struct iovec187    DisplayBytes(buf, *(void **)data, data_size);188    LLDB_LOGV(log, "PTRACE_SETREGSET {0}", buf.GetData());189    break;190  }191  default: {}192  }193}194 195static constexpr unsigned k_ptrace_word_size = sizeof(void *);196static_assert(sizeof(long) >= k_ptrace_word_size,197              "Size of long must be larger than ptrace word size");198 199// Simple helper function to ensure flags are enabled on the given file200// descriptor.201static Status EnsureFDFlags(int fd, int flags) {202  Status error;203 204  int status = fcntl(fd, F_GETFL);205  if (status == -1) {206    error = Status::FromErrno();207    return error;208  }209 210  if (fcntl(fd, F_SETFL, status | flags) == -1) {211    error = Status::FromErrno();212    return error;213  }214 215  return error;216}217 218static llvm::Error AddPtraceScopeNote(llvm::Error original_error) {219  Expected<int> ptrace_scope = GetPtraceScope();220  if (auto E = ptrace_scope.takeError()) {221    LLDB_LOG_ERROR(GetLog(POSIXLog::Process), std::move(E),222                   "error reading value of ptrace_scope: {0}");223 224    // The original error is probably more interesting than not being able to225    // read or interpret ptrace_scope.226    return original_error;227  }228 229  // We only have suggestions to provide for 1-3.230  switch (*ptrace_scope) {231  case 1:232  case 2:233    llvm::consumeError(std::move(original_error));234    return llvm::createStringError(235        std::error_code(errno, std::generic_category()),236        "The current value of ptrace_scope is %d, which can cause ptrace to "237        "fail to attach to a running process. To fix this, run:\n"238        "\tsudo sysctl -w kernel.yama.ptrace_scope=0\n"239        "For more information, see: "240        "https://www.kernel.org/doc/Documentation/security/Yama.txt.",241        *ptrace_scope);242  case 3:243    llvm::consumeError(std::move(original_error));244    return llvm::createStringError(245        std::error_code(errno, std::generic_category()),246        "The current value of ptrace_scope is 3, which will cause ptrace to "247        "fail to attach to a running process. This value cannot be changed "248        "without rebooting.\n"249        "For more information, see: "250        "https://www.kernel.org/doc/Documentation/security/Yama.txt.");251  case 0:252  default:253    return original_error;254  }255}256 257NativeProcessLinux::Manager::Manager(MainLoop &mainloop)258    : NativeProcessProtocol::Manager(mainloop) {259  Status status;260  m_sigchld_handle = mainloop.RegisterSignal(261      SIGCHLD, [this](MainLoopBase &) { SigchldHandler(); }, status);262  assert(m_sigchld_handle && status.Success());263}264 265llvm::Expected<std::unique_ptr<NativeProcessProtocol>>266NativeProcessLinux::Manager::Launch(ProcessLaunchInfo &launch_info,267                                    NativeDelegate &native_delegate) {268  Log *log = GetLog(POSIXLog::Process);269 270  MaybeLogLaunchInfo(launch_info);271 272  Status status;273  ::pid_t pid = ProcessLauncherPosixFork()274                    .LaunchProcess(launch_info, status)275                    .GetProcessId();276  LLDB_LOG(log, "pid = {0:x}", pid);277  if (status.Fail()) {278    LLDB_LOG(log, "failed to launch process: {0}", status);279    return status.ToError();280  }281 282  // Wait for the child process to trap on its call to execve.283  int wstatus = 0;284  ::pid_t wpid = llvm::sys::RetryAfterSignal(-1, ::waitpid, pid, &wstatus, 0);285  assert(wpid == pid);286  UNUSED_IF_ASSERT_DISABLED(wpid);287  if (!WIFSTOPPED(wstatus)) {288    LLDB_LOG(log, "Could not sync with inferior process: wstatus={1}",289             WaitStatus::Decode(wstatus));290    return llvm::make_error<StringError>("Could not sync with inferior process",291                                         llvm::inconvertibleErrorCode());292  }293  LLDB_LOG(log, "inferior started, now in stopped state");294 295  status = SetDefaultPtraceOpts(pid);296  if (status.Fail()) {297    LLDB_LOG(log, "failed to set default ptrace options: {0}", status);298    return status.ToError();299  }300 301  llvm::Expected<ArchSpec> arch_or =302      NativeRegisterContextLinux::DetermineArchitecture(pid);303  if (!arch_or)304    return arch_or.takeError();305 306  return std::unique_ptr<NativeProcessLinux>(new NativeProcessLinux(307      pid, launch_info.GetPTY().ReleasePrimaryFileDescriptor(), native_delegate,308      *arch_or, *this, {pid}));309}310 311llvm::Expected<std::unique_ptr<NativeProcessProtocol>>312NativeProcessLinux::Manager::Attach(313    lldb::pid_t pid, NativeProcessProtocol::NativeDelegate &native_delegate) {314  Log *log = GetLog(POSIXLog::Process);315  LLDB_LOG(log, "pid = {0:x}", pid);316 317  auto tids_or = NativeProcessLinux::Attach(pid);318  if (!tids_or)319    return tids_or.takeError();320  ArrayRef<::pid_t> tids = *tids_or;321  llvm::Expected<ArchSpec> arch_or =322      NativeRegisterContextLinux::DetermineArchitecture(tids[0]);323  if (!arch_or)324    return arch_or.takeError();325 326  return std::unique_ptr<NativeProcessLinux>(327      new NativeProcessLinux(pid, -1, native_delegate, *arch_or, *this, tids));328}329 330NativeProcessLinux::Extension331NativeProcessLinux::Manager::GetSupportedExtensions() const {332  NativeProcessLinux::Extension supported =333      Extension::multiprocess | Extension::fork | Extension::vfork |334      Extension::pass_signals | Extension::auxv | Extension::libraries_svr4 |335      Extension::siginfo_read;336 337#ifdef __aarch64__338  // At this point we do not have a process so read auxv directly.339  if ((getauxval(AT_HWCAP2) & HWCAP2_MTE))340    supported |= Extension::memory_tagging;341#endif342 343  return supported;344}345 346static std::optional<std::pair<lldb::pid_t, WaitStatus>> WaitPid() {347  Log *log = GetLog(POSIXLog::Process);348 349  int status;350  ::pid_t wait_pid = llvm::sys::RetryAfterSignal(351      -1, ::waitpid, -1, &status, __WALL | __WNOTHREAD | WNOHANG);352 353  if (wait_pid == 0)354    return std::nullopt;355 356  if (wait_pid == -1) {357    Status error(errno, eErrorTypePOSIX);358    LLDB_LOG(log, "waitpid(-1, &status, _) failed: {0}", error);359    return std::nullopt;360  }361 362  WaitStatus wait_status = WaitStatus::Decode(status);363 364  LLDB_LOG(log, "waitpid(-1, &status, _) = {0}, status = {1}", wait_pid,365           wait_status);366  return std::make_pair(wait_pid, wait_status);367}368 369void NativeProcessLinux::Manager::SigchldHandler() {370  Log *log = GetLog(POSIXLog::Process);371  while (true) {372    auto wait_result = WaitPid();373    if (!wait_result)374      return;375    lldb::pid_t pid = wait_result->first;376    WaitStatus status = wait_result->second;377 378    // Ask each process whether it wants to handle the event. Each event should379    // be handled by exactly one process, but thread creation events require380    // special handling.381    // Thread creation consists of two events (one on the parent and one on the382    // child thread) and they can arrive in any order nondeterministically. The383    // parent event carries the information about the child thread, but not384    // vice-versa. This means that if the child event arrives first, it may not385    // be handled by any process (because it doesn't know the thread belongs to386    // it).387    bool handled = llvm::any_of(m_processes, [&](NativeProcessLinux *process) {388      return process->TryHandleWaitStatus(pid, status);389    });390    if (!handled) {391      if (status.type == WaitStatus::Stop && status.status == SIGSTOP) {392        // Store the thread creation event for later collection.393        m_unowned_threads.insert(pid);394      } else {395        LLDB_LOG(log, "Ignoring waitpid event {0} for pid {1}", status, pid);396      }397    }398  }399}400 401void NativeProcessLinux::Manager::CollectThread(::pid_t tid) {402  Log *log = GetLog(POSIXLog::Process);403 404  if (m_unowned_threads.erase(tid))405    return; // We've encountered this thread already.406 407  // The TID is not tracked yet, let's wait for it to appear.408  int status = -1;409  LLDB_LOG(log,410           "received clone event for tid {0}. tid not tracked yet, "411           "waiting for it to appear...",412           tid);413  ::pid_t wait_pid =414      llvm::sys::RetryAfterSignal(-1, ::waitpid, tid, &status, __WALL);415 416  // It's theoretically possible to get other events if the entire process was417  // SIGKILLed before we got a chance to check this. In that case, we'll just418  // clean everything up when we get the process exit event.419 420  LLDB_LOG(log,421           "waitpid({0}, &status, __WALL) => {1} (errno: {2}, status = {3})",422           tid, wait_pid, errno, WaitStatus::Decode(status));423}424 425// Public Instance Methods426 427NativeProcessLinux::NativeProcessLinux(::pid_t pid, int terminal_fd,428                                       NativeDelegate &delegate,429                                       const ArchSpec &arch, Manager &manager,430                                       llvm::ArrayRef<::pid_t> tids)431    : NativeProcessELF(pid, terminal_fd, delegate), m_manager(manager),432      m_arch(arch), m_intel_pt_collector(*this) {433  manager.AddProcess(*this);434  if (m_terminal_fd != -1) {435    Status status = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);436    assert(status.Success());437  }438 439  for (const auto &tid : tids) {440    NativeThreadLinux &thread = AddThread(tid, /*resume*/ false);441    ThreadWasCreated(thread);442  }443 444  // Let our process instance know the thread has stopped.445  SetCurrentThreadID(tids[0]);446  SetState(StateType::eStateStopped, false);447}448 449llvm::Expected<std::vector<::pid_t>> NativeProcessLinux::Attach(::pid_t pid) {450  Log *log = GetLog(POSIXLog::Process);451 452  Status status;453  // Use a map to keep track of the threads which we have attached/need to454  // attach.455  Host::TidMap tids_to_attach;456  while (Host::FindProcessThreads(pid, tids_to_attach)) {457    for (Host::TidMap::iterator it = tids_to_attach.begin();458         it != tids_to_attach.end();) {459      if (it->second == false) {460        lldb::tid_t tid = it->first;461 462        // Attach to the requested process.463        // An attach will cause the thread to stop with a SIGSTOP.464        if ((status = PtraceWrapper(PTRACE_ATTACH, tid)).Fail()) {465          // No such thread. The thread may have exited. More error handling466          // may be needed.467          if (status.GetError() == ESRCH) {468            it = tids_to_attach.erase(it);469            continue;470          }471          if (status.GetError() == EPERM) {472            // Depending on the value of ptrace_scope, we can return a different473            // error that suggests how to fix it.474            return AddPtraceScopeNote(status.ToError());475          }476          return status.ToError();477        }478 479        int wpid =480            llvm::sys::RetryAfterSignal(-1, ::waitpid, tid, nullptr, __WALL);481        // Need to use __WALL otherwise we receive an error with errno=ECHLD At482        // this point we should have a thread stopped if waitpid succeeds.483        if (wpid < 0) {484          // No such thread. The thread may have exited. More error handling485          // may be needed.486          if (errno == ESRCH) {487            it = tids_to_attach.erase(it);488            continue;489          }490          return llvm::errorCodeToError(491              std::error_code(errno, std::generic_category()));492        }493 494        if ((status = SetDefaultPtraceOpts(tid)).Fail())495          return status.ToError();496 497        LLDB_LOG(log, "adding tid = {0}", tid);498        it->second = true;499      }500 501      // move the loop forward502      ++it;503    }504  }505 506  size_t tid_count = tids_to_attach.size();507  if (tid_count == 0)508    return llvm::make_error<StringError>("No such process",509                                         llvm::inconvertibleErrorCode());510 511  std::vector<::pid_t> tids;512  tids.reserve(tid_count);513  for (const auto &p : tids_to_attach)514    tids.push_back(p.first);515  return std::move(tids);516}517 518Status NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid) {519  long ptrace_opts = 0;520 521  // Have the child raise an event on exit.  This is used to keep the child in522  // limbo until it is destroyed.523  ptrace_opts |= PTRACE_O_TRACEEXIT;524 525  // Have the tracer trace threads which spawn in the inferior process.526  ptrace_opts |= PTRACE_O_TRACECLONE;527 528  // Have the tracer notify us before execve returns (needed to disable legacy529  // SIGTRAP generation)530  ptrace_opts |= PTRACE_O_TRACEEXEC;531 532  // Have the tracer trace forked children.533  ptrace_opts |= PTRACE_O_TRACEFORK;534 535  // Have the tracer trace vforks.536  ptrace_opts |= PTRACE_O_TRACEVFORK;537 538  // Have the tracer trace vfork-done in order to restore breakpoints after539  // the child finishes sharing memory.540  ptrace_opts |= PTRACE_O_TRACEVFORKDONE;541 542  return PtraceWrapper(PTRACE_SETOPTIONS, pid, nullptr, (void *)ptrace_opts);543}544 545bool NativeProcessLinux::TryHandleWaitStatus(lldb::pid_t pid,546                                             WaitStatus status) {547  if (pid == GetID() &&548      (status.type == WaitStatus::Exit || status.type == WaitStatus::Signal)) {549    // The process exited.  We're done monitoring.  Report to delegate.550    SetExitStatus(status, true);551    return true;552  }553  if (NativeThreadLinux *thread = GetThreadByID(pid)) {554    MonitorCallback(*thread, status);555    return true;556  }557  return false;558}559 560void NativeProcessLinux::MonitorCallback(NativeThreadLinux &thread,561                                         WaitStatus status) {562  Log *log = GetLog(LLDBLog::Process);563 564  // Certain activities differ based on whether the pid is the tid of the main565  // thread.566  const bool is_main_thread = (thread.GetID() == GetID());567 568  // Handle when the thread exits.569  if (status.type == WaitStatus::Exit || status.type == WaitStatus::Signal) {570    LLDB_LOG(log,571             "got exit status({0}) , tid = {1} ({2} main thread), process "572             "state = {3}",573             status, thread.GetID(), is_main_thread ? "is" : "is not",574             GetState());575 576    // This is a thread that exited.  Ensure we're not tracking it anymore.577    StopTrackingThread(thread);578 579    assert(!is_main_thread && "Main thread exits handled elsewhere");580    return;581  }582 583  siginfo_t info;584  const auto info_err = GetSignalInfo(thread.GetID(), &info);585 586  // Get details on the signal raised.587  if (info_err.Success()) {588    // We have retrieved the signal info.  Dispatch appropriately.589    if (info.si_signo == SIGTRAP)590      MonitorSIGTRAP(info, thread);591    else592      MonitorSignal(info, thread);593  } else {594    if (info_err.GetError() == EINVAL) {595      // This is a group stop reception for this tid. We can reach here if we596      // reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU into the tracee,597      // triggering the group-stop mechanism. Normally receiving these would598      // stop the process, pending a SIGCONT. Simulating this state in a599      // debugger is hard and is generally not needed (one use case is600      // debugging background task being managed by a shell). For general use,601      // it is sufficient to stop the process in a signal-delivery stop which602      // happens before the group stop. This done by MonitorSignal and works603      // correctly for all signals.604      LLDB_LOG(log,605               "received a group stop for pid {0} tid {1}. Transparent "606               "handling of group stops not supported, resuming the "607               "thread.",608               GetID(), thread.GetID());609      ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);610    } else {611      // ptrace(GETSIGINFO) failed (but not due to group-stop).612 613      // A return value of ESRCH means the thread/process has died in the mean614      // time. This can (e.g.) happen when another thread does an exit_group(2)615      // or the entire process get SIGKILLed.616      // We can't do anything with this thread anymore, but we keep it around617      // until we get the WIFEXITED event.618 619      LLDB_LOG(log,620               "GetSignalInfo({0}) failed: {1}, status = {2}, main_thread = "621               "{3}. Expecting WIFEXITED soon.",622               thread.GetID(), info_err, status, is_main_thread);623    }624  }625}626 627void NativeProcessLinux::MonitorSIGTRAP(const siginfo_t &info,628                                        NativeThreadLinux &thread) {629  Log *log = GetLog(POSIXLog::Process);630  const bool is_main_thread = (thread.GetID() == GetID());631 632  assert(info.si_signo == SIGTRAP && "Unexpected child signal!");633 634  switch (info.si_code) {635  case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):636  case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):637  case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)): {638    // This can either mean a new thread or a new process spawned via639    // clone(2) without SIGCHLD or CLONE_VFORK flag.  Note that clone(2)640    // can also cause PTRACE_EVENT_FORK and PTRACE_EVENT_VFORK if one641    // of these flags are passed.642 643    unsigned long event_message = 0;644    if (GetEventMessage(thread.GetID(), &event_message).Fail()) {645      LLDB_LOG(log,646               "pid {0} received clone() event but GetEventMessage failed "647               "so we don't know the new pid/tid",648               thread.GetID());649      ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);650    } else {651      MonitorClone(thread, event_message, info.si_code >> 8);652    }653 654    break;655  }656 657  case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)): {658    LLDB_LOG(log, "received exec event, code = {0}", info.si_code ^ SIGTRAP);659 660    // Exec clears any pending notifications.661    m_pending_notification_tid = LLDB_INVALID_THREAD_ID;662 663    // Remove all but the main thread here.  Linux fork creates a new process664    // which only copies the main thread.665    LLDB_LOG(log, "exec received, stop tracking all but main thread");666 667    llvm::erase_if(m_threads, [&](std::unique_ptr<NativeThreadProtocol> &t) {668      return t->GetID() != GetID();669    });670    assert(m_threads.size() == 1);671    auto *main_thread = static_cast<NativeThreadLinux *>(m_threads[0].get());672 673    SetCurrentThreadID(main_thread->GetID());674    main_thread->SetStoppedByExec();675 676    // Tell coordinator about the "new" (since exec) stopped main thread.677    ThreadWasCreated(*main_thread);678 679    // Let our delegate know we have just exec'd.680    NotifyDidExec();681 682    // Let the process know we're stopped.683    StopRunningThreads(main_thread->GetID());684 685    break;686  }687 688  case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)): {689    // The inferior process or one of its threads is about to exit. We don't690    // want to do anything with the thread so we just resume it. In case we691    // want to implement "break on thread exit" functionality, we would need to692    // stop here.693 694    unsigned long data = 0;695    if (GetEventMessage(thread.GetID(), &data).Fail())696      data = -1;697 698    LLDB_LOG(log,699             "received PTRACE_EVENT_EXIT, data = {0:x}, WIFEXITED={1}, "700             "WIFSIGNALED={2}, pid = {3}, main_thread = {4}",701             data, WIFEXITED(data), WIFSIGNALED(data), thread.GetID(),702             is_main_thread);703 704 705    StateType state = thread.GetState();706    if (!StateIsRunningState(state)) {707      // Due to a kernel bug, we may sometimes get this stop after the inferior708      // gets a SIGKILL. This confuses our state tracking logic in709      // ResumeThread(), since normally, we should not be receiving any ptrace710      // events while the inferior is stopped. This makes sure that the711      // inferior is resumed and exits normally.712      state = eStateRunning;713    }714    ResumeThread(thread, state, LLDB_INVALID_SIGNAL_NUMBER);715 716    if (is_main_thread) {717      // Main thread report the read (WIFEXITED) event only after all threads in718      // the process exit, so we need to stop tracking it here instead of in719      // MonitorCallback720      StopTrackingThread(thread);721    }722 723    break;724  }725 726  case (SIGTRAP | (PTRACE_EVENT_VFORK_DONE << 8)): {727    if (bool(m_enabled_extensions & Extension::vfork)) {728      thread.SetStoppedByVForkDone();729      StopRunningThreads(thread.GetID());730    }731    else732      ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);733    break;734  }735 736  case 0:737  case TRAP_TRACE:  // We receive this on single stepping.738  case TRAP_HWBKPT: // We receive this on watchpoint hit739  {740    // If a watchpoint was hit, report it741    uint32_t wp_index;742    Status error = thread.GetRegisterContext().GetWatchpointHitIndex(743        wp_index, (uintptr_t)info.si_addr);744    if (error.Fail())745      LLDB_LOG(log,746               "received error while checking for watchpoint hits, pid = "747               "{0}, error = {1}",748               thread.GetID(), error);749    if (wp_index != LLDB_INVALID_INDEX32) {750      MonitorWatchpoint(thread, wp_index);751      break;752    }753 754    // If a breakpoint was hit, report it755    uint32_t bp_index;756    error = thread.GetRegisterContext().GetHardwareBreakHitIndex(757        bp_index, (uintptr_t)info.si_addr);758    if (error.Fail())759      LLDB_LOG(log, "received error while checking for hardware "760                    "breakpoint hits, pid = {0}, error = {1}",761               thread.GetID(), error);762    if (bp_index != LLDB_INVALID_INDEX32) {763      MonitorBreakpoint(thread);764      break;765    }766 767    // Otherwise, report step over768    MonitorTrace(thread);769    break;770  }771 772  case SI_KERNEL:773#if defined __mips__774    // For mips there is no special signal for watchpoint So we check for775    // watchpoint in kernel trap776    {777      // If a watchpoint was hit, report it778      uint32_t wp_index;779      Status error = thread.GetRegisterContext().GetWatchpointHitIndex(780          wp_index, LLDB_INVALID_ADDRESS);781      if (error.Fail())782        LLDB_LOG(log,783                 "received error while checking for watchpoint hits, pid = "784                 "{0}, error = {1}",785                 thread.GetID(), error);786      if (wp_index != LLDB_INVALID_INDEX32) {787        MonitorWatchpoint(thread, wp_index);788        break;789      }790    }791// NO BREAK792#endif793  case TRAP_BRKPT:794    MonitorBreakpoint(thread);795    break;796 797  case SIGTRAP:798  case (SIGTRAP | 0x80):799    LLDB_LOG(800        log,801        "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}, resuming",802        info.si_code, GetID(), thread.GetID());803 804    // Ignore these signals until we know more about them.805    ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);806    break;807 808  default:809    LLDB_LOG(log, "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}",810             info.si_code, GetID(), thread.GetID());811    MonitorSignal(info, thread);812    break;813  }814}815 816void NativeProcessLinux::MonitorTrace(NativeThreadLinux &thread) {817  Log *log = GetLog(POSIXLog::Process);818  LLDB_LOG(log, "received trace event, pid = {0}", thread.GetID());819 820  // This thread is currently stopped.821  thread.SetStoppedByTrace();822 823  StopRunningThreads(thread.GetID());824}825 826void NativeProcessLinux::MonitorBreakpoint(NativeThreadLinux &thread) {827  Log *log = GetLog(LLDBLog::Process | LLDBLog::Breakpoints);828  LLDB_LOG(log, "received breakpoint event, pid = {0}", thread.GetID());829 830  // Mark the thread as stopped at breakpoint.831  thread.SetStoppedByBreakpoint();832  FixupBreakpointPCAsNeeded(thread);833 834  NativeRegisterContextLinux &reg_ctx = thread.GetRegisterContext();835  auto stepping_with_bp_it =836      m_threads_stepping_with_breakpoint.find(thread.GetID());837  if (stepping_with_bp_it != m_threads_stepping_with_breakpoint.end() &&838      llvm::is_contained(stepping_with_bp_it->second, reg_ctx.GetPC()))839    thread.SetStoppedByTrace();840 841  StopRunningThreads(thread.GetID());842}843 844void NativeProcessLinux::MonitorWatchpoint(NativeThreadLinux &thread,845                                           uint32_t wp_index) {846  Log *log = GetLog(LLDBLog::Process | LLDBLog::Watchpoints);847  LLDB_LOG(log, "received watchpoint event, pid = {0}, wp_index = {1}",848           thread.GetID(), wp_index);849 850  // Mark the thread as stopped at watchpoint. The address is at851  // (lldb::addr_t)info->si_addr if we need it.852  thread.SetStoppedByWatchpoint(wp_index);853 854  // We need to tell all other running threads before we notify the delegate855  // about this stop.856  StopRunningThreads(thread.GetID());857}858 859void NativeProcessLinux::MonitorSignal(const siginfo_t &info,860                                       NativeThreadLinux &thread) {861  const int signo = info.si_signo;862  const bool is_from_llgs = info.si_pid == getpid();863 864  Log *log = GetLog(POSIXLog::Process);865 866  // POSIX says that process behaviour is undefined after it ignores a SIGFPE,867  // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a kill(2)868  // or raise(3).  Similarly for tgkill(2) on Linux.869  //870  // IOW, user generated signals never generate what we consider to be a871  // "crash".872  //873  // Similarly, ACK signals generated by this monitor.874 875  // Handle the signal.876  LLDB_LOG(log,877           "received signal {0} ({1}) with code {2}, (siginfo pid = {3}, "878           "waitpid pid = {4})",879           Host::GetSignalAsCString(signo), signo, info.si_code, info.si_pid,880           thread.GetID());881 882  // Check for thread stop notification.883  if (is_from_llgs && (info.si_code == SI_TKILL) && (signo == SIGSTOP)) {884    // This is a tgkill()-based stop.885    LLDB_LOG(log, "pid {0} tid {1}, thread stopped", GetID(), thread.GetID());886 887    // Check that we're not already marked with a stop reason. Note this thread888    // really shouldn't already be marked as stopped - if we were, that would889    // imply that the kernel signaled us with the thread stopping which we890    // handled and marked as stopped, and that, without an intervening resume,891    // we received another stop.  It is more likely that we are missing the892    // marking of a run state somewhere if we find that the thread was marked893    // as stopped.894    const StateType thread_state = thread.GetState();895    if (!StateIsStoppedState(thread_state, false)) {896      // An inferior thread has stopped because of a SIGSTOP we have sent it.897      // Generally, these are not important stops and we don't want to report898      // them as they are just used to stop other threads when one thread (the899      // one with the *real* stop reason) hits a breakpoint (watchpoint,900      // etc...). However, in the case of an asynchronous Interrupt(), this901      // *is* the real stop reason, so we leave the signal intact if this is902      // the thread that was chosen as the triggering thread.903      if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) {904        if (m_pending_notification_tid == thread.GetID())905          thread.SetStoppedBySignal(SIGSTOP, &info);906        else907          thread.SetStoppedWithNoReason();908 909        SetCurrentThreadID(thread.GetID());910        SignalIfAllThreadsStopped();911      } else {912        // We can end up here if stop was initiated by LLGS but by this time a913        // thread stop has occurred - maybe initiated by another event.914        Status error = ResumeThread(thread, thread.GetState(), 0);915        if (error.Fail())916          LLDB_LOG(log, "failed to resume thread {0}: {1}", thread.GetID(),917                   error);918      }919    } else {920      LLDB_LOG(log,921               "pid {0} tid {1}, thread was already marked as a stopped "922               "state (state={2}), leaving stop signal as is",923               GetID(), thread.GetID(), thread_state);924      SignalIfAllThreadsStopped();925    }926 927    // Done handling.928    return;929  }930 931  // Check if debugger should stop at this signal or just ignore it and resume932  // the inferior.933  if (m_signals_to_ignore.contains(signo)) {934     ResumeThread(thread, thread.GetState(), signo);935     return;936  }937 938  // This thread is stopped.939  LLDB_LOG(log, "received signal {0}", Host::GetSignalAsCString(signo));940  thread.SetStoppedBySignal(signo, &info);941 942  // Send a stop to the debugger after we get all other threads to stop.943  StopRunningThreads(thread.GetID());944}945 946bool NativeProcessLinux::MonitorClone(NativeThreadLinux &parent,947                                      lldb::pid_t child_pid, int event) {948  Log *log = GetLog(POSIXLog::Process);949  LLDB_LOG(log, "parent_tid={0}, child_pid={1}, event={2}", parent.GetID(),950           child_pid, event);951 952  m_manager.CollectThread(child_pid);953 954  switch (event) {955  case PTRACE_EVENT_CLONE: {956    // PTRACE_EVENT_CLONE can either mean a new thread or a new process.957    // Try to grab the new process' PGID to figure out which one it is.958    // If PGID is the same as the PID, then it's a new process.  Otherwise,959    // it's a thread.960    auto tgid_ret = getPIDForTID(child_pid);961    if (tgid_ret != child_pid) {962      // A new thread should have PGID matching our process' PID.963      assert(!tgid_ret || *tgid_ret == GetID());964 965      NativeThreadLinux &child_thread = AddThread(child_pid, /*resume*/ true);966      ThreadWasCreated(child_thread);967 968      // Resume the parent.969      ResumeThread(parent, parent.GetState(), LLDB_INVALID_SIGNAL_NUMBER);970      break;971    }972  }973    [[fallthrough]];974  case PTRACE_EVENT_FORK:975  case PTRACE_EVENT_VFORK: {976    bool is_vfork = event == PTRACE_EVENT_VFORK;977    std::unique_ptr<NativeProcessLinux> child_process{new NativeProcessLinux(978        static_cast<::pid_t>(child_pid), m_terminal_fd, m_delegate, m_arch,979        m_manager, {static_cast<::pid_t>(child_pid)})};980    if (!is_vfork)981      child_process->m_software_breakpoints = m_software_breakpoints;982 983    Extension expected_ext = is_vfork ? Extension::vfork : Extension::fork;984    if (bool(m_enabled_extensions & expected_ext)) {985      m_delegate.NewSubprocess(this, std::move(child_process));986      // NB: non-vfork clone() is reported as fork987      parent.SetStoppedByFork(is_vfork, child_pid);988      StopRunningThreads(parent.GetID());989    } else {990      child_process->Detach();991      ResumeThread(parent, parent.GetState(), LLDB_INVALID_SIGNAL_NUMBER);992    }993    break;994  }995  default:996    llvm_unreachable("unknown clone_info.event");997  }998 999  return true;1000}1001 1002bool NativeProcessLinux::SupportHardwareSingleStepping() const {1003  if (m_arch.IsMIPS() || m_arch.GetMachine() == llvm::Triple::arm ||1004      m_arch.GetTriple().isRISCV() || m_arch.GetTriple().isLoongArch())1005    return false;1006  return true;1007}1008 1009Status NativeProcessLinux::Resume(const ResumeActionList &resume_actions) {1010  Log *log = GetLog(POSIXLog::Process);1011  LLDB_LOG(log, "pid {0}", GetID());1012 1013  NotifyTracersProcessWillResume();1014 1015  bool software_single_step = !SupportHardwareSingleStepping();1016 1017  if (software_single_step) {1018    for (const auto &thread : m_threads) {1019      assert(thread && "thread list should not contain NULL threads");1020 1021      const ResumeAction *const action =1022          resume_actions.GetActionForThread(thread->GetID(), true);1023      if (action == nullptr)1024        continue;1025 1026      if (action->state == eStateStepping) {1027        Status error = SetupSoftwareSingleStepping(1028            static_cast<NativeThreadLinux &>(*thread));1029        if (error.Fail())1030          return error;1031      }1032    }1033  }1034 1035  for (const auto &thread : m_threads) {1036    assert(thread && "thread list should not contain NULL threads");1037 1038    const ResumeAction *const action =1039        resume_actions.GetActionForThread(thread->GetID(), true);1040 1041    if (action == nullptr) {1042      LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(),1043               thread->GetID());1044      continue;1045    }1046 1047    LLDB_LOG(log, "processing resume action state {0} for pid {1} tid {2}",1048             action->state, GetID(), thread->GetID());1049 1050    switch (action->state) {1051    case eStateRunning:1052    case eStateStepping: {1053      // Run the thread, possibly feeding it the signal.1054      const int signo = action->signal;1055      Status error = ResumeThread(static_cast<NativeThreadLinux &>(*thread),1056                                  action->state, signo);1057      if (error.Fail())1058        return Status::FromErrorStringWithFormat(1059            "NativeProcessLinux::%s: failed to resume thread "1060            "for pid %" PRIu64 ", tid %" PRIu64 ", error = %s",1061            __FUNCTION__, GetID(), thread->GetID(), error.AsCString());1062 1063      break;1064    }1065 1066    case eStateSuspended:1067    case eStateStopped:1068      break;1069 1070    default:1071      return Status::FromErrorStringWithFormat(1072          "NativeProcessLinux::%s (): unexpected state %s specified "1073          "for pid %" PRIu64 ", tid %" PRIu64,1074          __FUNCTION__, StateAsCString(action->state), GetID(),1075          thread->GetID());1076    }1077  }1078 1079  return Status();1080}1081 1082Status NativeProcessLinux::Halt() {1083  Status error;1084 1085  if (kill(GetID(), SIGSTOP) != 0)1086    error = Status::FromErrno();1087 1088  return error;1089}1090 1091Status NativeProcessLinux::Detach() {1092  Status error;1093 1094  // Tell ptrace to detach from the process.1095  if (GetID() == LLDB_INVALID_PROCESS_ID)1096    return error;1097 1098  // Cancel out any SIGSTOPs we may have sent while stopping the process.1099  // Otherwise, the process may stop as soon as we detach from it.1100  kill(GetID(), SIGCONT);1101 1102  for (const auto &thread : m_threads) {1103    Status e = Detach(thread->GetID());1104     // Save the error, but still attempt to detach from other threads.1105    if (e.Fail())1106      error = e.Clone();1107  }1108 1109  m_intel_pt_collector.Clear();1110 1111  return error;1112}1113 1114Status NativeProcessLinux::Signal(int signo) {1115  Status error;1116 1117  Log *log = GetLog(POSIXLog::Process);1118  LLDB_LOG(log, "sending signal {0} ({1}) to pid {1}", signo,1119           Host::GetSignalAsCString(signo), GetID());1120 1121  if (kill(GetID(), signo))1122    error = Status::FromErrno();1123 1124  return error;1125}1126 1127Status NativeProcessLinux::Interrupt() {1128  // Pick a running thread (or if none, a not-dead stopped thread) as the1129  // chosen thread that will be the stop-reason thread.1130  Log *log = GetLog(POSIXLog::Process);1131 1132  NativeThreadProtocol *running_thread = nullptr;1133  NativeThreadProtocol *stopped_thread = nullptr;1134 1135  LLDB_LOG(log, "selecting running thread for interrupt target");1136  for (const auto &thread : m_threads) {1137    // If we have a running or stepping thread, we'll call that the target of1138    // the interrupt.1139    const auto thread_state = thread->GetState();1140    if (thread_state == eStateRunning || thread_state == eStateStepping) {1141      running_thread = thread.get();1142      break;1143    } else if (!stopped_thread && StateIsStoppedState(thread_state, true)) {1144      // Remember the first non-dead stopped thread.  We'll use that as a1145      // backup if there are no running threads.1146      stopped_thread = thread.get();1147    }1148  }1149 1150  if (!running_thread && !stopped_thread) {1151    Status error("found no running/stepping or live stopped threads as target "1152                 "for interrupt");1153    LLDB_LOG(log, "skipping due to error: {0}", error);1154 1155    return error;1156  }1157 1158  NativeThreadProtocol *deferred_signal_thread =1159      running_thread ? running_thread : stopped_thread;1160 1161  LLDB_LOG(log, "pid {0} {1} tid {2} chosen for interrupt target", GetID(),1162           running_thread ? "running" : "stopped",1163           deferred_signal_thread->GetID());1164 1165  StopRunningThreads(deferred_signal_thread->GetID());1166 1167  return Status();1168}1169 1170Status NativeProcessLinux::Kill() {1171  Log *log = GetLog(POSIXLog::Process);1172  LLDB_LOG(log, "pid {0}", GetID());1173 1174  Status error;1175 1176  switch (m_state) {1177  case StateType::eStateInvalid:1178  case StateType::eStateExited:1179  case StateType::eStateCrashed:1180  case StateType::eStateDetached:1181  case StateType::eStateUnloaded:1182    // Nothing to do - the process is already dead.1183    LLDB_LOG(log, "ignored for PID {0} due to current state: {1}", GetID(),1184             m_state);1185    return error;1186 1187  case StateType::eStateConnected:1188  case StateType::eStateAttaching:1189  case StateType::eStateLaunching:1190  case StateType::eStateStopped:1191  case StateType::eStateRunning:1192  case StateType::eStateStepping:1193  case StateType::eStateSuspended:1194    // We can try to kill a process in these states.1195    break;1196  }1197 1198  if (kill(GetID(), SIGKILL) != 0) {1199    error = Status::FromErrno();1200    return error;1201  }1202 1203  return error;1204}1205 1206Status NativeProcessLinux::GetMemoryRegionInfo(lldb::addr_t load_addr,1207                                               MemoryRegionInfo &range_info) {1208  // FIXME review that the final memory region returned extends to the end of1209  // the virtual address space,1210  // with no perms if it is not mapped.1211 1212  // Use an approach that reads memory regions from /proc/{pid}/maps. Assume1213  // proc maps entries are in ascending order.1214  // FIXME assert if we find differently.1215 1216  if (m_supports_mem_region == LazyBool::eLazyBoolNo) {1217    // We're done.1218    return Status::FromErrorString("unsupported");1219  }1220 1221  Status error = PopulateMemoryRegionCache();1222  if (error.Fail()) {1223    return error;1224  }1225 1226  lldb::addr_t prev_base_address = 0;1227 1228  // FIXME start by finding the last region that is <= target address using1229  // binary search.  Data is sorted.1230  // There can be a ton of regions on pthreads apps with lots of threads.1231  for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end();1232       ++it) {1233    MemoryRegionInfo &proc_entry_info = it->first;1234 1235    // Sanity check assumption that /proc/{pid}/maps entries are ascending.1236    assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) &&1237           "descending /proc/pid/maps entries detected, unexpected");1238    prev_base_address = proc_entry_info.GetRange().GetRangeBase();1239    UNUSED_IF_ASSERT_DISABLED(prev_base_address);1240 1241    // If the target address comes before this entry, indicate distance to next1242    // region.1243    if (load_addr < proc_entry_info.GetRange().GetRangeBase()) {1244      range_info.GetRange().SetRangeBase(load_addr);1245      range_info.GetRange().SetByteSize(1246          proc_entry_info.GetRange().GetRangeBase() - load_addr);1247      range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);1248      range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);1249      range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);1250      range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);1251 1252      return error;1253    } else if (proc_entry_info.GetRange().Contains(load_addr)) {1254      // The target address is within the memory region we're processing here.1255      range_info = proc_entry_info;1256      return error;1257    }1258 1259    // The target memory address comes somewhere after the region we just1260    // parsed.1261  }1262 1263  // If we made it here, we didn't find an entry that contained the given1264  // address. Return the load_addr as start and the amount of bytes betwwen1265  // load address and the end of the memory as size.1266  range_info.GetRange().SetRangeBase(load_addr);1267  range_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS);1268  range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);1269  range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);1270  range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);1271  range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);1272  return error;1273}1274 1275Status NativeProcessLinux::PopulateMemoryRegionCache() {1276  Log *log = GetLog(POSIXLog::Process);1277 1278  // If our cache is empty, pull the latest.  There should always be at least1279  // one memory region if memory region handling is supported.1280  if (!m_mem_region_cache.empty()) {1281    LLDB_LOG(log, "reusing {0} cached memory region entries",1282             m_mem_region_cache.size());1283    return Status();1284  }1285 1286  Status Result;1287  LinuxMapCallback callback = [&](llvm::Expected<MemoryRegionInfo> Info) {1288    if (Info) {1289      FileSpec file_spec(Info->GetName().GetCString());1290      FileSystem::Instance().Resolve(file_spec);1291      m_mem_region_cache.emplace_back(*Info, file_spec);1292      return true;1293    }1294 1295    Result = Status::FromError(Info.takeError());1296    m_supports_mem_region = LazyBool::eLazyBoolNo;1297    LLDB_LOG(log, "failed to parse proc maps: {0}", Result);1298    return false;1299  };1300 1301  // Linux kernel since 2.6.14 has /proc/{pid}/smaps1302  // if CONFIG_PROC_PAGE_MONITOR is enabled1303  auto BufferOrError = getProcFile(GetID(), GetCurrentThreadID(), "smaps");1304  if (BufferOrError)1305    ParseLinuxSMapRegions(BufferOrError.get()->getBuffer(), callback);1306  else {1307    BufferOrError = getProcFile(GetID(), GetCurrentThreadID(), "maps");1308    if (!BufferOrError) {1309      m_supports_mem_region = LazyBool::eLazyBoolNo;1310      return BufferOrError.getError();1311    }1312 1313    ParseLinuxMapRegions(BufferOrError.get()->getBuffer(), callback);1314  }1315 1316  if (Result.Fail())1317    return Result;1318 1319  if (m_mem_region_cache.empty()) {1320    // No entries after attempting to read them.  This shouldn't happen if1321    // /proc/{pid}/maps is supported. Assume we don't support map entries via1322    // procfs.1323    m_supports_mem_region = LazyBool::eLazyBoolNo;1324    LLDB_LOG(log,1325             "failed to find any procfs maps entries, assuming no support "1326             "for memory region metadata retrieval");1327    return Status::FromErrorString("not supported");1328  }1329 1330  LLDB_LOG(log, "read {0} memory region entries from /proc/{1}/maps",1331           m_mem_region_cache.size(), GetID());1332 1333  // We support memory retrieval, remember that.1334  m_supports_mem_region = LazyBool::eLazyBoolYes;1335  return Status();1336}1337 1338void NativeProcessLinux::DoStopIDBumped(uint32_t newBumpId) {1339  Log *log = GetLog(POSIXLog::Process);1340  LLDB_LOG(log, "newBumpId={0}", newBumpId);1341  LLDB_LOG(log, "clearing {0} entries from memory region cache",1342           m_mem_region_cache.size());1343  m_mem_region_cache.clear();1344}1345 1346llvm::Expected<uint64_t>1347NativeProcessLinux::Syscall(llvm::ArrayRef<uint64_t> args) {1348  PopulateMemoryRegionCache();1349  auto region_it = llvm::find_if(m_mem_region_cache, [](const auto &pair) {1350    return pair.first.GetExecutable() == MemoryRegionInfo::eYes &&1351        pair.first.GetShared() != MemoryRegionInfo::eYes;1352  });1353  if (region_it == m_mem_region_cache.end())1354    return llvm::createStringError(llvm::inconvertibleErrorCode(),1355                                   "No executable memory region found!");1356 1357  addr_t exe_addr = region_it->first.GetRange().GetRangeBase();1358 1359  NativeThreadLinux &thread = *GetCurrentThread();1360  assert(thread.GetState() == eStateStopped);1361  NativeRegisterContextLinux &reg_ctx = thread.GetRegisterContext();1362 1363  NativeRegisterContextLinux::SyscallData syscall_data =1364      *reg_ctx.GetSyscallData();1365 1366  WritableDataBufferSP registers_sp;1367  if (llvm::Error Err = reg_ctx.ReadAllRegisterValues(registers_sp).ToError())1368    return std::move(Err);1369  auto restore_regs = llvm::make_scope_exit(1370      [&] { reg_ctx.WriteAllRegisterValues(registers_sp); });1371 1372  llvm::SmallVector<uint8_t, 8> memory(syscall_data.Insn.size());1373  size_t bytes_read;1374  if (llvm::Error Err =1375          ReadMemory(exe_addr, memory.data(), memory.size(), bytes_read)1376              .ToError()) {1377    return std::move(Err);1378  }1379 1380  auto restore_mem = llvm::make_scope_exit(1381      [&] { WriteMemory(exe_addr, memory.data(), memory.size(), bytes_read); });1382 1383  if (llvm::Error Err = reg_ctx.SetPC(exe_addr).ToError())1384    return std::move(Err);1385 1386  for (const auto &zip : llvm::zip_first(args, syscall_data.Args)) {1387    if (llvm::Error Err =1388            reg_ctx1389                .WriteRegisterFromUnsigned(std::get<1>(zip), std::get<0>(zip))1390                .ToError()) {1391      return std::move(Err);1392    }1393  }1394  if (llvm::Error Err = WriteMemory(exe_addr, syscall_data.Insn.data(),1395                                    syscall_data.Insn.size(), bytes_read)1396                            .ToError())1397    return std::move(Err);1398 1399  m_mem_region_cache.clear();1400 1401  // With software single stepping the syscall insn buffer must also include a1402  // trap instruction to stop the process.1403  int req = SupportHardwareSingleStepping() ? PTRACE_SINGLESTEP : PTRACE_CONT;1404  if (llvm::Error Err =1405          PtraceWrapper(req, thread.GetID(), nullptr, nullptr).ToError())1406    return std::move(Err);1407 1408  int status;1409  ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, thread.GetID(),1410                                                 &status, __WALL);1411  if (wait_pid == -1) {1412    return llvm::errorCodeToError(1413        std::error_code(errno, std::generic_category()));1414  }1415  assert((unsigned)wait_pid == thread.GetID());1416 1417  uint64_t result = reg_ctx.ReadRegisterAsUnsigned(syscall_data.Result, -ESRCH);1418 1419  // Values larger than this are actually negative errno numbers.1420  uint64_t errno_threshold =1421      (uint64_t(-1) >> (64 - 8 * m_arch.GetAddressByteSize())) - 0x1000;1422  if (result > errno_threshold) {1423    return llvm::errorCodeToError(1424        std::error_code(-result & 0xfff, std::generic_category()));1425  }1426 1427  return result;1428}1429 1430llvm::Expected<addr_t>1431NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions) {1432 1433  std::optional<NativeRegisterContextLinux::MmapData> mmap_data =1434      GetCurrentThread()->GetRegisterContext().GetMmapData();1435  if (!mmap_data)1436    return llvm::make_error<UnimplementedError>();1437 1438  unsigned prot = PROT_NONE;1439  assert((permissions & (ePermissionsReadable | ePermissionsWritable |1440                         ePermissionsExecutable)) == permissions &&1441         "Unknown permission!");1442  if (permissions & ePermissionsReadable)1443    prot |= PROT_READ;1444  if (permissions & ePermissionsWritable)1445    prot |= PROT_WRITE;1446  if (permissions & ePermissionsExecutable)1447    prot |= PROT_EXEC;1448 1449  llvm::Expected<uint64_t> Result =1450      Syscall({mmap_data->SysMmap, 0, size, prot, MAP_ANONYMOUS | MAP_PRIVATE,1451               uint64_t(-1), 0});1452  if (Result)1453    m_allocated_memory.try_emplace(*Result, size);1454  return Result;1455}1456 1457llvm::Error NativeProcessLinux::DeallocateMemory(lldb::addr_t addr) {1458  std::optional<NativeRegisterContextLinux::MmapData> mmap_data =1459      GetCurrentThread()->GetRegisterContext().GetMmapData();1460  if (!mmap_data)1461    return llvm::make_error<UnimplementedError>();1462 1463  auto it = m_allocated_memory.find(addr);1464  if (it == m_allocated_memory.end())1465    return llvm::createStringError(llvm::errc::invalid_argument,1466                                   "Memory not allocated by the debugger.");1467 1468  llvm::Expected<uint64_t> Result =1469      Syscall({mmap_data->SysMunmap, addr, it->second});1470  if (!Result)1471    return Result.takeError();1472 1473  m_allocated_memory.erase(it);1474  return llvm::Error::success();1475}1476 1477Status NativeProcessLinux::ReadMemoryTags(int32_t type, lldb::addr_t addr,1478                                          size_t len,1479                                          std::vector<uint8_t> &tags) {1480  llvm::Expected<NativeRegisterContextLinux::MemoryTaggingDetails> details =1481      GetCurrentThread()->GetRegisterContext().GetMemoryTaggingDetails(type);1482  if (!details)1483    return Status::FromError(details.takeError());1484 1485  // Ignore 0 length read1486  if (!len)1487    return Status();1488 1489  // lldb will align the range it requests but it is not required to by1490  // the protocol so we'll do it again just in case.1491  // Remove tag bits too. Ptrace calls may work regardless but that1492  // is not a guarantee.1493  MemoryTagManager::TagRange range(details->manager->RemoveTagBits(addr), len);1494  range = details->manager->ExpandToGranule(range);1495 1496  // Allocate enough space for all tags to be read1497  size_t num_tags = range.GetByteSize() / details->manager->GetGranuleSize();1498  tags.resize(num_tags * details->manager->GetTagSizeInBytes());1499 1500  struct iovec tags_iovec;1501  uint8_t *dest = tags.data();1502  lldb::addr_t read_addr = range.GetRangeBase();1503 1504  // This call can return partial data so loop until we error or1505  // get all tags back.1506  while (num_tags) {1507    tags_iovec.iov_base = dest;1508    tags_iovec.iov_len = num_tags;1509 1510    Status error = NativeProcessLinux::PtraceWrapper(1511        details->ptrace_read_req, GetCurrentThreadID(),1512        reinterpret_cast<void *>(read_addr), static_cast<void *>(&tags_iovec),1513        0, nullptr);1514 1515    if (error.Fail()) {1516      // Discard partial reads1517      tags.resize(0);1518      return error;1519    }1520 1521    size_t tags_read = tags_iovec.iov_len;1522    assert(tags_read && (tags_read <= num_tags));1523 1524    dest += tags_read * details->manager->GetTagSizeInBytes();1525    read_addr += details->manager->GetGranuleSize() * tags_read;1526    num_tags -= tags_read;1527  }1528 1529  return Status();1530}1531 1532Status NativeProcessLinux::WriteMemoryTags(int32_t type, lldb::addr_t addr,1533                                           size_t len,1534                                           const std::vector<uint8_t> &tags) {1535  llvm::Expected<NativeRegisterContextLinux::MemoryTaggingDetails> details =1536      GetCurrentThread()->GetRegisterContext().GetMemoryTaggingDetails(type);1537  if (!details)1538    return Status::FromError(details.takeError());1539 1540  // Ignore 0 length write1541  if (!len)1542    return Status();1543 1544  // lldb will align the range it requests but it is not required to by1545  // the protocol so we'll do it again just in case.1546  // Remove tag bits too. Ptrace calls may work regardless but that1547  // is not a guarantee.1548  MemoryTagManager::TagRange range(details->manager->RemoveTagBits(addr), len);1549  range = details->manager->ExpandToGranule(range);1550 1551  // Not checking number of tags here, we may repeat them below1552  llvm::Expected<std::vector<lldb::addr_t>> unpacked_tags_or_err =1553      details->manager->UnpackTagsData(tags);1554  if (!unpacked_tags_or_err)1555    return Status::FromError(unpacked_tags_or_err.takeError());1556 1557  llvm::Expected<std::vector<lldb::addr_t>> repeated_tags_or_err =1558      details->manager->RepeatTagsForRange(*unpacked_tags_or_err, range);1559  if (!repeated_tags_or_err)1560    return Status::FromError(repeated_tags_or_err.takeError());1561 1562  // Repack them for ptrace to use1563  llvm::Expected<std::vector<uint8_t>> final_tag_data =1564      details->manager->PackTags(*repeated_tags_or_err);1565  if (!final_tag_data)1566    return Status::FromError(final_tag_data.takeError());1567 1568  struct iovec tags_vec;1569  uint8_t *src = final_tag_data->data();1570  lldb::addr_t write_addr = range.GetRangeBase();1571  // unpacked tags size because the number of bytes per tag might not be 11572  size_t num_tags = repeated_tags_or_err->size();1573 1574  // This call can partially write tags, so we loop until we1575  // error or all tags have been written.1576  while (num_tags > 0) {1577    tags_vec.iov_base = src;1578    tags_vec.iov_len = num_tags;1579 1580    Status error = NativeProcessLinux::PtraceWrapper(1581        details->ptrace_write_req, GetCurrentThreadID(),1582        reinterpret_cast<void *>(write_addr), static_cast<void *>(&tags_vec), 0,1583        nullptr);1584 1585    if (error.Fail()) {1586      // Don't attempt to restore the original values in the case of a partial1587      // write1588      return error;1589    }1590 1591    size_t tags_written = tags_vec.iov_len;1592    assert(tags_written && (tags_written <= num_tags));1593 1594    src += tags_written * details->manager->GetTagSizeInBytes();1595    write_addr += details->manager->GetGranuleSize() * tags_written;1596    num_tags -= tags_written;1597  }1598 1599  return Status();1600}1601 1602size_t NativeProcessLinux::UpdateThreads() {1603  // The NativeProcessLinux monitoring threads are always up to date with1604  // respect to thread state and they keep the thread list populated properly.1605  // All this method needs to do is return the thread count.1606  return m_threads.size();1607}1608 1609Status NativeProcessLinux::SetBreakpoint(lldb::addr_t addr, uint32_t size,1610                                         bool hardware) {1611  if (hardware)1612    return SetHardwareBreakpoint(addr, size);1613  else1614    return SetSoftwareBreakpoint(addr, size);1615}1616 1617Status NativeProcessLinux::RemoveBreakpoint(lldb::addr_t addr, bool hardware) {1618  if (hardware)1619    return RemoveHardwareBreakpoint(addr);1620  else1621    return NativeProcessProtocol::RemoveBreakpoint(addr);1622}1623 1624llvm::Expected<llvm::ArrayRef<uint8_t>>1625NativeProcessLinux::GetSoftwareBreakpointTrapOpcode(size_t size_hint) {1626  // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the1627  // linux kernel does otherwise.1628  static const uint8_t g_arm_opcode[] = {0xf0, 0x01, 0xf0, 0xe7};1629  static const uint8_t g_thumb_opcode[] = {0x01, 0xde};1630 1631  switch (GetArchitecture().GetMachine()) {1632  case llvm::Triple::arm:1633    switch (size_hint) {1634    case 2:1635      return llvm::ArrayRef(g_thumb_opcode);1636    case 4:1637      return llvm::ArrayRef(g_arm_opcode);1638    default:1639      return llvm::createStringError(llvm::inconvertibleErrorCode(),1640                                     "Unrecognised trap opcode size hint!");1641    }1642  default:1643    return NativeProcessProtocol::GetSoftwareBreakpointTrapOpcode(size_hint);1644  }1645}1646 1647Status NativeProcessLinux::ReadMemory(lldb::addr_t addr, void *buf, size_t size,1648                                      size_t &bytes_read) {1649  Log *log = GetLog(POSIXLog::Memory);1650  LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);1651 1652  bytes_read = 0;1653  if (ProcessVmReadvSupported()) {1654    // The process_vm_readv path is about 50 times faster than ptrace api. We1655    // want to use this syscall if it is supported.1656 1657    struct iovec local_iov, remote_iov;1658    local_iov.iov_base = buf;1659    local_iov.iov_len = size;1660    remote_iov.iov_base = reinterpret_cast<void *>(addr);1661    remote_iov.iov_len = size;1662 1663    ssize_t read_result = process_vm_readv(GetCurrentThreadID(), &local_iov, 1,1664                                           &remote_iov, 1, 0);1665    int error = 0;1666    if (read_result < 0)1667      error = errno;1668    else1669      bytes_read = read_result;1670 1671    LLDB_LOG(log,1672             "process_vm_readv({0}, [iovec({1}, {2})], [iovec({3:x}, {2})], 1, "1673             "0) => {4} ({5})",1674             GetCurrentThreadID(), buf, size, addr, read_result,1675             error > 0 ? llvm::sys::StrError(errno) : "sucesss");1676  }1677 1678  unsigned char *dst = static_cast<unsigned char *>(buf);1679  size_t remainder;1680  long data;1681 1682  for (; bytes_read < size; bytes_read += remainder) {1683    Status error = NativeProcessLinux::PtraceWrapper(1684        PTRACE_PEEKDATA, GetCurrentThreadID(),1685        reinterpret_cast<void *>(addr + bytes_read), nullptr, 0, &data);1686    if (error.Fail())1687      return error;1688 1689    remainder = size - bytes_read;1690    remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;1691 1692    // Copy the data into our buffer1693    memcpy(dst + bytes_read, &data, remainder);1694  }1695  return Status();1696}1697 1698Status NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf,1699                                       size_t size, size_t &bytes_written) {1700  const unsigned char *src = static_cast<const unsigned char *>(buf);1701  size_t remainder;1702  Status error;1703 1704  Log *log = GetLog(POSIXLog::Memory);1705  LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);1706 1707  for (bytes_written = 0; bytes_written < size; bytes_written += remainder) {1708    remainder = size - bytes_written;1709    remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;1710 1711    if (remainder == k_ptrace_word_size) {1712      unsigned long data = 0;1713      memcpy(&data, src, k_ptrace_word_size);1714 1715      LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data);1716      error = NativeProcessLinux::PtraceWrapper(1717          PTRACE_POKEDATA, GetCurrentThreadID(), (void *)addr, (void *)data);1718      if (error.Fail())1719        return error;1720    } else {1721      unsigned char buff[8];1722      size_t bytes_read;1723      error = ReadMemory(addr, buff, k_ptrace_word_size, bytes_read);1724      if (error.Fail())1725        return error;1726 1727      memcpy(buff, src, remainder);1728 1729      size_t bytes_written_rec;1730      error = WriteMemory(addr, buff, k_ptrace_word_size, bytes_written_rec);1731      if (error.Fail())1732        return error;1733 1734      LLDB_LOG(log, "[{0:x}]:{1:x} ({2:x})", addr, *(const unsigned long *)src,1735               *(unsigned long *)buff);1736    }1737 1738    addr += k_ptrace_word_size;1739    src += k_ptrace_word_size;1740  }1741  return error;1742}1743 1744Status NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo) const {1745  return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo);1746}1747 1748Status NativeProcessLinux::GetEventMessage(lldb::tid_t tid,1749                                           unsigned long *message) {1750  return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message);1751}1752 1753Status NativeProcessLinux::Detach(lldb::tid_t tid) {1754  if (tid == LLDB_INVALID_THREAD_ID)1755    return Status();1756 1757  return PtraceWrapper(PTRACE_DETACH, tid);1758}1759 1760bool NativeProcessLinux::HasThreadNoLock(lldb::tid_t thread_id) {1761  for (const auto &thread : m_threads) {1762    assert(thread && "thread list should not contain NULL threads");1763    if (thread->GetID() == thread_id) {1764      // We have this thread.1765      return true;1766    }1767  }1768 1769  // We don't have this thread.1770  return false;1771}1772 1773void NativeProcessLinux::StopTrackingThread(NativeThreadLinux &thread) {1774  Log *const log = GetLog(POSIXLog::Thread);1775  lldb::tid_t thread_id = thread.GetID();1776  LLDB_LOG(log, "tid: {0}", thread_id);1777 1778  auto it = llvm::find_if(m_threads, [&](const auto &thread_up) {1779    return thread_up.get() == &thread;1780  });1781  assert(it != m_threads.end());1782  m_threads.erase(it);1783 1784  NotifyTracersOfThreadDestroyed(thread_id);1785  SignalIfAllThreadsStopped();1786}1787 1788void NativeProcessLinux::NotifyTracersProcessDidStop() {1789  m_intel_pt_collector.ProcessDidStop();1790}1791 1792void NativeProcessLinux::NotifyTracersProcessWillResume() {1793  m_intel_pt_collector.ProcessWillResume();1794}1795 1796Status NativeProcessLinux::NotifyTracersOfNewThread(lldb::tid_t tid) {1797  Log *log = GetLog(POSIXLog::Thread);1798  Status error = Status::FromError(m_intel_pt_collector.OnThreadCreated(tid));1799  if (error.Fail())1800    LLDB_LOG(log, "Failed to trace a new thread with intel-pt, tid = {0}. {1}",1801             tid, error.AsCString());1802  return error;1803}1804 1805Status NativeProcessLinux::NotifyTracersOfThreadDestroyed(lldb::tid_t tid) {1806  Log *log = GetLog(POSIXLog::Thread);1807  Status error = Status::FromError(m_intel_pt_collector.OnThreadDestroyed(tid));1808  if (error.Fail())1809    LLDB_LOG(log,1810             "Failed to stop a destroyed thread with intel-pt, tid = {0}. {1}",1811             tid, error.AsCString());1812  return error;1813}1814 1815NativeThreadLinux &NativeProcessLinux::AddThread(lldb::tid_t thread_id,1816                                                 bool resume) {1817  Log *log = GetLog(POSIXLog::Thread);1818  LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id);1819 1820  assert(!HasThreadNoLock(thread_id) &&1821         "attempted to add a thread by id that already exists");1822 1823  // If this is the first thread, save it as the current thread1824  if (m_threads.empty())1825    SetCurrentThreadID(thread_id);1826 1827  m_threads.push_back(std::make_unique<NativeThreadLinux>(*this, thread_id));1828  NativeThreadLinux &thread =1829      static_cast<NativeThreadLinux &>(*m_threads.back());1830 1831  Status tracing_error = NotifyTracersOfNewThread(thread.GetID());1832  if (tracing_error.Fail()) {1833    thread.SetStoppedByProcessorTrace(tracing_error.AsCString());1834    StopRunningThreads(thread.GetID());1835  } else if (resume)1836    ResumeThread(thread, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);1837  else1838    thread.SetStoppedBySignal(SIGSTOP);1839 1840  return thread;1841}1842 1843Status NativeProcessLinux::GetLoadedModuleFileSpec(const char *module_path,1844                                                   FileSpec &file_spec) {1845  Status error = PopulateMemoryRegionCache();1846  if (error.Fail())1847    return error;1848 1849  FileSpec module_file_spec(module_path);1850  FileSystem::Instance().Resolve(module_file_spec);1851 1852  file_spec.Clear();1853  for (const auto &it : m_mem_region_cache) {1854    if (it.second.GetFilename() == module_file_spec.GetFilename()) {1855      file_spec = it.second;1856      return Status();1857    }1858  }1859  return Status::FromErrorStringWithFormat(1860      "Module file (%s) not found in /proc/%" PRIu64 "/maps file!",1861      module_file_spec.GetFilename().AsCString(), GetID());1862}1863 1864Status NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef &file_name,1865                                              lldb::addr_t &load_addr) {1866  load_addr = LLDB_INVALID_ADDRESS;1867  Status error = PopulateMemoryRegionCache();1868  if (error.Fail())1869    return error;1870 1871  FileSpec file(file_name);1872  for (const auto &it : m_mem_region_cache) {1873    if (it.second == file) {1874      load_addr = it.first.GetRange().GetRangeBase();1875      return Status();1876    }1877  }1878  return Status::FromErrorString("No load address found for specified file.");1879}1880 1881NativeThreadLinux *NativeProcessLinux::GetThreadByID(lldb::tid_t tid) {1882  return static_cast<NativeThreadLinux *>(1883      NativeProcessProtocol::GetThreadByID(tid));1884}1885 1886NativeThreadLinux *NativeProcessLinux::GetCurrentThread() {1887  return static_cast<NativeThreadLinux *>(1888      NativeProcessProtocol::GetCurrentThread());1889}1890 1891Status NativeProcessLinux::ResumeThread(NativeThreadLinux &thread,1892                                        lldb::StateType state, int signo) {1893  Log *const log = GetLog(POSIXLog::Thread);1894  LLDB_LOG(log, "tid: {0}", thread.GetID());1895 1896  // Before we do the resume below, first check if we have a pending stop1897  // notification that is currently waiting for all threads to stop.  This is1898  // potentially a buggy situation since we're ostensibly waiting for threads1899  // to stop before we send out the pending notification, and here we are1900  // resuming one before we send out the pending stop notification.1901  if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) {1902    LLDB_LOG(log,1903             "about to resume tid {0} per explicit request but we have a "1904             "pending stop notification (tid {1}) that is actively "1905             "waiting for this thread to stop. Valid sequence of events?",1906             thread.GetID(), m_pending_notification_tid);1907  }1908 1909  // Request a resume.  We expect this to be synchronous and the system to1910  // reflect it is running after this completes.1911  switch (state) {1912  case eStateRunning: {1913    Status resume_result = thread.Resume(signo);1914    if (resume_result.Success())1915      SetState(eStateRunning, true);1916    return resume_result;1917  }1918  case eStateStepping: {1919    Status step_result = thread.SingleStep(signo);1920    if (step_result.Success())1921      SetState(eStateRunning, true);1922    return step_result;1923  }1924  default:1925    LLDB_LOG(log, "Unhandled state {0}.", state);1926    llvm_unreachable("Unhandled state for resume");1927  }1928}1929 1930//===----------------------------------------------------------------------===//1931 1932void NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid) {1933  Log *const log = GetLog(POSIXLog::Thread);1934  LLDB_LOG(log, "about to process event: (triggering_tid: {0})",1935           triggering_tid);1936 1937  m_pending_notification_tid = triggering_tid;1938 1939  // Request a stop for all the thread stops that need to be stopped and are1940  // not already known to be stopped.1941  for (const auto &thread : m_threads) {1942    if (StateIsRunningState(thread->GetState()))1943      static_cast<NativeThreadLinux *>(thread.get())->RequestStop();1944  }1945 1946  SignalIfAllThreadsStopped();1947  LLDB_LOG(log, "event processing done");1948}1949 1950void NativeProcessLinux::SignalIfAllThreadsStopped() {1951  if (m_pending_notification_tid == LLDB_INVALID_THREAD_ID)1952    return; // No pending notification. Nothing to do.1953 1954  for (const auto &thread_sp : m_threads) {1955    if (StateIsRunningState(thread_sp->GetState()))1956      return; // Some threads are still running. Don't signal yet.1957  }1958 1959  // We have a pending notification and all threads have stopped.1960  Log *log = GetLog(LLDBLog::Process | LLDBLog::Breakpoints);1961 1962  // Clear any temporary breakpoints we used to implement software single1963  // stepping.1964  for (const auto &thread_info : m_threads_stepping_with_breakpoint) {1965    for (auto &&bp_addr : thread_info.second) {1966      Status error = RemoveBreakpoint(bp_addr);1967      if (error.Fail())1968        LLDB_LOG(log, "pid = {0} remove stepping breakpoint: {1}",1969                 thread_info.first, error);1970    }1971  }1972  m_threads_stepping_with_breakpoint.clear();1973 1974  // Notify the delegate about the stop1975  SetCurrentThreadID(m_pending_notification_tid);1976  SetState(StateType::eStateStopped, true);1977  m_pending_notification_tid = LLDB_INVALID_THREAD_ID;1978}1979 1980void NativeProcessLinux::ThreadWasCreated(NativeThreadLinux &thread) {1981  Log *const log = GetLog(POSIXLog::Thread);1982  LLDB_LOG(log, "tid: {0}", thread.GetID());1983 1984  if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID &&1985      StateIsRunningState(thread.GetState())) {1986    // We will need to wait for this new thread to stop as well before firing1987    // the notification.1988    thread.RequestStop();1989  }1990}1991 1992// Wrapper for ptrace to catch errors and log calls. Note that ptrace sets1993// errno on error because -1 can be a valid result (i.e. for PTRACE_PEEK*)1994Status NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr,1995                                         void *data, size_t data_size,1996                                         long *result) {1997  Status error;1998  long int ret;1999 2000  Log *log = GetLog(POSIXLog::Ptrace);2001 2002  PtraceDisplayBytes(req, data, data_size);2003 2004  errno = 0;2005  if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)2006    ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),2007                 *(unsigned int *)addr, data);2008  else2009    ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),2010                 addr, data);2011 2012  if (ret == -1)2013    error = Status::FromErrno();2014 2015  if (result)2016    *result = ret;2017 2018  LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3}, {4})={5:x}", req, pid, addr, data,2019           data_size, ret);2020 2021  PtraceDisplayBytes(req, data, data_size);2022 2023  if (error.Fail())2024    LLDB_LOG(log, "ptrace() failed: {0}", error);2025 2026  return error;2027}2028 2029llvm::Expected<TraceSupportedResponse> NativeProcessLinux::TraceSupported() {2030  if (IntelPTCollector::IsSupported())2031    return TraceSupportedResponse{"intel-pt", "Intel Processor Trace"};2032  return NativeProcessProtocol::TraceSupported();2033}2034 2035Error NativeProcessLinux::TraceStart(StringRef json_request, StringRef type) {2036  if (type == "intel-pt") {2037    if (Expected<TraceIntelPTStartRequest> request =2038            json::parse<TraceIntelPTStartRequest>(json_request,2039                                                  "TraceIntelPTStartRequest")) {2040      return m_intel_pt_collector.TraceStart(*request);2041    } else2042      return request.takeError();2043  }2044 2045  return NativeProcessProtocol::TraceStart(json_request, type);2046}2047 2048Error NativeProcessLinux::TraceStop(const TraceStopRequest &request) {2049  if (request.type == "intel-pt")2050    return m_intel_pt_collector.TraceStop(request);2051  return NativeProcessProtocol::TraceStop(request);2052}2053 2054Expected<json::Value> NativeProcessLinux::TraceGetState(StringRef type) {2055  if (type == "intel-pt")2056    return m_intel_pt_collector.GetState();2057  return NativeProcessProtocol::TraceGetState(type);2058}2059 2060Expected<std::vector<uint8_t>> NativeProcessLinux::TraceGetBinaryData(2061    const TraceGetBinaryDataRequest &request) {2062  if (request.type == "intel-pt")2063    return m_intel_pt_collector.GetBinaryData(request);2064  return NativeProcessProtocol::TraceGetBinaryData(request);2065}2066