blob: 7c04df7a0e9d6f0fd65fa1b5257776cf7a5bef97 [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 <lib/fit/defer.h>
#include <chrono>
#include <functional>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include <dap/protocol.h>
#include <dap/typeof.h>
#include <gtest/gtest.h>
#include "src/developer/debug/ipc/protocol.h"
#include "src/developer/debug/shared/test_stream_buffer.h"
#include "src/developer/debug/zxdb/client/analytics_event.h"
#include "src/developer/debug/zxdb/client/analytics_reporter.h"
#include "src/developer/debug/zxdb/client/breakpoint.h"
#include "src/developer/debug/zxdb/client/mock_remote_api.h"
#include "src/developer/debug/zxdb/client/target_impl.h"
#include "src/developer/debug/zxdb/console/mock_console.h"
#include "src/developer/debug/zxdb/debug_adapter/async_backtrace_subscription.h"
#include "src/developer/debug/zxdb/debug_adapter/context_test.h"
#include "src/developer/debug/zxdb/debug_adapter/dap_session_decorator.h"
#include "src/developer/debug/zxdb/debug_adapter/handlers/request_attach.h"
#include "src/developer/debug/zxdb/debug_adapter/handlers/request_launch.h"
#include "src/developer/debug/zxdb/debug_adapter/handlers/request_pause.h"
#include "src/developer/debug/zxdb/debug_adapter/handlers/request_threads.h"
#include "src/developer/debug/zxdb/debug_adapter/handlers/request_tracepoint.h"
namespace zxdb {
namespace {
// Create our own fake RemoteAPI to get the id of created breakpoints, which is needed for
// `ContextTest.StoppedEventProcessLevelBreakpoint`.
class FakeRemoteAPI : public MockRemoteAPI {
public:
std::vector<uint32_t>& added_breakpoint_ids() { return added_breakpoint_ids_; }
void AddOrChangeBreakpoint(
const debug_ipc::AddOrChangeBreakpointRequest& request,
fit::callback<void(const Err&, debug_ipc::AddOrChangeBreakpointReply)> cb) override {
added_breakpoint_ids_.push_back(request.breakpoint.id);
MockRemoteAPI::AddOrChangeBreakpoint(request, std::move(cb));
}
private:
std::vector<uint32_t> added_breakpoint_ids_;
};
class ContextTest : public DebugAdapterContextTest {
public:
FakeRemoteAPI* remote_api() { return remote_api_; }
void TearDown() override {
session().analytics().SetDapRequestObserverForTesting({});
session().analytics().SetDapEventSummaryObserverForTesting({});
DebugAdapterContextTest::TearDown();
}
protected:
std::unique_ptr<RemoteAPI> GetRemoteAPIImpl() override {
auto remote_api = std::make_unique<FakeRemoteAPI>();
remote_api_ = remote_api.get();
return remote_api;
}
private:
FakeRemoteAPI* remote_api_;
};
TEST_F(ContextTest, InitializeRequest) {
SetUpConnectedContext();
// Send initialize request from the client.
auto response = client().send(dap::InitializeRequest{});
// Read request and process it.
context().OnStreamReadable();
// Run client to receive response.
RunClient();
auto got = response.get();
EXPECT_EQ(got.error, false);
EXPECT_EQ(bool(got.response.supportsFunctionBreakpoints), true);
EXPECT_EQ(bool(got.response.supportsDataBreakpoints), true);
EXPECT_EQ(bool(got.response.supportsConditionalBreakpoints), true);
EXPECT_EQ(bool(got.response.supportsConfigurationDoneRequest), true);
}
TEST_F(ContextTest, InitializeRequestNotConnected) {
// Send initialize request from the client.
auto response = client().send(dap::InitializeRequest{});
// Read request and process it.
context().OnStreamReadable();
// Run client to receive response.
RunClient();
auto got = response.get();
EXPECT_EQ(got.error, true);
}
TEST_F(ContextTest, InitializedEvent) {
bool event_received = false;
client().registerHandler([&](const dap::InitializedEvent& arg) { event_received = true; });
// Send initialize request from the client.
auto response = client().send(dap::InitializeRequest{});
context().OnStreamReadable();
// Run client twice to receive response and event.
RunClient();
RunClient();
EXPECT_TRUE(event_received);
}
TEST_F(ContextTest, ProcessStartEvent) {
bool start_received = false;
client().registerHandler([&](const dap::ProcessEvent& arg) {
start_received = true;
EXPECT_EQ(arg.systemProcessId.value(0), static_cast<dap::integer>(kProcessKoid));
});
InitializeDebugging();
InjectProcess(kProcessKoid);
// Receive Process started event in client.
RunClient();
EXPECT_TRUE(start_received);
}
TEST_F(ContextTest, ThreadStartExitEvent) {
bool start_received = false;
bool exit_received = false;
client().registerHandler([&](const dap::ThreadEvent& arg) {
EXPECT_EQ(arg.threadId, static_cast<dap::integer>(kThreadKoid));
if (arg.reason == "started") {
start_received = true;
}
if (arg.reason == "exited") {
exit_received = true;
}
});
InitializeDebugging();
InjectProcess(kProcessKoid);
// Receive process started event in client.
RunClient();
InjectThread(kProcessKoid, kThreadKoid);
// Receive thread started event in client.
RunClient();
EXPECT_TRUE(start_received);
debug_ipc::NotifyThreadExiting notify;
notify.record.id = {.process = kProcessKoid, .thread = kThreadKoid};
notify.record.state = debug_ipc::ThreadRecord::State::kDying;
session().DispatchNotifyThreadExiting(notify);
// Receive thread exited event in client.
RunClient();
EXPECT_TRUE(exit_received);
}
TEST_F(ContextTest, StoppedEventException) {
bool event_received = false;
client().registerHandler([&](const dap::StoppedEvent& arg) {
EXPECT_EQ(arg.reason, "unknown");
EXPECT_TRUE(arg.threadId.has_value());
EXPECT_FALSE(arg.allThreadsStopped.value(false));
EXPECT_EQ(arg.threadId.value(), static_cast<dap::integer>(kThreadKoid));
event_received = true;
});
InitializeDebugging();
InjectProcessWithModule(kProcessKoid);
// Receive process started event in client.
RunClient();
InjectThread(kProcessKoid, kThreadKoid);
// Receive thread started event in client.
RunClient();
constexpr uint64_t kAddress = 0x12345678;
constexpr uint64_t kStack = 0x7890;
// Notify of thread stop due to a general exception (e.g., crash).
debug_ipc::NotifyException exception_notification;
exception_notification.type = debug_ipc::ExceptionType::kGeneral;
exception_notification.thread.id = {.process = kProcessKoid, .thread = kThreadKoid};
exception_notification.thread.state = debug_ipc::ThreadRecord::State::kBlocked;
exception_notification.thread.frames.emplace_back(kAddress, kStack, kStack);
InjectException(exception_notification);
// Receive thread stopped event in client.
RunClient();
EXPECT_TRUE(event_received);
}
TEST_F(ContextTest, StoppedEventThreadLevelBreakpoint) {
bool event_received = false;
client().registerHandler([&](const dap::StoppedEvent& arg) {
EXPECT_EQ(arg.reason, "breakpoint");
EXPECT_TRUE(arg.threadId.has_value());
EXPECT_FALSE(arg.allThreadsStopped.value(false));
EXPECT_EQ(arg.threadId.value(), static_cast<dap::integer>(kThreadKoid));
EXPECT_TRUE(arg.hitBreakpointIds.has_value());
ASSERT_EQ(1u, arg.hitBreakpointIds->size());
EXPECT_EQ(1, arg.hitBreakpointIds.value()[0]);
event_received = true;
});
InitializeDebugging();
InjectProcessWithModule(kProcessKoid);
// Receive process started event in client.
RunClient();
InjectThread(kProcessKoid, kThreadKoid);
// Receive thread started event in client.
RunClient();
constexpr uint64_t kAddress = 0x12345678;
constexpr uint64_t kStack = 0x7890;
// Create a thread-level breakpoint.
Breakpoint* bp = session().system().CreateNewBreakpoint();
BreakpointSettings settings;
settings.enabled = true;
settings.stop_mode = BreakpointSettings::StopMode::kThread;
settings.locations.emplace_back(kAddress);
bp->SetSettings(settings);
// Receive breakpoint changed event in client.
RunClient();
// Get the breakpoint id to be added to the `break_notification` exception.
ASSERT_EQ(1u, remote_api()->added_breakpoint_ids().size());
auto bp_id = remote_api()->added_breakpoint_ids().back();
// Notify of thread stop.
debug_ipc::NotifyException break_notification;
break_notification.type = debug_ipc::ExceptionType::kSoftwareBreakpoint;
break_notification.thread.id = {.process = kProcessKoid, .thread = kThreadKoid};
break_notification.thread.state = debug_ipc::ThreadRecord::State::kBlocked;
break_notification.thread.frames.emplace_back(kAddress, kStack, kStack);
// Add the breakpoint id associated with the thread-level breakpoint that was created above.
// This allows `DebugAdapterContext::OnThreadStopped()` to examine `StopInfo::hit_breakpoints` and
// set dap::StoppedEvent::allThreadsStopped accordingly.
break_notification.hit_breakpoints.push_back({.id = bp_id});
InjectException(break_notification);
// Receive thread stopped event in client.
RunClient();
EXPECT_TRUE(event_received);
}
TEST_F(ContextTest, StoppedEventProcessLevelBreakpoint) {
bool event_received = false;
client().registerHandler([&](const dap::StoppedEvent& arg) {
EXPECT_EQ(arg.reason, "breakpoint");
EXPECT_TRUE(arg.threadId.has_value());
EXPECT_TRUE(arg.allThreadsStopped.value(false));
EXPECT_EQ(arg.threadId.value(), static_cast<dap::integer>(kThreadKoid));
EXPECT_TRUE(arg.hitBreakpointIds.has_value());
ASSERT_EQ(1u, arg.hitBreakpointIds->size());
EXPECT_EQ(1, arg.hitBreakpointIds.value()[0]);
event_received = true;
});
InitializeDebugging();
InjectProcessWithModule(kProcessKoid);
// Receive process started event in client.
RunClient();
InjectThread(kProcessKoid, kThreadKoid);
// Receive thread started event in client.
RunClient();
constexpr uint64_t kAddress = 0x12345678;
constexpr uint64_t kStack = 0x7890;
// Create a process-level breakpoint.
Breakpoint* bp = session().system().CreateNewBreakpoint();
BreakpointSettings settings;
settings.enabled = true;
settings.stop_mode = BreakpointSettings::StopMode::kProcess;
settings.locations.emplace_back(kAddress);
bp->SetSettings(settings);
// Receive breakpoint changed event in client.
RunClient();
// Get the breakpoint id to be added to the `break_notification` exception.
ASSERT_EQ(1u, remote_api()->added_breakpoint_ids().size());
auto bp_id = remote_api()->added_breakpoint_ids().back();
// Notify of thread stop.
debug_ipc::NotifyException break_notification;
break_notification.type = debug_ipc::ExceptionType::kSoftwareBreakpoint;
break_notification.thread.id = {.process = kProcessKoid, .thread = kThreadKoid};
break_notification.thread.state = debug_ipc::ThreadRecord::State::kBlocked;
break_notification.thread.frames.emplace_back(kAddress, kStack, kStack);
// Add the breakpoint id associated with the process-level breakpoint that was created above.
// This allows `DebugAdapterContext::OnThreadStopped()` to examine `StopInfo::hit_breakpoints` and
// set dap::StoppedEvent::allThreadsStopped accordingly.
break_notification.hit_breakpoints.push_back({.id = bp_id});
InjectException(break_notification);
// Receive thread stopped event in client.
RunClient();
EXPECT_TRUE(event_received);
}
TEST_F(ContextTest, StoppedEventUnspecifiedAllLevelBreakpoint) {
bool event_received = false;
client().registerHandler([&](const dap::StoppedEvent& arg) {
EXPECT_EQ(arg.reason, "breakpoint");
EXPECT_TRUE(arg.threadId.has_value());
EXPECT_TRUE(arg.allThreadsStopped.value(false));
EXPECT_EQ(arg.threadId.value(), static_cast<dap::integer>(kThreadKoid));
EXPECT_TRUE(arg.hitBreakpointIds.has_value());
ASSERT_EQ(1u, arg.hitBreakpointIds->size());
EXPECT_EQ(1, arg.hitBreakpointIds.value()[0]);
event_received = true;
});
InitializeDebugging();
InjectProcessWithModule(kProcessKoid);
// Receive process started event in client.
RunClient();
InjectThread(kProcessKoid, kThreadKoid);
// Receive thread started event in client.
RunClient();
constexpr uint64_t kAddress = 0x12345678;
constexpr uint64_t kStack = 0x7890;
// Create a breakpoint with an unspecified `stop_mode`, which should default to StopMode::kAll`.
Breakpoint* bp = session().system().CreateNewBreakpoint();
BreakpointSettings settings;
settings.enabled = true;
settings.locations.emplace_back(kAddress);
bp->SetSettings(settings);
// Receive breakpoint changed event in client.
RunClient();
// Get the breakpoint id to be added to the `break_notification` exception.
ASSERT_EQ(1u, remote_api()->added_breakpoint_ids().size());
auto bp_id = remote_api()->added_breakpoint_ids().back();
// Notify of thread stop.
debug_ipc::NotifyException break_notification;
break_notification.type = debug_ipc::ExceptionType::kSoftwareBreakpoint;
break_notification.thread.id = {.process = kProcessKoid, .thread = kThreadKoid};
break_notification.thread.state = debug_ipc::ThreadRecord::State::kBlocked;
break_notification.thread.frames.emplace_back(kAddress, kStack, kStack);
// Add the breakpoint id associated with the process-level breakpoint that was created above.
// This allows `DebugAdapterContext::OnThreadStopped()` to examine `StopInfo::hit_breakpoints` and
// set dap::StoppedEvent::allThreadsStopped accordingly.
break_notification.hit_breakpoints.push_back({.id = bp_id});
InjectException(break_notification);
// Receive thread stopped event in client.
RunClient();
EXPECT_TRUE(event_received);
}
TEST_F(ContextTest, DisconnectRequest) {
bool request_received = false;
context().set_destroy_connection_callback([&request_received] { request_received = true; });
InitializeDebugging();
// Send disconnect request from client
auto response = client().send(dap::DisconnectRequest());
// Receive and process request in the server.
context().OnStreamReadable();
loop().RunUntilNoTasks();
// Run client to receive response.
RunClient();
auto got = response.get();
EXPECT_FALSE(got.error);
EXPECT_TRUE(request_received);
}
TEST_F(ContextTest, ExitedEvent) {
bool event_received = false;
client().registerHandler([&event_received](const dap::ExitedEvent& arg) {
EXPECT_EQ(arg.exitCode, 20);
event_received = true;
});
InitializeDebugging();
InjectProcess(kProcessKoid);
// Receive process started event in client.
RunClient();
InjectThread(kProcessKoid, kThreadKoid);
// Receive thread started event in client.
RunClient();
// Detach from target
auto targets = session().system().GetTargetImpls();
ASSERT_EQ(targets.size(), 1u);
targets[0]->OnProcessExiting(20, 0);
// Run client to receive event.
RunClient();
EXPECT_TRUE(event_received);
}
class ProcessDetachRemoteAPI : public MockRemoteAPI {
public:
void Detach(const debug_ipc::DetachRequest& request,
fit::callback<void(const Err&, debug_ipc::DetachReply)> cb) override {
debug_ipc::DetachReply reply;
cb(Err(), reply);
}
};
class ProcessDetachTest : public DebugAdapterContextTest {
public:
ProcessDetachRemoteAPI* remote_api() const { return remote_api_; }
protected:
std::unique_ptr<RemoteAPI> GetRemoteAPIImpl() override {
auto remote_api = std::make_unique<ProcessDetachRemoteAPI>();
remote_api_ = remote_api.get();
return remote_api;
}
private:
ProcessDetachRemoteAPI* remote_api_;
};
TEST_F(ProcessDetachTest, TerminatedEvent) {
bool event_received = false;
client().registerHandler(
[&event_received](const dap::TerminatedEvent& arg) { event_received = true; });
InitializeDebugging();
InjectProcess(kProcessKoid);
// Receive process started event in client.
RunClient();
InjectThread(kProcessKoid, kThreadKoid);
// Receive thread started event in client.
RunClient();
// Detach from target
auto targets = session().system().GetTargetImpls();
ASSERT_EQ(targets.size(), 1u);
targets[0]->Detach([](const fxl::WeakPtr<Target>& target, const Err& err) {});
// Run client to receive event.
RunClient();
EXPECT_TRUE(event_received);
}
TEST_F(ContextTest, PartialInitializeRequest) {
SetUpConnectedContext();
bool event_received = false;
client().registerHandler([&](const dap::InitializedEvent& arg) { event_received = true; });
std::string json =
"{\"arguments\":{\"adapterID\":\"zxdb\"},\"command\":\"initialize\",\"seq\":1,\"type\":"
"\"request\"}";
std::string header = "Content-Length: " + std::to_string(json.size()) + "\r\n\r\n";
std::string full_msg = header + json;
size_t split_pos = full_msg.size() / 2;
std::string part1 = full_msg.substr(0, split_pos);
std::string part2 = full_msg.substr(split_pos);
context().stream()->AddReadData(std::vector<char>(part1.begin(), part1.end()));
context().OnStreamReadable();
RunPendingClientCalls();
EXPECT_FALSE(event_received);
context().stream()->AddReadData(std::vector<char>(part2.begin(), part2.end()));
context().OnStreamReadable();
RunPendingClientCalls();
EXPECT_TRUE(event_received);
}
TEST_F(ContextTest, ThreadAndEventProcessId) {
InitializeDebugging();
// Test ThreadEvent has processId
bool event_received = false;
client().registerHandler([&](const dap::ThreadEventZxdb& arg) {
EXPECT_EQ(arg.threadId, static_cast<dap::integer>(kThreadKoid));
ASSERT_TRUE(arg.processId.has_value());
EXPECT_EQ(arg.processId.value(), static_cast<dap::integer>(kProcessKoid));
event_received = true;
});
InjectProcess(kProcessKoid);
RunClient(); // process started event
InjectThread(kProcessKoid, kThreadKoid);
RunClient(); // thread started event
EXPECT_TRUE(event_received);
// Test ThreadsResponse has processId in each thread
dap::ThreadsRequest req;
dap::ResponseOrError<dap::ThreadsResponseZxdb> got;
bool response_received = false;
client().send(dap::TypeOf<dap::ThreadsRequest>::type(),
dap::TypeOf<dap::ThreadsResponseZxdb>::type(), &req,
[&](const void* res, const dap::Error* err) {
if (err) {
got.error = *err;
} else {
got.response = *reinterpret_cast<const dap::ThreadsResponseZxdb*>(res);
}
response_received = true;
});
context().OnStreamReadable();
RunClient(); // run client to receive threads response
ASSERT_TRUE(response_received);
ASSERT_FALSE(got.error);
ASSERT_EQ(got.response.threads.size(), 1u);
EXPECT_EQ(got.response.threads[0].id, static_cast<dap::integer>(kThreadKoid));
ASSERT_TRUE(got.response.threads[0].processId.has_value());
EXPECT_EQ(got.response.threads[0].processId.value(), static_cast<dap::integer>(kProcessKoid));
}
TEST_F(ContextTest, ThreadStartImplicitlySuspended) {
InitializeDebugging();
InjectProcess(kProcessKoid);
RunClient(); // Process started event
std::vector<std::string> event_order;
std::optional<dap::ThreadEventZxdb> received_thread_event;
std::optional<dap::StoppedEvent> received_stopped_event;
client().registerHandler([&](const dap::ThreadEventZxdb& arg) {
event_order.push_back("thread_started");
received_thread_event = arg;
});
client().registerHandler([&](const dap::StoppedEvent& arg) {
event_order.push_back("thread_stopped");
received_stopped_event = arg;
});
// Inject a thread in the suspended state (implicit suspension race).
debug_ipc::NotifyThreadStarting notify;
notify.record.id = {.process = kProcessKoid, .thread = kThreadKoid};
notify.record.name = "suspended_thread";
notify.record.state = debug_ipc::ThreadRecord::State::kSuspended;
session().DispatchNotifyThreadStarting(notify);
// First event: ThreadEventZxdb
ASSERT_TRUE(HasPendingClientCalls());
RunClient();
ASSERT_TRUE(received_thread_event.has_value());
EXPECT_EQ(received_thread_event->reason, "started");
EXPECT_EQ(received_thread_event->threadId, static_cast<dap::integer>(kThreadKoid));
EXPECT_EQ(received_thread_event->processId.value(0), static_cast<dap::integer>(kProcessKoid));
ASSERT_TRUE(received_thread_event->isStopped.has_value());
EXPECT_TRUE(received_thread_event->isStopped.value());
// Second event: StoppedEvent
ASSERT_TRUE(HasPendingClientCalls());
RunClient();
ASSERT_TRUE(received_stopped_event.has_value());
EXPECT_EQ(received_stopped_event->reason, "pause");
ASSERT_TRUE(received_stopped_event->threadId.has_value());
EXPECT_EQ(received_stopped_event->threadId.value(), static_cast<dap::integer>(kThreadKoid));
// Verify ordering and no extra events.
ASSERT_EQ(event_order.size(), 2u);
EXPECT_EQ(event_order[0], "thread_started");
EXPECT_EQ(event_order[1], "thread_stopped");
EXPECT_FALSE(HasPendingClientCalls());
}
TEST_F(ContextTest, ThreadStartRunningDoesNotSendStoppedEvent) {
InitializeDebugging();
InjectProcess(kProcessKoid);
RunClient(); // Process started event
std::optional<dap::ThreadEventZxdb> received_thread_event;
bool stopped_received = false;
client().registerHandler([&](const dap::ThreadEventZxdb& arg) { received_thread_event = arg; });
client().registerHandler([&](const dap::StoppedEvent& arg) { stopped_received = true; });
InjectThread(kProcessKoid, kThreadKoid);
ASSERT_TRUE(HasPendingClientCalls());
RunClient();
ASSERT_TRUE(received_thread_event.has_value());
EXPECT_EQ(received_thread_event->reason, "started");
EXPECT_EQ(received_thread_event->threadId, static_cast<dap::integer>(kThreadKoid));
EXPECT_EQ(received_thread_event->processId.value(0), static_cast<dap::integer>(kProcessKoid));
ASSERT_TRUE(received_thread_event->isStopped.has_value());
EXPECT_FALSE(received_thread_event->isStopped.value());
EXPECT_FALSE(stopped_received);
EXPECT_FALSE(HasPendingClientCalls());
}
class AnalyticsTestRemoteAPI : public FakeRemoteAPI {
public:
void Detach(const debug_ipc::DetachRequest& request,
fit::callback<void(const Err&, debug_ipc::DetachReply)> cb) override {
cb(Err(), debug_ipc::DetachReply{});
}
};
class ContextAnalyticsTest : public RemoteAPITest {
public:
static constexpr uint64_t kProcessKoid = DebugAdapterContextTest::kProcessKoid;
static constexpr uint64_t kThreadKoid = DebugAdapterContextTest::kThreadKoid;
AnalyticsTestRemoteAPI* remote_api() const { return remote_api_; }
DebugAdapterContext& context() { return *context_; }
dap::Session& client() { return *client_; }
void SetUp() override {
RemoteAPITest::SetUp();
session().set_stream(&session_stream_.stream());
console_ = std::make_unique<MockConsole>(&session());
console_->Init();
context_ = std::make_unique<DebugAdapterContext>(console_.get(), pipe_.end1());
client_ = dap::Session::create();
client_->connect(std::make_shared<DebugAdapterReader>(pipe_.end2()),
std::make_shared<DebugAdapterWriter>(pipe_.end2()));
}
void TearDown() override {
session().analytics().SetDapRequestObserverForTesting({});
session().analytics().SetDapEventSummaryObserverForTesting({});
ResetContext();
client_.reset();
console_.reset();
session().set_stream(nullptr);
RemoteAPITest::TearDown();
}
void ResetContext() { context_.reset(); }
void RunPendingClientCalls() {
while (pipe_.end2()->IsAvailable(1)) {
if (auto payload = client_->getPayload()) {
payload();
}
}
}
void InitializeSession(bool supports_run_in_terminal = false) {
dap::InitializeRequest req;
req.supportsRunInTerminalRequest = supports_run_in_terminal;
auto response = client().send(req);
context().OnStreamReadable();
loop().RunUntilNoTasks();
RunPendingClientCalls();
ASSERT_FALSE(response.get().error);
context().DeinitializeAsyncBacktraceSubscriptionForTesting();
}
protected:
std::unique_ptr<RemoteAPI> GetRemoteAPIImpl() override {
auto remote_api = std::make_unique<AnalyticsTestRemoteAPI>();
remote_api_ = remote_api.get();
return remote_api;
}
private:
AnalyticsTestRemoteAPI* remote_api_ = nullptr;
debug::TestStreamBuffer session_stream_;
TestPipe pipe_;
std::unique_ptr<MockConsole> console_;
std::unique_ptr<DebugAdapterContext> context_;
std::unique_ptr<dap::Session> client_;
};
TEST_F(ContextTest, CompletedProtocolRequestsEmitDapRequestReports) {
std::vector<DapRequestReport> reports;
session().analytics().SetDapRequestObserverForTesting(
[&reports](const DapRequestReport& report) { reports.push_back(report); });
SetUpConnectedContext();
auto init_resp = client().send(dap::InitializeRequest{});
context().OnStreamReadable();
RunPendingClientCalls();
ASSERT_FALSE(init_resp.get().error);
DeinitializeAsyncBacktraceSubscription();
auto config_resp = client().send(dap::ConfigurationDoneRequest{});
context().OnStreamReadable();
loop().RunUntilNoTasks();
RunPendingClientCalls();
ASSERT_FALSE(config_resp.get().error);
auto exc_bp_resp = client().send(dap::SetExceptionBreakpointsRequest{});
context().OnStreamReadable();
loop().RunUntilNoTasks();
RunPendingClientCalls();
ASSERT_FALSE(exc_bp_resp.get().error);
auto disconnect_resp = client().send(dap::DisconnectRequest{});
context().OnStreamReadable();
loop().RunUntilNoTasks();
RunPendingClientCalls();
ASSERT_FALSE(disconnect_resp.get().error);
ASSERT_EQ(reports.size(), 4u);
const std::vector<std::string> kExpectedNames = {
"initialize",
"configurationDone",
"setExceptionBreakpoints",
"disconnect",
};
for (size_t i = 0; i < kExpectedNames.size(); ++i) {
EXPECT_EQ(reports[i].request, kExpectedNames[i]);
EXPECT_FALSE(reports[i].has_error);
EXPECT_FALSE(reports[i].cancelled);
EXPECT_GE(reports[i].duration, std::chrono::milliseconds{0});
}
}
TEST_F(ContextTest, FailingRequestEmitsErrorReport) {
InitializeDebugging();
std::vector<DapRequestReport> reports;
session().analytics().SetDapRequestObserverForTesting(
[&reports](const DapRequestReport& report) { reports.push_back(report); });
dap::AttachRequestZxdb req = {};
req.process = "0";
auto response = client().send(req);
context().OnStreamReadable();
RunClient();
ASSERT_TRUE(response.get().error);
ASSERT_EQ(reports.size(), 1u);
EXPECT_EQ(reports[0].request, "attach");
EXPECT_TRUE(reports[0].has_error);
EXPECT_FALSE(reports[0].cancelled);
EXPECT_GE(reports[0].duration, std::chrono::milliseconds{0});
}
TEST_F(ContextAnalyticsTest, InFlightAsyncRequestCancelledOnTeardownAndLateCallbackSafe) {
std::vector<DapRequestReport> reports;
session().analytics().SetDapRequestObserverForTesting(
[&reports](const DapRequestReport& report) { reports.push_back(report); });
InitializeSession();
reports.clear();
std::vector<std::function<void(dap::ResponseOrError<dap::LoadedSourcesResponse>)>> deferred_cbs;
context().dap().registerHandler(
[&deferred_cbs](const dap::LoadedSourcesRequest&,
std::function<void(dap::ResponseOrError<dap::LoadedSourcesResponse>)> cb) {
deferred_cbs.push_back(std::move(cb));
});
auto response1 = client().send(dap::LoadedSourcesRequest{});
context().OnStreamReadable();
auto response2 = client().send(dap::LoadedSourcesRequest{});
context().OnStreamReadable();
loop().RunUntilNoTasks();
ASSERT_EQ(deferred_cbs.size(), 2u);
EXPECT_TRUE(reports.empty());
ResetContext();
// Context teardown must immediately emit cancellation reports even while callbacks remain held.
ASSERT_EQ(reports.size(), 2u);
for (const auto& report : reports) {
EXPECT_EQ(report.request, "loadedSources");
EXPECT_FALSE(report.has_error);
EXPECT_TRUE(report.cancelled);
EXPECT_GE(report.duration, std::chrono::milliseconds{0});
}
// Invoking or dropping held callbacks after context destruction must not UAF or emit again.
deferred_cbs[0](dap::Error("late failure"));
deferred_cbs[0] = nullptr;
deferred_cbs[1] = nullptr;
loop().RunUntilNoTasks();
EXPECT_EQ(reports.size(), 2u);
}
TEST_F(ContextTest, InitializeFailureEmitsErrorReport) {
std::vector<DapRequestReport> reports;
session().analytics().SetDapRequestObserverForTesting(
[&reports](const DapRequestReport& report) { reports.push_back(report); });
bool connect_resolved = false;
session().Connect({.type = SessionConnectionType::kUnix, .host = "/dev/null/nonexistent.sock"},
[this, &connect_resolved](const Err&) {
connect_resolved = true;
loop().QuitNow();
});
auto cleanup_connect = fit::defer([this, &connect_resolved] {
if (!connect_resolved) {
loop().Run();
}
(void)session().Disconnect();
});
ASSERT_TRUE(session().HasPendingConnection());
auto init_resp = client().send(dap::InitializeRequest{});
context().OnStreamReadable();
EXPECT_TRUE(reports.empty());
const std::string kHostError =
"Failed to resolve secret-host.corp.example: Name or service not known.";
context().DidResolveConnection(Err(kHostError));
RunPendingClientCalls();
auto got = init_resp.get();
ASSERT_TRUE(got.error);
EXPECT_EQ(got.error.message, kHostError);
ASSERT_EQ(reports.size(), 1u);
EXPECT_EQ(reports[0].request, "initialize");
EXPECT_TRUE(reports[0].has_error);
EXPECT_FALSE(reports[0].cancelled);
EXPECT_GE(reports[0].duration, std::chrono::milliseconds{0});
}
TEST_F(ContextAnalyticsTest, DeferredInitializeCancelledOnContextTeardown) {
Console* shared_console = context().console();
ResetContext();
session().set_stream(nullptr);
std::vector<DapRequestReport> reports;
session().analytics().SetDapRequestObserverForTesting(
[&reports](const DapRequestReport& report) { reports.push_back(report); });
bool connect_resolved = false;
session().Connect({.type = SessionConnectionType::kUnix, .host = "/dev/null/nonexistent.sock"},
[this, &connect_resolved](const Err&) {
connect_resolved = true;
loop().QuitNow();
});
auto cleanup_connect = fit::defer([this, &connect_resolved] {
if (!connect_resolved) {
loop().Run();
}
(void)session().Disconnect();
});
ASSERT_TRUE(session().HasPendingConnection());
TestPipe pending_pipe;
auto pending_context = std::make_unique<DebugAdapterContext>(shared_console, pending_pipe.end1());
auto pending_client = dap::Session::create();
pending_client->connect(std::make_shared<DebugAdapterReader>(pending_pipe.end2()),
std::make_shared<DebugAdapterWriter>(pending_pipe.end2()));
auto init_resp = pending_client->send(dap::InitializeRequest{});
pending_context->OnStreamReadable();
EXPECT_TRUE(reports.empty());
pending_context.reset();
ASSERT_EQ(reports.size(), 1u);
EXPECT_EQ(reports[0].request, "initialize");
EXPECT_FALSE(reports[0].has_error);
EXPECT_TRUE(reports[0].cancelled);
EXPECT_GE(reports[0].duration, std::chrono::milliseconds{0});
}
TEST_F(ContextAnalyticsTest, DroppedHandlerCallbackEmitsCancelledReportWithoutTeardown) {
std::vector<DapRequestReport> reports;
session().analytics().SetDapRequestObserverForTesting(
[&reports](const DapRequestReport& report) { reports.push_back(report); });
InitializeSession();
reports.clear();
context().dap().registerHandler(
[](const dap::LoadedSourcesRequest&,
std::function<void(dap::ResponseOrError<dap::LoadedSourcesResponse>)> cb) { cb = {}; });
auto response = client().send(dap::LoadedSourcesRequest{});
context().OnStreamReadable();
loop().RunUntilNoTasks();
ASSERT_EQ(reports.size(), 1u);
EXPECT_EQ(reports[0].request, "loadedSources");
EXPECT_FALSE(reports[0].has_error);
EXPECT_TRUE(reports[0].cancelled);
EXPECT_GE(reports[0].duration, std::chrono::milliseconds{0});
}
TEST_F(ContextAnalyticsTest,
DecoratorReadsContextAtDispatchAndMarksExpiredContextCompleteAsCancelled) {
std::vector<DapRequestReport> reports;
session().analytics().SetDapRequestObserverForTesting(
[&reports](const DapRequestReport& report) { reports.push_back(report); });
TestPipe local_pipe;
DapSessionDecorator decorator(dap::Session::create(), session().GetWeakPtr());
auto local_client = dap::Session::create();
decorator.connect(std::make_shared<DebugAdapterReader>(local_pipe.end1()),
std::make_shared<DebugAdapterWriter>(local_pipe.end1()));
local_client->connect(std::make_shared<DebugAdapterReader>(local_pipe.end2()),
std::make_shared<DebugAdapterWriter>(local_pipe.end2()));
// Register handlers before calling SetContext to verify dispatch-time context lookup.
decorator.registerHandler(
[](const dap::ConfigurationDoneRequest&) { return dap::ConfigurationDoneResponse{}; });
std::function<void(dap::ResponseOrError<dap::LoadedSourcesResponse>)> deferred_cb;
decorator.registerHandler(
[&deferred_cb](const dap::LoadedSourcesRequest&,
std::function<void(dap::ResponseOrError<dap::LoadedSourcesResponse>)> cb) {
deferred_cb = std::move(cb);
});
decorator.SetContext(context().GetWeakPtr());
auto config_resp = local_client->send(dap::ConfigurationDoneRequest{});
if (auto payload = decorator.getPayload()) {
payload();
}
if (auto payload = local_client->getPayload()) {
payload();
}
ASSERT_FALSE(config_resp.get().error);
ASSERT_EQ(reports.size(), 1u);
EXPECT_EQ(reports[0].request, "configurationDone");
EXPECT_FALSE(reports[0].has_error);
EXPECT_FALSE(reports[0].cancelled);
auto loaded_resp = local_client->send(dap::LoadedSourcesRequest{});
if (auto payload = decorator.getPayload()) {
payload();
}
ASSERT_TRUE(static_cast<bool>(deferred_cb));
EXPECT_EQ(reports.size(), 1u);
// Destroy DebugAdapterContext without calling decorator.CancelInFlightRequests() so Complete()
// exercises the expired weak_context_ path directly.
ResetContext();
EXPECT_EQ(reports.size(), 1u);
deferred_cb(dap::Error("late failure"));
ASSERT_EQ(reports.size(), 2u);
EXPECT_EQ(reports[1].request, "loadedSources");
EXPECT_FALSE(reports[1].has_error);
EXPECT_TRUE(reports[1].cancelled);
EXPECT_GE(reports[1].duration, std::chrono::milliseconds{0});
EXPECT_FALSE(local_pipe.end2()->IsAvailable(1));
}
TEST_F(ContextAnalyticsTest, OutboundEventsAccumulateAndEmitSummaryOnTeardown) {
std::vector<DapEventSummaryReport> summaries;
session().analytics().SetDapEventSummaryObserverForTesting(
[&summaries](const DapEventSummaryReport& report) { summaries.push_back(report); });
bool run_in_terminal_received = false;
client().registerHandler([&run_in_terminal_received](const dap::RunInTerminalRequest&) {
run_in_terminal_received = true;
return dap::RunInTerminalResponse();
});
InitializeSession(/*supports_run_in_terminal=*/true);
dap::LaunchRequestZxdb launch_req = {};
launch_req.process = "test";
launch_req.launchCommand = "fx run test";
auto launch_resp = client().send(launch_req);
context().OnStreamReadable();
RunPendingClientCalls();
ASSERT_FALSE(launch_resp.get().error);
EXPECT_TRUE(run_in_terminal_received);
InjectProcessWithModule(kProcessKoid);
RunPendingClientCalls();
InjectThread(kProcessKoid, kThreadKoid);
RunPendingClientCalls();
constexpr uint64_t kAddress = 0x12345678;
constexpr uint64_t kStack = 0x7890;
Breakpoint* bp = session().system().CreateNewBreakpoint();
BreakpointSettings settings;
settings.enabled = true;
settings.locations.emplace_back(kAddress);
bp->SetSettings(settings);
RunPendingClientCalls();
ASSERT_FALSE(remote_api()->added_breakpoint_ids().empty());
debug_ipc::NotifyException break_notification;
break_notification.type = debug_ipc::ExceptionType::kSoftwareBreakpoint;
break_notification.thread.id = {.process = kProcessKoid, .thread = kThreadKoid};
break_notification.thread.state = debug_ipc::ThreadRecord::State::kBlocked;
break_notification.thread.frames.emplace_back(kAddress, kStack, kStack);
break_notification.hit_breakpoints.push_back({.id = remote_api()->added_breakpoint_ids().back()});
InjectException(break_notification);
RunPendingClientCalls();
debug_ipc::NotifyException general_notification;
general_notification.type = debug_ipc::ExceptionType::kGeneral;
general_notification.thread.id = {.process = kProcessKoid, .thread = kThreadKoid};
general_notification.thread.state = debug_ipc::ThreadRecord::State::kBlocked;
general_notification.thread.frames.emplace_back(kAddress, kStack, kStack);
InjectException(general_notification);
RunPendingClientCalls();
for (const char* reason : {"data breakpoint", "exception", "pause", "step"}) {
dap::StoppedEvent stopped;
stopped.reason = reason;
context().dap().send(stopped);
}
dap::ProcessStoppedEventZxdb process_stopped;
process_stopped.processId = kProcessKoid;
context().dap().send(process_stopped);
context().dap().send(dap::ZxdbTracepointEvent{});
dap::AsyncBacktraceUpdate abt_update;
abt_update.id = kThreadKoid;
abt_update.processId = kProcessKoid;
context().dap().send(abt_update);
dap::ThreadEvent thread_event;
thread_event.reason = "started";
thread_event.threadId = kThreadKoid;
context().dap().send(thread_event);
context().dap().send(dap::InvalidatedEvent{});
context().dap().send(dap::ExitedEvent{});
RunPendingClientCalls();
debug_ipc::NotifyThreadExiting thread_exit;
thread_exit.record.id = {.process = kProcessKoid, .thread = kThreadKoid};
thread_exit.record.state = debug_ipc::ThreadRecord::State::kDying;
session().DispatchNotifyThreadExiting(thread_exit);
RunPendingClientCalls();
auto targets = session().system().GetTargetImpls();
ASSERT_EQ(targets.size(), 1u);
targets[0]->Detach([](const fxl::WeakPtr<Target>&, const Err&) {});
RunPendingClientCalls();
EXPECT_TRUE(summaries.empty());
ResetContext();
ASSERT_EQ(summaries.size(), 1u);
const auto& summary = summaries[0];
EXPECT_EQ(summary.initialized_count, 1);
EXPECT_EQ(summary.process_count, 1);
EXPECT_EQ(summary.stopped_breakpoint_count, 2);
EXPECT_EQ(summary.stopped_exception_count, 1);
EXPECT_EQ(summary.stopped_pause_count, 1);
EXPECT_EQ(summary.stopped_step_count, 1);
EXPECT_EQ(summary.stopped_other_count, 1);
EXPECT_EQ(summary.process_stopped_count, 1);
EXPECT_EQ(summary.thread_event_count, 3);
EXPECT_EQ(summary.breakpoint_event_count, 1);
EXPECT_EQ(summary.tracepoint_hit_count, 1);
EXPECT_EQ(summary.async_backtrace_update_count, 1);
EXPECT_EQ(summary.invalidated_count, 1);
EXPECT_EQ(summary.exited_count, 1);
EXPECT_EQ(summary.terminated_count, 1);
EXPECT_EQ(summary.TotalCount(), 18);
}
TEST_F(ContextAnalyticsTest, UnsentOutboundEventsAreNotCountedInSummary) {
Console* shared_console = context().console();
ResetContext();
std::vector<DapEventSummaryReport> summaries;
session().analytics().SetDapEventSummaryObserverForTesting(
[&summaries](const DapEventSummaryReport& report) { summaries.push_back(report); });
auto disconnected_context = std::make_unique<DebugAdapterContext>(shared_console, nullptr);
dap::StoppedEvent stopped;
stopped.reason = "breakpoint";
disconnected_context->dap().send(stopped);
dap::TerminatedEvent terminated;
EXPECT_FALSE(
disconnected_context->dap().send(dap::TypeOf<dap::TerminatedEvent>::type(), &terminated));
disconnected_context.reset();
EXPECT_TRUE(summaries.empty());
}
} // namespace
} // namespace zxdb