blob: b2f6fad58a5756427c377ac7601769546502eb44 [file]
// Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/developer/debug/debug_agent/zircon_thread_handle.h"
#include <lib/zx/clock.h>
#include <zircon/syscalls/exception.h>
#include <algorithm>
#include <chrono>
#include <map>
#include "src/developer/debug/debug_agent/zircon_arch.h"
#include "src/developer/debug/debug_agent/zircon_suspend_handle.h"
#include "src/developer/debug/debug_agent/zircon_utils.h"
#include "src/developer/debug/shared/logging/logging.h"
#include "src/developer/debug/shared/zx_status.h"
namespace debug_agent {
namespace {
debug_ipc::ThreadRecord::BlockedReason ThreadStateBlockedReasonToEnum(uint32_t state) {
FX_DCHECK(ZX_THREAD_STATE_BASIC(state) == // NOLINT(bugprone-signed-bitwise)
ZX_THREAD_STATE_BLOCKED);
switch (state) {
case ZX_THREAD_STATE_BLOCKED_EXCEPTION:
return debug_ipc::ThreadRecord::BlockedReason::kException;
case ZX_THREAD_STATE_BLOCKED_SLEEPING:
return debug_ipc::ThreadRecord::BlockedReason::kSleeping;
case ZX_THREAD_STATE_BLOCKED_FUTEX:
return debug_ipc::ThreadRecord::BlockedReason::kFutex;
case ZX_THREAD_STATE_BLOCKED_PORT:
return debug_ipc::ThreadRecord::BlockedReason::kPort;
case ZX_THREAD_STATE_BLOCKED_CHANNEL:
return debug_ipc::ThreadRecord::BlockedReason::kChannel;
case ZX_THREAD_STATE_BLOCKED_WAIT_ONE:
return debug_ipc::ThreadRecord::BlockedReason::kWaitOne;
case ZX_THREAD_STATE_BLOCKED_WAIT_MANY:
return debug_ipc::ThreadRecord::BlockedReason::kWaitMany;
case ZX_THREAD_STATE_BLOCKED_INTERRUPT:
return debug_ipc::ThreadRecord::BlockedReason::kInterrupt;
case ZX_THREAD_STATE_BLOCKED_PAGER:
return debug_ipc::ThreadRecord::BlockedReason::kPager;
default:
FX_NOTREACHED();
return debug_ipc::ThreadRecord::BlockedReason::kNotBlocked;
}
}
ThreadHandle::State ThreadStateToEnums(uint32_t input) {
struct Mapping {
uint32_t int_state;
debug_ipc::ThreadRecord::State enum_state;
};
static const Mapping mappings[] = {
{.int_state = ZX_THREAD_STATE_NEW, .enum_state = debug_ipc::ThreadRecord::State::kNew},
{
.int_state = ZX_THREAD_STATE_RUNNING,
.enum_state = debug_ipc::ThreadRecord::State::kRunning,
},
{
.int_state = ZX_THREAD_STATE_SUSPENDED,
.enum_state = debug_ipc::ThreadRecord::State::kSuspended,
},
{
.int_state = ZX_THREAD_STATE_BLOCKED,
.enum_state = debug_ipc::ThreadRecord::State::kBlocked,
},
{.int_state = ZX_THREAD_STATE_DYING, .enum_state = debug_ipc::ThreadRecord::State::kDying},
{.int_state = ZX_THREAD_STATE_DEAD, .enum_state = debug_ipc::ThreadRecord::State::kDead},
};
const uint32_t basic_state = ZX_THREAD_STATE_BASIC(input); // NOLINT(bugprone-signed-bitwise)
for (const Mapping& mapping : mappings) {
if (mapping.int_state == basic_state) {
if (mapping.enum_state == debug_ipc::ThreadRecord::State::kBlocked)
return ThreadHandle::State(mapping.enum_state, ThreadStateBlockedReasonToEnum(input));
return ThreadHandle::State(mapping.enum_state);
}
}
return ThreadHandle::State(debug_ipc::ThreadRecord::State::kDead);
}
} // namespace
ZirconThreadHandle::ZirconThreadHandle(zx::thread t)
: thread_koid_(zircon::KoidForObject(t)), thread_(std::move(t)) {}
std::string ZirconThreadHandle::GetName() const { return zircon::NameForObject(thread_); }
ThreadHandle::State ZirconThreadHandle::GetState() const {
zx_info_thread info;
if (thread_.get_info(ZX_INFO_THREAD, &info, sizeof(info), nullptr, nullptr) == ZX_OK)
return ThreadStateToEnums(info.state);
return State(debug_ipc::ThreadRecord::State::kDead); // Assume failures mean the thread is dead.
}
bool ZirconThreadHandle::IsInThreadStartingException() const {
zx_exception_report_t report = {};
if (thread_.get_info(ZX_INFO_THREAD_EXCEPTION_REPORT, // NOLINT(bugprone-signed-bitwise)
&report, sizeof(report), nullptr, nullptr) != ZX_OK) {
return false;
}
return report.header.type == ZX_EXCP_THREAD_STARTING;
}
std::unique_ptr<SuspendHandle> ZirconThreadHandle::Suspend() {
zx::suspend_token token;
if (thread_.suspend(&token) != ZX_OK) {
return nullptr;
}
return std::make_unique<ZirconSuspendHandle>(std::move(token), thread_koid_,
ZirconSuspendHandle::TaskKind::kThread);
}
bool ZirconThreadHandle::WaitForSuspension(TickTimePoint deadline) const {
return WaitForSuspensionState(deadline, /*accept_exception=*/true);
}
bool ZirconThreadHandle::WaitForSuspensionSignal(TickTimePoint deadline) const {
return WaitForSuspensionState(deadline, /*accept_exception=*/false);
}
bool ZirconThreadHandle::WaitForSuspensionState(TickTimePoint deadline,
bool accept_exception) const {
auto is_desired_state = [accept_exception](const State& state) {
return state.state == debug_ipc::ThreadRecord::State::kSuspended ||
(accept_exception && state.is_blocked_on_exception());
};
// TickTimePoint uses steady_clock, which matches zircon's monotonic nanosecond timeline. Poll in
// short slices so a thread stuck in an exception or exit state doesn't stall the message loop for
// the full deadline, and re-verify GetState() because dying threads keep ZX_THREAD_SUSPENDED
// asserted until ZX_THREAD_TERMINATED.
const zx::time final_deadline(
std::chrono::duration_cast<std::chrono::nanoseconds>(deadline.time_since_epoch()).count());
constexpr zx::duration kPollInterval = zx::msec(10);
while (true) {
State state = GetState();
if (is_desired_state(state)) {
return true;
}
if (state.state == debug_ipc::ThreadRecord::State::kDying ||
state.state == debug_ipc::ThreadRecord::State::kDead) {
return false;
}
if (zx::clock::get_monotonic() >= final_deadline) {
return false;
}
zx::time slice_deadline = std::min(zx::deadline_after(kPollInterval), final_deadline);
zx_signals_t observed = 0;
zx_status_t status = thread_.wait_one(
ZX_THREAD_SUSPENDED | ZX_THREAD_TERMINATED, // NOLINT(bugprone-signed-bitwise)
slice_deadline, &observed);
if (status == ZX_OK && (observed & ZX_THREAD_TERMINATED)) { // NOLINT(bugprone-signed-bitwise)
return false;
}
if (status != ZX_ERR_TIMED_OUT || zx::clock::get_monotonic() >= final_deadline) {
return is_desired_state(GetState());
}
}
}
debug_ipc::ThreadRecord ZirconThreadHandle::GetThreadRecord(zx_koid_t process_koid) const {
debug_ipc::ThreadRecord record;
record.id = {.process = process_koid, .thread = thread_koid_};
// Name.
char name[ZX_MAX_NAME_LEN];
if (thread_.get_property(ZX_PROP_NAME, name, sizeof(name)) == ZX_OK)
record.name = name;
// State (running, blocked, etc.).
auto state = GetState();
record.state = state.state;
record.blocked_reason = state.blocked_reason;
return record;
}
std::optional<GeneralRegisters> ZirconThreadHandle::GetGeneralRegisters() const {
zx_thread_state_general_regs_t r;
if (thread_.read_state(ZX_THREAD_STATE_GENERAL_REGS, &r, sizeof(r)) == ZX_OK)
return GeneralRegisters(r);
return std::nullopt;
}
void ZirconThreadHandle::SetGeneralRegisters(const GeneralRegisters& regs) {
thread_.write_state(ZX_THREAD_STATE_GENERAL_REGS, &regs.GetNativeRegisters(),
sizeof(zx_thread_state_general_regs_t));
}
std::optional<DebugRegisters> ZirconThreadHandle::GetDebugRegisters() const {
zx_thread_state_debug_regs_t regs;
if (thread_.read_state(ZX_THREAD_STATE_DEBUG_REGS, &regs, sizeof(regs)) == ZX_OK)
return DebugRegisters(regs);
return std::nullopt;
}
bool ZirconThreadHandle::SetDebugRegisters(const DebugRegisters& regs) {
return thread_.write_state(ZX_THREAD_STATE_DEBUG_REGS, &regs.GetNativeRegisters(),
sizeof(zx_thread_state_debug_regs_t)) == ZX_OK;
}
void ZirconThreadHandle::SetSingleStep(bool single_step) {
zx_thread_state_single_step_t value = single_step ? 1 : 0;
// This could fail for legitimate reasons, like the process could have just closed the thread.
thread_.write_state(ZX_THREAD_STATE_SINGLE_STEP, &value, sizeof(value));
}
std::vector<debug::RegisterValue> ZirconThreadHandle::ReadRegisters(
const std::vector<debug::RegisterCategory>& cats_to_get) const {
std::vector<debug::RegisterValue> regs;
for (const auto& cat_type : cats_to_get)
arch::ReadRegisters(thread_, cat_type, regs);
return regs;
}
std::vector<debug::RegisterValue> ZirconThreadHandle::WriteRegisters(
const std::vector<debug::RegisterValue>& regs) {
std::vector<debug::RegisterValue> written;
// Figure out which registers will change.
std::map<debug::RegisterCategory, std::vector<debug::RegisterValue>> categories;
for (const debug::RegisterValue& reg : regs) {
auto cat_type = debug::RegisterIDToCategory(reg.id);
if (cat_type == debug::RegisterCategory::kNone) {
LOGS(Warn) << "Attempting to change register without category: "
<< debug::RegisterIDToString(reg.id);
continue;
}
categories[cat_type].push_back(reg);
}
for (const auto& [cat_type, cat_regs] : categories) {
FX_DCHECK(cat_type != debug::RegisterCategory::kNone);
if (auto res = arch::WriteRegisters(thread_, cat_type, cat_regs); res != ZX_OK) {
LOGS(Warn) << "Could not write category " << debug::RegisterCategoryToString(cat_type) << ": "
<< debug::ZxStatusToString(res);
}
if (auto res = arch::ReadRegisters(thread_, cat_type, written); res != ZX_OK) {
LOGS(Warn) << "Could not read category " << debug::RegisterCategoryToString(cat_type) << ": "
<< debug::ZxStatusToString(res);
}
}
return written;
}
bool ZirconThreadHandle::InstallHWBreakpoint(uint64_t address) {
std::optional<DebugRegisters> regs = GetDebugRegisters();
if (!regs)
return false;
DEBUG_LOG(Thread) << "Before installing HW breakpoint:\n" << regs->ToString();
if (!regs->SetHWBreakpoint(address))
return false;
DEBUG_LOG(Thread) << "After installing HW breakpoint:\n" << regs->ToString();
return SetDebugRegisters(*regs);
}
bool ZirconThreadHandle::UninstallHWBreakpoint(uint64_t address) {
std::optional<DebugRegisters> regs = GetDebugRegisters();
if (!regs)
return false;
DEBUG_LOG(Thread) << "Before uninstalling HW breakpoint:\n" << regs->ToString();
if (!regs->RemoveHWBreakpoint(address))
return false;
DEBUG_LOG(Thread) << "After uninstalling HW breakpoint:\n" << regs->ToString();
return SetDebugRegisters(*regs);
}
std::optional<WatchpointInfo> ZirconThreadHandle::InstallWatchpoint(
debug_ipc::BreakpointType type, const debug::AddressRange& range) {
if (!debug_ipc::IsWatchpointType(type))
return std::nullopt;
std::optional<DebugRegisters> regs = GetDebugRegisters();
if (!regs)
return std::nullopt;
DEBUG_LOG(Thread) << "Before installing watchpoint for range " << range.ToString() << '\n'
<< regs->ToString();
auto result = regs->SetWatchpoint(type, range, arch::GetHardwareWatchpointCount());
if (!result)
return std::nullopt;
DEBUG_LOG(Thread) << "After installing watchpoint:\n" << regs->ToString();
if (!SetDebugRegisters(*regs))
return std::nullopt;
return result;
}
bool ZirconThreadHandle::UninstallWatchpoint(const debug::AddressRange& range) {
std::optional<DebugRegisters> regs = GetDebugRegisters();
if (!regs)
return false;
DEBUG_LOG(Thread) << "Before uninstalling watchpoint:\n" << regs->ToString();
// x64 doesn't support ranges.
if (!regs->RemoveWatchpoint(range, arch::GetHardwareWatchpointCount()))
return false;
DEBUG_LOG(Thread) << "After uninstalling watchpoint:\n" << regs->ToString();
return SetDebugRegisters(*regs);
}
} // namespace debug_agent