gdbstub.cpp 39 KB

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