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 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. * @param v Value to convert.
  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. VAddr 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. if (!Memory::IsValidVirtualAddress(addr)) {
  553. return SendReply("E00");
  554. }
  555. std::vector<u8> data(len);
  556. Memory::ReadBlock(addr, data.data(), len);
  557. MemToGdbHex(reply, data.data(), len);
  558. reply[len * 2] = '\0';
  559. SendReply(reinterpret_cast<char*>(reply));
  560. }
  561. /// Modify location in memory with data received from the gdb client.
  562. static void WriteMemory() {
  563. auto start_offset = command_buffer + 1;
  564. auto addr_pos = std::find(start_offset, command_buffer + command_length, ',');
  565. VAddr addr = HexToInt(start_offset, static_cast<u32>(addr_pos - start_offset));
  566. start_offset = addr_pos + 1;
  567. auto len_pos = std::find(start_offset, command_buffer + command_length, ':');
  568. u32 len = HexToInt(start_offset, static_cast<u32>(len_pos - start_offset));
  569. if (!Memory::IsValidVirtualAddress(addr)) {
  570. return SendReply("E00");
  571. }
  572. std::vector<u8> data(len);
  573. GdbHexToMem(data.data(), len_pos + 1, len);
  574. Memory::WriteBlock(addr, data.data(), len);
  575. SendReply("OK");
  576. }
  577. void Break(bool is_memory_break) {
  578. if (!halt_loop) {
  579. halt_loop = true;
  580. SendSignal(SIGTRAP);
  581. }
  582. memory_break = is_memory_break;
  583. }
  584. /// Tell the CPU that it should perform a single step.
  585. static void Step() {
  586. step_loop = true;
  587. halt_loop = true;
  588. step_break = true;
  589. SendSignal(SIGTRAP);
  590. }
  591. bool IsMemoryBreak() {
  592. if (IsConnected()) {
  593. return false;
  594. }
  595. return memory_break;
  596. }
  597. /// Tell the CPU to continue executing.
  598. static void Continue() {
  599. memory_break = false;
  600. step_break = false;
  601. step_loop = false;
  602. halt_loop = false;
  603. }
  604. /**
  605. * Commit breakpoint to list of breakpoints.
  606. *
  607. * @param type Type of breakpoint.
  608. * @param addr Address of breakpoint.
  609. * @param len Length of breakpoint.
  610. */
  611. static bool CommitBreakpoint(BreakpointType type, PAddr addr, u32 len) {
  612. std::map<u32, Breakpoint>& p = GetBreakpointList(type);
  613. Breakpoint breakpoint;
  614. breakpoint.active = true;
  615. breakpoint.addr = addr;
  616. breakpoint.len = len;
  617. p.insert({addr, breakpoint});
  618. LOG_DEBUG(Debug_GDBStub, "gdb: added %d breakpoint: %08x bytes at %08x\n", type, breakpoint.len,
  619. breakpoint.addr);
  620. return true;
  621. }
  622. /// Handle add breakpoint command from gdb client.
  623. static void AddBreakpoint() {
  624. BreakpointType type;
  625. u8 type_id = HexCharToValue(command_buffer[1]);
  626. switch (type_id) {
  627. case 0:
  628. case 1:
  629. type = BreakpointType::Execute;
  630. break;
  631. case 2:
  632. type = BreakpointType::Write;
  633. break;
  634. case 3:
  635. type = BreakpointType::Read;
  636. break;
  637. case 4:
  638. type = BreakpointType::Access;
  639. break;
  640. default:
  641. return SendReply("E01");
  642. }
  643. auto start_offset = command_buffer + 3;
  644. auto addr_pos = std::find(start_offset, command_buffer + command_length, ',');
  645. PAddr addr = HexToInt(start_offset, static_cast<u32>(addr_pos - start_offset));
  646. start_offset = addr_pos + 1;
  647. u32 len =
  648. HexToInt(start_offset, static_cast<u32>((command_buffer + command_length) - start_offset));
  649. if (type == BreakpointType::Access) {
  650. // Access is made up of Read and Write types, so add both breakpoints
  651. type = BreakpointType::Read;
  652. if (!CommitBreakpoint(type, addr, len)) {
  653. return SendReply("E02");
  654. }
  655. type = BreakpointType::Write;
  656. }
  657. if (!CommitBreakpoint(type, addr, len)) {
  658. return SendReply("E02");
  659. }
  660. SendReply("OK");
  661. }
  662. /// Handle remove breakpoint command from gdb client.
  663. static void RemoveBreakpoint() {
  664. BreakpointType type;
  665. u8 type_id = HexCharToValue(command_buffer[1]);
  666. switch (type_id) {
  667. case 0:
  668. case 1:
  669. type = BreakpointType::Execute;
  670. break;
  671. case 2:
  672. type = BreakpointType::Write;
  673. break;
  674. case 3:
  675. type = BreakpointType::Read;
  676. break;
  677. case 4:
  678. type = BreakpointType::Access;
  679. break;
  680. default:
  681. return SendReply("E01");
  682. }
  683. auto start_offset = command_buffer + 3;
  684. auto addr_pos = std::find(start_offset, command_buffer + command_length, ',');
  685. PAddr addr = HexToInt(start_offset, static_cast<u32>(addr_pos - start_offset));
  686. if (type == BreakpointType::Access) {
  687. // Access is made up of Read and Write types, so add both breakpoints
  688. type = BreakpointType::Read;
  689. RemoveBreakpoint(type, addr);
  690. type = BreakpointType::Write;
  691. }
  692. RemoveBreakpoint(type, addr);
  693. SendReply("OK");
  694. }
  695. void HandlePacket() {
  696. if (!IsConnected()) {
  697. return;
  698. }
  699. if (!IsDataAvailable()) {
  700. return;
  701. }
  702. ReadCommand();
  703. if (command_length == 0) {
  704. return;
  705. }
  706. LOG_DEBUG(Debug_GDBStub, "Packet: %s", command_buffer);
  707. switch (command_buffer[0]) {
  708. case 'q':
  709. HandleQuery();
  710. break;
  711. case 'H':
  712. HandleSetThread();
  713. break;
  714. case '?':
  715. SendSignal(latest_signal);
  716. break;
  717. case 'k':
  718. Shutdown();
  719. LOG_INFO(Debug_GDBStub, "killed by gdb");
  720. return;
  721. case 'g':
  722. ReadRegisters();
  723. break;
  724. case 'G':
  725. WriteRegisters();
  726. break;
  727. case 'p':
  728. ReadRegister();
  729. break;
  730. case 'P':
  731. WriteRegister();
  732. break;
  733. case 'm':
  734. ReadMemory();
  735. break;
  736. case 'M':
  737. WriteMemory();
  738. break;
  739. case 's':
  740. Step();
  741. return;
  742. case 'C':
  743. case 'c':
  744. Continue();
  745. return;
  746. case 'z':
  747. RemoveBreakpoint();
  748. break;
  749. case 'Z':
  750. AddBreakpoint();
  751. break;
  752. default:
  753. SendReply("");
  754. break;
  755. }
  756. }
  757. void SetServerPort(u16 port) {
  758. gdbstub_port = port;
  759. }
  760. void ToggleServer(bool status) {
  761. if (status) {
  762. server_enabled = status;
  763. // Start server
  764. if (!IsConnected() && Core::System().GetInstance().IsPoweredOn()) {
  765. Init();
  766. }
  767. } else {
  768. // Stop server
  769. if (IsConnected()) {
  770. Shutdown();
  771. }
  772. server_enabled = status;
  773. }
  774. }
  775. static void Init(u16 port) {
  776. if (!server_enabled) {
  777. // Set the halt loop to false in case the user enabled the gdbstub mid-execution.
  778. // This way the CPU can still execute normally.
  779. halt_loop = false;
  780. step_loop = false;
  781. return;
  782. }
  783. // Setup initial gdbstub status
  784. halt_loop = true;
  785. step_loop = false;
  786. breakpoints_execute.clear();
  787. breakpoints_read.clear();
  788. breakpoints_write.clear();
  789. // Start gdb server
  790. LOG_INFO(Debug_GDBStub, "Starting GDB server on port %d...", port);
  791. sockaddr_in saddr_server = {};
  792. saddr_server.sin_family = AF_INET;
  793. saddr_server.sin_port = htons(port);
  794. saddr_server.sin_addr.s_addr = INADDR_ANY;
  795. #ifdef _WIN32
  796. WSAStartup(MAKEWORD(2, 2), &InitData);
  797. #endif
  798. int tmpsock = static_cast<int>(socket(PF_INET, SOCK_STREAM, 0));
  799. if (tmpsock == -1) {
  800. LOG_ERROR(Debug_GDBStub, "Failed to create gdb socket");
  801. }
  802. // Set socket to SO_REUSEADDR so it can always bind on the same port
  803. int reuse_enabled = 1;
  804. if (setsockopt(tmpsock, SOL_SOCKET, SO_REUSEADDR, (const char*)&reuse_enabled,
  805. sizeof(reuse_enabled)) < 0) {
  806. LOG_ERROR(Debug_GDBStub, "Failed to set gdb socket option");
  807. }
  808. const sockaddr* server_addr = reinterpret_cast<const sockaddr*>(&saddr_server);
  809. socklen_t server_addrlen = sizeof(saddr_server);
  810. if (bind(tmpsock, server_addr, server_addrlen) < 0) {
  811. LOG_ERROR(Debug_GDBStub, "Failed to bind gdb socket");
  812. }
  813. if (listen(tmpsock, 1) < 0) {
  814. LOG_ERROR(Debug_GDBStub, "Failed to listen to gdb socket");
  815. }
  816. // Wait for gdb to connect
  817. LOG_INFO(Debug_GDBStub, "Waiting for gdb to connect...\n");
  818. sockaddr_in saddr_client;
  819. sockaddr* client_addr = reinterpret_cast<sockaddr*>(&saddr_client);
  820. socklen_t client_addrlen = sizeof(saddr_client);
  821. gdbserver_socket = static_cast<int>(accept(tmpsock, client_addr, &client_addrlen));
  822. if (gdbserver_socket < 0) {
  823. // In the case that we couldn't start the server for whatever reason, just start CPU
  824. // execution like normal.
  825. halt_loop = false;
  826. step_loop = false;
  827. LOG_ERROR(Debug_GDBStub, "Failed to accept gdb client");
  828. } else {
  829. LOG_INFO(Debug_GDBStub, "Client connected.\n");
  830. saddr_client.sin_addr.s_addr = ntohl(saddr_client.sin_addr.s_addr);
  831. }
  832. // Clean up temporary socket if it's still alive at this point.
  833. if (tmpsock != -1) {
  834. shutdown(tmpsock, SHUT_RDWR);
  835. }
  836. }
  837. void Init() {
  838. Init(gdbstub_port);
  839. }
  840. void Shutdown() {
  841. if (!server_enabled) {
  842. return;
  843. }
  844. LOG_INFO(Debug_GDBStub, "Stopping GDB ...");
  845. if (gdbserver_socket != -1) {
  846. shutdown(gdbserver_socket, SHUT_RDWR);
  847. gdbserver_socket = -1;
  848. }
  849. #ifdef _WIN32
  850. WSACleanup();
  851. #endif
  852. LOG_INFO(Debug_GDBStub, "GDB stopped.");
  853. }
  854. bool IsServerEnabled() {
  855. return server_enabled;
  856. }
  857. bool IsConnected() {
  858. return IsServerEnabled() && gdbserver_socket != -1;
  859. }
  860. bool GetCpuHaltFlag() {
  861. return halt_loop;
  862. }
  863. bool GetCpuStepFlag() {
  864. return step_loop;
  865. }
  866. void SetCpuStepFlag(bool is_step) {
  867. step_loop = is_step;
  868. }
  869. };