debugger.cpp 12 KB

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