gdbstub.cpp 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398
  1. // Copyright 2013 Dolphin Emulator Project
  2. // Licensed under GPLv2+
  3. // Refer to the license.txt file included.
  4. // Originally written by Sven Peter <sven@fail0verflow.com> for anergistic.
  5. #include <algorithm>
  6. #include <atomic>
  7. #include <climits>
  8. #include <csignal>
  9. #include <cstdarg>
  10. #include <cstdio>
  11. #include <cstring>
  12. #include <map>
  13. #include <numeric>
  14. #include <fcntl.h>
  15. #ifdef _WIN32
  16. #include <winsock2.h>
  17. // winsock2.h needs to be included first to prevent winsock.h being included by other includes
  18. #include <io.h>
  19. #include <iphlpapi.h>
  20. #include <ws2tcpip.h>
  21. #define SHUT_RDWR 2
  22. #else
  23. #include <netinet/in.h>
  24. #include <sys/select.h>
  25. #include <sys/socket.h>
  26. #include <sys/un.h>
  27. #include <unistd.h>
  28. #endif
  29. #include "common/logging/log.h"
  30. #include "common/string_util.h"
  31. #include "common/swap.h"
  32. #include "core/arm/arm_interface.h"
  33. #include "core/core.h"
  34. #include "core/core_manager.h"
  35. #include "core/gdbstub/gdbstub.h"
  36. #include "core/hle/kernel/process.h"
  37. #include "core/hle/kernel/scheduler.h"
  38. #include "core/hle/kernel/vm_manager.h"
  39. #include "core/loader/loader.h"
  40. #include "core/memory.h"
  41. namespace GDBStub {
  42. namespace {
  43. constexpr int GDB_BUFFER_SIZE = 10000;
  44. constexpr char GDB_STUB_START = '$';
  45. constexpr char GDB_STUB_END = '#';
  46. constexpr char GDB_STUB_ACK = '+';
  47. constexpr char GDB_STUB_NACK = '-';
  48. #ifndef SIGTRAP
  49. constexpr u32 SIGTRAP = 5;
  50. #endif
  51. #ifndef SIGTERM
  52. constexpr u32 SIGTERM = 15;
  53. #endif
  54. #ifndef MSG_WAITALL
  55. constexpr u32 MSG_WAITALL = 8;
  56. #endif
  57. constexpr u32 LR_REGISTER = 30;
  58. constexpr u32 SP_REGISTER = 31;
  59. constexpr u32 PC_REGISTER = 32;
  60. constexpr u32 PSTATE_REGISTER = 33;
  61. constexpr u32 UC_ARM64_REG_Q0 = 34;
  62. constexpr u32 FPCR_REGISTER = 66;
  63. // For sample XML files see the GDB source /gdb/features
  64. // GDB also wants the l character at the start
  65. // This XML defines what the registers are for this specific ARM device
  66. constexpr char target_xml[] =
  67. R"(l<?xml version="1.0"?>
  68. <!DOCTYPE target SYSTEM "gdb-target.dtd">
  69. <target version="1.0">
  70. <feature name="org.gnu.gdb.aarch64.core">
  71. <reg name="x0" bitsize="64"/>
  72. <reg name="x1" bitsize="64"/>
  73. <reg name="x2" bitsize="64"/>
  74. <reg name="x3" bitsize="64"/>
  75. <reg name="x4" bitsize="64"/>
  76. <reg name="x5" bitsize="64"/>
  77. <reg name="x6" bitsize="64"/>
  78. <reg name="x7" bitsize="64"/>
  79. <reg name="x8" bitsize="64"/>
  80. <reg name="x9" bitsize="64"/>
  81. <reg name="x10" bitsize="64"/>
  82. <reg name="x11" bitsize="64"/>
  83. <reg name="x12" bitsize="64"/>
  84. <reg name="x13" bitsize="64"/>
  85. <reg name="x14" bitsize="64"/>
  86. <reg name="x15" bitsize="64"/>
  87. <reg name="x16" bitsize="64"/>
  88. <reg name="x17" bitsize="64"/>
  89. <reg name="x18" bitsize="64"/>
  90. <reg name="x19" bitsize="64"/>
  91. <reg name="x20" bitsize="64"/>
  92. <reg name="x21" bitsize="64"/>
  93. <reg name="x22" bitsize="64"/>
  94. <reg name="x23" bitsize="64"/>
  95. <reg name="x24" bitsize="64"/>
  96. <reg name="x25" bitsize="64"/>
  97. <reg name="x26" bitsize="64"/>
  98. <reg name="x27" bitsize="64"/>
  99. <reg name="x28" bitsize="64"/>
  100. <reg name="x29" bitsize="64"/>
  101. <reg name="x30" bitsize="64"/>
  102. <reg name="sp" bitsize="64" type="data_ptr"/>
  103. <reg name="pc" bitsize="64" type="code_ptr"/>
  104. <flags id="pstate_flags" size="4">
  105. <field name="SP" start="0" end="0"/>
  106. <field name="" start="1" end="1"/>
  107. <field name="EL" start="2" end="3"/>
  108. <field name="nRW" start="4" end="4"/>
  109. <field name="" start="5" end="5"/>
  110. <field name="F" start="6" end="6"/>
  111. <field name="I" start="7" end="7"/>
  112. <field name="A" start="8" end="8"/>
  113. <field name="D" start="9" end="9"/>
  114. <field name="IL" start="20" end="20"/>
  115. <field name="SS" start="21" end="21"/>
  116. <field name="V" start="28" end="28"/>
  117. <field name="C" start="29" end="29"/>
  118. <field name="Z" start="30" end="30"/>
  119. <field name="N" start="31" end="31"/>
  120. </flags>
  121. <reg name="pstate" bitsize="32" type="pstate_flags"/>
  122. </feature>
  123. <feature name="org.gnu.gdb.aarch64.fpu">
  124. </feature>
  125. </target>
  126. )";
  127. int gdbserver_socket = -1;
  128. bool defer_start = false;
  129. u8 command_buffer[GDB_BUFFER_SIZE];
  130. u32 command_length;
  131. u32 latest_signal = 0;
  132. bool memory_break = false;
  133. Kernel::Thread* current_thread = nullptr;
  134. u32 current_core = 0;
  135. // Binding to a port within the reserved ports range (0-1023) requires root permissions,
  136. // so default to a port outside of that range.
  137. u16 gdbstub_port = 24689;
  138. bool halt_loop = true;
  139. bool step_loop = false;
  140. bool send_trap = false;
  141. // If set to false, the server will never be started and no
  142. // gdbstub-related functions will be executed.
  143. std::atomic<bool> server_enabled(false);
  144. #ifdef _WIN32
  145. WSADATA InitData;
  146. #endif
  147. struct Breakpoint {
  148. bool active;
  149. VAddr addr;
  150. u64 len;
  151. std::array<u8, 4> inst;
  152. };
  153. using BreakpointMap = std::map<VAddr, Breakpoint>;
  154. BreakpointMap breakpoints_execute;
  155. BreakpointMap breakpoints_read;
  156. BreakpointMap breakpoints_write;
  157. struct Module {
  158. std::string name;
  159. VAddr beg;
  160. VAddr end;
  161. };
  162. std::vector<Module> modules;
  163. } // Anonymous namespace
  164. void RegisterModule(std::string name, VAddr beg, VAddr end, bool add_elf_ext) {
  165. Module module;
  166. if (add_elf_ext) {
  167. Common::SplitPath(name, nullptr, &module.name, nullptr);
  168. module.name += ".elf";
  169. } else {
  170. module.name = std::move(name);
  171. }
  172. module.beg = beg;
  173. module.end = end;
  174. modules.push_back(std::move(module));
  175. }
  176. static Kernel::Thread* FindThreadById(s64 id) {
  177. const auto& threads = Core::System::GetInstance().GlobalScheduler().GetThreadList();
  178. for (auto& thread : threads) {
  179. if (thread->GetThreadID() == static_cast<u64>(id)) {
  180. current_core = thread->GetProcessorID();
  181. return thread.get();
  182. }
  183. }
  184. return nullptr;
  185. }
  186. static u64 RegRead(std::size_t id, Kernel::Thread* thread = nullptr) {
  187. if (!thread) {
  188. return 0;
  189. }
  190. const auto& thread_context = thread->GetContext64();
  191. if (id < SP_REGISTER) {
  192. return thread_context.cpu_registers[id];
  193. } else if (id == SP_REGISTER) {
  194. return thread_context.sp;
  195. } else if (id == PC_REGISTER) {
  196. return thread_context.pc;
  197. } else if (id == PSTATE_REGISTER) {
  198. return thread_context.pstate;
  199. } else if (id > PSTATE_REGISTER && id < FPCR_REGISTER) {
  200. return thread_context.vector_registers[id - UC_ARM64_REG_Q0][0];
  201. } else {
  202. return 0;
  203. }
  204. }
  205. static void RegWrite(std::size_t id, u64 val, Kernel::Thread* thread = nullptr) {
  206. if (!thread) {
  207. return;
  208. }
  209. auto& thread_context = thread->GetContext64();
  210. if (id < SP_REGISTER) {
  211. thread_context.cpu_registers[id] = val;
  212. } else if (id == SP_REGISTER) {
  213. thread_context.sp = val;
  214. } else if (id == PC_REGISTER) {
  215. thread_context.pc = val;
  216. } else if (id == PSTATE_REGISTER) {
  217. thread_context.pstate = static_cast<u32>(val);
  218. } else if (id > PSTATE_REGISTER && id < FPCR_REGISTER) {
  219. thread_context.vector_registers[id - (PSTATE_REGISTER + 1)][0] = val;
  220. }
  221. }
  222. static u128 FpuRead(std::size_t id, Kernel::Thread* thread = nullptr) {
  223. if (!thread) {
  224. return u128{0};
  225. }
  226. auto& thread_context = thread->GetContext64();
  227. if (id >= UC_ARM64_REG_Q0 && id < FPCR_REGISTER) {
  228. return thread_context.vector_registers[id - UC_ARM64_REG_Q0];
  229. } else if (id == FPCR_REGISTER) {
  230. return u128{thread_context.fpcr, 0};
  231. } else {
  232. return u128{0};
  233. }
  234. }
  235. static void FpuWrite(std::size_t id, u128 val, Kernel::Thread* thread = nullptr) {
  236. if (!thread) {
  237. return;
  238. }
  239. auto& thread_context = thread->GetContext64();
  240. if (id >= UC_ARM64_REG_Q0 && id < FPCR_REGISTER) {
  241. thread_context.vector_registers[id - UC_ARM64_REG_Q0] = val;
  242. } else if (id == FPCR_REGISTER) {
  243. thread_context.fpcr = static_cast<u32>(val[0]);
  244. }
  245. }
  246. /**
  247. * Turns hex string character into the equivalent byte.
  248. *
  249. * @param hex Input hex character to be turned into byte.
  250. */
  251. static u8 HexCharToValue(u8 hex) {
  252. if (hex >= '0' && hex <= '9') {
  253. return hex - '0';
  254. } else if (hex >= 'a' && hex <= 'f') {
  255. return hex - 'a' + 0xA;
  256. } else if (hex >= 'A' && hex <= 'F') {
  257. return hex - 'A' + 0xA;
  258. }
  259. LOG_ERROR(Debug_GDBStub, "Invalid nibble: {} ({:02X})", hex, hex);
  260. return 0;
  261. }
  262. /**
  263. * Turn nibble of byte into hex string character.
  264. *
  265. * @param n Nibble to be turned into hex character.
  266. */
  267. static u8 NibbleToHex(u8 n) {
  268. n &= 0xF;
  269. if (n < 0xA) {
  270. return '0' + n;
  271. } else {
  272. return 'a' + n - 0xA;
  273. }
  274. }
  275. /**
  276. * Converts input hex string characters into an array of equivalent of u8 bytes.
  277. *
  278. * @param src Pointer to array of output hex string characters.
  279. * @param len Length of src array.
  280. */
  281. static u32 HexToInt(const u8* src, std::size_t len) {
  282. u32 output = 0;
  283. while (len-- > 0) {
  284. output = (output << 4) | HexCharToValue(src[0]);
  285. src++;
  286. }
  287. return output;
  288. }
  289. /**
  290. * Converts input hex string characters into an array of equivalent of u8 bytes.
  291. *
  292. * @param src Pointer to array of output hex string characters.
  293. * @param len Length of src array.
  294. */
  295. static u64 HexToLong(const u8* src, std::size_t len) {
  296. u64 output = 0;
  297. while (len-- > 0) {
  298. output = (output << 4) | HexCharToValue(src[0]);
  299. src++;
  300. }
  301. return output;
  302. }
  303. /**
  304. * Converts input array of u8 bytes into their equivalent hex string characters.
  305. *
  306. * @param dest Pointer to buffer to store output hex string characters.
  307. * @param src Pointer to array of u8 bytes.
  308. * @param len Length of src array.
  309. */
  310. static void MemToGdbHex(u8* dest, const u8* src, std::size_t len) {
  311. while (len-- > 0) {
  312. u8 tmp = *src++;
  313. *dest++ = NibbleToHex(tmp >> 4);
  314. *dest++ = NibbleToHex(tmp);
  315. }
  316. }
  317. /**
  318. * Converts input gdb-formatted hex string characters into an array of equivalent of u8 bytes.
  319. *
  320. * @param dest Pointer to buffer to store u8 bytes.
  321. * @param src Pointer to array of output hex string characters.
  322. * @param len Length of src array.
  323. */
  324. static void GdbHexToMem(u8* dest, const u8* src, std::size_t len) {
  325. while (len-- > 0) {
  326. *dest++ = (HexCharToValue(src[0]) << 4) | HexCharToValue(src[1]);
  327. src += 2;
  328. }
  329. }
  330. /**
  331. * Convert a u32 into a gdb-formatted hex string.
  332. *
  333. * @param dest Pointer to buffer to store output hex string characters.
  334. * @param v Value to convert.
  335. */
  336. static void IntToGdbHex(u8* dest, u32 v) {
  337. for (int i = 0; i < 8; i += 2) {
  338. dest[i + 1] = NibbleToHex(static_cast<u8>(v >> (4 * i)));
  339. dest[i] = NibbleToHex(static_cast<u8>(v >> (4 * (i + 1))));
  340. }
  341. }
  342. /**
  343. * Convert a u64 into a gdb-formatted hex string.
  344. *
  345. * @param dest Pointer to buffer to store output hex string characters.
  346. * @param v Value to convert.
  347. */
  348. static void LongToGdbHex(u8* dest, u64 v) {
  349. for (int i = 0; i < 16; i += 2) {
  350. dest[i + 1] = NibbleToHex(static_cast<u8>(v >> (4 * i)));
  351. dest[i] = NibbleToHex(static_cast<u8>(v >> (4 * (i + 1))));
  352. }
  353. }
  354. /**
  355. * Convert a gdb-formatted hex string into a u32.
  356. *
  357. * @param src Pointer to hex string.
  358. */
  359. static u32 GdbHexToInt(const u8* src) {
  360. u32 output = 0;
  361. for (int i = 0; i < 8; i += 2) {
  362. output = (output << 4) | HexCharToValue(src[7 - i - 1]);
  363. output = (output << 4) | HexCharToValue(src[7 - i]);
  364. }
  365. return output;
  366. }
  367. /**
  368. * Convert a gdb-formatted hex string into a u64.
  369. *
  370. * @param src Pointer to hex string.
  371. */
  372. static u64 GdbHexToLong(const u8* src) {
  373. u64 output = 0;
  374. for (int i = 0; i < 16; i += 2) {
  375. output = (output << 4) | HexCharToValue(src[15 - i - 1]);
  376. output = (output << 4) | HexCharToValue(src[15 - i]);
  377. }
  378. return output;
  379. }
  380. /**
  381. * Convert a gdb-formatted hex string into a u128.
  382. *
  383. * @param src Pointer to hex string.
  384. */
  385. static u128 GdbHexToU128(const u8* src) {
  386. u128 output;
  387. for (int i = 0; i < 16; i += 2) {
  388. output[0] = (output[0] << 4) | HexCharToValue(src[15 - i - 1]);
  389. output[0] = (output[0] << 4) | HexCharToValue(src[15 - i]);
  390. }
  391. for (int i = 0; i < 16; i += 2) {
  392. output[1] = (output[1] << 4) | HexCharToValue(src[16 + 15 - i - 1]);
  393. output[1] = (output[1] << 4) | HexCharToValue(src[16 + 15 - i]);
  394. }
  395. return output;
  396. }
  397. /// Read a byte from the gdb client.
  398. static u8 ReadByte() {
  399. u8 c;
  400. std::size_t received_size = recv(gdbserver_socket, reinterpret_cast<char*>(&c), 1, MSG_WAITALL);
  401. if (received_size != 1) {
  402. LOG_ERROR(Debug_GDBStub, "recv failed: {}", received_size);
  403. Shutdown();
  404. }
  405. return c;
  406. }
  407. /// Calculate the checksum of the current command buffer.
  408. static u8 CalculateChecksum(const u8* buffer, std::size_t length) {
  409. return static_cast<u8>(std::accumulate(buffer, buffer + length, u8{0},
  410. [](u8 lhs, u8 rhs) { return u8(lhs + rhs); }));
  411. }
  412. /**
  413. * Get the map of breakpoints for a given breakpoint type.
  414. *
  415. * @param type Type of breakpoint map.
  416. */
  417. static BreakpointMap& GetBreakpointMap(BreakpointType type) {
  418. switch (type) {
  419. case BreakpointType::Execute:
  420. return breakpoints_execute;
  421. case BreakpointType::Read:
  422. return breakpoints_read;
  423. case BreakpointType::Write:
  424. return breakpoints_write;
  425. default:
  426. return breakpoints_read;
  427. }
  428. }
  429. /**
  430. * Remove the breakpoint from the given address of the specified type.
  431. *
  432. * @param type Type of breakpoint.
  433. * @param addr Address of breakpoint.
  434. */
  435. static void RemoveBreakpoint(BreakpointType type, VAddr addr) {
  436. BreakpointMap& p = GetBreakpointMap(type);
  437. const auto bp = p.find(addr);
  438. if (bp == p.end()) {
  439. return;
  440. }
  441. LOG_DEBUG(Debug_GDBStub, "gdb: removed a breakpoint: {:016X} bytes at {:016X} of type {}",
  442. bp->second.len, bp->second.addr, static_cast<int>(type));
  443. if (type == BreakpointType::Execute) {
  444. auto& system = Core::System::GetInstance();
  445. system.Memory().WriteBlock(bp->second.addr, bp->second.inst.data(), bp->second.inst.size());
  446. system.InvalidateCpuInstructionCaches();
  447. }
  448. p.erase(addr);
  449. }
  450. BreakpointAddress GetNextBreakpointFromAddress(VAddr addr, BreakpointType type) {
  451. const BreakpointMap& p = GetBreakpointMap(type);
  452. const auto next_breakpoint = p.lower_bound(addr);
  453. BreakpointAddress breakpoint;
  454. if (next_breakpoint != p.end()) {
  455. breakpoint.address = next_breakpoint->first;
  456. breakpoint.type = type;
  457. } else {
  458. breakpoint.address = 0;
  459. breakpoint.type = BreakpointType::None;
  460. }
  461. return breakpoint;
  462. }
  463. bool CheckBreakpoint(VAddr addr, BreakpointType type) {
  464. if (!IsConnected()) {
  465. return false;
  466. }
  467. const BreakpointMap& p = GetBreakpointMap(type);
  468. const auto bp = p.find(addr);
  469. if (bp == p.end()) {
  470. return false;
  471. }
  472. u64 len = bp->second.len;
  473. // IDA Pro defaults to 4-byte breakpoints for all non-hardware breakpoints
  474. // no matter if it's a 4-byte or 2-byte instruction. When you execute a
  475. // Thumb instruction with a 4-byte breakpoint set, it will set a breakpoint on
  476. // two instructions instead of the single instruction you placed the breakpoint
  477. // on. So, as a way to make sure that execution breakpoints are only breaking
  478. // on the instruction that was specified, set the length of an execution
  479. // breakpoint to 1. This should be fine since the CPU should never begin executing
  480. // an instruction anywhere except the beginning of the instruction.
  481. if (type == BreakpointType::Execute) {
  482. len = 1;
  483. }
  484. if (bp->second.active && (addr >= bp->second.addr && addr < bp->second.addr + len)) {
  485. LOG_DEBUG(Debug_GDBStub,
  486. "Found breakpoint type {} @ {:016X}, range: {:016X}"
  487. " - {:016X} ({:X} bytes)",
  488. static_cast<int>(type), addr, bp->second.addr, bp->second.addr + len, len);
  489. return true;
  490. }
  491. return false;
  492. }
  493. /**
  494. * Send packet to gdb client.
  495. *
  496. * @param packet Packet to be sent to client.
  497. */
  498. static void SendPacket(const char packet) {
  499. std::size_t sent_size = send(gdbserver_socket, &packet, 1, 0);
  500. if (sent_size != 1) {
  501. LOG_ERROR(Debug_GDBStub, "send failed");
  502. }
  503. }
  504. /**
  505. * Send reply to gdb client.
  506. *
  507. * @param reply Reply to be sent to client.
  508. */
  509. static void SendReply(const char* reply) {
  510. if (!IsConnected()) {
  511. return;
  512. }
  513. LOG_DEBUG(Debug_GDBStub, "Reply: {}", reply);
  514. memset(command_buffer, 0, sizeof(command_buffer));
  515. command_length = static_cast<u32>(strlen(reply));
  516. if (command_length + 4 > sizeof(command_buffer)) {
  517. LOG_ERROR(Debug_GDBStub, "command_buffer overflow in SendReply");
  518. return;
  519. }
  520. memcpy(command_buffer + 1, reply, command_length);
  521. u8 checksum = CalculateChecksum(command_buffer, command_length + 1);
  522. command_buffer[0] = GDB_STUB_START;
  523. command_buffer[command_length + 1] = GDB_STUB_END;
  524. command_buffer[command_length + 2] = NibbleToHex(checksum >> 4);
  525. command_buffer[command_length + 3] = NibbleToHex(checksum);
  526. u8* ptr = command_buffer;
  527. u32 left = command_length + 4;
  528. while (left > 0) {
  529. int sent_size = send(gdbserver_socket, reinterpret_cast<char*>(ptr), left, 0);
  530. if (sent_size < 0) {
  531. LOG_ERROR(Debug_GDBStub, "gdb: send failed");
  532. return Shutdown();
  533. }
  534. left -= sent_size;
  535. ptr += sent_size;
  536. }
  537. }
  538. /// Handle query command from gdb client.
  539. static void HandleQuery() {
  540. LOG_DEBUG(Debug_GDBStub, "gdb: query '{}'", command_buffer + 1);
  541. const char* query = reinterpret_cast<const char*>(command_buffer + 1);
  542. if (strcmp(query, "TStatus") == 0) {
  543. SendReply("T0");
  544. } else if (strncmp(query, "Supported", strlen("Supported")) == 0) {
  545. // PacketSize needs to be large enough for target xml
  546. std::string buffer = "PacketSize=2000;qXfer:features:read+;qXfer:threads:read+";
  547. if (!modules.empty()) {
  548. buffer += ";qXfer:libraries:read+";
  549. }
  550. SendReply(buffer.c_str());
  551. } else if (strncmp(query, "Xfer:features:read:target.xml:",
  552. strlen("Xfer:features:read:target.xml:")) == 0) {
  553. SendReply(target_xml);
  554. } else if (strncmp(query, "Offsets", strlen("Offsets")) == 0) {
  555. const VAddr base_address =
  556. Core::System::GetInstance().CurrentProcess()->VMManager().GetCodeRegionBaseAddress();
  557. std::string buffer = fmt::format("TextSeg={:0x}", base_address);
  558. SendReply(buffer.c_str());
  559. } else if (strncmp(query, "fThreadInfo", strlen("fThreadInfo")) == 0) {
  560. std::string val = "m";
  561. const auto& threads = Core::System::GetInstance().GlobalScheduler().GetThreadList();
  562. for (const auto& thread : threads) {
  563. val += fmt::format("{:x},", thread->GetThreadID());
  564. }
  565. val.pop_back();
  566. SendReply(val.c_str());
  567. } else if (strncmp(query, "sThreadInfo", strlen("sThreadInfo")) == 0) {
  568. SendReply("l");
  569. } else if (strncmp(query, "Xfer:threads:read", strlen("Xfer:threads:read")) == 0) {
  570. std::string buffer;
  571. buffer += "l<?xml version=\"1.0\"?>";
  572. buffer += "<threads>";
  573. const auto& threads = Core::System::GetInstance().GlobalScheduler().GetThreadList();
  574. for (const auto& thread : threads) {
  575. buffer +=
  576. fmt::format(R"*(<thread id="{:x}" core="{:d}" name="Thread {:x}"></thread>)*",
  577. thread->GetThreadID(), thread->GetProcessorID(), thread->GetThreadID());
  578. }
  579. buffer += "</threads>";
  580. SendReply(buffer.c_str());
  581. } else if (strncmp(query, "Xfer:libraries:read", strlen("Xfer:libraries:read")) == 0) {
  582. std::string buffer;
  583. buffer += "l<?xml version=\"1.0\"?>";
  584. buffer += "<library-list>";
  585. for (const auto& module : modules) {
  586. buffer +=
  587. fmt::format(R"*("<library name = "{}"><segment address = "0x{:x}"/></library>)*",
  588. module.name, module.beg);
  589. }
  590. buffer += "</library-list>";
  591. SendReply(buffer.c_str());
  592. } else {
  593. SendReply("");
  594. }
  595. }
  596. /// Handle set thread command from gdb client.
  597. static void HandleSetThread() {
  598. int thread_id = -1;
  599. if (command_buffer[2] != '-') {
  600. thread_id = static_cast<int>(HexToInt(command_buffer + 2, command_length - 2));
  601. }
  602. if (thread_id >= 1) {
  603. current_thread = FindThreadById(thread_id);
  604. }
  605. if (!current_thread) {
  606. thread_id = 1;
  607. current_thread = FindThreadById(thread_id);
  608. }
  609. if (current_thread) {
  610. SendReply("OK");
  611. return;
  612. }
  613. SendReply("E01");
  614. }
  615. /// Handle thread alive command from gdb client.
  616. static void HandleThreadAlive() {
  617. int thread_id = static_cast<int>(HexToInt(command_buffer + 1, command_length - 1));
  618. if (thread_id == 0) {
  619. thread_id = 1;
  620. }
  621. if (FindThreadById(thread_id)) {
  622. SendReply("OK");
  623. return;
  624. }
  625. SendReply("E01");
  626. }
  627. /**
  628. * Send signal packet to client.
  629. *
  630. * @param signal Signal to be sent to client.
  631. */
  632. static void SendSignal(Kernel::Thread* thread, u32 signal, bool full = true) {
  633. if (gdbserver_socket == -1) {
  634. return;
  635. }
  636. latest_signal = signal;
  637. if (!thread) {
  638. full = false;
  639. }
  640. std::string buffer;
  641. if (full) {
  642. buffer = fmt::format("T{:02x}{:02x}:{:016x};{:02x}:{:016x};{:02x}:{:016x}", latest_signal,
  643. PC_REGISTER, Common::swap64(RegRead(PC_REGISTER, thread)), SP_REGISTER,
  644. Common::swap64(RegRead(SP_REGISTER, thread)), LR_REGISTER,
  645. Common::swap64(RegRead(LR_REGISTER, thread)));
  646. } else {
  647. buffer = fmt::format("T{:02x}", latest_signal);
  648. }
  649. if (thread) {
  650. buffer += fmt::format(";thread:{:x};", thread->GetThreadID());
  651. }
  652. SendReply(buffer.c_str());
  653. }
  654. /// Read command from gdb client.
  655. static void ReadCommand() {
  656. command_length = 0;
  657. memset(command_buffer, 0, sizeof(command_buffer));
  658. u8 c = ReadByte();
  659. if (c == '+') {
  660. // ignore ack
  661. return;
  662. } else if (c == 0x03) {
  663. LOG_INFO(Debug_GDBStub, "gdb: found break command");
  664. halt_loop = true;
  665. SendSignal(current_thread, SIGTRAP);
  666. return;
  667. } else if (c != GDB_STUB_START) {
  668. LOG_DEBUG(Debug_GDBStub, "gdb: read invalid byte {:02X}", c);
  669. return;
  670. }
  671. while ((c = ReadByte()) != GDB_STUB_END) {
  672. if (command_length >= sizeof(command_buffer)) {
  673. LOG_ERROR(Debug_GDBStub, "gdb: command_buffer overflow");
  674. SendPacket(GDB_STUB_NACK);
  675. return;
  676. }
  677. command_buffer[command_length++] = c;
  678. }
  679. u8 checksum_received = HexCharToValue(ReadByte()) << 4;
  680. checksum_received |= HexCharToValue(ReadByte());
  681. u8 checksum_calculated = CalculateChecksum(command_buffer, command_length);
  682. if (checksum_received != checksum_calculated) {
  683. LOG_ERROR(Debug_GDBStub,
  684. "gdb: invalid checksum: calculated {:02X} and read {:02X} for ${}# (length: {})",
  685. checksum_calculated, checksum_received, command_buffer, command_length);
  686. command_length = 0;
  687. SendPacket(GDB_STUB_NACK);
  688. return;
  689. }
  690. SendPacket(GDB_STUB_ACK);
  691. }
  692. /// Check if there is data to be read from the gdb client.
  693. static bool IsDataAvailable() {
  694. if (!IsConnected()) {
  695. return false;
  696. }
  697. fd_set fd_socket;
  698. FD_ZERO(&fd_socket);
  699. FD_SET(static_cast<u32>(gdbserver_socket), &fd_socket);
  700. struct timeval t;
  701. t.tv_sec = 0;
  702. t.tv_usec = 0;
  703. if (select(gdbserver_socket + 1, &fd_socket, nullptr, nullptr, &t) < 0) {
  704. LOG_ERROR(Debug_GDBStub, "select failed");
  705. return false;
  706. }
  707. return FD_ISSET(gdbserver_socket, &fd_socket) != 0;
  708. }
  709. /// Send requested register to gdb client.
  710. static void ReadRegister() {
  711. static u8 reply[64];
  712. memset(reply, 0, sizeof(reply));
  713. u32 id = HexCharToValue(command_buffer[1]);
  714. if (command_buffer[2] != '\0') {
  715. id <<= 4;
  716. id |= HexCharToValue(command_buffer[2]);
  717. }
  718. if (id <= SP_REGISTER) {
  719. LongToGdbHex(reply, RegRead(id, current_thread));
  720. } else if (id == PC_REGISTER) {
  721. LongToGdbHex(reply, RegRead(id, current_thread));
  722. } else if (id == PSTATE_REGISTER) {
  723. IntToGdbHex(reply, static_cast<u32>(RegRead(id, current_thread)));
  724. } else if (id >= UC_ARM64_REG_Q0 && id < FPCR_REGISTER) {
  725. u128 r = FpuRead(id, current_thread);
  726. LongToGdbHex(reply, r[0]);
  727. LongToGdbHex(reply + 16, r[1]);
  728. } else if (id == FPCR_REGISTER) {
  729. u128 r = FpuRead(id, current_thread);
  730. IntToGdbHex(reply, static_cast<u32>(r[0]));
  731. } else if (id == FPCR_REGISTER + 1) {
  732. u128 r = FpuRead(id, current_thread);
  733. IntToGdbHex(reply, static_cast<u32>(r[0] >> 32));
  734. }
  735. SendReply(reinterpret_cast<char*>(reply));
  736. }
  737. /// Send all registers to the gdb client.
  738. static void ReadRegisters() {
  739. static u8 buffer[GDB_BUFFER_SIZE - 4];
  740. memset(buffer, 0, sizeof(buffer));
  741. u8* bufptr = buffer;
  742. for (u32 reg = 0; reg <= SP_REGISTER; reg++) {
  743. LongToGdbHex(bufptr + reg * 16, RegRead(reg, current_thread));
  744. }
  745. bufptr += 32 * 16;
  746. LongToGdbHex(bufptr, RegRead(PC_REGISTER, current_thread));
  747. bufptr += 16;
  748. IntToGdbHex(bufptr, static_cast<u32>(RegRead(PSTATE_REGISTER, current_thread)));
  749. bufptr += 8;
  750. u128 r;
  751. for (u32 reg = UC_ARM64_REG_Q0; reg < FPCR_REGISTER; reg++) {
  752. r = FpuRead(reg, current_thread);
  753. LongToGdbHex(bufptr + reg * 32, r[0]);
  754. LongToGdbHex(bufptr + reg * 32 + 16, r[1]);
  755. }
  756. bufptr += 32 * 32;
  757. r = FpuRead(FPCR_REGISTER, current_thread);
  758. IntToGdbHex(bufptr, static_cast<u32>(r[0]));
  759. bufptr += 8;
  760. SendReply(reinterpret_cast<char*>(buffer));
  761. }
  762. /// Modify data of register specified by gdb client.
  763. static void WriteRegister() {
  764. const u8* buffer_ptr = command_buffer + 3;
  765. u32 id = HexCharToValue(command_buffer[1]);
  766. if (command_buffer[2] != '=') {
  767. ++buffer_ptr;
  768. id <<= 4;
  769. id |= HexCharToValue(command_buffer[2]);
  770. }
  771. if (id <= SP_REGISTER) {
  772. RegWrite(id, GdbHexToLong(buffer_ptr), current_thread);
  773. } else if (id == PC_REGISTER) {
  774. RegWrite(id, GdbHexToLong(buffer_ptr), current_thread);
  775. } else if (id == PSTATE_REGISTER) {
  776. RegWrite(id, GdbHexToInt(buffer_ptr), current_thread);
  777. } else if (id >= UC_ARM64_REG_Q0 && id < FPCR_REGISTER) {
  778. FpuWrite(id, GdbHexToU128(buffer_ptr), current_thread);
  779. } else if (id == FPCR_REGISTER) {
  780. } else if (id == FPCR_REGISTER + 1) {
  781. }
  782. // Update ARM context, skipping scheduler - no running threads at this point
  783. Core::System::GetInstance()
  784. .ArmInterface(current_core)
  785. .LoadContext(current_thread->GetContext64());
  786. SendReply("OK");
  787. }
  788. /// Modify all registers with data received from the client.
  789. static void WriteRegisters() {
  790. const u8* buffer_ptr = command_buffer + 1;
  791. if (command_buffer[0] != 'G')
  792. return SendReply("E01");
  793. for (u32 i = 0, reg = 0; reg <= FPCR_REGISTER; i++, reg++) {
  794. if (reg <= SP_REGISTER) {
  795. RegWrite(reg, GdbHexToLong(buffer_ptr + i * 16), current_thread);
  796. } else if (reg == PC_REGISTER) {
  797. RegWrite(PC_REGISTER, GdbHexToLong(buffer_ptr + i * 16), current_thread);
  798. } else if (reg == PSTATE_REGISTER) {
  799. RegWrite(PSTATE_REGISTER, GdbHexToInt(buffer_ptr + i * 16), current_thread);
  800. } else if (reg >= UC_ARM64_REG_Q0 && reg < FPCR_REGISTER) {
  801. RegWrite(reg, GdbHexToLong(buffer_ptr + i * 16), current_thread);
  802. } else if (reg == FPCR_REGISTER) {
  803. RegWrite(FPCR_REGISTER, GdbHexToLong(buffer_ptr + i * 16), current_thread);
  804. } else if (reg == FPCR_REGISTER + 1) {
  805. RegWrite(FPCR_REGISTER, GdbHexToLong(buffer_ptr + i * 16), current_thread);
  806. }
  807. }
  808. // Update ARM context, skipping scheduler - no running threads at this point
  809. Core::System::GetInstance()
  810. .ArmInterface(current_core)
  811. .LoadContext(current_thread->GetContext64());
  812. SendReply("OK");
  813. }
  814. /// Read location in memory specified by gdb client.
  815. static void ReadMemory() {
  816. static u8 reply[GDB_BUFFER_SIZE - 4];
  817. auto start_offset = command_buffer + 1;
  818. const auto addr_pos = std::find(start_offset, command_buffer + command_length, ',');
  819. const VAddr addr = HexToLong(start_offset, static_cast<u64>(addr_pos - start_offset));
  820. start_offset = addr_pos + 1;
  821. const u64 len =
  822. HexToLong(start_offset, static_cast<u64>((command_buffer + command_length) - start_offset));
  823. LOG_DEBUG(Debug_GDBStub, "gdb: addr: {:016X} len: {:016X}", addr, len);
  824. if (len * 2 > sizeof(reply)) {
  825. SendReply("E01");
  826. }
  827. auto& memory = Core::System::GetInstance().Memory();
  828. if (!memory.IsValidVirtualAddress(addr)) {
  829. return SendReply("E00");
  830. }
  831. std::vector<u8> data(len);
  832. memory.ReadBlock(addr, data.data(), len);
  833. MemToGdbHex(reply, data.data(), len);
  834. reply[len * 2] = '\0';
  835. SendReply(reinterpret_cast<char*>(reply));
  836. }
  837. /// Modify location in memory with data received from the gdb client.
  838. static void WriteMemory() {
  839. auto start_offset = command_buffer + 1;
  840. const auto addr_pos = std::find(start_offset, command_buffer + command_length, ',');
  841. const VAddr addr = HexToLong(start_offset, static_cast<u64>(addr_pos - start_offset));
  842. start_offset = addr_pos + 1;
  843. const auto len_pos = std::find(start_offset, command_buffer + command_length, ':');
  844. const u64 len = HexToLong(start_offset, static_cast<u64>(len_pos - start_offset));
  845. auto& system = Core::System::GetInstance();
  846. auto& memory = system.Memory();
  847. if (!memory.IsValidVirtualAddress(addr)) {
  848. return SendReply("E00");
  849. }
  850. std::vector<u8> data(len);
  851. GdbHexToMem(data.data(), len_pos + 1, len);
  852. memory.WriteBlock(addr, data.data(), len);
  853. system.InvalidateCpuInstructionCaches();
  854. SendReply("OK");
  855. }
  856. void Break(bool is_memory_break) {
  857. send_trap = true;
  858. memory_break = is_memory_break;
  859. }
  860. /// Tell the CPU that it should perform a single step.
  861. static void Step() {
  862. if (command_length > 1) {
  863. RegWrite(PC_REGISTER, GdbHexToLong(command_buffer + 1), current_thread);
  864. // Update ARM context, skipping scheduler - no running threads at this point
  865. Core::System::GetInstance()
  866. .ArmInterface(current_core)
  867. .LoadContext(current_thread->GetContext64());
  868. }
  869. step_loop = true;
  870. halt_loop = true;
  871. send_trap = true;
  872. Core::System::GetInstance().InvalidateCpuInstructionCaches();
  873. }
  874. /// Tell the CPU if we hit a memory breakpoint.
  875. bool IsMemoryBreak() {
  876. if (!IsConnected()) {
  877. return false;
  878. }
  879. return memory_break;
  880. }
  881. /// Tell the CPU to continue executing.
  882. static void Continue() {
  883. memory_break = false;
  884. step_loop = false;
  885. halt_loop = false;
  886. Core::System::GetInstance().InvalidateCpuInstructionCaches();
  887. }
  888. /**
  889. * Commit breakpoint to list of breakpoints.
  890. *
  891. * @param type Type of breakpoint.
  892. * @param addr Address of breakpoint.
  893. * @param len Length of breakpoint.
  894. */
  895. static bool CommitBreakpoint(BreakpointType type, VAddr addr, u64 len) {
  896. BreakpointMap& p = GetBreakpointMap(type);
  897. Breakpoint breakpoint;
  898. breakpoint.active = true;
  899. breakpoint.addr = addr;
  900. breakpoint.len = len;
  901. auto& system = Core::System::GetInstance();
  902. auto& memory = system.Memory();
  903. memory.ReadBlock(addr, breakpoint.inst.data(), breakpoint.inst.size());
  904. static constexpr std::array<u8, 4> btrap{0x00, 0x7d, 0x20, 0xd4};
  905. if (type == BreakpointType::Execute) {
  906. memory.WriteBlock(addr, btrap.data(), btrap.size());
  907. system.InvalidateCpuInstructionCaches();
  908. }
  909. p.insert({addr, breakpoint});
  910. LOG_DEBUG(Debug_GDBStub, "gdb: added {} breakpoint: {:016X} bytes at {:016X}",
  911. static_cast<int>(type), breakpoint.len, breakpoint.addr);
  912. return true;
  913. }
  914. /// Handle add breakpoint command from gdb client.
  915. static void AddBreakpoint() {
  916. BreakpointType type;
  917. u8 type_id = HexCharToValue(command_buffer[1]);
  918. switch (type_id) {
  919. case 0:
  920. case 1:
  921. type = BreakpointType::Execute;
  922. break;
  923. case 2:
  924. type = BreakpointType::Write;
  925. break;
  926. case 3:
  927. type = BreakpointType::Read;
  928. break;
  929. case 4:
  930. type = BreakpointType::Access;
  931. break;
  932. default:
  933. return SendReply("E01");
  934. }
  935. auto start_offset = command_buffer + 3;
  936. auto addr_pos = std::find(start_offset, command_buffer + command_length, ',');
  937. VAddr addr = HexToLong(start_offset, static_cast<u64>(addr_pos - start_offset));
  938. start_offset = addr_pos + 1;
  939. u64 len =
  940. HexToLong(start_offset, static_cast<u64>((command_buffer + command_length) - start_offset));
  941. if (type == BreakpointType::Access) {
  942. // Access is made up of Read and Write types, so add both breakpoints
  943. type = BreakpointType::Read;
  944. if (!CommitBreakpoint(type, addr, len)) {
  945. return SendReply("E02");
  946. }
  947. type = BreakpointType::Write;
  948. }
  949. if (!CommitBreakpoint(type, addr, len)) {
  950. return SendReply("E02");
  951. }
  952. SendReply("OK");
  953. }
  954. /// Handle remove breakpoint command from gdb client.
  955. static void RemoveBreakpoint() {
  956. BreakpointType type;
  957. u8 type_id = HexCharToValue(command_buffer[1]);
  958. switch (type_id) {
  959. case 0:
  960. case 1:
  961. type = BreakpointType::Execute;
  962. break;
  963. case 2:
  964. type = BreakpointType::Write;
  965. break;
  966. case 3:
  967. type = BreakpointType::Read;
  968. break;
  969. case 4:
  970. type = BreakpointType::Access;
  971. break;
  972. default:
  973. return SendReply("E01");
  974. }
  975. auto start_offset = command_buffer + 3;
  976. auto addr_pos = std::find(start_offset, command_buffer + command_length, ',');
  977. VAddr addr = HexToLong(start_offset, static_cast<u64>(addr_pos - start_offset));
  978. if (type == BreakpointType::Access) {
  979. // Access is made up of Read and Write types, so add both breakpoints
  980. type = BreakpointType::Read;
  981. RemoveBreakpoint(type, addr);
  982. type = BreakpointType::Write;
  983. }
  984. RemoveBreakpoint(type, addr);
  985. SendReply("OK");
  986. }
  987. void HandlePacket() {
  988. if (!IsConnected()) {
  989. if (defer_start) {
  990. ToggleServer(true);
  991. }
  992. return;
  993. }
  994. if (!IsDataAvailable()) {
  995. return;
  996. }
  997. ReadCommand();
  998. if (command_length == 0) {
  999. return;
  1000. }
  1001. LOG_DEBUG(Debug_GDBStub, "Packet: {}", command_buffer);
  1002. switch (command_buffer[0]) {
  1003. case 'q':
  1004. HandleQuery();
  1005. break;
  1006. case 'H':
  1007. HandleSetThread();
  1008. break;
  1009. case '?':
  1010. SendSignal(current_thread, latest_signal);
  1011. break;
  1012. case 'k':
  1013. Shutdown();
  1014. LOG_INFO(Debug_GDBStub, "killed by gdb");
  1015. return;
  1016. case 'g':
  1017. ReadRegisters();
  1018. break;
  1019. case 'G':
  1020. WriteRegisters();
  1021. break;
  1022. case 'p':
  1023. ReadRegister();
  1024. break;
  1025. case 'P':
  1026. WriteRegister();
  1027. break;
  1028. case 'm':
  1029. ReadMemory();
  1030. break;
  1031. case 'M':
  1032. WriteMemory();
  1033. break;
  1034. case 's':
  1035. Step();
  1036. return;
  1037. case 'C':
  1038. case 'c':
  1039. Continue();
  1040. return;
  1041. case 'z':
  1042. RemoveBreakpoint();
  1043. break;
  1044. case 'Z':
  1045. AddBreakpoint();
  1046. break;
  1047. case 'T':
  1048. HandleThreadAlive();
  1049. break;
  1050. default:
  1051. SendReply("");
  1052. break;
  1053. }
  1054. }
  1055. void SetServerPort(u16 port) {
  1056. gdbstub_port = port;
  1057. }
  1058. void ToggleServer(bool status) {
  1059. if (status) {
  1060. server_enabled = status;
  1061. // Start server
  1062. if (!IsConnected() && Core::System::GetInstance().IsPoweredOn()) {
  1063. Init();
  1064. }
  1065. } else {
  1066. // Stop server
  1067. if (IsConnected()) {
  1068. Shutdown();
  1069. }
  1070. server_enabled = status;
  1071. }
  1072. }
  1073. void DeferStart() {
  1074. defer_start = true;
  1075. }
  1076. static void Init(u16 port) {
  1077. if (!server_enabled) {
  1078. // Set the halt loop to false in case the user enabled the gdbstub mid-execution.
  1079. // This way the CPU can still execute normally.
  1080. halt_loop = false;
  1081. step_loop = false;
  1082. return;
  1083. }
  1084. // Setup initial gdbstub status
  1085. halt_loop = true;
  1086. step_loop = false;
  1087. breakpoints_execute.clear();
  1088. breakpoints_read.clear();
  1089. breakpoints_write.clear();
  1090. modules.clear();
  1091. // Start gdb server
  1092. LOG_INFO(Debug_GDBStub, "Starting GDB server on port {}...", port);
  1093. sockaddr_in saddr_server = {};
  1094. saddr_server.sin_family = AF_INET;
  1095. saddr_server.sin_port = htons(port);
  1096. saddr_server.sin_addr.s_addr = INADDR_ANY;
  1097. #ifdef _WIN32
  1098. WSAStartup(MAKEWORD(2, 2), &InitData);
  1099. #endif
  1100. int tmpsock = static_cast<int>(socket(PF_INET, SOCK_STREAM, 0));
  1101. if (tmpsock == -1) {
  1102. LOG_ERROR(Debug_GDBStub, "Failed to create gdb socket");
  1103. }
  1104. // Set socket to SO_REUSEADDR so it can always bind on the same port
  1105. int reuse_enabled = 1;
  1106. if (setsockopt(tmpsock, SOL_SOCKET, SO_REUSEADDR, (const char*)&reuse_enabled,
  1107. sizeof(reuse_enabled)) < 0) {
  1108. LOG_ERROR(Debug_GDBStub, "Failed to set gdb socket option");
  1109. }
  1110. const sockaddr* server_addr = reinterpret_cast<const sockaddr*>(&saddr_server);
  1111. socklen_t server_addrlen = sizeof(saddr_server);
  1112. if (bind(tmpsock, server_addr, server_addrlen) < 0) {
  1113. LOG_ERROR(Debug_GDBStub, "Failed to bind gdb socket");
  1114. }
  1115. if (listen(tmpsock, 1) < 0) {
  1116. LOG_ERROR(Debug_GDBStub, "Failed to listen to gdb socket");
  1117. }
  1118. // Wait for gdb to connect
  1119. LOG_INFO(Debug_GDBStub, "Waiting for gdb to connect...");
  1120. sockaddr_in saddr_client;
  1121. sockaddr* client_addr = reinterpret_cast<sockaddr*>(&saddr_client);
  1122. socklen_t client_addrlen = sizeof(saddr_client);
  1123. gdbserver_socket = static_cast<int>(accept(tmpsock, client_addr, &client_addrlen));
  1124. if (gdbserver_socket < 0) {
  1125. // In the case that we couldn't start the server for whatever reason, just start CPU
  1126. // execution like normal.
  1127. halt_loop = false;
  1128. step_loop = false;
  1129. LOG_ERROR(Debug_GDBStub, "Failed to accept gdb client");
  1130. } else {
  1131. LOG_INFO(Debug_GDBStub, "Client connected.");
  1132. saddr_client.sin_addr.s_addr = ntohl(saddr_client.sin_addr.s_addr);
  1133. }
  1134. // Clean up temporary socket if it's still alive at this point.
  1135. if (tmpsock != -1) {
  1136. shutdown(tmpsock, SHUT_RDWR);
  1137. }
  1138. }
  1139. void Init() {
  1140. Init(gdbstub_port);
  1141. }
  1142. void Shutdown() {
  1143. if (!server_enabled) {
  1144. return;
  1145. }
  1146. defer_start = false;
  1147. LOG_INFO(Debug_GDBStub, "Stopping GDB ...");
  1148. if (gdbserver_socket != -1) {
  1149. shutdown(gdbserver_socket, SHUT_RDWR);
  1150. gdbserver_socket = -1;
  1151. }
  1152. #ifdef _WIN32
  1153. WSACleanup();
  1154. #endif
  1155. LOG_INFO(Debug_GDBStub, "GDB stopped.");
  1156. }
  1157. bool IsServerEnabled() {
  1158. return server_enabled;
  1159. }
  1160. bool IsConnected() {
  1161. return IsServerEnabled() && gdbserver_socket != -1;
  1162. }
  1163. bool GetCpuHaltFlag() {
  1164. return halt_loop;
  1165. }
  1166. bool GetCpuStepFlag() {
  1167. return step_loop;
  1168. }
  1169. void SetCpuStepFlag(bool is_step) {
  1170. step_loop = is_step;
  1171. }
  1172. void SendTrap(Kernel::Thread* thread, int trap) {
  1173. if (!send_trap) {
  1174. return;
  1175. }
  1176. current_thread = thread;
  1177. SendSignal(thread, trap);
  1178. halt_loop = true;
  1179. send_trap = false;
  1180. }
  1181. }; // namespace GDBStub