blob: 400bbd59ef3134aec2b7ceba08bba0d34fbed96c [file]
// Copyright 2026 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/component/incoming/cpp/protocol.h>
#include <lib/fit/defer.h>
#include <lib/zx/channel.h>
#include <lib/zx/event.h>
#include <lib/zx/exception.h>
#include <lib/zx/process.h>
#include <lib/zx/suspend_token.h>
#include <lib/zx/thread.h>
#include <lib/zx/time.h>
#include <zircon/syscalls/exception.h>
#include <zircon/syscalls/object.h>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <cstdint>
#include <memory>
#include <mutex>
#include <thread>
#include <gtest/gtest.h>
#include "src/developer/debug/debug_agent/debugged_thread.h"
#include "src/developer/debug/debug_agent/process_handle.h"
#include "src/developer/debug/debug_agent/suspend_handle.h"
#include "src/developer/debug/debug_agent/test_utils.h"
#include "src/developer/debug/debug_agent/time.h"
#include "src/developer/debug/debug_agent/zircon_binary_launcher.h"
namespace debug_agent {
namespace {
struct LiveZirconWorker {
zx::event stop_event;
std::thread worker;
zx::thread thread;
~LiveZirconWorker() {
if (stop_event.is_valid()) {
stop_event.signal(0, ZX_USER_SIGNAL_0); // NOLINT(bugprone-signed-bitwise)
}
if (worker.joinable()) {
worker.join();
}
}
};
void StartLiveZirconWorker(LiveZirconWorker* out) {
ASSERT_ZX_EQ(zx::event::create(0, &out->stop_event), ZX_OK);
std::mutex mutex;
std::condition_variable ready_cv;
bool ready = false;
zx_status_t dup_status = ZX_ERR_INTERNAL;
out->worker = std::thread([out, &mutex, &ready_cv, &ready, &dup_status] {
zx::thread self_dup;
zx_status_t status = zx::thread::self()->duplicate(
ZX_RIGHT_SAME_RIGHTS, &self_dup); // NOLINT(bugprone-signed-bitwise)
{
std::scoped_lock lock(mutex);
dup_status = status;
out->thread = std::move(self_dup);
ready = true;
ready_cv.notify_one();
}
if (status == ZX_OK) {
out->stop_event.wait_one(ZX_USER_SIGNAL_0, // NOLINT(bugprone-signed-bitwise)
zx::time::infinite(), nullptr);
}
});
{
std::unique_lock<std::mutex> lock(mutex);
ready_cv.wait(lock, [&] { return ready; });
}
ASSERT_ZX_EQ(dup_status, ZX_OK);
ASSERT_TRUE(out->thread.is_valid());
}
zx_status_t WaitForThreadBlockedWaitOne(const zx::unowned_thread& thread,
const std::atomic<bool>& wait_done) {
constexpr zx::duration kPollingInterval = zx::msec(1);
while (!wait_done.load(std::memory_order_acquire)) {
zx_info_thread_t info = {};
zx_status_t status = thread->get_info(ZX_INFO_THREAD, &info, sizeof(info), nullptr, nullptr);
if (status != ZX_OK) {
return status;
}
if (info.state == ZX_THREAD_STATE_BLOCKED_WAIT_ONE) {
return ZX_OK;
}
zx::nanosleep(zx::deadline_after(kPollingInterval));
}
return ZX_ERR_CANCELED;
}
struct ExceptionBlockedChild {
std::unique_ptr<ProcessHandle> process_handle;
zx::process child_process;
zx::channel exc_channel;
zx::exception exception;
zx::thread thread;
~ExceptionBlockedChild() {
if (child_process.is_valid()) {
child_process.kill();
}
}
};
void WaitAndReadException(ExceptionBlockedChild* out, zx_excp_type_t expected_type) {
zx_signals_t observed = 0;
ASSERT_ZX_EQ(out->exc_channel.wait_one(ZX_CHANNEL_READABLE, // NOLINT(bugprone-signed-bitwise)
zx::deadline_after(zx::sec(10)), &observed),
ZX_OK);
ASSERT_TRUE(observed & ZX_CHANNEL_READABLE); // NOLINT(bugprone-signed-bitwise)
zx_exception_info_t info = {};
uint32_t actual_bytes = 0;
uint32_t actual_handles = 0;
ASSERT_ZX_EQ(out->exc_channel.read(0, &info, out->exception.reset_and_get_address(), sizeof(info),
1, &actual_bytes, &actual_handles),
ZX_OK);
ASSERT_EQ(actual_bytes, sizeof(info));
ASSERT_EQ(actual_handles, 1u);
ASSERT_EQ(info.type, expected_type);
ASSERT_ZX_EQ(out->exception.get_thread(&out->thread), ZX_OK);
}
void StartChildBlockedInStartException(ExceptionBlockedChild* out) {
auto svc_dir = component::OpenServiceRoot();
ASSERT_TRUE(svc_dir.is_ok()) << svc_dir.status_string();
ZirconBinaryLauncher launcher(*svc_dir);
ASSERT_TRUE(
launcher.Setup({"/pkg/test/debug_agent_unit_tests", "--gtest_filter=NonExistent"}).ok());
out->process_handle = launcher.GetProcess();
ASSERT_TRUE(out->process_handle);
const zx_status_t dup_status = out->process_handle->GetNativeHandle().duplicate(
ZX_RIGHT_SAME_RIGHTS, &out->child_process); // NOLINT(bugprone-signed-bitwise)
ASSERT_ZX_EQ(dup_status, ZX_OK);
ASSERT_ZX_EQ(
out->child_process.create_exception_channel(ZX_EXCEPTION_CHANNEL_DEBUGGER, &out->exc_channel),
ZX_OK);
ASSERT_TRUE(launcher.Start().ok());
ASSERT_NO_FATAL_FAILURE(WaitAndReadException(out, ZX_EXCP_THREAD_STARTING));
}
TEST(ZirconThreadHandleTest, WaitForSuspensionSignalReturnsFalseOnTimeoutAndTrueWhenSuspended) {
LiveZirconWorker live;
ASSERT_NO_FATAL_FAILURE(StartLiveZirconWorker(&live));
// Declare the thread handle and suspend token after live so the thread resumes before join.
ZirconThreadHandle thread_handle(std::move(live.thread));
EXPECT_FALSE(thread_handle.WaitForSuspensionSignal(TickTimePoint{}));
EXPECT_FALSE(thread_handle.WaitForSuspensionSignal(std::chrono::steady_clock::now()));
std::unique_ptr<SuspendHandle> suspend = thread_handle.Suspend();
ASSERT_TRUE(suspend);
EXPECT_TRUE(thread_handle.WaitForSuspensionSignal(DebuggedThread::DefaultSuspendDeadline()));
EXPECT_TRUE(thread_handle.WaitForSuspensionSignal(TickTimePoint{}));
}
TEST(ZirconThreadHandleTest, WaitForSuspensionSignalReturnsFalseWhenBlockedOnException) {
ExceptionBlockedChild child;
ASSERT_NO_FATAL_FAILURE(StartChildBlockedInStartException(&child));
ZirconThreadHandle thread_handle(std::move(child.thread));
ASSERT_TRUE(thread_handle.GetState().is_blocked_on_exception());
EXPECT_FALSE(thread_handle.WaitForSuspensionSignal(TickTimePoint{}));
EXPECT_FALSE(thread_handle.WaitForSuspensionSignal(std::chrono::steady_clock::now()));
}
void CreateTerminatedZirconThread(zx::thread* out) {
zx_status_t dup_status = ZX_ERR_INTERNAL;
std::thread worker([&] {
// NOLINTNEXTLINE(bugprone-signed-bitwise)
dup_status = zx::thread::self()->duplicate(ZX_RIGHT_SAME_RIGHTS, out);
});
worker.join();
ASSERT_ZX_EQ(dup_status, ZX_OK);
ASSERT_TRUE(out->is_valid());
ASSERT_ZX_EQ(out->wait_one(ZX_THREAD_TERMINATED, // NOLINT(bugprone-signed-bitwise)
zx::deadline_after(zx::sec(10)), nullptr),
ZX_OK);
}
TEST(ZirconThreadHandleTest, WaitForSuspensionSignalReturnsFalseWhenThreadTerminated) {
zx::thread worker_thread;
ASSERT_NO_FATAL_FAILURE(CreateTerminatedZirconThread(&worker_thread));
ZirconThreadHandle thread_handle(std::move(worker_thread));
const TickTimePoint signal_deadline = std::chrono::steady_clock::now() + std::chrono::seconds(10);
EXPECT_FALSE(thread_handle.WaitForSuspensionSignal(signal_deadline));
EXPECT_LT(std::chrono::steady_clock::now(), signal_deadline);
const TickTimePoint wait_deadline = std::chrono::steady_clock::now() + std::chrono::seconds(10);
EXPECT_FALSE(thread_handle.WaitForSuspension(wait_deadline));
EXPECT_LT(std::chrono::steady_clock::now(), wait_deadline);
}
TEST(ZirconThreadHandleTest, WaitForSuspensionReturnsFalseOnExpiredAndShortDeadlines) {
LiveZirconWorker live;
ASSERT_NO_FATAL_FAILURE(StartLiveZirconWorker(&live));
ZirconThreadHandle thread_handle(std::move(live.thread));
EXPECT_FALSE(thread_handle.IsInThreadStartingException());
EXPECT_FALSE(thread_handle.WaitForSuspension(TickTimePoint{}));
EXPECT_FALSE(thread_handle.WaitForSuspension(std::chrono::steady_clock::now()));
EXPECT_FALSE(thread_handle.WaitForSuspension(std::chrono::steady_clock::now() +
std::chrono::milliseconds(3)));
}
TEST(ZirconThreadHandleTest, WaitForSuspensionWakesWhenThreadSuspendsMidWait) {
LiveZirconWorker live;
ASSERT_NO_FATAL_FAILURE(StartLiveZirconWorker(&live));
zx::thread suspender_target;
ASSERT_ZX_EQ(live.thread.duplicate(ZX_RIGHT_SAME_RIGHTS, // NOLINT(bugprone-signed-bitwise)
&suspender_target),
ZX_OK);
zx::thread waiter_thread;
// NOLINTNEXTLINE(bugprone-signed-bitwise)
ASSERT_ZX_EQ(zx::thread::self()->duplicate(ZX_RIGHT_SAME_RIGHTS, &waiter_thread), ZX_OK);
// Declare suspend_token after live so it closes and resumes the worker before live joins.
zx::suspend_token suspend_token;
ZirconThreadHandle thread_handle(std::move(live.thread));
std::atomic<bool> wait_done{false};
zx_status_t wait_status = ZX_ERR_INTERNAL;
zx_status_t suspend_status = ZX_ERR_INTERNAL;
std::thread suspender;
auto cleanup_suspender = fit::defer([&] {
wait_done.store(true, std::memory_order_release);
if (suspender.joinable()) {
suspender.join();
}
});
suspender = std::thread([&] {
wait_status = WaitForThreadBlockedWaitOne(waiter_thread.borrow(), wait_done);
if (wait_status == ZX_OK) {
suspend_status = suspender_target.suspend(&suspend_token);
}
});
EXPECT_TRUE(
thread_handle.WaitForSuspension(std::chrono::steady_clock::now() + std::chrono::seconds(10)));
wait_done.store(true, std::memory_order_release);
cleanup_suspender.call();
ASSERT_ZX_EQ(wait_status, ZX_OK);
ASSERT_ZX_EQ(suspend_status, ZX_OK);
EXPECT_TRUE(thread_handle.WaitForSuspension(TickTimePoint{}));
}
TEST(ZirconThreadHandleTest, WaitForSuspensionReturnsTrueWhenBlockedOnException) {
ExceptionBlockedChild child;
ASSERT_NO_FATAL_FAILURE(StartChildBlockedInStartException(&child));
ZirconThreadHandle thread_handle(std::move(child.thread));
ASSERT_TRUE(thread_handle.GetState().is_blocked_on_exception());
EXPECT_TRUE(thread_handle.IsInThreadStartingException());
EXPECT_TRUE(thread_handle.WaitForSuspension(TickTimePoint{}));
EXPECT_TRUE(thread_handle.WaitForSuspension(DebuggedThread::DefaultSuspendDeadline()));
}
TEST(ZirconThreadHandleTest, IsInThreadStartingExceptionReturnsFalseForNonStartException) {
ExceptionBlockedChild child;
ASSERT_NO_FATAL_FAILURE(StartChildBlockedInStartException(&child));
constexpr uintptr_t kBreakOnLoad = 1;
ASSERT_ZX_EQ(child.child_process.set_property(ZX_PROP_PROCESS_BREAK_ON_LOAD, &kBreakOnLoad,
sizeof(kBreakOnLoad)),
ZX_OK);
// Release ZX_EXCP_THREAD_STARTING so ld.so runs until its loader breakpoint.
child.thread.reset();
child.exception.reset();
ASSERT_NO_FATAL_FAILURE(WaitAndReadException(&child, ZX_EXCP_SW_BREAKPOINT));
ZirconThreadHandle thread_handle(std::move(child.thread));
ASSERT_TRUE(thread_handle.GetState().is_blocked_on_exception());
EXPECT_FALSE(thread_handle.IsInThreadStartingException());
}
TEST(ZirconThreadHandleTest, WaitForSuspensionReturnsFalseWhenThreadTerminatesMidWait) {
LiveZirconWorker live;
ASSERT_NO_FATAL_FAILURE(StartLiveZirconWorker(&live));
zx::thread waiter_thread;
// NOLINTNEXTLINE(bugprone-signed-bitwise)
ASSERT_ZX_EQ(zx::thread::self()->duplicate(ZX_RIGHT_SAME_RIGHTS, &waiter_thread), ZX_OK);
ZirconThreadHandle thread_handle(std::move(live.thread));
std::atomic<bool> wait_done{false};
zx_status_t wait_status = ZX_ERR_INTERNAL;
std::thread terminator;
auto cleanup_terminator = fit::defer([&] {
wait_done.store(true, std::memory_order_release);
if (terminator.joinable()) {
terminator.join();
}
});
const TickTimePoint deadline = std::chrono::steady_clock::now() + std::chrono::seconds(10);
terminator = std::thread([&] {
wait_status = WaitForThreadBlockedWaitOne(waiter_thread.borrow(), wait_done);
if (wait_status == ZX_OK) {
live.stop_event.signal(0, ZX_USER_SIGNAL_0); // NOLINT(bugprone-signed-bitwise)
}
});
EXPECT_FALSE(thread_handle.WaitForSuspension(deadline));
EXPECT_LT(std::chrono::steady_clock::now(), deadline);
wait_done.store(true, std::memory_order_release);
cleanup_terminator.call();
ASSERT_ZX_EQ(wait_status, ZX_OK);
}
TEST(ZirconThreadHandleTest, SuspendReturnsNullptrWhenThreadTerminated) {
zx::thread worker_thread;
ASSERT_NO_FATAL_FAILURE(CreateTerminatedZirconThread(&worker_thread));
ZirconThreadHandle thread_handle(std::move(worker_thread));
EXPECT_EQ(thread_handle.Suspend(), nullptr);
}
} // namespace
} // namespace debug_agent