gdbstub.cpp 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199
  1. // Copyright 2013 Dolphin Emulator Project
  2. // Licensed under GPLv2+
  3. // Refer to the license.txt file included.
  4. // Originally written by Sven Peter <sven@fail0verflow.com> for anergistic.
  5. #include <algorithm>
  6. #include <atomic>
  7. #include <climits>
  8. #include <csignal>
  9. #include <cstdarg>
  10. #include <cstdio>
  11. #include <cstring>
  12. #include <map>
  13. #include <numeric>
  14. #include <fcntl.h>
  15. #ifdef _WIN32
  16. #include <winsock2.h>
  17. // winsock2.h needs to be included first to prevent winsock.h being included by other includes
  18. #include <io.h>
  19. #include <iphlpapi.h>
  20. #include <ws2tcpip.h>
  21. #define SHUT_RDWR 2
  22. #else
  23. #include <netinet/in.h>
  24. #include <sys/select.h>
  25. #include <sys/socket.h>
  26. #include <sys/un.h>
  27. #include <unistd.h>
  28. #endif
  29. #include "common/logging/log.h"
  30. #include "common/string_util.h"
  31. #include "common/swap.h"
  32. #include "core/arm/arm_interface.h"
  33. #include "core/core.h"
  34. #include "core/core_cpu.h"
  35. #include "core/gdbstub/gdbstub.h"
  36. #include "core/hle/kernel/kernel.h"
  37. #include "core/hle/kernel/scheduler.h"
  38. #include "core/loader/loader.h"
  39. #include "core/memory.h"
  40. const int GDB_BUFFER_SIZE = 10000;
  41. const char GDB_STUB_START = '$';
  42. const char GDB_STUB_END = '#';
  43. const char GDB_STUB_ACK = '+';
  44. const char GDB_STUB_NACK = '-';
  45. #ifndef SIGTRAP
  46. const u32 SIGTRAP = 5;
  47. #endif
  48. #ifndef SIGTERM
  49. const u32 SIGTERM = 15;
  50. #endif
  51. #ifndef MSG_WAITALL
  52. const u32 MSG_WAITALL = 8;
  53. #endif
  54. const u32 X30_REGISTER = 30;
  55. const u32 SP_REGISTER = 31;
  56. const u32 PC_REGISTER = 32;
  57. const u32 CPSR_REGISTER = 33;
  58. // For sample XML files see the GDB source /gdb/features
  59. // GDB also wants the l character at the start
  60. // This XML defines what the registers are for this specific ARM device
  61. static const char* target_xml =
  62. R"(l<?xml version="1.0"?>
  63. <!DOCTYPE target SYSTEM "gdb-target.dtd">
  64. <target version="1.0">
  65. <feature name="org.gnu.gdb.aarch64.core">
  66. <reg name="x0" bitsize="64"/>
  67. <reg name="x1" bitsize="64"/>
  68. <reg name="x2" bitsize="64"/>
  69. <reg name="x3" bitsize="64"/>
  70. <reg name="x4" bitsize="64"/>
  71. <reg name="x5" bitsize="64"/>
  72. <reg name="x6" bitsize="64"/>
  73. <reg name="x7" bitsize="64"/>
  74. <reg name="x8" bitsize="64"/>
  75. <reg name="x9" bitsize="64"/>
  76. <reg name="x10" bitsize="64"/>
  77. <reg name="x11" bitsize="64"/>
  78. <reg name="x12" bitsize="64"/>
  79. <reg name="x13" bitsize="64"/>
  80. <reg name="x14" bitsize="64"/>
  81. <reg name="x15" bitsize="64"/>
  82. <reg name="x16" bitsize="64"/>
  83. <reg name="x17" bitsize="64"/>
  84. <reg name="x18" bitsize="64"/>
  85. <reg name="x19" bitsize="64"/>
  86. <reg name="x20" bitsize="64"/>
  87. <reg name="x21" bitsize="64"/>
  88. <reg name="x22" bitsize="64"/>
  89. <reg name="x23" bitsize="64"/>
  90. <reg name="x24" bitsize="64"/>
  91. <reg name="x25" bitsize="64"/>
  92. <reg name="x26" bitsize="64"/>
  93. <reg name="x27" bitsize="64"/>
  94. <reg name="x28" bitsize="64"/>
  95. <reg name="x29" bitsize="64"/>
  96. <reg name="x30" bitsize="64"/>
  97. <reg name="sp" bitsize="64" type="data_ptr"/>
  98. <reg name="pc" bitsize="64" type="code_ptr"/>
  99. <flags id="cpsr_flags" size="4">
  100. <field name="SP" start="0" end="0"/>
  101. <field name="" start="1" end="1"/>
  102. <field name="EL" start="2" end="3"/>
  103. <field name="nRW" start="4" end="4"/>
  104. <field name="" start="5" end="5"/>
  105. <field name="F" start="6" end="6"/>
  106. <field name="I" start="7" end="7"/>
  107. <field name="A" start="8" end="8"/>
  108. <field name="D" start="9" end="9"/>
  109. <field name="IL" start="20" end="20"/>
  110. <field name="SS" start="21" end="21"/>
  111. <field name="V" start="28" end="28"/>
  112. <field name="C" start="29" end="29"/>
  113. <field name="Z" start="30" end="30"/>
  114. <field name="N" start="31" end="31"/>
  115. </flags>
  116. <reg name="cpsr" bitsize="32" type="cpsr_flags"/>
  117. </feature>
  118. </target>
  119. )";
  120. namespace GDBStub {
  121. static int gdbserver_socket = -1;
  122. static u8 command_buffer[GDB_BUFFER_SIZE];
  123. static u32 command_length;
  124. static u32 latest_signal = 0;
  125. static bool memory_break = false;
  126. static Kernel::Thread* current_thread = nullptr;
  127. // Binding to a port within the reserved ports range (0-1023) requires root permissions,
  128. // so default to a port outside of that range.
  129. static u16 gdbstub_port = 24689;
  130. static bool halt_loop = true;
  131. static bool step_loop = false;
  132. static bool send_trap = false;
  133. // If set to false, the server will never be started and no
  134. // gdbstub-related functions will be executed.
  135. static std::atomic<bool> server_enabled(false);
  136. #ifdef _WIN32
  137. WSADATA InitData;
  138. #endif
  139. struct Breakpoint {
  140. bool active;
  141. PAddr addr;
  142. u64 len;
  143. };
  144. static std::map<u64, Breakpoint> breakpoints_execute;
  145. static std::map<u64, Breakpoint> breakpoints_read;
  146. static std::map<u64, Breakpoint> breakpoints_write;
  147. static Kernel::Thread* FindThreadById(int id) {
  148. for (int core = 0; core < Core::NUM_CPU_CORES; core++) {
  149. auto threads = Core::System::GetInstance().Scheduler(core)->GetThreadList();
  150. for (auto thread : threads) {
  151. if (thread->GetThreadId() == id) {
  152. current_thread = thread.get();
  153. return current_thread;
  154. }
  155. }
  156. }
  157. return nullptr;
  158. }
  159. static u64 RegRead(int id, Kernel::Thread* thread = nullptr) {
  160. if (!thread) {
  161. return 0;
  162. }
  163. if (id < SP_REGISTER) {
  164. return thread->context.cpu_registers[id];
  165. } else if (id == SP_REGISTER) {
  166. return thread->context.sp;
  167. } else if (id == PC_REGISTER) {
  168. return thread->context.pc;
  169. } else if (id == CPSR_REGISTER) {
  170. return thread->context.cpsr;
  171. } else {
  172. return 0;
  173. }
  174. }
  175. static void RegWrite(int id, u64 val, Kernel::Thread* thread = nullptr) {
  176. if (!thread) {
  177. return;
  178. }
  179. if (id < SP_REGISTER) {
  180. thread->context.cpu_registers[id] = val;
  181. } else if (id == SP_REGISTER) {
  182. thread->context.sp = val;
  183. } else if (id == PC_REGISTER) {
  184. thread->context.pc = val;
  185. } else if (id == CPSR_REGISTER) {
  186. thread->context.cpsr = val;
  187. }
  188. }
  189. /**
  190. * Turns hex string character into the equivalent byte.
  191. *
  192. * @param hex Input hex character to be turned into byte.
  193. */
  194. static u8 HexCharToValue(u8 hex) {
  195. if (hex >= '0' && hex <= '9') {
  196. return hex - '0';
  197. } else if (hex >= 'a' && hex <= 'f') {
  198. return hex - 'a' + 0xA;
  199. } else if (hex >= 'A' && hex <= 'F') {
  200. return hex - 'A' + 0xA;
  201. }
  202. LOG_ERROR(Debug_GDBStub, "Invalid nibble: {} ({:02X})", hex, hex);
  203. return 0;
  204. }
  205. /**
  206. * Turn nibble of byte into hex string character.
  207. *
  208. * @param n Nibble to be turned into hex character.
  209. */
  210. static u8 NibbleToHex(u8 n) {
  211. n &= 0xF;
  212. if (n < 0xA) {
  213. return '0' + n;
  214. } else {
  215. return 'a' + n - 0xA;
  216. }
  217. }
  218. /**
  219. * Converts input hex string characters into an array of equivalent of u8 bytes.
  220. *
  221. * @param src Pointer to array of output hex string characters.
  222. * @param len Length of src array.
  223. */
  224. static u32 HexToInt(const u8* src, size_t len) {
  225. u32 output = 0;
  226. while (len-- > 0) {
  227. output = (output << 4) | HexCharToValue(src[0]);
  228. src++;
  229. }
  230. return output;
  231. }
  232. /**
  233. * Converts input hex string characters into an array of equivalent of u8 bytes.
  234. *
  235. * @param src Pointer to array of output hex string characters.
  236. * @param len Length of src array.
  237. */
  238. static u64 HexToLong(const u8* src, size_t len) {
  239. u64 output = 0;
  240. while (len-- > 0) {
  241. output = (output << 4) | HexCharToValue(src[0]);
  242. src++;
  243. }
  244. return output;
  245. }
  246. /**
  247. * Converts input array of u8 bytes into their equivalent hex string characters.
  248. *
  249. * @param dest Pointer to buffer to store output hex string characters.
  250. * @param src Pointer to array of u8 bytes.
  251. * @param len Length of src array.
  252. */
  253. static void MemToGdbHex(u8* dest, const u8* src, size_t len) {
  254. while (len-- > 0) {
  255. u8 tmp = *src++;
  256. *dest++ = NibbleToHex(tmp >> 4);
  257. *dest++ = NibbleToHex(tmp);
  258. }
  259. }
  260. /**
  261. * Converts input gdb-formatted hex string characters into an array of equivalent of u8 bytes.
  262. *
  263. * @param dest Pointer to buffer to store u8 bytes.
  264. * @param src Pointer to array of output hex string characters.
  265. * @param len Length of src array.
  266. */
  267. static void GdbHexToMem(u8* dest, const u8* src, size_t len) {
  268. while (len-- > 0) {
  269. *dest++ = (HexCharToValue(src[0]) << 4) | HexCharToValue(src[1]);
  270. src += 2;
  271. }
  272. }
  273. /**
  274. * Convert a u32 into a gdb-formatted hex string.
  275. *
  276. * @param dest Pointer to buffer to store output hex string characters.
  277. * @param v Value to convert.
  278. */
  279. static void IntToGdbHex(u8* dest, u32 v) {
  280. for (int i = 0; i < 8; i += 2) {
  281. dest[i + 1] = NibbleToHex(static_cast<u8>(v >> (4 * i)));
  282. dest[i] = NibbleToHex(static_cast<u8>(v >> (4 * (i + 1))));
  283. }
  284. }
  285. /**
  286. * Convert a u64 into a gdb-formatted hex string.
  287. *
  288. * @param dest Pointer to buffer to store output hex string characters.
  289. * @param v Value to convert.
  290. */
  291. static void LongToGdbHex(u8* dest, u64 v) {
  292. for (int i = 0; i < 16; i += 2) {
  293. dest[i + 1] = NibbleToHex(static_cast<u8>(v >> (4 * i)));
  294. dest[i] = NibbleToHex(static_cast<u8>(v >> (4 * (i + 1))));
  295. }
  296. }
  297. /**
  298. * Convert a gdb-formatted hex string into a u32.
  299. *
  300. * @param src Pointer to hex string.
  301. */
  302. static u32 GdbHexToInt(const u8* src) {
  303. u32 output = 0;
  304. for (int i = 0; i < 8; i += 2) {
  305. output = (output << 4) | HexCharToValue(src[7 - i - 1]);
  306. output = (output << 4) | HexCharToValue(src[7 - i]);
  307. }
  308. return output;
  309. }
  310. /**
  311. * Convert a gdb-formatted hex string into a u64.
  312. *
  313. * @param src Pointer to hex string.
  314. */
  315. static u64 GdbHexToLong(const u8* src) {
  316. u64 output = 0;
  317. for (int i = 0; i < 16; i += 2) {
  318. output = (output << 4) | HexCharToValue(src[15 - i - 1]);
  319. output = (output << 4) | HexCharToValue(src[15 - i]);
  320. }
  321. return output;
  322. }
  323. /// Read a byte from the gdb client.
  324. static u8 ReadByte() {
  325. u8 c;
  326. size_t received_size = recv(gdbserver_socket, reinterpret_cast<char*>(&c), 1, MSG_WAITALL);
  327. if (received_size != 1) {
  328. LOG_ERROR(Debug_GDBStub, "recv failed: {}", received_size);
  329. Shutdown();
  330. }
  331. return c;
  332. }
  333. /// Calculate the checksum of the current command buffer.
  334. static u8 CalculateChecksum(const u8* buffer, size_t length) {
  335. return static_cast<u8>(std::accumulate(buffer, buffer + length, 0, std::plus<u8>()));
  336. }
  337. /**
  338. * Get the list of breakpoints for a given breakpoint type.
  339. *
  340. * @param type Type of breakpoint list.
  341. */
  342. static std::map<u64, Breakpoint>& GetBreakpointList(BreakpointType type) {
  343. switch (type) {
  344. case BreakpointType::Execute:
  345. return breakpoints_execute;
  346. case BreakpointType::Read:
  347. return breakpoints_read;
  348. case BreakpointType::Write:
  349. return breakpoints_write;
  350. default:
  351. return breakpoints_read;
  352. }
  353. }
  354. /**
  355. * Remove the breakpoint from the given address of the specified type.
  356. *
  357. * @param type Type of breakpoint.
  358. * @param addr Address of breakpoint.
  359. */
  360. static void RemoveBreakpoint(BreakpointType type, PAddr addr) {
  361. std::map<u64, Breakpoint>& p = GetBreakpointList(type);
  362. auto bp = p.find(static_cast<u64>(addr));
  363. if (bp != p.end()) {
  364. LOG_DEBUG(Debug_GDBStub, "gdb: removed a breakpoint: {:016X} bytes at {:016X} of type {}",
  365. bp->second.len, bp->second.addr, static_cast<int>(type));
  366. p.erase(static_cast<u64>(addr));
  367. }
  368. }
  369. BreakpointAddress GetNextBreakpointFromAddress(PAddr addr, BreakpointType type) {
  370. std::map<u64, Breakpoint>& p = GetBreakpointList(type);
  371. auto next_breakpoint = p.lower_bound(static_cast<u64>(addr));
  372. BreakpointAddress breakpoint;
  373. if (next_breakpoint != p.end()) {
  374. breakpoint.address = next_breakpoint->first;
  375. breakpoint.type = type;
  376. } else {
  377. breakpoint.address = 0;
  378. breakpoint.type = BreakpointType::None;
  379. }
  380. return breakpoint;
  381. }
  382. bool CheckBreakpoint(PAddr addr, BreakpointType type) {
  383. if (!IsConnected()) {
  384. return false;
  385. }
  386. std::map<u64, Breakpoint>& p = GetBreakpointList(type);
  387. auto bp = p.find(static_cast<u64>(addr));
  388. if (bp != p.end()) {
  389. u64 len = bp->second.len;
  390. // IDA Pro defaults to 4-byte breakpoints for all non-hardware breakpoints
  391. // no matter if it's a 4-byte or 2-byte instruction. When you execute a
  392. // Thumb instruction with a 4-byte breakpoint set, it will set a breakpoint on
  393. // two instructions instead of the single instruction you placed the breakpoint
  394. // on. So, as a way to make sure that execution breakpoints are only breaking
  395. // on the instruction that was specified, set the length of an execution
  396. // breakpoint to 1. This should be fine since the CPU should never begin executing
  397. // an instruction anywhere except the beginning of the instruction.
  398. if (type == BreakpointType::Execute) {
  399. len = 1;
  400. }
  401. if (bp->second.active && (addr >= bp->second.addr && addr < bp->second.addr + len)) {
  402. LOG_DEBUG(Debug_GDBStub,
  403. "Found breakpoint type {} @ {:016X}, range: {:016X}"
  404. " - {:016X} ({:X} bytes)",
  405. static_cast<int>(type), addr, bp->second.addr, bp->second.addr + len, len);
  406. return true;
  407. }
  408. }
  409. return false;
  410. }
  411. /**
  412. * Send packet to gdb client.
  413. *
  414. * @param packet Packet to be sent to client.
  415. */
  416. static void SendPacket(const char packet) {
  417. size_t sent_size = send(gdbserver_socket, &packet, 1, 0);
  418. if (sent_size != 1) {
  419. LOG_ERROR(Debug_GDBStub, "send failed");
  420. }
  421. }
  422. /**
  423. * Send reply to gdb client.
  424. *
  425. * @param reply Reply to be sent to client.
  426. */
  427. static void SendReply(const char* reply) {
  428. if (!IsConnected()) {
  429. return;
  430. }
  431. LOG_DEBUG(Debug_GDBStub, "Reply: {}", reply);
  432. memset(command_buffer, 0, sizeof(command_buffer));
  433. command_length = static_cast<u32>(strlen(reply));
  434. if (command_length + 4 > sizeof(command_buffer)) {
  435. LOG_ERROR(Debug_GDBStub, "command_buffer overflow in SendReply");
  436. return;
  437. }
  438. memcpy(command_buffer + 1, reply, command_length);
  439. u8 checksum = CalculateChecksum(command_buffer, command_length + 1);
  440. command_buffer[0] = GDB_STUB_START;
  441. command_buffer[command_length + 1] = GDB_STUB_END;
  442. command_buffer[command_length + 2] = NibbleToHex(checksum >> 4);
  443. command_buffer[command_length + 3] = NibbleToHex(checksum);
  444. u8* ptr = command_buffer;
  445. u32 left = command_length + 4;
  446. while (left > 0) {
  447. int sent_size = send(gdbserver_socket, reinterpret_cast<char*>(ptr), left, 0);
  448. if (sent_size < 0) {
  449. LOG_ERROR(Debug_GDBStub, "gdb: send failed");
  450. return Shutdown();
  451. }
  452. left -= sent_size;
  453. ptr += sent_size;
  454. }
  455. }
  456. /// Handle query command from gdb client.
  457. static void HandleQuery() {
  458. LOG_DEBUG(Debug_GDBStub, "gdb: query '{}'", command_buffer + 1);
  459. const char* query = reinterpret_cast<const char*>(command_buffer + 1);
  460. if (strcmp(query, "TStatus") == 0) {
  461. SendReply("T0");
  462. } else if (strncmp(query, "Supported", strlen("Supported")) == 0) {
  463. // PacketSize needs to be large enough for target xml
  464. SendReply("PacketSize=2000;qXfer:features:read+");
  465. } else if (strncmp(query, "Xfer:features:read:target.xml:",
  466. strlen("Xfer:features:read:target.xml:")) == 0) {
  467. SendReply(target_xml);
  468. } else if (strncmp(query, "Offsets", strlen("Offsets")) == 0) {
  469. std::string buffer = fmt::format("TextSeg={:0x}", Memory::PROCESS_IMAGE_VADDR);
  470. SendReply(buffer.c_str());
  471. } else if (strncmp(query, "fThreadInfo", strlen("fThreadInfo")) == 0) {
  472. std::string val = "m";
  473. for (int core = 0; core < Core::NUM_CPU_CORES; core++) {
  474. auto threads = Core::System::GetInstance().Scheduler(core)->GetThreadList();
  475. for (auto thread : threads) {
  476. val += fmt::format("{:x}", thread->GetThreadId());
  477. val += ",";
  478. }
  479. }
  480. val.pop_back();
  481. SendReply(val.c_str());
  482. } else if (strncmp(query, "sThreadInfo", strlen("sThreadInfo")) == 0) {
  483. SendReply("l");
  484. } else {
  485. SendReply("");
  486. }
  487. }
  488. /// Handle set thread command from gdb client.
  489. static void HandleSetThread() {
  490. if (memcmp(command_buffer, "Hc", 2) == 0 || memcmp(command_buffer, "Hg", 2) == 0) {
  491. int thread_id = -1;
  492. if (command_buffer[2] != '-') {
  493. thread_id = static_cast<int>(HexToInt(
  494. command_buffer + 2,
  495. command_length - 2 /*strlen(reinterpret_cast<char*>(command_buffer) + 2)*/));
  496. }
  497. if (thread_id >= 1) {
  498. current_thread = FindThreadById(thread_id);
  499. }
  500. if (!current_thread) {
  501. thread_id = 1;
  502. current_thread = FindThreadById(thread_id);
  503. }
  504. if (current_thread) {
  505. SendReply("OK");
  506. return;
  507. }
  508. }
  509. SendReply("E01");
  510. }
  511. /// Handle thread alive command from gdb client.
  512. static void HandleThreadAlive() {
  513. int thread_id = static_cast<int>(
  514. HexToInt(command_buffer + 1,
  515. command_length - 1 /*strlen(reinterpret_cast<char*>(command_buffer) + 1)*/));
  516. if (thread_id == 0) {
  517. thread_id = 1;
  518. }
  519. if (FindThreadById(thread_id)) {
  520. SendReply("OK");
  521. return;
  522. }
  523. SendReply("E01");
  524. }
  525. /**
  526. * Send signal packet to client.
  527. *
  528. * @param signal Signal to be sent to client.
  529. */
  530. static void SendSignal(Kernel::Thread* thread, u32 signal, bool full = true) {
  531. if (gdbserver_socket == -1) {
  532. return;
  533. }
  534. latest_signal = signal;
  535. std::string buffer;
  536. if (full) {
  537. buffer = fmt::format("T{:02x}{:02x}:{:016x};{:02x}:{:016x};", latest_signal, PC_REGISTER,
  538. Common::swap64(RegRead(PC_REGISTER, thread)), SP_REGISTER,
  539. Common::swap64(RegRead(SP_REGISTER, thread)));
  540. } else {
  541. buffer = fmt::format("T{:02x};", latest_signal);
  542. }
  543. buffer += fmt::format("thread:{:x};", thread->GetThreadId());
  544. SendReply(buffer.c_str());
  545. }
  546. /// Read command from gdb client.
  547. static void ReadCommand() {
  548. command_length = 0;
  549. memset(command_buffer, 0, sizeof(command_buffer));
  550. u8 c = ReadByte();
  551. if (c == '+') {
  552. // ignore ack
  553. return;
  554. } else if (c == 0x03) {
  555. LOG_INFO(Debug_GDBStub, "gdb: found break command");
  556. halt_loop = true;
  557. SendSignal(current_thread, SIGTRAP);
  558. return;
  559. } else if (c != GDB_STUB_START) {
  560. LOG_DEBUG(Debug_GDBStub, "gdb: read invalid byte {:02X}", c);
  561. return;
  562. }
  563. while ((c = ReadByte()) != GDB_STUB_END) {
  564. if (command_length >= sizeof(command_buffer)) {
  565. LOG_ERROR(Debug_GDBStub, "gdb: command_buffer overflow");
  566. SendPacket(GDB_STUB_NACK);
  567. return;
  568. }
  569. command_buffer[command_length++] = c;
  570. }
  571. u8 checksum_received = HexCharToValue(ReadByte()) << 4;
  572. checksum_received |= HexCharToValue(ReadByte());
  573. u8 checksum_calculated = CalculateChecksum(command_buffer, command_length);
  574. if (checksum_received != checksum_calculated) {
  575. LOG_ERROR(Debug_GDBStub,
  576. "gdb: invalid checksum: calculated {:02X} and read {:02X} for ${}# (length: {})",
  577. checksum_calculated, checksum_received, command_buffer, command_length);
  578. command_length = 0;
  579. SendPacket(GDB_STUB_NACK);
  580. return;
  581. }
  582. SendPacket(GDB_STUB_ACK);
  583. }
  584. /// Check if there is data to be read from the gdb client.
  585. static bool IsDataAvailable() {
  586. if (!IsConnected()) {
  587. return false;
  588. }
  589. fd_set fd_socket;
  590. FD_ZERO(&fd_socket);
  591. FD_SET(gdbserver_socket, &fd_socket);
  592. struct timeval t;
  593. t.tv_sec = 0;
  594. t.tv_usec = 0;
  595. if (select(gdbserver_socket + 1, &fd_socket, nullptr, nullptr, &t) < 0) {
  596. LOG_ERROR(Debug_GDBStub, "select failed");
  597. return false;
  598. }
  599. return FD_ISSET(gdbserver_socket, &fd_socket) != 0;
  600. }
  601. /// Send requested register to gdb client.
  602. static void ReadRegister() {
  603. static u8 reply[64];
  604. memset(reply, 0, sizeof(reply));
  605. u32 id = HexCharToValue(command_buffer[1]);
  606. if (command_buffer[2] != '\0') {
  607. id <<= 4;
  608. id |= HexCharToValue(command_buffer[2]);
  609. }
  610. if (id <= SP_REGISTER) {
  611. LongToGdbHex(reply, RegRead(id, current_thread));
  612. } else if (id == PC_REGISTER) {
  613. LongToGdbHex(reply, RegRead(id, current_thread));
  614. } else if (id == CPSR_REGISTER) {
  615. IntToGdbHex(reply, (u32)RegRead(id, current_thread));
  616. } else {
  617. return SendReply("E01");
  618. }
  619. SendReply(reinterpret_cast<char*>(reply));
  620. }
  621. /// Send all registers to the gdb client.
  622. static void ReadRegisters() {
  623. static u8 buffer[GDB_BUFFER_SIZE - 4];
  624. memset(buffer, 0, sizeof(buffer));
  625. u8* bufptr = buffer;
  626. for (int reg = 0; reg <= SP_REGISTER; reg++) {
  627. LongToGdbHex(bufptr + reg * 16, RegRead(reg, current_thread));
  628. }
  629. bufptr += (32 * 16);
  630. LongToGdbHex(bufptr, RegRead(PC_REGISTER, current_thread));
  631. bufptr += 16;
  632. IntToGdbHex(bufptr, (u32)RegRead(CPSR_REGISTER, current_thread));
  633. bufptr += 8;
  634. SendReply(reinterpret_cast<char*>(buffer));
  635. }
  636. /// Modify data of register specified by gdb client.
  637. static void WriteRegister() {
  638. const u8* buffer_ptr = command_buffer + 3;
  639. u32 id = HexCharToValue(command_buffer[1]);
  640. if (command_buffer[2] != '=') {
  641. ++buffer_ptr;
  642. id <<= 4;
  643. id |= HexCharToValue(command_buffer[2]);
  644. }
  645. if (id <= SP_REGISTER) {
  646. RegWrite(id, GdbHexToLong(buffer_ptr), current_thread);
  647. } else if (id == PC_REGISTER) {
  648. RegWrite(id, GdbHexToLong(buffer_ptr), current_thread);
  649. } else if (id == CPSR_REGISTER) {
  650. RegWrite(id, GdbHexToInt(buffer_ptr), current_thread);
  651. } else {
  652. return SendReply("E01");
  653. }
  654. SendReply("OK");
  655. }
  656. /// Modify all registers with data received from the client.
  657. static void WriteRegisters() {
  658. const u8* buffer_ptr = command_buffer + 1;
  659. if (command_buffer[0] != 'G')
  660. return SendReply("E01");
  661. for (int i = 0, reg = 0; reg <= CPSR_REGISTER; i++, reg++) {
  662. if (reg <= SP_REGISTER) {
  663. RegWrite(reg, GdbHexToLong(buffer_ptr + i * 16), current_thread);
  664. } else if (reg == PC_REGISTER) {
  665. RegWrite(PC_REGISTER, GdbHexToLong(buffer_ptr + i * 16), current_thread);
  666. } else if (reg == CPSR_REGISTER) {
  667. RegWrite(CPSR_REGISTER, GdbHexToInt(buffer_ptr + i * 16), current_thread);
  668. } else {
  669. UNIMPLEMENTED();
  670. }
  671. }
  672. SendReply("OK");
  673. }
  674. /// Read location in memory specified by gdb client.
  675. static void ReadMemory() {
  676. static u8 reply[GDB_BUFFER_SIZE - 4];
  677. auto start_offset = command_buffer + 1;
  678. auto addr_pos = std::find(start_offset, command_buffer + command_length, ',');
  679. VAddr addr = HexToLong(start_offset, static_cast<u64>(addr_pos - start_offset));
  680. start_offset = addr_pos + 1;
  681. u64 len =
  682. HexToLong(start_offset, static_cast<u64>((command_buffer + command_length) - start_offset));
  683. LOG_DEBUG(Debug_GDBStub, "gdb: addr: {:016X} len: {:016X}", addr, len);
  684. if (len * 2 > sizeof(reply)) {
  685. SendReply("E01");
  686. }
  687. if (!Memory::IsValidVirtualAddress(addr)) {
  688. return SendReply("E00");
  689. }
  690. std::vector<u8> data(len);
  691. Memory::ReadBlock(addr, data.data(), len);
  692. MemToGdbHex(reply, data.data(), len);
  693. reply[len * 2] = '\0';
  694. SendReply(reinterpret_cast<char*>(reply));
  695. }
  696. /// Modify location in memory with data received from the gdb client.
  697. static void WriteMemory() {
  698. auto start_offset = command_buffer + 1;
  699. auto addr_pos = std::find(start_offset, command_buffer + command_length, ',');
  700. VAddr addr = HexToLong(start_offset, static_cast<u64>(addr_pos - start_offset));
  701. start_offset = addr_pos + 1;
  702. auto len_pos = std::find(start_offset, command_buffer + command_length, ':');
  703. u64 len = HexToLong(start_offset, static_cast<u64>(len_pos - start_offset));
  704. if (!Memory::IsValidVirtualAddress(addr)) {
  705. return SendReply("E00");
  706. }
  707. std::vector<u8> data(len);
  708. GdbHexToMem(data.data(), len_pos + 1, len);
  709. Memory::WriteBlock(addr, data.data(), len);
  710. SendReply("OK");
  711. }
  712. void Break(bool is_memory_break) {
  713. if (!halt_loop) {
  714. halt_loop = true;
  715. send_trap = true;
  716. }
  717. memory_break = is_memory_break;
  718. }
  719. /// Tell the CPU that it should perform a single step.
  720. static void Step() {
  721. step_loop = true;
  722. halt_loop = true;
  723. send_trap = true;
  724. }
  725. /// Tell the CPU if we hit a memory breakpoint.
  726. bool IsMemoryBreak() {
  727. if (IsConnected()) {
  728. return false;
  729. }
  730. return memory_break;
  731. }
  732. /// Tell the CPU to continue executing.
  733. static void Continue() {
  734. memory_break = false;
  735. step_loop = false;
  736. halt_loop = false;
  737. }
  738. /**
  739. * Commit breakpoint to list of breakpoints.
  740. *
  741. * @param type Type of breakpoint.
  742. * @param addr Address of breakpoint.
  743. * @param len Length of breakpoint.
  744. */
  745. static bool CommitBreakpoint(BreakpointType type, PAddr addr, u64 len) {
  746. std::map<u64, Breakpoint>& p = GetBreakpointList(type);
  747. Breakpoint breakpoint;
  748. breakpoint.active = true;
  749. breakpoint.addr = addr;
  750. breakpoint.len = len;
  751. p.insert({addr, breakpoint});
  752. LOG_DEBUG(Debug_GDBStub, "gdb: added {} breakpoint: {:016X} bytes at {:016X}",
  753. static_cast<int>(type), breakpoint.len, breakpoint.addr);
  754. return true;
  755. }
  756. /// Handle add breakpoint command from gdb client.
  757. static void AddBreakpoint() {
  758. BreakpointType type;
  759. u8 type_id = HexCharToValue(command_buffer[1]);
  760. switch (type_id) {
  761. case 0:
  762. case 1:
  763. type = BreakpointType::Execute;
  764. break;
  765. case 2:
  766. type = BreakpointType::Write;
  767. break;
  768. case 3:
  769. type = BreakpointType::Read;
  770. break;
  771. case 4:
  772. type = BreakpointType::Access;
  773. break;
  774. default:
  775. return SendReply("E01");
  776. }
  777. auto start_offset = command_buffer + 3;
  778. auto addr_pos = std::find(start_offset, command_buffer + command_length, ',');
  779. PAddr addr = HexToLong(start_offset, static_cast<u64>(addr_pos - start_offset));
  780. start_offset = addr_pos + 1;
  781. u64 len =
  782. HexToLong(start_offset, static_cast<u64>((command_buffer + command_length) - start_offset));
  783. if (type == BreakpointType::Access) {
  784. // Access is made up of Read and Write types, so add both breakpoints
  785. type = BreakpointType::Read;
  786. if (!CommitBreakpoint(type, addr, len)) {
  787. return SendReply("E02");
  788. }
  789. type = BreakpointType::Write;
  790. }
  791. if (!CommitBreakpoint(type, addr, len)) {
  792. return SendReply("E02");
  793. }
  794. SendReply("OK");
  795. }
  796. /// Handle remove breakpoint command from gdb client.
  797. static void RemoveBreakpoint() {
  798. BreakpointType type;
  799. u8 type_id = HexCharToValue(command_buffer[1]);
  800. switch (type_id) {
  801. case 0:
  802. case 1:
  803. type = BreakpointType::Execute;
  804. break;
  805. case 2:
  806. type = BreakpointType::Write;
  807. break;
  808. case 3:
  809. type = BreakpointType::Read;
  810. break;
  811. case 4:
  812. type = BreakpointType::Access;
  813. break;
  814. default:
  815. return SendReply("E01");
  816. }
  817. auto start_offset = command_buffer + 3;
  818. auto addr_pos = std::find(start_offset, command_buffer + command_length, ',');
  819. PAddr addr = HexToLong(start_offset, static_cast<u64>(addr_pos - start_offset));
  820. if (type == BreakpointType::Access) {
  821. // Access is made up of Read and Write types, so add both breakpoints
  822. type = BreakpointType::Read;
  823. RemoveBreakpoint(type, addr);
  824. type = BreakpointType::Write;
  825. }
  826. RemoveBreakpoint(type, addr);
  827. SendReply("OK");
  828. }
  829. void HandlePacket() {
  830. if (!IsConnected()) {
  831. return;
  832. }
  833. if (!IsDataAvailable()) {
  834. return;
  835. }
  836. ReadCommand();
  837. if (command_length == 0) {
  838. return;
  839. }
  840. LOG_DEBUG(Debug_GDBStub, "Packet: {}", command_buffer);
  841. switch (command_buffer[0]) {
  842. case 'q':
  843. HandleQuery();
  844. break;
  845. case 'H':
  846. HandleSetThread();
  847. break;
  848. case '?':
  849. SendSignal(current_thread, latest_signal);
  850. break;
  851. case 'k':
  852. Shutdown();
  853. LOG_INFO(Debug_GDBStub, "killed by gdb");
  854. return;
  855. case 'g':
  856. ReadRegisters();
  857. break;
  858. case 'G':
  859. WriteRegisters();
  860. break;
  861. case 'p':
  862. ReadRegister();
  863. break;
  864. case 'P':
  865. WriteRegister();
  866. break;
  867. case 'm':
  868. ReadMemory();
  869. break;
  870. case 'M':
  871. WriteMemory();
  872. break;
  873. case 's':
  874. Step();
  875. return;
  876. case 'C':
  877. case 'c':
  878. Continue();
  879. return;
  880. case 'z':
  881. RemoveBreakpoint();
  882. break;
  883. case 'Z':
  884. AddBreakpoint();
  885. break;
  886. case 'T':
  887. HandleThreadAlive();
  888. break;
  889. default:
  890. SendReply("");
  891. break;
  892. }
  893. }
  894. void SetServerPort(u16 port) {
  895. gdbstub_port = port;
  896. }
  897. void ToggleServer(bool status) {
  898. if (status) {
  899. server_enabled = status;
  900. // Start server
  901. if (!IsConnected() && Core::System::GetInstance().IsPoweredOn()) {
  902. Init();
  903. }
  904. } else {
  905. // Stop server
  906. if (IsConnected()) {
  907. Shutdown();
  908. }
  909. server_enabled = status;
  910. }
  911. }
  912. static void Init(u16 port) {
  913. if (!server_enabled) {
  914. // Set the halt loop to false in case the user enabled the gdbstub mid-execution.
  915. // This way the CPU can still execute normally.
  916. halt_loop = false;
  917. step_loop = false;
  918. return;
  919. }
  920. // Setup initial gdbstub status
  921. halt_loop = true;
  922. step_loop = false;
  923. breakpoints_execute.clear();
  924. breakpoints_read.clear();
  925. breakpoints_write.clear();
  926. // Start gdb server
  927. LOG_INFO(Debug_GDBStub, "Starting GDB server on port {}...", port);
  928. sockaddr_in saddr_server = {};
  929. saddr_server.sin_family = AF_INET;
  930. saddr_server.sin_port = htons(port);
  931. saddr_server.sin_addr.s_addr = INADDR_ANY;
  932. #ifdef _WIN32
  933. WSAStartup(MAKEWORD(2, 2), &InitData);
  934. #endif
  935. int tmpsock = static_cast<int>(socket(PF_INET, SOCK_STREAM, 0));
  936. if (tmpsock == -1) {
  937. LOG_ERROR(Debug_GDBStub, "Failed to create gdb socket");
  938. }
  939. // Set socket to SO_REUSEADDR so it can always bind on the same port
  940. int reuse_enabled = 1;
  941. if (setsockopt(tmpsock, SOL_SOCKET, SO_REUSEADDR, (const char*)&reuse_enabled,
  942. sizeof(reuse_enabled)) < 0) {
  943. LOG_ERROR(Debug_GDBStub, "Failed to set gdb socket option");
  944. }
  945. const sockaddr* server_addr = reinterpret_cast<const sockaddr*>(&saddr_server);
  946. socklen_t server_addrlen = sizeof(saddr_server);
  947. if (bind(tmpsock, server_addr, server_addrlen) < 0) {
  948. LOG_ERROR(Debug_GDBStub, "Failed to bind gdb socket");
  949. }
  950. if (listen(tmpsock, 1) < 0) {
  951. LOG_ERROR(Debug_GDBStub, "Failed to listen to gdb socket");
  952. }
  953. // Wait for gdb to connect
  954. LOG_INFO(Debug_GDBStub, "Waiting for gdb to connect...");
  955. sockaddr_in saddr_client;
  956. sockaddr* client_addr = reinterpret_cast<sockaddr*>(&saddr_client);
  957. socklen_t client_addrlen = sizeof(saddr_client);
  958. gdbserver_socket = static_cast<int>(accept(tmpsock, client_addr, &client_addrlen));
  959. if (gdbserver_socket < 0) {
  960. // In the case that we couldn't start the server for whatever reason, just start CPU
  961. // execution like normal.
  962. halt_loop = false;
  963. step_loop = false;
  964. LOG_ERROR(Debug_GDBStub, "Failed to accept gdb client");
  965. } else {
  966. LOG_INFO(Debug_GDBStub, "Client connected.");
  967. saddr_client.sin_addr.s_addr = ntohl(saddr_client.sin_addr.s_addr);
  968. }
  969. // Clean up temporary socket if it's still alive at this point.
  970. if (tmpsock != -1) {
  971. shutdown(tmpsock, SHUT_RDWR);
  972. }
  973. }
  974. void Init() {
  975. Init(gdbstub_port);
  976. }
  977. void Shutdown() {
  978. if (!server_enabled) {
  979. return;
  980. }
  981. LOG_INFO(Debug_GDBStub, "Stopping GDB ...");
  982. if (gdbserver_socket != -1) {
  983. shutdown(gdbserver_socket, SHUT_RDWR);
  984. gdbserver_socket = -1;
  985. }
  986. #ifdef _WIN32
  987. WSACleanup();
  988. #endif
  989. LOG_INFO(Debug_GDBStub, "GDB stopped.");
  990. }
  991. bool IsServerEnabled() {
  992. return server_enabled;
  993. }
  994. bool IsConnected() {
  995. return IsServerEnabled() && gdbserver_socket != -1;
  996. }
  997. bool GetCpuHaltFlag() {
  998. return halt_loop;
  999. }
  1000. bool GetCpuStepFlag() {
  1001. return step_loop;
  1002. }
  1003. void SetCpuStepFlag(bool is_step) {
  1004. step_loop = is_step;
  1005. }
  1006. void SendTrap(Kernel::Thread* thread, int trap) {
  1007. if (send_trap) {
  1008. send_trap = false;
  1009. SendSignal(thread, trap);
  1010. }
  1011. }
  1012. }; // namespace GDBStub