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