gdbstub.cpp 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382
  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(int id) {
  176. for (u32 core = 0; core < Core::NUM_CPU_CORES; core++) {
  177. const auto& threads = Core::System::GetInstance().Scheduler(core).GetThreadList();
  178. for (auto& thread : threads) {
  179. if (thread->GetThreadID() == static_cast<u32>(id)) {
  180. current_core = core;
  181. return thread.get();
  182. }
  183. }
  184. }
  185. return nullptr;
  186. }
  187. static u64 RegRead(std::size_t id, Kernel::Thread* thread = nullptr) {
  188. if (!thread) {
  189. return 0;
  190. }
  191. const auto& thread_context = thread->GetContext();
  192. if (id < SP_REGISTER) {
  193. return thread_context.cpu_registers[id];
  194. } else if (id == SP_REGISTER) {
  195. return thread_context.sp;
  196. } else if (id == PC_REGISTER) {
  197. return thread_context.pc;
  198. } else if (id == PSTATE_REGISTER) {
  199. return thread_context.pstate;
  200. } else if (id > PSTATE_REGISTER && id < FPCR_REGISTER) {
  201. return thread_context.vector_registers[id - UC_ARM64_REG_Q0][0];
  202. } else {
  203. return 0;
  204. }
  205. }
  206. static void RegWrite(std::size_t id, u64 val, Kernel::Thread* thread = nullptr) {
  207. if (!thread) {
  208. return;
  209. }
  210. auto& thread_context = thread->GetContext();
  211. if (id < SP_REGISTER) {
  212. thread_context.cpu_registers[id] = val;
  213. } else if (id == SP_REGISTER) {
  214. thread_context.sp = val;
  215. } else if (id == PC_REGISTER) {
  216. thread_context.pc = val;
  217. } else if (id == PSTATE_REGISTER) {
  218. thread_context.pstate = static_cast<u32>(val);
  219. } else if (id > PSTATE_REGISTER && id < FPCR_REGISTER) {
  220. thread_context.vector_registers[id - (PSTATE_REGISTER + 1)][0] = val;
  221. }
  222. }
  223. static u128 FpuRead(std::size_t id, Kernel::Thread* thread = nullptr) {
  224. if (!thread) {
  225. return u128{0};
  226. }
  227. auto& thread_context = thread->GetContext();
  228. if (id >= UC_ARM64_REG_Q0 && id < FPCR_REGISTER) {
  229. return thread_context.vector_registers[id - UC_ARM64_REG_Q0];
  230. } else if (id == FPCR_REGISTER) {
  231. return u128{thread_context.fpcr, 0};
  232. } else {
  233. return u128{0};
  234. }
  235. }
  236. static void FpuWrite(std::size_t id, u128 val, Kernel::Thread* thread = nullptr) {
  237. if (!thread) {
  238. return;
  239. }
  240. auto& thread_context = thread->GetContext();
  241. if (id >= UC_ARM64_REG_Q0 && id < FPCR_REGISTER) {
  242. thread_context.vector_registers[id - UC_ARM64_REG_Q0] = val;
  243. } else if (id == FPCR_REGISTER) {
  244. thread_context.fpcr = static_cast<u32>(val[0]);
  245. }
  246. }
  247. /**
  248. * Turns hex string character into the equivalent byte.
  249. *
  250. * @param hex Input hex character to be turned into byte.
  251. */
  252. static u8 HexCharToValue(u8 hex) {
  253. if (hex >= '0' && hex <= '9') {
  254. return hex - '0';
  255. } else if (hex >= 'a' && hex <= 'f') {
  256. return hex - 'a' + 0xA;
  257. } else if (hex >= 'A' && hex <= 'F') {
  258. return hex - 'A' + 0xA;
  259. }
  260. LOG_ERROR(Debug_GDBStub, "Invalid nibble: {} ({:02X})", hex, hex);
  261. return 0;
  262. }
  263. /**
  264. * Turn nibble of byte into hex string character.
  265. *
  266. * @param n Nibble to be turned into hex character.
  267. */
  268. static u8 NibbleToHex(u8 n) {
  269. n &= 0xF;
  270. if (n < 0xA) {
  271. return '0' + n;
  272. } else {
  273. return 'a' + n - 0xA;
  274. }
  275. }
  276. /**
  277. * Converts input hex string characters into an array of equivalent of u8 bytes.
  278. *
  279. * @param src Pointer to array of output hex string characters.
  280. * @param len Length of src array.
  281. */
  282. static u32 HexToInt(const u8* src, std::size_t len) {
  283. u32 output = 0;
  284. while (len-- > 0) {
  285. output = (output << 4) | HexCharToValue(src[0]);
  286. src++;
  287. }
  288. return output;
  289. }
  290. /**
  291. * Converts input hex string characters into an array of equivalent of u8 bytes.
  292. *
  293. * @param src Pointer to array of output hex string characters.
  294. * @param len Length of src array.
  295. */
  296. static u64 HexToLong(const u8* src, std::size_t len) {
  297. u64 output = 0;
  298. while (len-- > 0) {
  299. output = (output << 4) | HexCharToValue(src[0]);
  300. src++;
  301. }
  302. return output;
  303. }
  304. /**
  305. * Converts input array of u8 bytes into their equivalent hex string characters.
  306. *
  307. * @param dest Pointer to buffer to store output hex string characters.
  308. * @param src Pointer to array of u8 bytes.
  309. * @param len Length of src array.
  310. */
  311. static void MemToGdbHex(u8* dest, const u8* src, std::size_t len) {
  312. while (len-- > 0) {
  313. u8 tmp = *src++;
  314. *dest++ = NibbleToHex(tmp >> 4);
  315. *dest++ = NibbleToHex(tmp);
  316. }
  317. }
  318. /**
  319. * Converts input gdb-formatted hex string characters into an array of equivalent of u8 bytes.
  320. *
  321. * @param dest Pointer to buffer to store u8 bytes.
  322. * @param src Pointer to array of output hex string characters.
  323. * @param len Length of src array.
  324. */
  325. static void GdbHexToMem(u8* dest, const u8* src, std::size_t len) {
  326. while (len-- > 0) {
  327. *dest++ = (HexCharToValue(src[0]) << 4) | HexCharToValue(src[1]);
  328. src += 2;
  329. }
  330. }
  331. /**
  332. * Convert a u32 into a gdb-formatted hex string.
  333. *
  334. * @param dest Pointer to buffer to store output hex string characters.
  335. * @param v Value to convert.
  336. */
  337. static void IntToGdbHex(u8* dest, u32 v) {
  338. for (int i = 0; i < 8; i += 2) {
  339. dest[i + 1] = NibbleToHex(static_cast<u8>(v >> (4 * i)));
  340. dest[i] = NibbleToHex(static_cast<u8>(v >> (4 * (i + 1))));
  341. }
  342. }
  343. /**
  344. * Convert a u64 into a gdb-formatted hex string.
  345. *
  346. * @param dest Pointer to buffer to store output hex string characters.
  347. * @param v Value to convert.
  348. */
  349. static void LongToGdbHex(u8* dest, u64 v) {
  350. for (int i = 0; i < 16; i += 2) {
  351. dest[i + 1] = NibbleToHex(static_cast<u8>(v >> (4 * i)));
  352. dest[i] = NibbleToHex(static_cast<u8>(v >> (4 * (i + 1))));
  353. }
  354. }
  355. /**
  356. * Convert a gdb-formatted hex string into a u32.
  357. *
  358. * @param src Pointer to hex string.
  359. */
  360. static u32 GdbHexToInt(const u8* src) {
  361. u32 output = 0;
  362. for (int i = 0; i < 8; i += 2) {
  363. output = (output << 4) | HexCharToValue(src[7 - i - 1]);
  364. output = (output << 4) | HexCharToValue(src[7 - i]);
  365. }
  366. return output;
  367. }
  368. /**
  369. * Convert a gdb-formatted hex string into a u64.
  370. *
  371. * @param src Pointer to hex string.
  372. */
  373. static u64 GdbHexToLong(const u8* src) {
  374. u64 output = 0;
  375. for (int i = 0; i < 16; i += 2) {
  376. output = (output << 4) | HexCharToValue(src[15 - i - 1]);
  377. output = (output << 4) | HexCharToValue(src[15 - i]);
  378. }
  379. return output;
  380. }
  381. /**
  382. * Convert a gdb-formatted hex string into a u128.
  383. *
  384. * @param src Pointer to hex string.
  385. */
  386. static u128 GdbHexToU128(const u8* src) {
  387. u128 output;
  388. for (int i = 0; i < 16; i += 2) {
  389. output[0] = (output[0] << 4) | HexCharToValue(src[15 - i - 1]);
  390. output[0] = (output[0] << 4) | HexCharToValue(src[15 - i]);
  391. }
  392. for (int i = 0; i < 16; i += 2) {
  393. output[1] = (output[1] << 4) | HexCharToValue(src[16 + 15 - i - 1]);
  394. output[1] = (output[1] << 4) | HexCharToValue(src[16 + 15 - i]);
  395. }
  396. return output;
  397. }
  398. /// Read a byte from the gdb client.
  399. static u8 ReadByte() {
  400. u8 c;
  401. std::size_t received_size = recv(gdbserver_socket, reinterpret_cast<char*>(&c), 1, MSG_WAITALL);
  402. if (received_size != 1) {
  403. LOG_ERROR(Debug_GDBStub, "recv failed: {}", received_size);
  404. Shutdown();
  405. }
  406. return c;
  407. }
  408. /// Calculate the checksum of the current command buffer.
  409. static u8 CalculateChecksum(const u8* buffer, std::size_t length) {
  410. return static_cast<u8>(std::accumulate(buffer, buffer + length, 0, std::plus<u8>()));
  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. Memory::WriteBlock(bp->second.addr, bp->second.inst.data(), bp->second.inst.size());
  444. Core::System::GetInstance().InvalidateCpuInstructionCaches();
  445. p.erase(addr);
  446. }
  447. BreakpointAddress GetNextBreakpointFromAddress(VAddr addr, BreakpointType type) {
  448. const BreakpointMap& p = GetBreakpointMap(type);
  449. const auto next_breakpoint = p.lower_bound(addr);
  450. BreakpointAddress breakpoint;
  451. if (next_breakpoint != p.end()) {
  452. breakpoint.address = next_breakpoint->first;
  453. breakpoint.type = type;
  454. } else {
  455. breakpoint.address = 0;
  456. breakpoint.type = BreakpointType::None;
  457. }
  458. return breakpoint;
  459. }
  460. bool CheckBreakpoint(VAddr addr, BreakpointType type) {
  461. if (!IsConnected()) {
  462. return false;
  463. }
  464. const BreakpointMap& p = GetBreakpointMap(type);
  465. const auto bp = p.find(addr);
  466. if (bp == p.end()) {
  467. return false;
  468. }
  469. u64 len = bp->second.len;
  470. // IDA Pro defaults to 4-byte breakpoints for all non-hardware breakpoints
  471. // no matter if it's a 4-byte or 2-byte instruction. When you execute a
  472. // Thumb instruction with a 4-byte breakpoint set, it will set a breakpoint on
  473. // two instructions instead of the single instruction you placed the breakpoint
  474. // on. So, as a way to make sure that execution breakpoints are only breaking
  475. // on the instruction that was specified, set the length of an execution
  476. // breakpoint to 1. This should be fine since the CPU should never begin executing
  477. // an instruction anywhere except the beginning of the instruction.
  478. if (type == BreakpointType::Execute) {
  479. len = 1;
  480. }
  481. if (bp->second.active && (addr >= bp->second.addr && addr < bp->second.addr + len)) {
  482. LOG_DEBUG(Debug_GDBStub,
  483. "Found breakpoint type {} @ {:016X}, range: {:016X}"
  484. " - {:016X} ({:X} bytes)",
  485. static_cast<int>(type), addr, bp->second.addr, bp->second.addr + len, len);
  486. return true;
  487. }
  488. return false;
  489. }
  490. /**
  491. * Send packet to gdb client.
  492. *
  493. * @param packet Packet to be sent to client.
  494. */
  495. static void SendPacket(const char packet) {
  496. std::size_t sent_size = send(gdbserver_socket, &packet, 1, 0);
  497. if (sent_size != 1) {
  498. LOG_ERROR(Debug_GDBStub, "send failed");
  499. }
  500. }
  501. /**
  502. * Send reply to gdb client.
  503. *
  504. * @param reply Reply to be sent to client.
  505. */
  506. static void SendReply(const char* reply) {
  507. if (!IsConnected()) {
  508. return;
  509. }
  510. LOG_DEBUG(Debug_GDBStub, "Reply: {}", reply);
  511. memset(command_buffer, 0, sizeof(command_buffer));
  512. command_length = static_cast<u32>(strlen(reply));
  513. if (command_length + 4 > sizeof(command_buffer)) {
  514. LOG_ERROR(Debug_GDBStub, "command_buffer overflow in SendReply");
  515. return;
  516. }
  517. memcpy(command_buffer + 1, reply, command_length);
  518. u8 checksum = CalculateChecksum(command_buffer, command_length + 1);
  519. command_buffer[0] = GDB_STUB_START;
  520. command_buffer[command_length + 1] = GDB_STUB_END;
  521. command_buffer[command_length + 2] = NibbleToHex(checksum >> 4);
  522. command_buffer[command_length + 3] = NibbleToHex(checksum);
  523. u8* ptr = command_buffer;
  524. u32 left = command_length + 4;
  525. while (left > 0) {
  526. int sent_size = send(gdbserver_socket, reinterpret_cast<char*>(ptr), left, 0);
  527. if (sent_size < 0) {
  528. LOG_ERROR(Debug_GDBStub, "gdb: send failed");
  529. return Shutdown();
  530. }
  531. left -= sent_size;
  532. ptr += sent_size;
  533. }
  534. }
  535. /// Handle query command from gdb client.
  536. static void HandleQuery() {
  537. LOG_DEBUG(Debug_GDBStub, "gdb: query '{}'", command_buffer + 1);
  538. const char* query = reinterpret_cast<const char*>(command_buffer + 1);
  539. if (strcmp(query, "TStatus") == 0) {
  540. SendReply("T0");
  541. } else if (strncmp(query, "Supported", strlen("Supported")) == 0) {
  542. // PacketSize needs to be large enough for target xml
  543. std::string buffer = "PacketSize=2000;qXfer:features:read+;qXfer:threads:read+";
  544. if (!modules.empty()) {
  545. buffer += ";qXfer:libraries:read+";
  546. }
  547. SendReply(buffer.c_str());
  548. } else if (strncmp(query, "Xfer:features:read:target.xml:",
  549. strlen("Xfer:features:read:target.xml:")) == 0) {
  550. SendReply(target_xml);
  551. } else if (strncmp(query, "Offsets", strlen("Offsets")) == 0) {
  552. const VAddr base_address = Core::CurrentProcess()->VMManager().GetCodeRegionBaseAddress();
  553. std::string buffer = fmt::format("TextSeg={:0x}", base_address);
  554. SendReply(buffer.c_str());
  555. } else if (strncmp(query, "fThreadInfo", strlen("fThreadInfo")) == 0) {
  556. std::string val = "m";
  557. for (u32 core = 0; core < Core::NUM_CPU_CORES; core++) {
  558. const auto& threads = Core::System::GetInstance().Scheduler(core).GetThreadList();
  559. for (const auto& thread : threads) {
  560. val += fmt::format("{:x},", thread->GetThreadID());
  561. }
  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. for (u32 core = 0; core < Core::NUM_CPU_CORES; core++) {
  572. const auto& threads = Core::System::GetInstance().Scheduler(core).GetThreadList();
  573. for (const auto& thread : threads) {
  574. buffer +=
  575. fmt::format(R"*(<thread id="{:x}" core="{:d}" name="Thread {:x}"></thread>)*",
  576. thread->GetThreadID(), core, thread->GetThreadID());
  577. }
  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->GetContext());
  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->GetContext());
  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. if (!Memory::IsValidVirtualAddress(addr)) {
  828. return SendReply("E00");
  829. }
  830. std::vector<u8> data(len);
  831. Memory::ReadBlock(addr, data.data(), len);
  832. MemToGdbHex(reply, data.data(), len);
  833. reply[len * 2] = '\0';
  834. SendReply(reinterpret_cast<char*>(reply));
  835. }
  836. /// Modify location in memory with data received from the gdb client.
  837. static void WriteMemory() {
  838. auto start_offset = command_buffer + 1;
  839. auto addr_pos = std::find(start_offset, command_buffer + command_length, ',');
  840. VAddr addr = HexToLong(start_offset, static_cast<u64>(addr_pos - start_offset));
  841. start_offset = addr_pos + 1;
  842. auto len_pos = std::find(start_offset, command_buffer + command_length, ':');
  843. u64 len = HexToLong(start_offset, static_cast<u64>(len_pos - start_offset));
  844. if (!Memory::IsValidVirtualAddress(addr)) {
  845. return SendReply("E00");
  846. }
  847. std::vector<u8> data(len);
  848. GdbHexToMem(data.data(), len_pos + 1, len);
  849. Memory::WriteBlock(addr, data.data(), len);
  850. Core::System::GetInstance().InvalidateCpuInstructionCaches();
  851. SendReply("OK");
  852. }
  853. void Break(bool is_memory_break) {
  854. send_trap = true;
  855. memory_break = is_memory_break;
  856. }
  857. /// Tell the CPU that it should perform a single step.
  858. static void Step() {
  859. if (command_length > 1) {
  860. RegWrite(PC_REGISTER, GdbHexToLong(command_buffer + 1), current_thread);
  861. // Update ARM context, skipping scheduler - no running threads at this point
  862. Core::System::GetInstance()
  863. .ArmInterface(current_core)
  864. .LoadContext(current_thread->GetContext());
  865. }
  866. step_loop = true;
  867. halt_loop = true;
  868. send_trap = true;
  869. Core::System::GetInstance().InvalidateCpuInstructionCaches();
  870. }
  871. /// Tell the CPU if we hit a memory breakpoint.
  872. bool IsMemoryBreak() {
  873. if (IsConnected()) {
  874. return false;
  875. }
  876. return memory_break;
  877. }
  878. /// Tell the CPU to continue executing.
  879. static void Continue() {
  880. memory_break = false;
  881. step_loop = false;
  882. halt_loop = false;
  883. Core::System::GetInstance().InvalidateCpuInstructionCaches();
  884. }
  885. /**
  886. * Commit breakpoint to list of breakpoints.
  887. *
  888. * @param type Type of breakpoint.
  889. * @param addr Address of breakpoint.
  890. * @param len Length of breakpoint.
  891. */
  892. static bool CommitBreakpoint(BreakpointType type, VAddr addr, u64 len) {
  893. BreakpointMap& p = GetBreakpointMap(type);
  894. Breakpoint breakpoint;
  895. breakpoint.active = true;
  896. breakpoint.addr = addr;
  897. breakpoint.len = len;
  898. Memory::ReadBlock(addr, breakpoint.inst.data(), breakpoint.inst.size());
  899. static constexpr std::array<u8, 4> btrap{0x00, 0x7d, 0x20, 0xd4};
  900. Memory::WriteBlock(addr, btrap.data(), btrap.size());
  901. Core::System::GetInstance().InvalidateCpuInstructionCaches();
  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