debugger.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. // SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include <algorithm>
  4. #include <mutex>
  5. #include <thread>
  6. #include <boost/asio.hpp>
  7. #include <boost/process/async_pipe.hpp>
  8. #include "common/logging/log.h"
  9. #include "common/polyfill_thread.h"
  10. #include "common/thread.h"
  11. #include "core/core.h"
  12. #include "core/debugger/debugger.h"
  13. #include "core/debugger/debugger_interface.h"
  14. #include "core/debugger/gdbstub.h"
  15. #include "core/hle/kernel/global_scheduler_context.h"
  16. #include "core/hle/kernel/k_scheduler.h"
  17. template <typename Readable, typename Buffer, typename Callback>
  18. static void AsyncReceiveInto(Readable& r, Buffer& buffer, Callback&& c) {
  19. static_assert(std::is_trivial_v<Buffer>);
  20. auto boost_buffer{boost::asio::buffer(&buffer, sizeof(Buffer))};
  21. r.async_read_some(
  22. boost_buffer, [&, c](const boost::system::error_code& error, size_t bytes_read) {
  23. if (!error.failed()) {
  24. const u8* buffer_start = reinterpret_cast<const u8*>(&buffer);
  25. std::span<const u8> received_data{buffer_start, buffer_start + bytes_read};
  26. c(received_data);
  27. AsyncReceiveInto(r, buffer, c);
  28. }
  29. });
  30. }
  31. template <typename Callback>
  32. static void AsyncAccept(boost::asio::ip::tcp::acceptor& acceptor, Callback&& c) {
  33. acceptor.async_accept([&, c](const boost::system::error_code& error, auto&& peer_socket) {
  34. if (!error.failed()) {
  35. c(peer_socket);
  36. AsyncAccept(acceptor, c);
  37. }
  38. });
  39. }
  40. template <typename Readable, typename Buffer>
  41. static std::span<const u8> ReceiveInto(Readable& r, Buffer& buffer) {
  42. static_assert(std::is_trivial_v<Buffer>);
  43. auto boost_buffer{boost::asio::buffer(&buffer, sizeof(Buffer))};
  44. size_t bytes_read = r.read_some(boost_buffer);
  45. const u8* buffer_start = reinterpret_cast<const u8*>(&buffer);
  46. std::span<const u8> received_data{buffer_start, buffer_start + bytes_read};
  47. return received_data;
  48. }
  49. enum class SignalType {
  50. Stopped,
  51. Watchpoint,
  52. ShuttingDown,
  53. };
  54. struct SignalInfo {
  55. SignalType type;
  56. Kernel::KThread* thread;
  57. const Kernel::DebugWatchpoint* watchpoint;
  58. };
  59. namespace Core {
  60. class DebuggerImpl : public DebuggerBackend {
  61. public:
  62. explicit DebuggerImpl(Core::System& system_, u16 port) : system{system_} {
  63. InitializeServer(port);
  64. }
  65. ~DebuggerImpl() override {
  66. ShutdownServer();
  67. }
  68. bool SignalDebugger(SignalInfo signal_info) {
  69. std::scoped_lock lk{connection_lock};
  70. if (stopped || !state) {
  71. // Do not notify the debugger about another event.
  72. // It should be ignored.
  73. return false;
  74. }
  75. // Set up the state.
  76. stopped = true;
  77. state->info = signal_info;
  78. // Write a single byte into the pipe to wake up the debug interface.
  79. boost::asio::write(state->signal_pipe, boost::asio::buffer(&stopped, sizeof(stopped)));
  80. return true;
  81. }
  82. // These functions are callbacks from the frontend, and the lock will be held.
  83. // There is no need to relock it.
  84. std::span<const u8> ReadFromClient() override {
  85. return ReceiveInto(state->client_socket, state->client_data);
  86. }
  87. void WriteToClient(std::span<const u8> data) override {
  88. boost::asio::write(state->client_socket,
  89. boost::asio::buffer(data.data(), data.size_bytes()));
  90. }
  91. void SetActiveThread(Kernel::KThread* thread) override {
  92. state->active_thread = thread;
  93. }
  94. Kernel::KThread* GetActiveThread() override {
  95. return state->active_thread;
  96. }
  97. private:
  98. void InitializeServer(u16 port) {
  99. using boost::asio::ip::tcp;
  100. LOG_INFO(Debug_GDBStub, "Starting server on port {}...", port);
  101. // Run the connection thread.
  102. connection_thread = std::jthread([&, port](std::stop_token stop_token) {
  103. Common::SetCurrentThreadName("Debugger");
  104. try {
  105. // Initialize the listening socket and accept a new client.
  106. tcp::endpoint endpoint{boost::asio::ip::address_v4::any(), port};
  107. tcp::acceptor acceptor{io_context, endpoint};
  108. AsyncAccept(acceptor, [&](auto&& peer) { AcceptConnection(std::move(peer)); });
  109. while (!stop_token.stop_requested() && io_context.run()) {
  110. }
  111. } catch (const std::exception& ex) {
  112. LOG_CRITICAL(Debug_GDBStub, "Stopping server: {}", ex.what());
  113. }
  114. });
  115. }
  116. void AcceptConnection(boost::asio::ip::tcp::socket&& peer) {
  117. LOG_INFO(Debug_GDBStub, "Accepting new peer connection");
  118. std::scoped_lock lk{connection_lock};
  119. // Ensure everything is stopped.
  120. PauseEmulation();
  121. // Set up the new frontend.
  122. frontend = std::make_unique<GDBStub>(*this, system);
  123. // Set the new state. This will tear down any existing state.
  124. state = ConnectionState{
  125. .client_socket{std::move(peer)},
  126. .signal_pipe{io_context},
  127. .info{},
  128. .active_thread{},
  129. .client_data{},
  130. .pipe_data{},
  131. };
  132. // Set up the client signals for new data.
  133. AsyncReceiveInto(state->signal_pipe, state->pipe_data, [&](auto d) { PipeData(d); });
  134. AsyncReceiveInto(state->client_socket, state->client_data, [&](auto d) { ClientData(d); });
  135. // Set the active thread.
  136. UpdateActiveThread();
  137. // Set up the frontend.
  138. frontend->Connected();
  139. }
  140. void ShutdownServer() {
  141. connection_thread.request_stop();
  142. io_context.stop();
  143. connection_thread.join();
  144. }
  145. void PipeData(std::span<const u8> data) {
  146. std::scoped_lock lk{connection_lock};
  147. switch (state->info.type) {
  148. case SignalType::Stopped:
  149. case SignalType::Watchpoint:
  150. // Stop emulation.
  151. PauseEmulation();
  152. // Notify the client.
  153. state->active_thread = state->info.thread;
  154. UpdateActiveThread();
  155. if (state->info.type == SignalType::Watchpoint) {
  156. frontend->Watchpoint(state->active_thread, *state->info.watchpoint);
  157. } else {
  158. frontend->Stopped(state->active_thread);
  159. }
  160. break;
  161. case SignalType::ShuttingDown:
  162. frontend->ShuttingDown();
  163. // Wait for emulation to shut down gracefully now.
  164. state->signal_pipe.close();
  165. state->client_socket.shutdown(boost::asio::socket_base::shutdown_both);
  166. LOG_INFO(Debug_GDBStub, "Shut down server");
  167. break;
  168. }
  169. }
  170. void ClientData(std::span<const u8> data) {
  171. std::scoped_lock lk{connection_lock};
  172. const auto actions{frontend->ClientData(data)};
  173. for (const auto action : actions) {
  174. switch (action) {
  175. case DebuggerAction::Interrupt: {
  176. stopped = true;
  177. PauseEmulation();
  178. UpdateActiveThread();
  179. frontend->Stopped(state->active_thread);
  180. break;
  181. }
  182. case DebuggerAction::Continue:
  183. MarkResumed([&] { ResumeEmulation(); });
  184. break;
  185. case DebuggerAction::StepThreadUnlocked:
  186. MarkResumed([&] {
  187. state->active_thread->SetStepState(Kernel::StepState::StepPending);
  188. state->active_thread->Resume(Kernel::SuspendType::Debug);
  189. ResumeEmulation(state->active_thread);
  190. });
  191. break;
  192. case DebuggerAction::StepThreadLocked: {
  193. MarkResumed([&] {
  194. state->active_thread->SetStepState(Kernel::StepState::StepPending);
  195. state->active_thread->Resume(Kernel::SuspendType::Debug);
  196. });
  197. break;
  198. }
  199. case DebuggerAction::ShutdownEmulation: {
  200. // Spawn another thread that will exit after shutdown,
  201. // to avoid a deadlock
  202. Core::System* system_ref{&system};
  203. std::thread t([system_ref] { system_ref->Exit(); });
  204. t.detach();
  205. break;
  206. }
  207. }
  208. }
  209. }
  210. void PauseEmulation() {
  211. Kernel::KScopedSchedulerLock sl{system.Kernel()};
  212. // Put all threads to sleep on next scheduler round.
  213. for (auto* thread : ThreadList()) {
  214. thread->RequestSuspend(Kernel::SuspendType::Debug);
  215. }
  216. }
  217. void ResumeEmulation(Kernel::KThread* except = nullptr) {
  218. // Wake up all threads.
  219. for (auto* thread : ThreadList()) {
  220. if (thread == except) {
  221. continue;
  222. }
  223. thread->SetStepState(Kernel::StepState::NotStepping);
  224. thread->Resume(Kernel::SuspendType::Debug);
  225. }
  226. }
  227. template <typename Callback>
  228. void MarkResumed(Callback&& cb) {
  229. Kernel::KScopedSchedulerLock sl{system.Kernel()};
  230. stopped = false;
  231. cb();
  232. }
  233. void UpdateActiveThread() {
  234. const auto& threads{ThreadList()};
  235. if (std::find(threads.begin(), threads.end(), state->active_thread) == threads.end()) {
  236. state->active_thread = threads[0];
  237. }
  238. }
  239. const std::vector<Kernel::KThread*>& ThreadList() {
  240. return system.GlobalSchedulerContext().GetThreadList();
  241. }
  242. private:
  243. System& system;
  244. std::unique_ptr<DebuggerFrontend> frontend;
  245. boost::asio::io_context io_context;
  246. std::jthread connection_thread;
  247. std::mutex connection_lock;
  248. struct ConnectionState {
  249. boost::asio::ip::tcp::socket client_socket;
  250. boost::process::async_pipe signal_pipe;
  251. SignalInfo info;
  252. Kernel::KThread* active_thread;
  253. std::array<u8, 4096> client_data;
  254. bool pipe_data;
  255. };
  256. std::optional<ConnectionState> state{};
  257. bool stopped{};
  258. };
  259. Debugger::Debugger(Core::System& system, u16 port) {
  260. try {
  261. impl = std::make_unique<DebuggerImpl>(system, port);
  262. } catch (const std::exception& ex) {
  263. LOG_CRITICAL(Debug_GDBStub, "Failed to initialize debugger: {}", ex.what());
  264. }
  265. }
  266. Debugger::~Debugger() = default;
  267. bool Debugger::NotifyThreadStopped(Kernel::KThread* thread) {
  268. return impl && impl->SignalDebugger(SignalInfo{SignalType::Stopped, thread, nullptr});
  269. }
  270. bool Debugger::NotifyThreadWatchpoint(Kernel::KThread* thread,
  271. const Kernel::DebugWatchpoint& watch) {
  272. return impl && impl->SignalDebugger(SignalInfo{SignalType::Watchpoint, thread, &watch});
  273. }
  274. void Debugger::NotifyShutdown() {
  275. if (impl) {
  276. impl->SignalDebugger(SignalInfo{SignalType::ShuttingDown, nullptr, nullptr});
  277. }
  278. }
  279. } // namespace Core