gdbstub.cpp 28 KB

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