gdbstub.cpp 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040
  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 "core/arm/arm_interface.h"
  32. #include "core/core.h"
  33. #include "core/gdbstub/gdbstub.h"
  34. #include "core/memory.h"
  35. const int GDB_BUFFER_SIZE = 10000;
  36. const char GDB_STUB_START = '$';
  37. const char GDB_STUB_END = '#';
  38. const char GDB_STUB_ACK = '+';
  39. const char GDB_STUB_NACK = '-';
  40. #ifndef SIGTRAP
  41. const u32 SIGTRAP = 5;
  42. #endif
  43. #ifndef SIGTERM
  44. const u32 SIGTERM = 15;
  45. #endif
  46. #ifndef MSG_WAITALL
  47. const u32 MSG_WAITALL = 8;
  48. #endif
  49. const u32 R0_REGISTER = 0;
  50. const u32 R15_REGISTER = 15;
  51. const u32 CPSR_REGISTER = 25;
  52. const u32 FPSCR_REGISTER = 58;
  53. // For sample XML files see the GDB source /gdb/features
  54. // GDB also wants the l character at the start
  55. // This XML defines what the registers are for this specific ARM device
  56. static const char* target_xml =
  57. R"(l<?xml version="1.0"?>
  58. <!DOCTYPE target SYSTEM "gdb-target.dtd">
  59. <target version="1.0">
  60. <feature name="org.gnu.gdb.arm.core">
  61. <reg name="r0" bitsize="32"/>
  62. <reg name="r1" bitsize="32"/>
  63. <reg name="r2" bitsize="32"/>
  64. <reg name="r3" bitsize="32"/>
  65. <reg name="r4" bitsize="32"/>
  66. <reg name="r5" bitsize="32"/>
  67. <reg name="r6" bitsize="32"/>
  68. <reg name="r7" bitsize="32"/>
  69. <reg name="r8" bitsize="32"/>
  70. <reg name="r9" bitsize="32"/>
  71. <reg name="r10" bitsize="32"/>
  72. <reg name="r11" bitsize="32"/>
  73. <reg name="r12" bitsize="32"/>
  74. <reg name="sp" bitsize="32" type="data_ptr"/>
  75. <reg name="lr" bitsize="32"/>
  76. <reg name="pc" bitsize="32" type="code_ptr"/>
  77. <!-- The CPSR is register 25, rather than register 16, because
  78. the FPA registers historically were placed between the PC
  79. and the CPSR in the "g" packet. -->
  80. <reg name="cpsr" bitsize="32" regnum="25"/>
  81. </feature>
  82. <feature name="org.gnu.gdb.arm.vfp">
  83. <reg name="d0" bitsize="64" type="float"/>
  84. <reg name="d1" bitsize="64" type="float"/>
  85. <reg name="d2" bitsize="64" type="float"/>
  86. <reg name="d3" bitsize="64" type="float"/>
  87. <reg name="d4" bitsize="64" type="float"/>
  88. <reg name="d5" bitsize="64" type="float"/>
  89. <reg name="d6" bitsize="64" type="float"/>
  90. <reg name="d7" bitsize="64" type="float"/>
  91. <reg name="d8" bitsize="64" type="float"/>
  92. <reg name="d9" bitsize="64" type="float"/>
  93. <reg name="d10" bitsize="64" type="float"/>
  94. <reg name="d11" bitsize="64" type="float"/>
  95. <reg name="d12" bitsize="64" type="float"/>
  96. <reg name="d13" bitsize="64" type="float"/>
  97. <reg name="d14" bitsize="64" type="float"/>
  98. <reg name="d15" bitsize="64" type="float"/>
  99. <reg name="fpscr" bitsize="32" type="int" group="float"/>
  100. </feature>
  101. </target>
  102. )";
  103. namespace GDBStub {
  104. static int gdbserver_socket = -1;
  105. static u8 command_buffer[GDB_BUFFER_SIZE];
  106. static u32 command_length;
  107. static u32 latest_signal = 0;
  108. static bool step_break = false;
  109. static bool memory_break = false;
  110. // Binding to a port within the reserved ports range (0-1023) requires root permissions,
  111. // so default to a port outside of that range.
  112. static u16 gdbstub_port = 24689;
  113. static bool halt_loop = true;
  114. static bool step_loop = false;
  115. // If set to false, the server will never be started and no
  116. // gdbstub-related functions will be executed.
  117. static std::atomic<bool> server_enabled(false);
  118. #ifdef _WIN32
  119. WSADATA InitData;
  120. #endif
  121. struct Breakpoint {
  122. bool active;
  123. PAddr addr;
  124. u32 len;
  125. };
  126. static std::map<u32, Breakpoint> breakpoints_execute;
  127. static std::map<u32, Breakpoint> breakpoints_read;
  128. static std::map<u32, Breakpoint> breakpoints_write;
  129. /**
  130. * Turns hex string character into the equivalent byte.
  131. *
  132. * @param hex Input hex character to be turned into byte.
  133. */
  134. static u8 HexCharToValue(u8 hex) {
  135. if (hex >= '0' && hex <= '9') {
  136. return hex - '0';
  137. } else if (hex >= 'a' && hex <= 'f') {
  138. return hex - 'a' + 0xA;
  139. } else if (hex >= 'A' && hex <= 'F') {
  140. return hex - 'A' + 0xA;
  141. }
  142. LOG_ERROR(Debug_GDBStub, "Invalid nibble: %c (%02x)\n", hex, hex);
  143. return 0;
  144. }
  145. /**
  146. * Turn nibble of byte into hex string character.
  147. *
  148. * @param n Nibble to be turned into hex character.
  149. */
  150. static u8 NibbleToHex(u8 n) {
  151. n &= 0xF;
  152. if (n < 0xA) {
  153. return '0' + n;
  154. } else {
  155. return 'A' + n - 0xA;
  156. }
  157. }
  158. /**
  159. * Converts input hex string characters into an array of equivalent of u8 bytes.
  160. *
  161. * @param src Pointer to array of output hex string characters.
  162. * @param len Length of src array.
  163. */
  164. static u32 HexToInt(const u8* src, size_t len) {
  165. u32 output = 0;
  166. while (len-- > 0) {
  167. output = (output << 4) | HexCharToValue(src[0]);
  168. src++;
  169. }
  170. return output;
  171. }
  172. /**
  173. * Converts input array of u8 bytes into their equivalent hex string characters.
  174. *
  175. * @param dest Pointer to buffer to store output hex string characters.
  176. * @param src Pointer to array of u8 bytes.
  177. * @param len Length of src array.
  178. */
  179. static void MemToGdbHex(u8* dest, const u8* src, size_t len) {
  180. while (len-- > 0) {
  181. u8 tmp = *src++;
  182. *dest++ = NibbleToHex(tmp >> 4);
  183. *dest++ = NibbleToHex(tmp);
  184. }
  185. }
  186. /**
  187. * Converts input gdb-formatted hex string characters into an array of equivalent of u8 bytes.
  188. *
  189. * @param dest Pointer to buffer to store u8 bytes.
  190. * @param src Pointer to array of output hex string characters.
  191. * @param len Length of src array.
  192. */
  193. static void GdbHexToMem(u8* dest, const u8* src, size_t len) {
  194. while (len-- > 0) {
  195. *dest++ = (HexCharToValue(src[0]) << 4) | HexCharToValue(src[1]);
  196. src += 2;
  197. }
  198. }
  199. /**
  200. * Convert a u32 into a gdb-formatted hex string.
  201. *
  202. * @param dest Pointer to buffer to store output hex string characters.
  203. */
  204. static void IntToGdbHex(u8* dest, u32 v) {
  205. for (int i = 0; i < 8; i += 2) {
  206. dest[i + 1] = NibbleToHex(v >> (4 * i));
  207. dest[i] = NibbleToHex(v >> (4 * (i + 1)));
  208. }
  209. }
  210. /**
  211. * Convert a gdb-formatted hex string into a u32.
  212. *
  213. * @param src Pointer to hex string.
  214. */
  215. static u32 GdbHexToInt(const u8* src) {
  216. u32 output = 0;
  217. for (int i = 0; i < 8; i += 2) {
  218. output = (output << 4) | HexCharToValue(src[7 - i - 1]);
  219. output = (output << 4) | HexCharToValue(src[7 - i]);
  220. }
  221. return output;
  222. }
  223. /// Read a byte from the gdb client.
  224. static u8 ReadByte() {
  225. u8 c;
  226. size_t received_size = recv(gdbserver_socket, reinterpret_cast<char*>(&c), 1, MSG_WAITALL);
  227. if (received_size != 1) {
  228. LOG_ERROR(Debug_GDBStub, "recv failed : %ld", received_size);
  229. Shutdown();
  230. }
  231. return c;
  232. }
  233. /// Calculate the checksum of the current command buffer.
  234. static u8 CalculateChecksum(const u8* buffer, size_t length) {
  235. return static_cast<u8>(std::accumulate(buffer, buffer + length, 0, std::plus<u8>()));
  236. }
  237. /**
  238. * Get the list of breakpoints for a given breakpoint type.
  239. *
  240. * @param type Type of breakpoint list.
  241. */
  242. static std::map<u32, Breakpoint>& GetBreakpointList(BreakpointType type) {
  243. switch (type) {
  244. case BreakpointType::Execute:
  245. return breakpoints_execute;
  246. case BreakpointType::Read:
  247. return breakpoints_read;
  248. case BreakpointType::Write:
  249. return breakpoints_write;
  250. default:
  251. return breakpoints_read;
  252. }
  253. }
  254. /**
  255. * Remove the breakpoint from the given address of the specified type.
  256. *
  257. * @param type Type of breakpoint.
  258. * @param addr Address of breakpoint.
  259. */
  260. static void RemoveBreakpoint(BreakpointType type, PAddr addr) {
  261. std::map<u32, Breakpoint>& p = GetBreakpointList(type);
  262. auto bp = p.find(addr);
  263. if (bp != p.end()) {
  264. LOG_DEBUG(Debug_GDBStub, "gdb: removed a breakpoint: %08x bytes at %08x of type %d\n",
  265. bp->second.len, bp->second.addr, type);
  266. p.erase(addr);
  267. }
  268. }
  269. BreakpointAddress GetNextBreakpointFromAddress(PAddr addr, BreakpointType type) {
  270. std::map<u32, Breakpoint>& p = GetBreakpointList(type);
  271. auto next_breakpoint = p.lower_bound(addr);
  272. BreakpointAddress breakpoint;
  273. if (next_breakpoint != p.end()) {
  274. breakpoint.address = next_breakpoint->first;
  275. breakpoint.type = type;
  276. } else {
  277. breakpoint.address = 0;
  278. breakpoint.type = BreakpointType::None;
  279. }
  280. return breakpoint;
  281. }
  282. bool CheckBreakpoint(PAddr addr, BreakpointType type) {
  283. if (!IsConnected()) {
  284. return false;
  285. }
  286. std::map<u32, Breakpoint>& p = GetBreakpointList(type);
  287. auto bp = p.find(addr);
  288. if (bp != p.end()) {
  289. u32 len = bp->second.len;
  290. // IDA Pro defaults to 4-byte breakpoints for all non-hardware breakpoints
  291. // no matter if it's a 4-byte or 2-byte instruction. When you execute a
  292. // Thumb instruction with a 4-byte breakpoint set, it will set a breakpoint on
  293. // two instructions instead of the single instruction you placed the breakpoint
  294. // on. So, as a way to make sure that execution breakpoints are only breaking
  295. // on the instruction that was specified, set the length of an execution
  296. // breakpoint to 1. This should be fine since the CPU should never begin executing
  297. // an instruction anywhere except the beginning of the instruction.
  298. if (type == BreakpointType::Execute) {
  299. len = 1;
  300. }
  301. if (bp->second.active && (addr >= bp->second.addr && addr < bp->second.addr + len)) {
  302. LOG_DEBUG(Debug_GDBStub,
  303. "Found breakpoint type %d @ %08x, range: %08x - %08x (%d bytes)\n", type,
  304. addr, bp->second.addr, bp->second.addr + len, len);
  305. return true;
  306. }
  307. }
  308. return false;
  309. }
  310. /**
  311. * Send packet to gdb client.
  312. *
  313. * @param packet Packet to be sent to client.
  314. */
  315. static void SendPacket(const char packet) {
  316. size_t sent_size = send(gdbserver_socket, &packet, 1, 0);
  317. if (sent_size != 1) {
  318. LOG_ERROR(Debug_GDBStub, "send failed");
  319. }
  320. }
  321. /**
  322. * Send reply to gdb client.
  323. *
  324. * @param reply Reply to be sent to client.
  325. */
  326. static void SendReply(const char* reply) {
  327. if (!IsConnected()) {
  328. return;
  329. }
  330. memset(command_buffer, 0, sizeof(command_buffer));
  331. command_length = static_cast<u32>(strlen(reply));
  332. if (command_length + 4 > sizeof(command_buffer)) {
  333. LOG_ERROR(Debug_GDBStub, "command_buffer overflow in SendReply");
  334. return;
  335. }
  336. memcpy(command_buffer + 1, reply, command_length);
  337. u8 checksum = CalculateChecksum(command_buffer, command_length + 1);
  338. command_buffer[0] = GDB_STUB_START;
  339. command_buffer[command_length + 1] = GDB_STUB_END;
  340. command_buffer[command_length + 2] = NibbleToHex(checksum >> 4);
  341. command_buffer[command_length + 3] = NibbleToHex(checksum);
  342. u8* ptr = command_buffer;
  343. u32 left = command_length + 4;
  344. while (left > 0) {
  345. int sent_size = send(gdbserver_socket, reinterpret_cast<char*>(ptr), left, 0);
  346. if (sent_size < 0) {
  347. LOG_ERROR(Debug_GDBStub, "gdb: send failed");
  348. return Shutdown();
  349. }
  350. left -= sent_size;
  351. ptr += sent_size;
  352. }
  353. }
  354. /// Handle query command from gdb client.
  355. static void HandleQuery() {
  356. LOG_DEBUG(Debug_GDBStub, "gdb: query '%s'\n", command_buffer + 1);
  357. const char* query = reinterpret_cast<const char*>(command_buffer + 1);
  358. if (strcmp(query, "TStatus") == 0) {
  359. SendReply("T0");
  360. } else if (strncmp(query, "Supported", strlen("Supported")) == 0) {
  361. // PacketSize needs to be large enough for target xml
  362. SendReply("PacketSize=800;qXfer:features:read+");
  363. } else if (strncmp(query, "Xfer:features:read:target.xml:",
  364. strlen("Xfer:features:read:target.xml:")) == 0) {
  365. SendReply(target_xml);
  366. } else {
  367. SendReply("");
  368. }
  369. }
  370. /// Handle set thread command from gdb client.
  371. static void HandleSetThread() {
  372. if (memcmp(command_buffer, "Hg0", 3) == 0 || memcmp(command_buffer, "Hc-1", 4) == 0 ||
  373. memcmp(command_buffer, "Hc0", 4) == 0 || memcmp(command_buffer, "Hc1", 4) == 0) {
  374. return SendReply("OK");
  375. }
  376. SendReply("E01");
  377. }
  378. /**
  379. * Send signal packet to client.
  380. *
  381. * @param signal Signal to be sent to client.
  382. */
  383. static void SendSignal(u32 signal) {
  384. if (gdbserver_socket == -1) {
  385. return;
  386. }
  387. latest_signal = signal;
  388. std::string buffer = Common::StringFromFormat("T%02x%02x:%08x;%02x:%08x;", latest_signal, 15,
  389. htonl(Core::g_app_core->GetPC()), 13,
  390. htonl(Core::g_app_core->GetReg(13)));
  391. LOG_DEBUG(Debug_GDBStub, "Response: %s", buffer.c_str());
  392. SendReply(buffer.c_str());
  393. }
  394. /// Read command from gdb client.
  395. static void ReadCommand() {
  396. command_length = 0;
  397. memset(command_buffer, 0, sizeof(command_buffer));
  398. u8 c = ReadByte();
  399. if (c == '+') {
  400. // ignore ack
  401. return;
  402. } else if (c == 0x03) {
  403. LOG_INFO(Debug_GDBStub, "gdb: found break command\n");
  404. halt_loop = true;
  405. SendSignal(SIGTRAP);
  406. return;
  407. } else if (c != GDB_STUB_START) {
  408. LOG_DEBUG(Debug_GDBStub, "gdb: read invalid byte %02x\n", c);
  409. return;
  410. }
  411. while ((c = ReadByte()) != GDB_STUB_END) {
  412. if (command_length >= sizeof(command_buffer)) {
  413. LOG_ERROR(Debug_GDBStub, "gdb: command_buffer overflow\n");
  414. SendPacket(GDB_STUB_NACK);
  415. return;
  416. }
  417. command_buffer[command_length++] = c;
  418. }
  419. u8 checksum_received = HexCharToValue(ReadByte()) << 4;
  420. checksum_received |= HexCharToValue(ReadByte());
  421. u8 checksum_calculated = CalculateChecksum(command_buffer, command_length);
  422. if (checksum_received != checksum_calculated) {
  423. LOG_ERROR(Debug_GDBStub,
  424. "gdb: invalid checksum: calculated %02x and read %02x for $%s# (length: %d)\n",
  425. checksum_calculated, checksum_received, command_buffer, command_length);
  426. command_length = 0;
  427. SendPacket(GDB_STUB_NACK);
  428. return;
  429. }
  430. SendPacket(GDB_STUB_ACK);
  431. }
  432. /// Check if there is data to be read from the gdb client.
  433. static bool IsDataAvailable() {
  434. if (!IsConnected()) {
  435. return false;
  436. }
  437. fd_set fd_socket;
  438. FD_ZERO(&fd_socket);
  439. FD_SET(gdbserver_socket, &fd_socket);
  440. struct timeval t;
  441. t.tv_sec = 0;
  442. t.tv_usec = 0;
  443. if (select(gdbserver_socket + 1, &fd_socket, nullptr, nullptr, &t) < 0) {
  444. LOG_ERROR(Debug_GDBStub, "select failed");
  445. return false;
  446. }
  447. return FD_ISSET(gdbserver_socket, &fd_socket) != 0;
  448. }
  449. /// Send requested register to gdb client.
  450. static void ReadRegister() {
  451. static u8 reply[64];
  452. memset(reply, 0, sizeof(reply));
  453. u32 id = HexCharToValue(command_buffer[1]);
  454. if (command_buffer[2] != '\0') {
  455. id <<= 4;
  456. id |= HexCharToValue(command_buffer[2]);
  457. }
  458. if (id <= R15_REGISTER) {
  459. IntToGdbHex(reply, Core::g_app_core->GetReg(id));
  460. } else if (id == CPSR_REGISTER) {
  461. IntToGdbHex(reply, Core::g_app_core->GetCPSR());
  462. } else if (id > CPSR_REGISTER && id < FPSCR_REGISTER) {
  463. IntToGdbHex(reply, Core::g_app_core->GetVFPReg(
  464. id - CPSR_REGISTER -
  465. 1)); // VFP registers should start at 26, so one after CSPR_REGISTER
  466. } else if (id == FPSCR_REGISTER) {
  467. IntToGdbHex(reply, Core::g_app_core->GetVFPSystemReg(VFP_FPSCR)); // Get FPSCR
  468. IntToGdbHex(reply + 8, 0);
  469. } else {
  470. return SendReply("E01");
  471. }
  472. SendReply(reinterpret_cast<char*>(reply));
  473. }
  474. /// Send all registers to the gdb client.
  475. static void ReadRegisters() {
  476. static u8 buffer[GDB_BUFFER_SIZE - 4];
  477. memset(buffer, 0, sizeof(buffer));
  478. u8* bufptr = buffer;
  479. for (int reg = 0; reg <= R15_REGISTER; reg++) {
  480. IntToGdbHex(bufptr + reg * CHAR_BIT, Core::g_app_core->GetReg(reg));
  481. }
  482. bufptr += (16 * CHAR_BIT);
  483. IntToGdbHex(bufptr, Core::g_app_core->GetCPSR());
  484. bufptr += CHAR_BIT;
  485. for (int reg = 0; reg <= 31; reg++) {
  486. IntToGdbHex(bufptr + reg * CHAR_BIT, Core::g_app_core->GetVFPReg(reg));
  487. }
  488. bufptr += (32 * CHAR_BIT);
  489. IntToGdbHex(bufptr, Core::g_app_core->GetVFPSystemReg(VFP_FPSCR));
  490. SendReply(reinterpret_cast<char*>(buffer));
  491. }
  492. /// Modify data of register specified by gdb client.
  493. static void WriteRegister() {
  494. const u8* buffer_ptr = command_buffer + 3;
  495. u32 id = HexCharToValue(command_buffer[1]);
  496. if (command_buffer[2] != '=') {
  497. ++buffer_ptr;
  498. id <<= 4;
  499. id |= HexCharToValue(command_buffer[2]);
  500. }
  501. if (id <= R15_REGISTER) {
  502. Core::g_app_core->SetReg(id, GdbHexToInt(buffer_ptr));
  503. } else if (id == CPSR_REGISTER) {
  504. Core::g_app_core->SetCPSR(GdbHexToInt(buffer_ptr));
  505. } else if (id > CPSR_REGISTER && id < FPSCR_REGISTER) {
  506. Core::g_app_core->SetVFPReg(id - CPSR_REGISTER - 1, GdbHexToInt(buffer_ptr));
  507. } else if (id == FPSCR_REGISTER) {
  508. Core::g_app_core->SetVFPSystemReg(VFP_FPSCR, GdbHexToInt(buffer_ptr));
  509. } else {
  510. return SendReply("E01");
  511. }
  512. SendReply("OK");
  513. }
  514. /// Modify all registers with data received from the client.
  515. static void WriteRegisters() {
  516. const u8* buffer_ptr = command_buffer + 1;
  517. if (command_buffer[0] != 'G')
  518. return SendReply("E01");
  519. for (int i = 0, reg = 0; reg <= FPSCR_REGISTER; i++, reg++) {
  520. if (reg <= R15_REGISTER) {
  521. Core::g_app_core->SetReg(reg, GdbHexToInt(buffer_ptr + i * CHAR_BIT));
  522. } else if (reg == CPSR_REGISTER) {
  523. Core::g_app_core->SetCPSR(GdbHexToInt(buffer_ptr + i * CHAR_BIT));
  524. } else if (reg == CPSR_REGISTER - 1) {
  525. // Dummy FPA register, ignore
  526. } else if (reg < CPSR_REGISTER) {
  527. // Dummy FPA registers, ignore
  528. i += 2;
  529. } else if (reg > CPSR_REGISTER && reg < FPSCR_REGISTER) {
  530. Core::g_app_core->SetVFPReg(reg - CPSR_REGISTER - 1,
  531. GdbHexToInt(buffer_ptr + i * CHAR_BIT));
  532. i++; // Skip padding
  533. } else if (reg == FPSCR_REGISTER) {
  534. Core::g_app_core->SetVFPSystemReg(VFP_FPSCR, GdbHexToInt(buffer_ptr + i * CHAR_BIT));
  535. }
  536. }
  537. SendReply("OK");
  538. }
  539. /// Read location in memory specified by gdb client.
  540. static void ReadMemory() {
  541. static u8 reply[GDB_BUFFER_SIZE - 4];
  542. auto start_offset = command_buffer + 1;
  543. auto addr_pos = std::find(start_offset, command_buffer + command_length, ',');
  544. PAddr addr = HexToInt(start_offset, static_cast<u32>(addr_pos - start_offset));
  545. start_offset = addr_pos + 1;
  546. u32 len =
  547. HexToInt(start_offset, static_cast<u32>((command_buffer + command_length) - start_offset));
  548. LOG_DEBUG(Debug_GDBStub, "gdb: addr: %08x len: %08x\n", addr, len);
  549. if (len * 2 > sizeof(reply)) {
  550. SendReply("E01");
  551. }
  552. const u8* data = Memory::GetPointer(addr);
  553. if (!data) {
  554. return SendReply("E00");
  555. }
  556. MemToGdbHex(reply, data, len);
  557. reply[len * 2] = '\0';
  558. SendReply(reinterpret_cast<char*>(reply));
  559. }
  560. /// Modify location in memory with data received from the gdb client.
  561. static void WriteMemory() {
  562. auto start_offset = command_buffer + 1;
  563. auto addr_pos = std::find(start_offset, command_buffer + command_length, ',');
  564. PAddr addr = HexToInt(start_offset, static_cast<u32>(addr_pos - start_offset));
  565. start_offset = addr_pos + 1;
  566. auto len_pos = std::find(start_offset, command_buffer + command_length, ':');
  567. u32 len = HexToInt(start_offset, static_cast<u32>(len_pos - start_offset));
  568. u8* dst = Memory::GetPointer(addr);
  569. if (!dst) {
  570. return SendReply("E00");
  571. }
  572. GdbHexToMem(dst, len_pos + 1, len);
  573. SendReply("OK");
  574. }
  575. void Break(bool is_memory_break) {
  576. if (!halt_loop) {
  577. halt_loop = true;
  578. SendSignal(SIGTRAP);
  579. }
  580. memory_break = is_memory_break;
  581. }
  582. /// Tell the CPU that it should perform a single step.
  583. static void Step() {
  584. step_loop = true;
  585. halt_loop = true;
  586. step_break = true;
  587. SendSignal(SIGTRAP);
  588. }
  589. bool IsMemoryBreak() {
  590. if (IsConnected()) {
  591. return false;
  592. }
  593. return memory_break;
  594. }
  595. /// Tell the CPU to continue executing.
  596. static void Continue() {
  597. memory_break = false;
  598. step_break = false;
  599. step_loop = false;
  600. halt_loop = false;
  601. }
  602. /**
  603. * Commit breakpoint to list of breakpoints.
  604. *
  605. * @param type Type of breakpoint.
  606. * @param addr Address of breakpoint.
  607. * @param len Length of breakpoint.
  608. */
  609. static bool CommitBreakpoint(BreakpointType type, PAddr addr, u32 len) {
  610. std::map<u32, Breakpoint>& p = GetBreakpointList(type);
  611. Breakpoint breakpoint;
  612. breakpoint.active = true;
  613. breakpoint.addr = addr;
  614. breakpoint.len = len;
  615. p.insert({addr, breakpoint});
  616. LOG_DEBUG(Debug_GDBStub, "gdb: added %d breakpoint: %08x bytes at %08x\n", type, breakpoint.len,
  617. breakpoint.addr);
  618. return true;
  619. }
  620. /// Handle add breakpoint command from gdb client.
  621. static void AddBreakpoint() {
  622. BreakpointType type;
  623. u8 type_id = HexCharToValue(command_buffer[1]);
  624. switch (type_id) {
  625. case 0:
  626. case 1:
  627. type = BreakpointType::Execute;
  628. break;
  629. case 2:
  630. type = BreakpointType::Write;
  631. break;
  632. case 3:
  633. type = BreakpointType::Read;
  634. break;
  635. case 4:
  636. type = BreakpointType::Access;
  637. break;
  638. default:
  639. return SendReply("E01");
  640. }
  641. auto start_offset = command_buffer + 3;
  642. auto addr_pos = std::find(start_offset, command_buffer + command_length, ',');
  643. PAddr addr = HexToInt(start_offset, static_cast<u32>(addr_pos - start_offset));
  644. start_offset = addr_pos + 1;
  645. u32 len =
  646. HexToInt(start_offset, static_cast<u32>((command_buffer + command_length) - start_offset));
  647. if (type == BreakpointType::Access) {
  648. // Access is made up of Read and Write types, so add both breakpoints
  649. type = BreakpointType::Read;
  650. if (!CommitBreakpoint(type, addr, len)) {
  651. return SendReply("E02");
  652. }
  653. type = BreakpointType::Write;
  654. }
  655. if (!CommitBreakpoint(type, addr, len)) {
  656. return SendReply("E02");
  657. }
  658. SendReply("OK");
  659. }
  660. /// Handle remove breakpoint command from gdb client.
  661. static void RemoveBreakpoint() {
  662. BreakpointType type;
  663. u8 type_id = HexCharToValue(command_buffer[1]);
  664. switch (type_id) {
  665. case 0:
  666. case 1:
  667. type = BreakpointType::Execute;
  668. break;
  669. case 2:
  670. type = BreakpointType::Write;
  671. break;
  672. case 3:
  673. type = BreakpointType::Read;
  674. break;
  675. case 4:
  676. type = BreakpointType::Access;
  677. break;
  678. default:
  679. return SendReply("E01");
  680. }
  681. auto start_offset = command_buffer + 3;
  682. auto addr_pos = std::find(start_offset, command_buffer + command_length, ',');
  683. PAddr addr = HexToInt(start_offset, static_cast<u32>(addr_pos - start_offset));
  684. start_offset = addr_pos + 1;
  685. u32 len =
  686. HexToInt(start_offset, static_cast<u32>((command_buffer + command_length) - start_offset));
  687. if (type == BreakpointType::Access) {
  688. // Access is made up of Read and Write types, so add both breakpoints
  689. type = BreakpointType::Read;
  690. RemoveBreakpoint(type, addr);
  691. type = BreakpointType::Write;
  692. }
  693. RemoveBreakpoint(type, addr);
  694. SendReply("OK");
  695. }
  696. void HandlePacket() {
  697. if (!IsConnected()) {
  698. return;
  699. }
  700. if (!IsDataAvailable()) {
  701. return;
  702. }
  703. ReadCommand();
  704. if (command_length == 0) {
  705. return;
  706. }
  707. LOG_DEBUG(Debug_GDBStub, "Packet: %s", command_buffer);
  708. switch (command_buffer[0]) {
  709. case 'q':
  710. HandleQuery();
  711. break;
  712. case 'H':
  713. HandleSetThread();
  714. break;
  715. case '?':
  716. SendSignal(latest_signal);
  717. break;
  718. case 'k':
  719. Shutdown();
  720. LOG_INFO(Debug_GDBStub, "killed by gdb");
  721. return;
  722. case 'g':
  723. ReadRegisters();
  724. break;
  725. case 'G':
  726. WriteRegisters();
  727. break;
  728. case 'p':
  729. ReadRegister();
  730. break;
  731. case 'P':
  732. WriteRegister();
  733. break;
  734. case 'm':
  735. ReadMemory();
  736. break;
  737. case 'M':
  738. WriteMemory();
  739. break;
  740. case 's':
  741. Step();
  742. return;
  743. case 'C':
  744. case 'c':
  745. Continue();
  746. return;
  747. case 'z':
  748. RemoveBreakpoint();
  749. break;
  750. case 'Z':
  751. AddBreakpoint();
  752. break;
  753. default:
  754. SendReply("");
  755. break;
  756. }
  757. }
  758. void SetServerPort(u16 port) {
  759. gdbstub_port = port;
  760. }
  761. void ToggleServer(bool status) {
  762. if (status) {
  763. server_enabled = status;
  764. // Start server
  765. if (!IsConnected() && Core::g_sys_core != nullptr) {
  766. Init();
  767. }
  768. } else {
  769. // Stop server
  770. if (IsConnected()) {
  771. Shutdown();
  772. }
  773. server_enabled = status;
  774. }
  775. }
  776. static void Init(u16 port) {
  777. if (!server_enabled) {
  778. // Set the halt loop to false in case the user enabled the gdbstub mid-execution.
  779. // This way the CPU can still execute normally.
  780. halt_loop = false;
  781. step_loop = false;
  782. return;
  783. }
  784. // Setup initial gdbstub status
  785. halt_loop = true;
  786. step_loop = false;
  787. breakpoints_execute.clear();
  788. breakpoints_read.clear();
  789. breakpoints_write.clear();
  790. // Start gdb server
  791. LOG_INFO(Debug_GDBStub, "Starting GDB server on port %d...", port);
  792. sockaddr_in saddr_server = {};
  793. saddr_server.sin_family = AF_INET;
  794. saddr_server.sin_port = htons(port);
  795. saddr_server.sin_addr.s_addr = INADDR_ANY;
  796. #ifdef _WIN32
  797. WSAStartup(MAKEWORD(2, 2), &InitData);
  798. #endif
  799. int tmpsock = socket(PF_INET, SOCK_STREAM, 0);
  800. if (tmpsock == -1) {
  801. LOG_ERROR(Debug_GDBStub, "Failed to create gdb socket");
  802. }
  803. // Set socket to SO_REUSEADDR so it can always bind on the same port
  804. int reuse_enabled = 1;
  805. if (setsockopt(tmpsock, SOL_SOCKET, SO_REUSEADDR, (const char*)&reuse_enabled,
  806. sizeof(reuse_enabled)) < 0) {
  807. LOG_ERROR(Debug_GDBStub, "Failed to set gdb socket option");
  808. }
  809. const sockaddr* server_addr = reinterpret_cast<const sockaddr*>(&saddr_server);
  810. socklen_t server_addrlen = sizeof(saddr_server);
  811. if (bind(tmpsock, server_addr, server_addrlen) < 0) {
  812. LOG_ERROR(Debug_GDBStub, "Failed to bind gdb socket");
  813. }
  814. if (listen(tmpsock, 1) < 0) {
  815. LOG_ERROR(Debug_GDBStub, "Failed to listen to gdb socket");
  816. }
  817. // Wait for gdb to connect
  818. LOG_INFO(Debug_GDBStub, "Waiting for gdb to connect...\n");
  819. sockaddr_in saddr_client;
  820. sockaddr* client_addr = reinterpret_cast<sockaddr*>(&saddr_client);
  821. socklen_t client_addrlen = sizeof(saddr_client);
  822. gdbserver_socket = accept(tmpsock, client_addr, &client_addrlen);
  823. if (gdbserver_socket < 0) {
  824. // In the case that we couldn't start the server for whatever reason, just start CPU
  825. // execution like normal.
  826. halt_loop = false;
  827. step_loop = false;
  828. LOG_ERROR(Debug_GDBStub, "Failed to accept gdb client");
  829. } else {
  830. LOG_INFO(Debug_GDBStub, "Client connected.\n");
  831. saddr_client.sin_addr.s_addr = ntohl(saddr_client.sin_addr.s_addr);
  832. }
  833. // Clean up temporary socket if it's still alive at this point.
  834. if (tmpsock != -1) {
  835. shutdown(tmpsock, SHUT_RDWR);
  836. }
  837. }
  838. void Init() {
  839. Init(gdbstub_port);
  840. }
  841. void Shutdown() {
  842. if (!server_enabled) {
  843. return;
  844. }
  845. LOG_INFO(Debug_GDBStub, "Stopping GDB ...");
  846. if (gdbserver_socket != -1) {
  847. shutdown(gdbserver_socket, SHUT_RDWR);
  848. gdbserver_socket = -1;
  849. }
  850. #ifdef _WIN32
  851. WSACleanup();
  852. #endif
  853. LOG_INFO(Debug_GDBStub, "GDB stopped.");
  854. }
  855. bool IsServerEnabled() {
  856. return server_enabled;
  857. }
  858. bool IsConnected() {
  859. return IsServerEnabled() && gdbserver_socket != -1;
  860. }
  861. bool GetCpuHaltFlag() {
  862. return halt_loop;
  863. }
  864. bool GetCpuStepFlag() {
  865. return step_loop;
  866. }
  867. void SetCpuStepFlag(bool is_step) {
  868. step_loop = is_step;
  869. }
  870. };