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/loader/loader.h"
  35. #include "core/memory.h"
  36. const int GDB_BUFFER_SIZE = 10000;
  37. const char GDB_STUB_START = '$';
  38. const char GDB_STUB_END = '#';
  39. const char GDB_STUB_ACK = '+';
  40. const char GDB_STUB_NACK = '-';
  41. #ifndef SIGTRAP
  42. const u32 SIGTRAP = 5;
  43. #endif
  44. #ifndef SIGTERM
  45. const u32 SIGTERM = 15;
  46. #endif
  47. #ifndef MSG_WAITALL
  48. const u32 MSG_WAITALL = 8;
  49. #endif
  50. const u32 R0_REGISTER = 0;
  51. const u32 R15_REGISTER = 15;
  52. const u32 CPSR_REGISTER = 25;
  53. const u32 FPSCR_REGISTER = 58;
  54. // For sample XML files see the GDB source /gdb/features
  55. // GDB also wants the l character at the start
  56. // This XML defines what the registers are for this specific ARM device
  57. static const char* target_xml =
  58. R"(l<?xml version="1.0"?>
  59. <!DOCTYPE target SYSTEM "gdb-target.dtd">
  60. <target version="1.0">
  61. <feature name="org.gnu.gdb.arm.core">
  62. <reg name="r0" bitsize="32"/>
  63. <reg name="r1" bitsize="32"/>
  64. <reg name="r2" bitsize="32"/>
  65. <reg name="r3" bitsize="32"/>
  66. <reg name="r4" bitsize="32"/>
  67. <reg name="r5" bitsize="32"/>
  68. <reg name="r6" bitsize="32"/>
  69. <reg name="r7" bitsize="32"/>
  70. <reg name="r8" bitsize="32"/>
  71. <reg name="r9" bitsize="32"/>
  72. <reg name="r10" bitsize="32"/>
  73. <reg name="r11" bitsize="32"/>
  74. <reg name="r12" bitsize="32"/>
  75. <reg name="sp" bitsize="32" type="data_ptr"/>
  76. <reg name="lr" bitsize="32"/>
  77. <reg name="pc" bitsize="32" type="code_ptr"/>
  78. <!-- The CPSR is register 25, rather than register 16, because
  79. the FPA registers historically were placed between the PC
  80. and the CPSR in the "g" packet. -->
  81. <reg name="cpsr" bitsize="32" regnum="25"/>
  82. </feature>
  83. <feature name="org.gnu.gdb.arm.vfp">
  84. <reg name="d0" bitsize="64" type="float"/>
  85. <reg name="d1" bitsize="64" type="float"/>
  86. <reg name="d2" bitsize="64" type="float"/>
  87. <reg name="d3" bitsize="64" type="float"/>
  88. <reg name="d4" bitsize="64" type="float"/>
  89. <reg name="d5" bitsize="64" type="float"/>
  90. <reg name="d6" bitsize="64" type="float"/>
  91. <reg name="d7" bitsize="64" type="float"/>
  92. <reg name="d8" bitsize="64" type="float"/>
  93. <reg name="d9" bitsize="64" type="float"/>
  94. <reg name="d10" bitsize="64" type="float"/>
  95. <reg name="d11" bitsize="64" type="float"/>
  96. <reg name="d12" bitsize="64" type="float"/>
  97. <reg name="d13" bitsize="64" type="float"/>
  98. <reg name="d14" bitsize="64" type="float"/>
  99. <reg name="d15" bitsize="64" type="float"/>
  100. <reg name="fpscr" bitsize="32" type="int" group="float"/>
  101. </feature>
  102. </target>
  103. )";
  104. namespace GDBStub {
  105. static int gdbserver_socket = -1;
  106. static u8 command_buffer[GDB_BUFFER_SIZE];
  107. static u32 command_length;
  108. static u32 latest_signal = 0;
  109. static bool step_break = false;
  110. static bool memory_break = false;
  111. // Binding to a port within the reserved ports range (0-1023) requires root permissions,
  112. // so default to a port outside of that range.
  113. static u16 gdbstub_port = 24689;
  114. static bool halt_loop = true;
  115. static bool step_loop = false;
  116. // If set to false, the server will never be started and no
  117. // gdbstub-related functions will be executed.
  118. static std::atomic<bool> server_enabled(false);
  119. #ifdef _WIN32
  120. WSADATA InitData;
  121. #endif
  122. struct Breakpoint {
  123. bool active;
  124. PAddr addr;
  125. u32 len;
  126. };
  127. static std::map<u32, Breakpoint> breakpoints_execute;
  128. static std::map<u32, Breakpoint> breakpoints_read;
  129. static std::map<u32, Breakpoint> breakpoints_write;
  130. /**
  131. * Turns hex string character into the equivalent byte.
  132. *
  133. * @param hex Input hex character to be turned into byte.
  134. */
  135. static u8 HexCharToValue(u8 hex) {
  136. if (hex >= '0' && hex <= '9') {
  137. return hex - '0';
  138. } else if (hex >= 'a' && hex <= 'f') {
  139. return hex - 'a' + 0xA;
  140. } else if (hex >= 'A' && hex <= 'F') {
  141. return hex - 'A' + 0xA;
  142. }
  143. LOG_ERROR(Debug_GDBStub, "Invalid nibble: %c (%02x)\n", hex, hex);
  144. return 0;
  145. }
  146. /**
  147. * Turn nibble of byte into hex string character.
  148. *
  149. * @param n Nibble to be turned into hex character.
  150. */
  151. static u8 NibbleToHex(u8 n) {
  152. n &= 0xF;
  153. if (n < 0xA) {
  154. return '0' + n;
  155. } else {
  156. return 'A' + n - 0xA;
  157. }
  158. }
  159. /**
  160. * Converts input hex string characters into an array of equivalent of u8 bytes.
  161. *
  162. * @param src Pointer to array of output hex string characters.
  163. * @param len Length of src array.
  164. */
  165. static u32 HexToInt(const u8* src, size_t len) {
  166. u32 output = 0;
  167. while (len-- > 0) {
  168. output = (output << 4) | HexCharToValue(src[0]);
  169. src++;
  170. }
  171. return output;
  172. }
  173. /**
  174. * Converts input array of u8 bytes into their equivalent hex string characters.
  175. *
  176. * @param dest Pointer to buffer to store output hex string characters.
  177. * @param src Pointer to array of u8 bytes.
  178. * @param len Length of src array.
  179. */
  180. static void MemToGdbHex(u8* dest, const u8* src, size_t len) {
  181. while (len-- > 0) {
  182. u8 tmp = *src++;
  183. *dest++ = NibbleToHex(tmp >> 4);
  184. *dest++ = NibbleToHex(tmp);
  185. }
  186. }
  187. /**
  188. * Converts input gdb-formatted hex string characters into an array of equivalent of u8 bytes.
  189. *
  190. * @param dest Pointer to buffer to store u8 bytes.
  191. * @param src Pointer to array of output hex string characters.
  192. * @param len Length of src array.
  193. */
  194. static void GdbHexToMem(u8* dest, const u8* src, size_t len) {
  195. while (len-- > 0) {
  196. *dest++ = (HexCharToValue(src[0]) << 4) | HexCharToValue(src[1]);
  197. src += 2;
  198. }
  199. }
  200. /**
  201. * Convert a u32 into a gdb-formatted hex string.
  202. *
  203. * @param dest Pointer to buffer to store output hex string characters.
  204. */
  205. static void IntToGdbHex(u8* dest, u32 v) {
  206. for (int i = 0; i < 8; i += 2) {
  207. dest[i + 1] = NibbleToHex(v >> (4 * i));
  208. dest[i] = NibbleToHex(v >> (4 * (i + 1)));
  209. }
  210. }
  211. /**
  212. * Convert a gdb-formatted hex string into a u32.
  213. *
  214. * @param src Pointer to hex string.
  215. */
  216. static u32 GdbHexToInt(const u8* src) {
  217. u32 output = 0;
  218. for (int i = 0; i < 8; i += 2) {
  219. output = (output << 4) | HexCharToValue(src[7 - i - 1]);
  220. output = (output << 4) | HexCharToValue(src[7 - i]);
  221. }
  222. return output;
  223. }
  224. /// Read a byte from the gdb client.
  225. static u8 ReadByte() {
  226. u8 c;
  227. size_t received_size = recv(gdbserver_socket, reinterpret_cast<char*>(&c), 1, MSG_WAITALL);
  228. if (received_size != 1) {
  229. LOG_ERROR(Debug_GDBStub, "recv failed : %ld", received_size);
  230. Shutdown();
  231. }
  232. return c;
  233. }
  234. /// Calculate the checksum of the current command buffer.
  235. static u8 CalculateChecksum(const u8* buffer, size_t length) {
  236. return static_cast<u8>(std::accumulate(buffer, buffer + length, 0, std::plus<u8>()));
  237. }
  238. /**
  239. * Get the list of breakpoints for a given breakpoint type.
  240. *
  241. * @param type Type of breakpoint list.
  242. */
  243. static std::map<u32, Breakpoint>& GetBreakpointList(BreakpointType type) {
  244. switch (type) {
  245. case BreakpointType::Execute:
  246. return breakpoints_execute;
  247. case BreakpointType::Read:
  248. return breakpoints_read;
  249. case BreakpointType::Write:
  250. return breakpoints_write;
  251. default:
  252. return breakpoints_read;
  253. }
  254. }
  255. /**
  256. * Remove the breakpoint from the given address of the specified type.
  257. *
  258. * @param type Type of breakpoint.
  259. * @param addr Address of breakpoint.
  260. */
  261. static void RemoveBreakpoint(BreakpointType type, PAddr addr) {
  262. std::map<u32, Breakpoint>& p = GetBreakpointList(type);
  263. auto bp = p.find(addr);
  264. if (bp != p.end()) {
  265. LOG_DEBUG(Debug_GDBStub, "gdb: removed a breakpoint: %08x bytes at %08x of type %d\n",
  266. bp->second.len, bp->second.addr, type);
  267. p.erase(addr);
  268. }
  269. }
  270. BreakpointAddress GetNextBreakpointFromAddress(PAddr addr, BreakpointType type) {
  271. std::map<u32, Breakpoint>& p = GetBreakpointList(type);
  272. auto next_breakpoint = p.lower_bound(addr);
  273. BreakpointAddress breakpoint;
  274. if (next_breakpoint != p.end()) {
  275. breakpoint.address = next_breakpoint->first;
  276. breakpoint.type = type;
  277. } else {
  278. breakpoint.address = 0;
  279. breakpoint.type = BreakpointType::None;
  280. }
  281. return breakpoint;
  282. }
  283. bool CheckBreakpoint(PAddr addr, BreakpointType type) {
  284. if (!IsConnected()) {
  285. return false;
  286. }
  287. std::map<u32, Breakpoint>& p = GetBreakpointList(type);
  288. auto bp = p.find(addr);
  289. if (bp != p.end()) {
  290. u32 len = bp->second.len;
  291. // IDA Pro defaults to 4-byte breakpoints for all non-hardware breakpoints
  292. // no matter if it's a 4-byte or 2-byte instruction. When you execute a
  293. // Thumb instruction with a 4-byte breakpoint set, it will set a breakpoint on
  294. // two instructions instead of the single instruction you placed the breakpoint
  295. // on. So, as a way to make sure that execution breakpoints are only breaking
  296. // on the instruction that was specified, set the length of an execution
  297. // breakpoint to 1. This should be fine since the CPU should never begin executing
  298. // an instruction anywhere except the beginning of the instruction.
  299. if (type == BreakpointType::Execute) {
  300. len = 1;
  301. }
  302. if (bp->second.active && (addr >= bp->second.addr && addr < bp->second.addr + len)) {
  303. LOG_DEBUG(Debug_GDBStub,
  304. "Found breakpoint type %d @ %08x, range: %08x - %08x (%d bytes)\n", type,
  305. addr, bp->second.addr, bp->second.addr + len, len);
  306. return true;
  307. }
  308. }
  309. return false;
  310. }
  311. /**
  312. * Send packet to gdb client.
  313. *
  314. * @param packet Packet to be sent to client.
  315. */
  316. static void SendPacket(const char packet) {
  317. size_t sent_size = send(gdbserver_socket, &packet, 1, 0);
  318. if (sent_size != 1) {
  319. LOG_ERROR(Debug_GDBStub, "send failed");
  320. }
  321. }
  322. /**
  323. * Send reply to gdb client.
  324. *
  325. * @param reply Reply to be sent to client.
  326. */
  327. static void SendReply(const char* reply) {
  328. if (!IsConnected()) {
  329. return;
  330. }
  331. memset(command_buffer, 0, sizeof(command_buffer));
  332. command_length = static_cast<u32>(strlen(reply));
  333. if (command_length + 4 > sizeof(command_buffer)) {
  334. LOG_ERROR(Debug_GDBStub, "command_buffer overflow in SendReply");
  335. return;
  336. }
  337. memcpy(command_buffer + 1, reply, command_length);
  338. u8 checksum = CalculateChecksum(command_buffer, command_length + 1);
  339. command_buffer[0] = GDB_STUB_START;
  340. command_buffer[command_length + 1] = GDB_STUB_END;
  341. command_buffer[command_length + 2] = NibbleToHex(checksum >> 4);
  342. command_buffer[command_length + 3] = NibbleToHex(checksum);
  343. u8* ptr = command_buffer;
  344. u32 left = command_length + 4;
  345. while (left > 0) {
  346. int sent_size = send(gdbserver_socket, reinterpret_cast<char*>(ptr), left, 0);
  347. if (sent_size < 0) {
  348. LOG_ERROR(Debug_GDBStub, "gdb: send failed");
  349. return Shutdown();
  350. }
  351. left -= sent_size;
  352. ptr += sent_size;
  353. }
  354. }
  355. /// Handle query command from gdb client.
  356. static void HandleQuery() {
  357. LOG_DEBUG(Debug_GDBStub, "gdb: query '%s'\n", command_buffer + 1);
  358. const char* query = reinterpret_cast<const char*>(command_buffer + 1);
  359. if (strcmp(query, "TStatus") == 0) {
  360. SendReply("T0");
  361. } else if (strncmp(query, "Supported", strlen("Supported")) == 0) {
  362. // PacketSize needs to be large enough for target xml
  363. SendReply("PacketSize=800;qXfer:features:read+");
  364. } else if (strncmp(query, "Xfer:features:read:target.xml:",
  365. strlen("Xfer:features:read:target.xml:")) == 0) {
  366. SendReply(target_xml);
  367. } else {
  368. SendReply("");
  369. }
  370. }
  371. /// Handle set thread command from gdb client.
  372. static void HandleSetThread() {
  373. if (memcmp(command_buffer, "Hg0", 3) == 0 || memcmp(command_buffer, "Hc-1", 4) == 0 ||
  374. memcmp(command_buffer, "Hc0", 4) == 0 || memcmp(command_buffer, "Hc1", 4) == 0) {
  375. return SendReply("OK");
  376. }
  377. SendReply("E01");
  378. }
  379. /**
  380. * Send signal packet to client.
  381. *
  382. * @param signal Signal to be sent to client.
  383. */
  384. static void SendSignal(u32 signal) {
  385. if (gdbserver_socket == -1) {
  386. return;
  387. }
  388. latest_signal = signal;
  389. std::string buffer =
  390. Common::StringFromFormat("T%02x%02x:%08x;%02x:%08x;", latest_signal, 15,
  391. htonl(Core::CPU().GetPC()), 13, htonl(Core::CPU().GetReg(13)));
  392. LOG_DEBUG(Debug_GDBStub, "Response: %s", buffer.c_str());
  393. SendReply(buffer.c_str());
  394. }
  395. /// Read command from gdb client.
  396. static void ReadCommand() {
  397. command_length = 0;
  398. memset(command_buffer, 0, sizeof(command_buffer));
  399. u8 c = ReadByte();
  400. if (c == '+') {
  401. // ignore ack
  402. return;
  403. } else if (c == 0x03) {
  404. LOG_INFO(Debug_GDBStub, "gdb: found break command\n");
  405. halt_loop = true;
  406. SendSignal(SIGTRAP);
  407. return;
  408. } else if (c != GDB_STUB_START) {
  409. LOG_DEBUG(Debug_GDBStub, "gdb: read invalid byte %02x\n", c);
  410. return;
  411. }
  412. while ((c = ReadByte()) != GDB_STUB_END) {
  413. if (command_length >= sizeof(command_buffer)) {
  414. LOG_ERROR(Debug_GDBStub, "gdb: command_buffer overflow\n");
  415. SendPacket(GDB_STUB_NACK);
  416. return;
  417. }
  418. command_buffer[command_length++] = c;
  419. }
  420. u8 checksum_received = HexCharToValue(ReadByte()) << 4;
  421. checksum_received |= HexCharToValue(ReadByte());
  422. u8 checksum_calculated = CalculateChecksum(command_buffer, command_length);
  423. if (checksum_received != checksum_calculated) {
  424. LOG_ERROR(Debug_GDBStub,
  425. "gdb: invalid checksum: calculated %02x and read %02x for $%s# (length: %d)\n",
  426. checksum_calculated, checksum_received, command_buffer, command_length);
  427. command_length = 0;
  428. SendPacket(GDB_STUB_NACK);
  429. return;
  430. }
  431. SendPacket(GDB_STUB_ACK);
  432. }
  433. /// Check if there is data to be read from the gdb client.
  434. static bool IsDataAvailable() {
  435. if (!IsConnected()) {
  436. return false;
  437. }
  438. fd_set fd_socket;
  439. FD_ZERO(&fd_socket);
  440. FD_SET(gdbserver_socket, &fd_socket);
  441. struct timeval t;
  442. t.tv_sec = 0;
  443. t.tv_usec = 0;
  444. if (select(gdbserver_socket + 1, &fd_socket, nullptr, nullptr, &t) < 0) {
  445. LOG_ERROR(Debug_GDBStub, "select failed");
  446. return false;
  447. }
  448. return FD_ISSET(gdbserver_socket, &fd_socket) != 0;
  449. }
  450. /// Send requested register to gdb client.
  451. static void ReadRegister() {
  452. static u8 reply[64];
  453. memset(reply, 0, sizeof(reply));
  454. u32 id = HexCharToValue(command_buffer[1]);
  455. if (command_buffer[2] != '\0') {
  456. id <<= 4;
  457. id |= HexCharToValue(command_buffer[2]);
  458. }
  459. if (id <= R15_REGISTER) {
  460. IntToGdbHex(reply, Core::CPU().GetReg(id));
  461. } else if (id == CPSR_REGISTER) {
  462. IntToGdbHex(reply, Core::CPU().GetCPSR());
  463. } else if (id > CPSR_REGISTER && id < FPSCR_REGISTER) {
  464. IntToGdbHex(reply, Core::CPU().GetVFPReg(
  465. id - CPSR_REGISTER -
  466. 1)); // VFP registers should start at 26, so one after CSPR_REGISTER
  467. } else if (id == FPSCR_REGISTER) {
  468. IntToGdbHex(reply, Core::CPU().GetVFPSystemReg(VFP_FPSCR)); // Get FPSCR
  469. IntToGdbHex(reply + 8, 0);
  470. } else {
  471. return SendReply("E01");
  472. }
  473. SendReply(reinterpret_cast<char*>(reply));
  474. }
  475. /// Send all registers to the gdb client.
  476. static void ReadRegisters() {
  477. static u8 buffer[GDB_BUFFER_SIZE - 4];
  478. memset(buffer, 0, sizeof(buffer));
  479. u8* bufptr = buffer;
  480. for (int reg = 0; reg <= R15_REGISTER; reg++) {
  481. IntToGdbHex(bufptr + reg * CHAR_BIT, Core::CPU().GetReg(reg));
  482. }
  483. bufptr += (16 * CHAR_BIT);
  484. IntToGdbHex(bufptr, Core::CPU().GetCPSR());
  485. bufptr += CHAR_BIT;
  486. for (int reg = 0; reg <= 31; reg++) {
  487. IntToGdbHex(bufptr + reg * CHAR_BIT, Core::CPU().GetVFPReg(reg));
  488. }
  489. bufptr += (32 * CHAR_BIT);
  490. IntToGdbHex(bufptr, Core::CPU().GetVFPSystemReg(VFP_FPSCR));
  491. SendReply(reinterpret_cast<char*>(buffer));
  492. }
  493. /// Modify data of register specified by gdb client.
  494. static void WriteRegister() {
  495. const u8* buffer_ptr = command_buffer + 3;
  496. u32 id = HexCharToValue(command_buffer[1]);
  497. if (command_buffer[2] != '=') {
  498. ++buffer_ptr;
  499. id <<= 4;
  500. id |= HexCharToValue(command_buffer[2]);
  501. }
  502. if (id <= R15_REGISTER) {
  503. Core::CPU().SetReg(id, GdbHexToInt(buffer_ptr));
  504. } else if (id == CPSR_REGISTER) {
  505. Core::CPU().SetCPSR(GdbHexToInt(buffer_ptr));
  506. } else if (id > CPSR_REGISTER && id < FPSCR_REGISTER) {
  507. Core::CPU().SetVFPReg(id - CPSR_REGISTER - 1, GdbHexToInt(buffer_ptr));
  508. } else if (id == FPSCR_REGISTER) {
  509. Core::CPU().SetVFPSystemReg(VFP_FPSCR, GdbHexToInt(buffer_ptr));
  510. } else {
  511. return SendReply("E01");
  512. }
  513. SendReply("OK");
  514. }
  515. /// Modify all registers with data received from the client.
  516. static void WriteRegisters() {
  517. const u8* buffer_ptr = command_buffer + 1;
  518. if (command_buffer[0] != 'G')
  519. return SendReply("E01");
  520. for (int i = 0, reg = 0; reg <= FPSCR_REGISTER; i++, reg++) {
  521. if (reg <= R15_REGISTER) {
  522. Core::CPU().SetReg(reg, GdbHexToInt(buffer_ptr + i * CHAR_BIT));
  523. } else if (reg == CPSR_REGISTER) {
  524. Core::CPU().SetCPSR(GdbHexToInt(buffer_ptr + i * CHAR_BIT));
  525. } else if (reg == CPSR_REGISTER - 1) {
  526. // Dummy FPA register, ignore
  527. } else if (reg < CPSR_REGISTER) {
  528. // Dummy FPA registers, ignore
  529. i += 2;
  530. } else if (reg > CPSR_REGISTER && reg < FPSCR_REGISTER) {
  531. Core::CPU().SetVFPReg(reg - CPSR_REGISTER - 1, GdbHexToInt(buffer_ptr + i * CHAR_BIT));
  532. i++; // Skip padding
  533. } else if (reg == FPSCR_REGISTER) {
  534. Core::CPU().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::System().GetInstance().IsPoweredOn()) {
  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. };