blob: 165fc96d3d75bd1aa9226a51903b120ac081b585 [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/performance/cpu_profiler/job_watcher.h"
#include <lib/async-loop/cpp/loop.h>
#include <lib/async-loop/default.h>
#include <lib/async/cpp/task.h>
#include <lib/async/cpp/wait.h>
#include <lib/fit/defer.h>
#include <lib/fit/function.h>
#include <lib/zx/channel.h>
#include <lib/zx/event.h>
#include <lib/zx/exception.h>
#include <lib/zx/job.h>
#include <lib/zx/process.h>
#include <lib/zx/result.h>
#include <lib/zx/thread.h>
#include <lib/zx/time.h>
#include <lib/zx/vmar.h>
#include <lib/zx/vmo.h>
#include <zircon/errors.h>
#include <zircon/syscalls.h>
#include <zircon/syscalls/exception.h>
#include <zircon/types.h>
#include <array>
#include <atomic>
#include <condition_variable>
#include <cstdint>
#include <memory>
#include <mutex>
#include <optional>
#include <thread>
#include <utility>
#include <vector>
#include <gtest/gtest.h>
#include "src/lib/fsl/handles/object_info.h"
namespace {
// Zircon flag macros expand to signed shifts/masks that trigger bugprone-signed-bitwise.
// NOLINTBEGIN(bugprone-signed-bitwise)
constexpr zx_vm_option_t kVmPermRead = ZX_VM_PERM_READ;
constexpr zx_vm_option_t kVmPermReadWrite = ZX_VM_PERM_READ | ZX_VM_PERM_WRITE;
constexpr zx_signals_t kChannelReadable = ZX_CHANNEL_READABLE;
constexpr zx_signals_t kChannelPeerClosed = ZX_CHANNEL_PEER_CLOSED;
constexpr zx_signals_t kChannelWaitSignals = ZX_CHANNEL_READABLE | ZX_CHANNEL_PEER_CLOSED;
constexpr zx_signals_t kWorkerExitedSignal = ZX_USER_SIGNAL_0;
// NOLINTEND(bugprone-signed-bitwise)
volatile uint32_t* ProbePtr(zx_vaddr_t addr) {
// zx::vmar::map returns a zx_vaddr_t integer address; convert here to probe the mapped page.
return reinterpret_cast<volatile uint32_t*>(addr); // NOLINT(performance-no-int-to-ptr)
}
class TestJobWatcher : public profiler::JobWatcher {
public:
using JobWatcher::JobWatcher;
using JobWatcher::WatchChannel;
};
// Raising ZX_EXCP_USER delivers an exception on real ZX_EXCEPTION_CHANNEL_DEBUGGER channels.
// Verify JobWatcher ignores non-start exceptions without invoking its callback.
TEST(JobWatcherTest, RealJobChannelIgnoresUserException) {
async::Loop loop(&kAsyncLoopConfigAttachToCurrentThread);
bool handler_called = false;
std::optional<profiler::JobWatcher> watcher;
watcher.emplace(zx::job::default_job(),
[&handler_called](zx_koid_t, zx::process) { handler_called = true; });
ASSERT_TRUE(watcher->Watch(loop.dispatcher()).is_ok());
std::atomic<zx_status_t> raise_status = ZX_ERR_INTERNAL;
std::thread worker([&] {
zx_exception_context_t context = {};
context.synth_code = ZX_EXCP_USER_CODE_USER0;
raise_status =
zx_thread_raise_exception(ZX_EXCEPTION_TARGET_JOB_DEBUGGER, ZX_EXCP_USER, &context);
async::PostTask(loop.dispatcher(), [&loop] { loop.Quit(); });
});
async::PostDelayedTask(
loop.dispatcher(),
[&] {
ADD_FAILURE() << "Timed out waiting for ZX_EXCP_USER to complete";
loop.Quit();
},
zx::sec(10));
loop.Run();
watcher.reset();
worker.join();
EXPECT_EQ(raise_status.load(), ZX_OK);
EXPECT_FALSE(handler_called);
}
// Bridges real worker page faults from a process debugger exception channel into a TestJobWatcher
// and verifies downstream process exception channel delivery and safe teardown.
class FaultTestHarness {
public:
FaultTestHarness() = default;
~FaultTestHarness() {
Cleanup();
UnmapPages();
}
FaultTestHarness(const FaultTestHarness&) = delete;
FaultTestHarness& operator=(const FaultTestHarness&) = delete;
zx_koid_t self_pid() const { return self_pid_; }
async_dispatcher_t* dispatcher() { return loop_.dispatcher(); }
void set_producer_channel(zx::channel chan) { producer_chan_ = std::move(chan); }
const std::unique_ptr<TestJobWatcher>& watcher() const { return watcher_; }
zx::result<zx_vaddr_t> MapReadOnlyPage() {
zx::vmo vmo;
if (zx_status_t status = zx::vmo::create(page_size_, 0, &vmo); status != ZX_OK) {
return zx::error(status);
}
zx_vaddr_t addr = 0;
if (zx_status_t status = zx::vmar::root_self()->map(kVmPermRead, 0, vmo, 0, page_size_, &addr);
status != ZX_OK) {
return zx::error(status);
}
pages_.push_back({.vmo = std::move(vmo), .addr = addr});
return zx::ok(addr);
}
zx_status_t UnprotectPage(zx_vaddr_t addr) const {
return zx::vmar::root_self()->protect(kVmPermReadWrite, addr, page_size_);
}
zx::result<> InitWatcher(fit::function<void(zx_koid_t pid, zx::process)> handler) {
zx::channel watcher_chan;
if (zx_status_t status = zx::channel::create(0, &watcher_chan, &producer_chan_);
status != ZX_OK) {
return zx::error(status);
}
watcher_ = std::make_unique<TestJobWatcher>(zx::job::default_job(), std::move(handler));
return watcher_->WatchChannel(loop_.dispatcher(), std::move(watcher_chan));
}
void ResetWatcher() { watcher_.reset(); }
void FailAndResumeException(const char* failure_message, zx::exception exc) {
ADD_FAILURE() << failure_message;
UnprotectAllPages();
uint32_t state = ZX_EXCEPTION_STATE_HANDLED;
exc.set_property(ZX_PROP_EXCEPTION_STATE, &state, sizeof(state));
Quit();
}
void RunProcessStart(fit::function<void()> worker_action, const char* timeout_message) {
bool proc_saw_exception = false;
ASSERT_NO_FATAL_FAILURE(Run(
std::move(worker_action),
[this](zx_exception_info_t& info, zx::exception&) {
info.type = ZX_EXCP_PROCESS_STARTING;
info.pid = self_pid_;
return true;
},
[this, &proc_saw_exception](const zx_exception_info_t&, zx::exception exc) {
proc_saw_exception = true;
FailAndResumeException("Process exception channel received exception instead of HANDLED",
std::move(exc));
return false;
},
timeout_message));
EXPECT_FALSE(proc_saw_exception);
}
void Run(fit::function<void()> worker_action,
fit::function<bool(zx_exception_info_t&, zx::exception&)> on_debug_fault,
fit::function<bool(const zx_exception_info_t&, zx::exception)> on_proc_fault,
const char* timeout_message) {
auto cleanup = fit::defer([this] { Cleanup(); });
ASSERT_EQ(ZX_OK, zx::event::create(0, &worker_exited_));
worker_ = std::thread([this, action = std::move(worker_action)] mutable {
auto signal_exit = fit::defer([this] { worker_exited_.signal(0, kWorkerExitedSignal); });
zx_koid_t tid = fsl::GetKoid(zx::thread::self()->get());
{
std::scoped_lock lock(mu_);
worker_tid_ = tid;
worker_ready_ = true;
}
cv_.notify_all();
{
std::unique_lock lock(mu_);
cv_.wait(lock, [this] { return start_faults_ || abort_worker_; });
if (abort_worker_) {
return;
}
}
action();
async::PostTask(loop_.dispatcher(), [this] { Quit(); });
});
{
std::unique_lock lock(mu_);
cv_.wait(lock, [this] { return worker_ready_; });
}
// Bind the process debugger channel after the worker thread has started so we only observe its
// faults. Because it is a debugger channel, its zx::exception handles carry process rights
// required by JobWatcher::HandleException's exception.get_process() call.
ASSERT_EQ(ZX_OK, zx::process::self()->create_exception_channel(ZX_EXCEPTION_CHANNEL_DEBUGGER,
&debug_exc_chan_));
ASSERT_EQ(ZX_OK, zx::process::self()->create_exception_channel(0, &proc_exc_chan_));
ArmExceptionWait(
debug_wait_, debug_exc_chan_, "debugger",
[this, on_debug_fault = std::move(on_debug_fault)](zx_exception_info_t& info,
zx::exception& exc) {
if (info.type != ZX_EXCP_FATAL_PAGE_FAULT) {
return true;
}
if (!on_debug_fault(info, exc)) {
return false;
}
zx_handle_t handle = exc.release();
if (zx_status_t write_status = producer_chan_.write(0, &info, sizeof(info), &handle, 1);
write_status != ZX_OK) {
UnprotectAllPages();
ADD_FAILURE() << "Failed to forward exception to JobWatcher channel: " << write_status;
Quit();
return false;
}
return true;
});
ArmExceptionWait(proc_wait_, proc_exc_chan_, "process",
[on_proc_fault = std::move(on_proc_fault)](const zx_exception_info_t& info,
zx::exception& exc) {
return on_proc_fault(info, std::move(exc));
});
ASSERT_EQ(ZX_OK, debug_wait_.Begin(loop_.dispatcher()));
ASSERT_EQ(ZX_OK, proc_wait_.Begin(loop_.dispatcher()));
{
std::scoped_lock lock(mu_);
start_faults_ = true;
}
cv_.notify_all();
async::PostDelayedTask(
loop_.dispatcher(),
[this, timeout_message] {
ADD_FAILURE() << timeout_message;
Quit();
},
zx::sec(10));
loop_.Run();
}
private:
struct MappedPage {
zx::vmo vmo;
zx_vaddr_t addr = 0;
};
void UnprotectAllPages() const {
for (const MappedPage& page : pages_) {
zx::vmar::root_self()->protect(kVmPermReadWrite, page.addr, page_size_);
}
}
void Quit() { loop_.Quit(); }
void ReArmWait(async_dispatcher_t* dispatcher, async::Wait* wait, const char* label) {
if (zx_status_t begin_status = wait->Begin(dispatcher); begin_status != ZX_OK) {
ADD_FAILURE() << "Failed to re-arm " << label << " wait: " << begin_status;
UnprotectAllPages();
Quit();
}
}
void ArmExceptionWait(
async::Wait& wait, const zx::channel& channel, const char* label,
fit::function<bool(zx_exception_info_t&, zx::exception&)> on_worker_exception) {
wait.set_object(channel.get());
wait.set_trigger(kChannelWaitSignals);
wait.set_handler([this, &channel, label, on_worker_exception = std::move(on_worker_exception)](
async_dispatcher_t* dispatcher, async::Wait* wait, zx_status_t status,
const zx_packet_signal_t* signal) mutable {
if (status != ZX_OK || !(signal->observed & kChannelReadable)) {
return;
}
zx_exception_info_t info;
zx::exception exc;
if (zx_status_t read_status = channel.read(0, &info, exc.reset_and_get_address(),
sizeof(info), 1, nullptr, nullptr);
read_status != ZX_OK) {
ADD_FAILURE() << "Failed to read " << label << " exception channel: " << read_status;
UnprotectAllPages();
Quit();
return;
}
if (info.tid != worker_tid_ || on_worker_exception(info, exc)) {
ReArmWait(dispatcher, wait, label);
}
});
}
void Cleanup() {
debug_wait_.Cancel();
proc_wait_.Cancel();
{
std::scoped_lock lock(mu_);
abort_worker_ = true;
}
cv_.notify_all();
UnprotectAllPages();
watcher_.reset();
producer_chan_.reset();
debug_exc_chan_.reset();
if (proc_exc_chan_.is_valid()) {
if (worker_.joinable() && worker_exited_.is_valid()) {
// Keep proc_exc_chan_ open until the worker exits so exceptions released asynchronously by
// closing watcher_, producer_chan_, or debug_exc_chan_ are resolved instead of crashing
// the test binary.
while (true) {
zx_wait_item_t items[2] = {
{
.handle = proc_exc_chan_.get(),
.waitfor = kChannelWaitSignals,
.pending = 0,
},
{
.handle = worker_exited_.get(),
.waitfor = kWorkerExitedSignal,
.pending = 0,
},
};
if (zx_object_wait_many(items, 2, ZX_TIME_INFINITE) != ZX_OK) {
break;
}
if (items[0].pending & kChannelReadable) {
zx_exception_info_t info;
zx::exception exc;
while (proc_exc_chan_.read(0, &info, exc.reset_and_get_address(), sizeof(info), 1,
nullptr, nullptr) == ZX_OK) {
if (info.tid == worker_tid_) {
uint32_t state = ZX_EXCEPTION_STATE_HANDLED;
exc.set_property(ZX_PROP_EXCEPTION_STATE, &state, sizeof(state));
}
}
}
if ((items[1].pending & kWorkerExitedSignal) || (items[0].pending & kChannelPeerClosed)) {
break;
}
}
}
proc_exc_chan_.reset();
}
if (worker_.joinable()) {
worker_.join();
}
}
void UnmapPages() {
for (const MappedPage& page : pages_) {
zx::vmar::root_self()->unmap(page.addr, page_size_);
}
pages_.clear();
}
const size_t page_size_ = zx_system_get_page_size();
const zx_koid_t self_pid_ = fsl::GetKoid(zx::process::self()->get());
async::Loop loop_{&kAsyncLoopConfigAttachToCurrentThread};
std::vector<MappedPage> pages_;
zx::channel producer_chan_;
std::unique_ptr<TestJobWatcher> watcher_;
zx::event worker_exited_;
std::mutex mu_;
std::condition_variable cv_;
bool worker_ready_ = false;
bool start_faults_ = false;
bool abort_worker_ = false;
zx_koid_t worker_tid_ = ZX_KOID_INVALID;
zx::channel debug_exc_chan_;
zx::channel proc_exc_chan_;
async::Wait debug_wait_;
async::Wait proc_wait_;
std::thread worker_;
};
// Verify JobWatcher leaves non-start exceptions at ZX_EXCEPTION_STATE_TRY_NEXT so downstream
// handlers still receive them, stays armed afterward, and handles a subsequent
// ZX_EXCP_PROCESS_STARTING event.
TEST(JobWatcherTest, IgnoresNonStartExceptionLeavesTryNextAndRemainsArmed) {
FaultTestHarness harness;
zx::result<zx_vaddr_t> addr1 = harness.MapReadOnlyPage();
ASSERT_TRUE(addr1.is_ok()) << addr1.status_string();
zx::result<zx_vaddr_t> addr2 = harness.MapReadOnlyPage();
ASSERT_TRUE(addr2.is_ok()) << addr2.status_string();
enum class Phase : uint8_t {
kExpectNonStartException,
kExpectProcessStarting,
};
Phase phase = Phase::kExpectNonStartException;
int handler_calls = 0;
int debug_faults_in_phase1 = 0;
int debug_faults_in_phase2 = 0;
bool proc_saw_phase1 = false;
bool proc_saw_unexpected = false;
ASSERT_TRUE(harness
.InitWatcher([&](zx_koid_t pid, zx::process process) {
EXPECT_EQ(phase, Phase::kExpectProcessStarting);
handler_calls++;
EXPECT_EQ(pid, harness.self_pid());
EXPECT_EQ(fsl::GetKoid(process.get()), harness.self_pid());
EXPECT_EQ(ZX_OK, harness.UnprotectPage(*addr2));
})
.is_ok());
ASSERT_NO_FATAL_FAILURE(harness.Run(
[&] {
*ProbePtr(*addr1) = 1;
*ProbePtr(*addr2) = 2;
},
[&](zx_exception_info_t& info, zx::exception& exc) {
if (phase == Phase::kExpectNonStartException) {
debug_faults_in_phase1++;
if (debug_faults_in_phase1 > 1) {
// Re-faulting on addr1 means JobWatcher marked the non-start exception handled instead
// of leaving it TRY_NEXT for the downstream process exception channel.
harness.FailAndResumeException(
"Non-start exception was marked handled instead of TRY_NEXT", std::move(exc));
return false;
}
} else {
debug_faults_in_phase2++;
// Relabel this second real kernel exception as ZX_EXCP_PROCESS_STARTING so JobWatcher
// exercises its process-start path while preserving real exception state propagation.
info.type = ZX_EXCP_PROCESS_STARTING;
info.pid = harness.self_pid();
}
return true;
},
[&](const zx_exception_info_t&, zx::exception exc) {
if (phase == Phase::kExpectNonStartException) {
EXPECT_EQ(handler_calls, 0);
proc_saw_phase1 = true;
EXPECT_EQ(ZX_OK, harness.UnprotectPage(*addr1));
uint32_t state = ZX_EXCEPTION_STATE_HANDLED;
EXPECT_EQ(ZX_OK, exc.set_property(ZX_PROP_EXCEPTION_STATE, &state, sizeof(state)));
phase = Phase::kExpectProcessStarting;
return true;
}
proc_saw_unexpected = true;
harness.FailAndResumeException(
"Process exception channel received ZX_EXCP_PROCESS_STARTING", std::move(exc));
return false;
},
"Timed out waiting for JobWatcher exception test"));
EXPECT_TRUE(proc_saw_phase1);
EXPECT_FALSE(proc_saw_unexpected);
EXPECT_EQ(debug_faults_in_phase1, 1);
EXPECT_EQ(debug_faults_in_phase2, 1);
EXPECT_EQ(handler_calls, 1);
EXPECT_EQ(*ProbePtr(*addr1), 1u);
EXPECT_EQ(*ProbePtr(*addr2), 2u);
}
// Verify JobWatcher keeps a heap-allocated handler closure alive when the callback synchronously
// destroys the JobWatcher during ZX_EXCP_PROCESS_STARTING, still marks the exception
// ZX_EXCEPTION_STATE_HANDLED, and does not dereference freed members afterward.
TEST(JobWatcherTest, CallbackDestroyingWatcherSynchronouslyResumesExceptionWithoutUaf) {
FaultTestHarness harness;
zx::result<zx_vaddr_t> addr = harness.MapReadOnlyPage();
ASSERT_TRUE(addr.is_ok()) << addr.status_string();
constexpr std::array<uint64_t, 4> kExpectedPayload = {
0x1111111111111111ull,
0x2222222222222222ull,
0x3333333333333333ull,
0x4444444444444444ull,
};
std::array<uint64_t, 4> observed_payload = {};
int handler_calls = 0;
auto handler = [&harness, &handler_calls, &observed_payload, addr = *addr,
payload = kExpectedPayload](zx_koid_t pid, zx::process process) {
handler_calls++;
EXPECT_EQ(pid, harness.self_pid());
EXPECT_EQ(fsl::GetKoid(process.get()), harness.self_pid());
EXPECT_EQ(ZX_OK, harness.UnprotectPage(addr));
harness.ResetWatcher();
// Read captured state after destroying JobWatcher to verify the heap-allocated fit::function
// target remains valid until the callback returns.
observed_payload = payload;
};
static_assert(sizeof(handler) > fit::default_inline_target_size);
ASSERT_TRUE(harness.InitWatcher(std::move(handler)).is_ok());
ASSERT_NO_FATAL_FAILURE(
harness.RunProcessStart([addr = *addr] { *ProbePtr(addr) = 42; },
"Timed out waiting for JobWatcher self-destruction test"));
EXPECT_EQ(handler_calls, 1);
EXPECT_EQ(observed_payload, kExpectedPayload);
EXPECT_EQ(harness.watcher(), nullptr);
EXPECT_EQ(*ProbePtr(*addr), 42u);
}
// Verify re-entrant WatchChannel() from handler_ preserves the new watch instead of failing
// WaitBase::Begin with ZX_ERR_ALREADY_EXISTS and resetting it, and handles a subsequent
// ZX_EXCP_PROCESS_STARTING event on the new channel.
TEST(JobWatcherTest, ReentrantWatchChannelPreservesNewWatchAndHandlesNextStart) {
FaultTestHarness harness;
zx::result<zx_vaddr_t> addr1 = harness.MapReadOnlyPage();
ASSERT_TRUE(addr1.is_ok()) << addr1.status_string();
zx::result<zx_vaddr_t> addr2 = harness.MapReadOnlyPage();
ASSERT_TRUE(addr2.is_ok()) << addr2.status_string();
int handler_calls = 0;
ASSERT_TRUE(
harness
.InitWatcher([&](zx_koid_t pid, zx::process process) {
handler_calls++;
EXPECT_EQ(pid, harness.self_pid());
EXPECT_EQ(fsl::GetKoid(process.get()), harness.self_pid());
if (handler_calls == 1) {
EXPECT_EQ(ZX_OK, harness.UnprotectPage(*addr1));
zx::channel new_watcher_chan;
zx::channel new_producer_chan;
ASSERT_EQ(ZX_OK, zx::channel::create(0, &new_watcher_chan, &new_producer_chan));
ASSERT_TRUE(harness.watcher()
->WatchChannel(harness.dispatcher(), std::move(new_watcher_chan))
.is_ok());
harness.set_producer_channel(std::move(new_producer_chan));
} else {
EXPECT_EQ(ZX_OK, harness.UnprotectPage(*addr2));
}
})
.is_ok());
ASSERT_NO_FATAL_FAILURE(harness.RunProcessStart(
[&] {
*ProbePtr(*addr1) = 1;
*ProbePtr(*addr2) = 2;
},
"Timed out waiting for JobWatcher re-entrant WatchChannel test"));
EXPECT_EQ(handler_calls, 2);
EXPECT_EQ(*ProbePtr(*addr1), 1u);
EXPECT_EQ(*ProbePtr(*addr2), 2u);
}
} // namespace