gdbstub.cpp 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388
  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. 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<u64>(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. if (type == BreakpointType::Execute) {
  444. Memory::WriteBlock(bp->second.addr, bp->second.inst.data(), bp->second.inst.size());
  445. Core::System::GetInstance().InvalidateCpuInstructionCaches();
  446. }
  447. p.erase(addr);
  448. }
  449. BreakpointAddress GetNextBreakpointFromAddress(VAddr addr, BreakpointType type) {
  450. const BreakpointMap& p = GetBreakpointMap(type);
  451. const auto next_breakpoint = p.lower_bound(addr);
  452. BreakpointAddress breakpoint;
  453. if (next_breakpoint != p.end()) {
  454. breakpoint.address = next_breakpoint->first;
  455. breakpoint.type = type;
  456. } else {
  457. breakpoint.address = 0;
  458. breakpoint.type = BreakpointType::None;
  459. }
  460. return breakpoint;
  461. }
  462. bool CheckBreakpoint(VAddr addr, BreakpointType type) {
  463. if (!IsConnected()) {
  464. return false;
  465. }
  466. const BreakpointMap& p = GetBreakpointMap(type);
  467. const auto bp = p.find(addr);
  468. if (bp == p.end()) {
  469. return false;
  470. }
  471. u64 len = bp->second.len;
  472. // IDA Pro defaults to 4-byte breakpoints for all non-hardware breakpoints
  473. // no matter if it's a 4-byte or 2-byte instruction. When you execute a
  474. // Thumb instruction with a 4-byte breakpoint set, it will set a breakpoint on
  475. // two instructions instead of the single instruction you placed the breakpoint
  476. // on. So, as a way to make sure that execution breakpoints are only breaking
  477. // on the instruction that was specified, set the length of an execution
  478. // breakpoint to 1. This should be fine since the CPU should never begin executing
  479. // an instruction anywhere except the beginning of the instruction.
  480. if (type == BreakpointType::Execute) {
  481. len = 1;
  482. }
  483. if (bp->second.active && (addr >= bp->second.addr && addr < bp->second.addr + len)) {
  484. LOG_DEBUG(Debug_GDBStub,
  485. "Found breakpoint type {} @ {:016X}, range: {:016X}"
  486. " - {:016X} ({:X} bytes)",
  487. static_cast<int>(type), addr, bp->second.addr, bp->second.addr + len, len);
  488. return true;
  489. }
  490. return false;
  491. }
  492. /**
  493. * Send packet to gdb client.
  494. *
  495. * @param packet Packet to be sent to client.
  496. */
  497. static void SendPacket(const char packet) {
  498. std::size_t sent_size = send(gdbserver_socket, &packet, 1, 0);
  499. if (sent_size != 1) {
  500. LOG_ERROR(Debug_GDBStub, "send failed");
  501. }
  502. }
  503. /**
  504. * Send reply to gdb client.
  505. *
  506. * @param reply Reply to be sent to client.
  507. */
  508. static void SendReply(const char* reply) {
  509. if (!IsConnected()) {
  510. return;
  511. }
  512. LOG_DEBUG(Debug_GDBStub, "Reply: {}", reply);
  513. memset(command_buffer, 0, sizeof(command_buffer));
  514. command_length = static_cast<u32>(strlen(reply));
  515. if (command_length + 4 > sizeof(command_buffer)) {
  516. LOG_ERROR(Debug_GDBStub, "command_buffer overflow in SendReply");
  517. return;
  518. }
  519. memcpy(command_buffer + 1, reply, command_length);
  520. u8 checksum = CalculateChecksum(command_buffer, command_length + 1);
  521. command_buffer[0] = GDB_STUB_START;
  522. command_buffer[command_length + 1] = GDB_STUB_END;
  523. command_buffer[command_length + 2] = NibbleToHex(checksum >> 4);
  524. command_buffer[command_length + 3] = NibbleToHex(checksum);
  525. u8* ptr = command_buffer;
  526. u32 left = command_length + 4;
  527. while (left > 0) {
  528. int sent_size = send(gdbserver_socket, reinterpret_cast<char*>(ptr), left, 0);
  529. if (sent_size < 0) {
  530. LOG_ERROR(Debug_GDBStub, "gdb: send failed");
  531. return Shutdown();
  532. }
  533. left -= sent_size;
  534. ptr += sent_size;
  535. }
  536. }
  537. /// Handle query command from gdb client.
  538. static void HandleQuery() {
  539. LOG_DEBUG(Debug_GDBStub, "gdb: query '{}'", command_buffer + 1);
  540. const char* query = reinterpret_cast<const char*>(command_buffer + 1);
  541. if (strcmp(query, "TStatus") == 0) {
  542. SendReply("T0");
  543. } else if (strncmp(query, "Supported", strlen("Supported")) == 0) {
  544. // PacketSize needs to be large enough for target xml
  545. std::string buffer = "PacketSize=2000;qXfer:features:read+;qXfer:threads:read+";
  546. if (!modules.empty()) {
  547. buffer += ";qXfer:libraries:read+";
  548. }
  549. SendReply(buffer.c_str());
  550. } else if (strncmp(query, "Xfer:features:read:target.xml:",
  551. strlen("Xfer:features:read:target.xml:")) == 0) {
  552. SendReply(target_xml);
  553. } else if (strncmp(query, "Offsets", strlen("Offsets")) == 0) {
  554. const VAddr base_address = Core::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. for (u32 core = 0; core < Core::NUM_CPU_CORES; core++) {
  560. const auto& threads = Core::System::GetInstance().Scheduler(core).GetThreadList();
  561. for (const auto& thread : threads) {
  562. val += fmt::format("{:x},", thread->GetThreadID());
  563. }
  564. }
  565. val.pop_back();
  566. SendReply(val.c_str());
  567. } else if (strncmp(query, "sThreadInfo", strlen("sThreadInfo")) == 0) {
  568. SendReply("l");
  569. } else if (strncmp(query, "Xfer:threads:read", strlen("Xfer:threads:read")) == 0) {
  570. std::string buffer;
  571. buffer += "l<?xml version=\"1.0\"?>";
  572. buffer += "<threads>";
  573. for (u32 core = 0; core < Core::NUM_CPU_CORES; core++) {
  574. const auto& threads = Core::System::GetInstance().Scheduler(core).GetThreadList();
  575. for (const auto& thread : threads) {
  576. buffer +=
  577. fmt::format(R"*(<thread id="{:x}" core="{:d}" name="Thread {:x}"></thread>)*",
  578. thread->GetThreadID(), core, thread->GetThreadID());
  579. }
  580. }
  581. buffer += "</threads>";
  582. SendReply(buffer.c_str());
  583. } else if (strncmp(query, "Xfer:libraries:read", strlen("Xfer:libraries:read")) == 0) {
  584. std::string buffer;
  585. buffer += "l<?xml version=\"1.0\"?>";
  586. buffer += "<library-list>";
  587. for (const auto& module : modules) {
  588. buffer +=
  589. fmt::format(R"*("<library name = "{}"><segment address = "0x{:x}"/></library>)*",
  590. module.name, module.beg);
  591. }
  592. buffer += "</library-list>";
  593. SendReply(buffer.c_str());
  594. } else {
  595. SendReply("");
  596. }
  597. }
  598. /// Handle set thread command from gdb client.
  599. static void HandleSetThread() {
  600. int thread_id = -1;
  601. if (command_buffer[2] != '-') {
  602. thread_id = static_cast<int>(HexToInt(command_buffer + 2, command_length - 2));
  603. }
  604. if (thread_id >= 1) {
  605. current_thread = FindThreadById(thread_id);
  606. }
  607. if (!current_thread) {
  608. thread_id = 1;
  609. current_thread = FindThreadById(thread_id);
  610. }
  611. if (current_thread) {
  612. SendReply("OK");
  613. return;
  614. }
  615. SendReply("E01");
  616. }
  617. /// Handle thread alive command from gdb client.
  618. static void HandleThreadAlive() {
  619. int thread_id = static_cast<int>(HexToInt(command_buffer + 1, command_length - 1));
  620. if (thread_id == 0) {
  621. thread_id = 1;
  622. }
  623. if (FindThreadById(thread_id)) {
  624. SendReply("OK");
  625. return;
  626. }
  627. SendReply("E01");
  628. }
  629. /**
  630. * Send signal packet to client.
  631. *
  632. * @param signal Signal to be sent to client.
  633. */
  634. static void SendSignal(Kernel::Thread* thread, u32 signal, bool full = true) {
  635. if (gdbserver_socket == -1) {
  636. return;
  637. }
  638. latest_signal = signal;
  639. if (!thread) {
  640. full = false;
  641. }
  642. std::string buffer;
  643. if (full) {
  644. buffer = fmt::format("T{:02x}{:02x}:{:016x};{:02x}:{:016x};{:02x}:{:016x}", latest_signal,
  645. PC_REGISTER, Common::swap64(RegRead(PC_REGISTER, thread)), SP_REGISTER,
  646. Common::swap64(RegRead(SP_REGISTER, thread)), LR_REGISTER,
  647. Common::swap64(RegRead(LR_REGISTER, thread)));
  648. } else {
  649. buffer = fmt::format("T{:02x}", latest_signal);
  650. }
  651. if (thread) {
  652. buffer += fmt::format(";thread:{:x};", thread->GetThreadID());
  653. }
  654. SendReply(buffer.c_str());
  655. }
  656. /// Read command from gdb client.
  657. static void ReadCommand() {
  658. command_length = 0;
  659. memset(command_buffer, 0, sizeof(command_buffer));
  660. u8 c = ReadByte();
  661. if (c == '+') {
  662. // ignore ack
  663. return;
  664. } else if (c == 0x03) {
  665. LOG_INFO(Debug_GDBStub, "gdb: found break command");
  666. halt_loop = true;
  667. SendSignal(current_thread, SIGTRAP);
  668. return;
  669. } else if (c != GDB_STUB_START) {
  670. LOG_DEBUG(Debug_GDBStub, "gdb: read invalid byte {:02X}", c);
  671. return;
  672. }
  673. while ((c = ReadByte()) != GDB_STUB_END) {
  674. if (command_length >= sizeof(command_buffer)) {
  675. LOG_ERROR(Debug_GDBStub, "gdb: command_buffer overflow");
  676. SendPacket(GDB_STUB_NACK);
  677. return;
  678. }
  679. command_buffer[command_length++] = c;
  680. }
  681. u8 checksum_received = HexCharToValue(ReadByte()) << 4;
  682. checksum_received |= HexCharToValue(ReadByte());
  683. u8 checksum_calculated = CalculateChecksum(command_buffer, command_length);
  684. if (checksum_received != checksum_calculated) {
  685. LOG_ERROR(Debug_GDBStub,
  686. "gdb: invalid checksum: calculated {:02X} and read {:02X} for ${}# (length: {})",
  687. checksum_calculated, checksum_received, command_buffer, command_length);
  688. command_length = 0;
  689. SendPacket(GDB_STUB_NACK);
  690. return;
  691. }
  692. SendPacket(GDB_STUB_ACK);
  693. }
  694. /// Check if there is data to be read from the gdb client.
  695. static bool IsDataAvailable() {
  696. if (!IsConnected()) {
  697. return false;
  698. }
  699. fd_set fd_socket;
  700. FD_ZERO(&fd_socket);
  701. FD_SET(static_cast<u32>(gdbserver_socket), &fd_socket);
  702. struct timeval t;
  703. t.tv_sec = 0;
  704. t.tv_usec = 0;
  705. if (select(gdbserver_socket + 1, &fd_socket, nullptr, nullptr, &t) < 0) {
  706. LOG_ERROR(Debug_GDBStub, "select failed");
  707. return false;
  708. }
  709. return FD_ISSET(gdbserver_socket, &fd_socket) != 0;
  710. }
  711. /// Send requested register to gdb client.
  712. static void ReadRegister() {
  713. static u8 reply[64];
  714. memset(reply, 0, sizeof(reply));
  715. u32 id = HexCharToValue(command_buffer[1]);
  716. if (command_buffer[2] != '\0') {
  717. id <<= 4;
  718. id |= HexCharToValue(command_buffer[2]);
  719. }
  720. if (id <= SP_REGISTER) {
  721. LongToGdbHex(reply, RegRead(id, current_thread));
  722. } else if (id == PC_REGISTER) {
  723. LongToGdbHex(reply, RegRead(id, current_thread));
  724. } else if (id == PSTATE_REGISTER) {
  725. IntToGdbHex(reply, static_cast<u32>(RegRead(id, current_thread)));
  726. } else if (id >= UC_ARM64_REG_Q0 && id < FPCR_REGISTER) {
  727. u128 r = FpuRead(id, current_thread);
  728. LongToGdbHex(reply, r[0]);
  729. LongToGdbHex(reply + 16, r[1]);
  730. } else if (id == FPCR_REGISTER) {
  731. u128 r = FpuRead(id, current_thread);
  732. IntToGdbHex(reply, static_cast<u32>(r[0]));
  733. } else if (id == FPCR_REGISTER + 1) {
  734. u128 r = FpuRead(id, current_thread);
  735. IntToGdbHex(reply, static_cast<u32>(r[0] >> 32));
  736. }
  737. SendReply(reinterpret_cast<char*>(reply));
  738. }
  739. /// Send all registers to the gdb client.
  740. static void ReadRegisters() {
  741. static u8 buffer[GDB_BUFFER_SIZE - 4];
  742. memset(buffer, 0, sizeof(buffer));
  743. u8* bufptr = buffer;
  744. for (u32 reg = 0; reg <= SP_REGISTER; reg++) {
  745. LongToGdbHex(bufptr + reg * 16, RegRead(reg, current_thread));
  746. }
  747. bufptr += 32 * 16;
  748. LongToGdbHex(bufptr, RegRead(PC_REGISTER, current_thread));
  749. bufptr += 16;
  750. IntToGdbHex(bufptr, static_cast<u32>(RegRead(PSTATE_REGISTER, current_thread)));
  751. bufptr += 8;
  752. u128 r;
  753. for (u32 reg = UC_ARM64_REG_Q0; reg < FPCR_REGISTER; reg++) {
  754. r = FpuRead(reg, current_thread);
  755. LongToGdbHex(bufptr + reg * 32, r[0]);
  756. LongToGdbHex(bufptr + reg * 32 + 16, r[1]);
  757. }
  758. bufptr += 32 * 32;
  759. r = FpuRead(FPCR_REGISTER, current_thread);
  760. IntToGdbHex(bufptr, static_cast<u32>(r[0]));
  761. bufptr += 8;
  762. SendReply(reinterpret_cast<char*>(buffer));
  763. }
  764. /// Modify data of register specified by gdb client.
  765. static void WriteRegister() {
  766. const u8* buffer_ptr = command_buffer + 3;
  767. u32 id = HexCharToValue(command_buffer[1]);
  768. if (command_buffer[2] != '=') {
  769. ++buffer_ptr;
  770. id <<= 4;
  771. id |= HexCharToValue(command_buffer[2]);
  772. }
  773. if (id <= SP_REGISTER) {
  774. RegWrite(id, GdbHexToLong(buffer_ptr), current_thread);
  775. } else if (id == PC_REGISTER) {
  776. RegWrite(id, GdbHexToLong(buffer_ptr), current_thread);
  777. } else if (id == PSTATE_REGISTER) {
  778. RegWrite(id, GdbHexToInt(buffer_ptr), current_thread);
  779. } else if (id >= UC_ARM64_REG_Q0 && id < FPCR_REGISTER) {
  780. FpuWrite(id, GdbHexToU128(buffer_ptr), current_thread);
  781. } else if (id == FPCR_REGISTER) {
  782. } else if (id == FPCR_REGISTER + 1) {
  783. }
  784. // Update ARM context, skipping scheduler - no running threads at this point
  785. Core::System::GetInstance()
  786. .ArmInterface(current_core)
  787. .LoadContext(current_thread->GetContext());
  788. SendReply("OK");
  789. }
  790. /// Modify all registers with data received from the client.
  791. static void WriteRegisters() {
  792. const u8* buffer_ptr = command_buffer + 1;
  793. if (command_buffer[0] != 'G')
  794. return SendReply("E01");
  795. for (u32 i = 0, reg = 0; reg <= FPCR_REGISTER; i++, reg++) {
  796. if (reg <= SP_REGISTER) {
  797. RegWrite(reg, GdbHexToLong(buffer_ptr + i * 16), current_thread);
  798. } else if (reg == PC_REGISTER) {
  799. RegWrite(PC_REGISTER, GdbHexToLong(buffer_ptr + i * 16), current_thread);
  800. } else if (reg == PSTATE_REGISTER) {
  801. RegWrite(PSTATE_REGISTER, GdbHexToInt(buffer_ptr + i * 16), current_thread);
  802. } else if (reg >= UC_ARM64_REG_Q0 && reg < FPCR_REGISTER) {
  803. RegWrite(reg, GdbHexToLong(buffer_ptr + i * 16), current_thread);
  804. } else if (reg == FPCR_REGISTER) {
  805. RegWrite(FPCR_REGISTER, GdbHexToLong(buffer_ptr + i * 16), current_thread);
  806. } else if (reg == FPCR_REGISTER + 1) {
  807. RegWrite(FPCR_REGISTER, GdbHexToLong(buffer_ptr + i * 16), current_thread);
  808. }
  809. }
  810. // Update ARM context, skipping scheduler - no running threads at this point
  811. Core::System::GetInstance()
  812. .ArmInterface(current_core)
  813. .LoadContext(current_thread->GetContext());
  814. SendReply("OK");
  815. }
  816. /// Read location in memory specified by gdb client.
  817. static void ReadMemory() {
  818. static u8 reply[GDB_BUFFER_SIZE - 4];
  819. auto start_offset = command_buffer + 1;
  820. const auto addr_pos = std::find(start_offset, command_buffer + command_length, ',');
  821. const VAddr addr = HexToLong(start_offset, static_cast<u64>(addr_pos - start_offset));
  822. start_offset = addr_pos + 1;
  823. const u64 len =
  824. HexToLong(start_offset, static_cast<u64>((command_buffer + command_length) - start_offset));
  825. LOG_DEBUG(Debug_GDBStub, "gdb: addr: {:016X} len: {:016X}", addr, len);
  826. if (len * 2 > sizeof(reply)) {
  827. SendReply("E01");
  828. }
  829. if (!Memory::IsValidVirtualAddress(addr)) {
  830. return SendReply("E00");
  831. }
  832. std::vector<u8> data(len);
  833. Memory::ReadBlock(addr, data.data(), len);
  834. MemToGdbHex(reply, data.data(), len);
  835. reply[len * 2] = '\0';
  836. SendReply(reinterpret_cast<char*>(reply));
  837. }
  838. /// Modify location in memory with data received from the gdb client.
  839. static void WriteMemory() {
  840. auto start_offset = command_buffer + 1;
  841. auto addr_pos = std::find(start_offset, command_buffer + command_length, ',');
  842. VAddr addr = HexToLong(start_offset, static_cast<u64>(addr_pos - start_offset));
  843. start_offset = addr_pos + 1;
  844. auto len_pos = std::find(start_offset, command_buffer + command_length, ':');
  845. u64 len = HexToLong(start_offset, static_cast<u64>(len_pos - start_offset));
  846. if (!Memory::IsValidVirtualAddress(addr)) {
  847. return SendReply("E00");
  848. }
  849. std::vector<u8> data(len);
  850. GdbHexToMem(data.data(), len_pos + 1, len);
  851. Memory::WriteBlock(addr, data.data(), len);
  852. Core::System::GetInstance().InvalidateCpuInstructionCaches();
  853. SendReply("OK");
  854. }
  855. void Break(bool is_memory_break) {
  856. send_trap = true;
  857. memory_break = is_memory_break;
  858. }
  859. /// Tell the CPU that it should perform a single step.
  860. static void Step() {
  861. if (command_length > 1) {
  862. RegWrite(PC_REGISTER, GdbHexToLong(command_buffer + 1), current_thread);
  863. // Update ARM context, skipping scheduler - no running threads at this point
  864. Core::System::GetInstance()
  865. .ArmInterface(current_core)
  866. .LoadContext(current_thread->GetContext());
  867. }
  868. step_loop = true;
  869. halt_loop = true;
  870. send_trap = true;
  871. Core::System::GetInstance().InvalidateCpuInstructionCaches();
  872. }
  873. /// Tell the CPU if we hit a memory breakpoint.
  874. bool IsMemoryBreak() {
  875. if (IsConnected()) {
  876. return false;
  877. }
  878. return memory_break;
  879. }
  880. /// Tell the CPU to continue executing.
  881. static void Continue() {
  882. memory_break = false;
  883. step_loop = false;
  884. halt_loop = false;
  885. Core::System::GetInstance().InvalidateCpuInstructionCaches();
  886. }
  887. /**
  888. * Commit breakpoint to list of breakpoints.
  889. *
  890. * @param type Type of breakpoint.
  891. * @param addr Address of breakpoint.
  892. * @param len Length of breakpoint.
  893. */
  894. static bool CommitBreakpoint(BreakpointType type, VAddr addr, u64 len) {
  895. BreakpointMap& p = GetBreakpointMap(type);
  896. Breakpoint breakpoint;
  897. breakpoint.active = true;
  898. breakpoint.addr = addr;
  899. breakpoint.len = len;
  900. Memory::ReadBlock(addr, breakpoint.inst.data(), breakpoint.inst.size());
  901. static constexpr std::array<u8, 4> btrap{0x00, 0x7d, 0x20, 0xd4};
  902. if (type == BreakpointType::Execute) {
  903. Memory::WriteBlock(addr, btrap.data(), btrap.size());
  904. Core::System::GetInstance().InvalidateCpuInstructionCaches();
  905. }
  906. p.insert({addr, breakpoint});
  907. LOG_DEBUG(Debug_GDBStub, "gdb: added {} breakpoint: {:016X} bytes at {:016X}",
  908. static_cast<int>(type), breakpoint.len, breakpoint.addr);
  909. return true;
  910. }
  911. /// Handle add breakpoint command from gdb client.
  912. static void AddBreakpoint() {
  913. BreakpointType type;
  914. u8 type_id = HexCharToValue(command_buffer[1]);
  915. switch (type_id) {
  916. case 0:
  917. case 1:
  918. type = BreakpointType::Execute;
  919. break;
  920. case 2:
  921. type = BreakpointType::Write;
  922. break;
  923. case 3:
  924. type = BreakpointType::Read;
  925. break;
  926. case 4:
  927. type = BreakpointType::Access;
  928. break;
  929. default:
  930. return SendReply("E01");
  931. }
  932. auto start_offset = command_buffer + 3;
  933. auto addr_pos = std::find(start_offset, command_buffer + command_length, ',');
  934. VAddr addr = HexToLong(start_offset, static_cast<u64>(addr_pos - start_offset));
  935. start_offset = addr_pos + 1;
  936. u64 len =
  937. HexToLong(start_offset, static_cast<u64>((command_buffer + command_length) - start_offset));
  938. if (type == BreakpointType::Access) {
  939. // Access is made up of Read and Write types, so add both breakpoints
  940. type = BreakpointType::Read;
  941. if (!CommitBreakpoint(type, addr, len)) {
  942. return SendReply("E02");
  943. }
  944. type = BreakpointType::Write;
  945. }
  946. if (!CommitBreakpoint(type, addr, len)) {
  947. return SendReply("E02");
  948. }
  949. SendReply("OK");
  950. }
  951. /// Handle remove breakpoint command from gdb client.
  952. static void RemoveBreakpoint() {
  953. BreakpointType type;
  954. u8 type_id = HexCharToValue(command_buffer[1]);
  955. switch (type_id) {
  956. case 0:
  957. case 1:
  958. type = BreakpointType::Execute;
  959. break;
  960. case 2:
  961. type = BreakpointType::Write;
  962. break;
  963. case 3:
  964. type = BreakpointType::Read;
  965. break;
  966. case 4:
  967. type = BreakpointType::Access;
  968. break;
  969. default:
  970. return SendReply("E01");
  971. }
  972. auto start_offset = command_buffer + 3;
  973. auto addr_pos = std::find(start_offset, command_buffer + command_length, ',');
  974. VAddr addr = HexToLong(start_offset, static_cast<u64>(addr_pos - start_offset));
  975. if (type == BreakpointType::Access) {
  976. // Access is made up of Read and Write types, so add both breakpoints
  977. type = BreakpointType::Read;
  978. RemoveBreakpoint(type, addr);
  979. type = BreakpointType::Write;
  980. }
  981. RemoveBreakpoint(type, addr);
  982. SendReply("OK");
  983. }
  984. void HandlePacket() {
  985. if (!IsConnected()) {
  986. return;
  987. }
  988. if (!IsDataAvailable()) {
  989. return;
  990. }
  991. ReadCommand();
  992. if (command_length == 0) {
  993. return;
  994. }
  995. LOG_DEBUG(Debug_GDBStub, "Packet: {}", command_buffer);
  996. switch (command_buffer[0]) {
  997. case 'q':
  998. HandleQuery();
  999. break;
  1000. case 'H':
  1001. HandleSetThread();
  1002. break;
  1003. case '?':
  1004. SendSignal(current_thread, latest_signal);
  1005. break;
  1006. case 'k':
  1007. Shutdown();
  1008. LOG_INFO(Debug_GDBStub, "killed by gdb");
  1009. return;
  1010. case 'g':
  1011. ReadRegisters();
  1012. break;
  1013. case 'G':
  1014. WriteRegisters();
  1015. break;
  1016. case 'p':
  1017. ReadRegister();
  1018. break;
  1019. case 'P':
  1020. WriteRegister();
  1021. break;
  1022. case 'm':
  1023. ReadMemory();
  1024. break;
  1025. case 'M':
  1026. WriteMemory();
  1027. break;
  1028. case 's':
  1029. Step();
  1030. return;
  1031. case 'C':
  1032. case 'c':
  1033. Continue();
  1034. return;
  1035. case 'z':
  1036. RemoveBreakpoint();
  1037. break;
  1038. case 'Z':
  1039. AddBreakpoint();
  1040. break;
  1041. case 'T':
  1042. HandleThreadAlive();
  1043. break;
  1044. default:
  1045. SendReply("");
  1046. break;
  1047. }
  1048. }
  1049. void SetServerPort(u16 port) {
  1050. gdbstub_port = port;
  1051. }
  1052. void ToggleServer(bool status) {
  1053. if (status) {
  1054. server_enabled = status;
  1055. // Start server
  1056. if (!IsConnected() && Core::System::GetInstance().IsPoweredOn()) {
  1057. Init();
  1058. }
  1059. } else {
  1060. // Stop server
  1061. if (IsConnected()) {
  1062. Shutdown();
  1063. }
  1064. server_enabled = status;
  1065. }
  1066. }
  1067. static void Init(u16 port) {
  1068. if (!server_enabled) {
  1069. // Set the halt loop to false in case the user enabled the gdbstub mid-execution.
  1070. // This way the CPU can still execute normally.
  1071. halt_loop = false;
  1072. step_loop = false;
  1073. return;
  1074. }
  1075. // Setup initial gdbstub status
  1076. halt_loop = true;
  1077. step_loop = false;
  1078. breakpoints_execute.clear();
  1079. breakpoints_read.clear();
  1080. breakpoints_write.clear();
  1081. modules.clear();
  1082. // Start gdb server
  1083. LOG_INFO(Debug_GDBStub, "Starting GDB server on port {}...", port);
  1084. sockaddr_in saddr_server = {};
  1085. saddr_server.sin_family = AF_INET;
  1086. saddr_server.sin_port = htons(port);
  1087. saddr_server.sin_addr.s_addr = INADDR_ANY;
  1088. #ifdef _WIN32
  1089. WSAStartup(MAKEWORD(2, 2), &InitData);
  1090. #endif
  1091. int tmpsock = static_cast<int>(socket(PF_INET, SOCK_STREAM, 0));
  1092. if (tmpsock == -1) {
  1093. LOG_ERROR(Debug_GDBStub, "Failed to create gdb socket");
  1094. }
  1095. // Set socket to SO_REUSEADDR so it can always bind on the same port
  1096. int reuse_enabled = 1;
  1097. if (setsockopt(tmpsock, SOL_SOCKET, SO_REUSEADDR, (const char*)&reuse_enabled,
  1098. sizeof(reuse_enabled)) < 0) {
  1099. LOG_ERROR(Debug_GDBStub, "Failed to set gdb socket option");
  1100. }
  1101. const sockaddr* server_addr = reinterpret_cast<const sockaddr*>(&saddr_server);
  1102. socklen_t server_addrlen = sizeof(saddr_server);
  1103. if (bind(tmpsock, server_addr, server_addrlen) < 0) {
  1104. LOG_ERROR(Debug_GDBStub, "Failed to bind gdb socket");
  1105. }
  1106. if (listen(tmpsock, 1) < 0) {
  1107. LOG_ERROR(Debug_GDBStub, "Failed to listen to gdb socket");
  1108. }
  1109. // Wait for gdb to connect
  1110. LOG_INFO(Debug_GDBStub, "Waiting for gdb to connect...");
  1111. sockaddr_in saddr_client;
  1112. sockaddr* client_addr = reinterpret_cast<sockaddr*>(&saddr_client);
  1113. socklen_t client_addrlen = sizeof(saddr_client);
  1114. gdbserver_socket = static_cast<int>(accept(tmpsock, client_addr, &client_addrlen));
  1115. if (gdbserver_socket < 0) {
  1116. // In the case that we couldn't start the server for whatever reason, just start CPU
  1117. // execution like normal.
  1118. halt_loop = false;
  1119. step_loop = false;
  1120. LOG_ERROR(Debug_GDBStub, "Failed to accept gdb client");
  1121. } else {
  1122. LOG_INFO(Debug_GDBStub, "Client connected.");
  1123. saddr_client.sin_addr.s_addr = ntohl(saddr_client.sin_addr.s_addr);
  1124. }
  1125. // Clean up temporary socket if it's still alive at this point.
  1126. if (tmpsock != -1) {
  1127. shutdown(tmpsock, SHUT_RDWR);
  1128. }
  1129. }
  1130. void Init() {
  1131. Init(gdbstub_port);
  1132. }
  1133. void Shutdown() {
  1134. if (!server_enabled) {
  1135. return;
  1136. }
  1137. LOG_INFO(Debug_GDBStub, "Stopping GDB ...");
  1138. if (gdbserver_socket != -1) {
  1139. shutdown(gdbserver_socket, SHUT_RDWR);
  1140. gdbserver_socket = -1;
  1141. }
  1142. #ifdef _WIN32
  1143. WSACleanup();
  1144. #endif
  1145. LOG_INFO(Debug_GDBStub, "GDB stopped.");
  1146. }
  1147. bool IsServerEnabled() {
  1148. return server_enabled;
  1149. }
  1150. bool IsConnected() {
  1151. return IsServerEnabled() && gdbserver_socket != -1;
  1152. }
  1153. bool GetCpuHaltFlag() {
  1154. return halt_loop;
  1155. }
  1156. bool GetCpuStepFlag() {
  1157. return step_loop;
  1158. }
  1159. void SetCpuStepFlag(bool is_step) {
  1160. step_loop = is_step;
  1161. }
  1162. void SendTrap(Kernel::Thread* thread, int trap) {
  1163. if (!send_trap) {
  1164. return;
  1165. }
  1166. if (!halt_loop || current_thread == thread) {
  1167. current_thread = thread;
  1168. SendSignal(thread, trap);
  1169. }
  1170. halt_loop = true;
  1171. send_trap = false;
  1172. }
  1173. }; // namespace GDBStub