gdbstub.cpp 37 KB

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