-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathgdbmiadapter.cpp
More file actions
1721 lines (1487 loc) · 54.1 KB
/
gdbmiadapter.cpp
File metadata and controls
1721 lines (1487 loc) · 54.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "gdbmiadapter.h"
#include <sstream>
#include <cinttypes>
#include "../debuggercontroller.h"
#include "../../cli/log.h"
using namespace BinaryNinja;
using namespace BinaryNinjaDebugger;
GdbMiAdapter::GdbMiAdapter(BinaryView* data) : DebugAdapter(data) {
m_lastStopReason = UnknownReason;
m_targetRunningAtomic.store(false, std::memory_order_release);
GenerateDefaultAdapterSettings(data);
}
GdbMiAdapter::~GdbMiAdapter() {
Stop();
}
intx::uint512 GdbMiAdapter::ParseGdbValue(const std::string& valueStr)
{
if (valueStr.empty()) return 0;
// Handle <unavailable> and other angle-bracket GDB markers
if (valueStr.front() == '<')
return 0;
// Handle composite struct values from vector/SIMD registers
// e.g. XMM: "{... uint128 = 0x...}"
// e.g. YMM: "{... v2_int128 = {0xHIGH, 0xLOW}}"
if (valueStr.front() == '{')
{
// Try v2_int128 first (YMM 256-bit registers)
auto v2pos = valueStr.find("v2_int128 = {");
if (v2pos != std::string::npos)
{
auto braceStart = valueStr.find('{', v2pos);
auto braceEnd = valueStr.find('}', braceStart);
if (braceStart != std::string::npos && braceEnd != std::string::npos)
{
std::string inner = valueStr.substr(braceStart + 1, braceEnd - braceStart - 1);
// Extract two hex values: "0xHIGH, 0xLOW"
auto commaPos = inner.find(',');
if (commaPos != std::string::npos)
{
// Trim whitespace around each value
std::string highStr = inner.substr(0, commaPos);
std::string lowStr = inner.substr(commaPos + 1);
// Trim leading/trailing spaces
auto trimWs = [](std::string& s) {
while (!s.empty() && s.front() == ' ') s.erase(s.begin());
while (!s.empty() && s.back() == ' ') s.pop_back();
};
trimWs(highStr);
trimWs(lowStr);
try {
auto high = intx::from_string<intx::uint256>(highStr);
auto low = intx::from_string<intx::uint256>(lowStr);
intx::uint512 result = intx::uint512(high) << 128 | intx::uint512(low);
return result;
} catch (...) {}
}
}
}
// Try uint128 (XMM 128-bit registers)
auto u128pos = valueStr.find("uint128 = ");
if (u128pos != std::string::npos)
{
auto hexStart = valueStr.find("0x", u128pos);
if (hexStart != std::string::npos)
{
// Find the end of the hex string (next non-hex char)
auto hexEnd = hexStart + 2;
while (hexEnd < valueStr.size() &&
std::isxdigit(static_cast<unsigned char>(valueStr[hexEnd])))
hexEnd++;
std::string hexStr = valueStr.substr(hexStart, hexEnd - hexStart);
try {
return intx::from_string<intx::uint512>(hexStr);
} catch (...) {}
}
}
// Composite value we couldn't extract from - return 0 silently
LogDebug("Skipping unparseable composite register value");
return 0;
}
try {
return intx::from_string<intx::uint512>(valueStr);
} catch(...) {
LogError("Failed to parse GDB value: \"%s\"", valueStr.c_str());
return 0;
}
}
// --- Helper to clear cache when target is resumed ---
void GdbMiAdapter::InvalidateCache() {
std::unique_lock lock(m_cacheMutex);
m_cachedThreads.clear();
m_cachedRegisters.clear();
m_cachedFrames.clear();
m_moduleCache.reset();
// Do not clear m_watchList here, as we want to preserve the watch expressions
}
// --- Internal methods to query GDB and fill the cache ---
void GdbMiAdapter::UpdateThreadList() {
auto result = m_mi->SendCommand("-thread-info");
if (result.command != "done") {
LogError("Failed to get thread info: %s", result.fullLine.c_str());
return;
}
std::vector<DebugThread> threads;
LogDebug("Thread info response: %s", result.payload.c_str());
// Try to parse the thread info - the response format varies by GDB version
auto value = MiValue::Parse(result.payload);
// Check if we have a threads list in the response (newer GDB versions)
if (value.Exists("threads")) {
const auto& threadsList = value["threads"].GetList();
LogDebug("Found %zu threads in thread-info response", threadsList.size());
for(const auto& threadVal : threadsList) {
try {
if (!threadVal.Exists("id")) {
LogError("Thread entry missing 'id' field");
continue;
}
uint32_t tid = std::stoi(threadVal["id"].GetString());
uint64_t pc = 0;
if (threadVal.Exists("frame.addr"))
{
try
{
pc = std::stoull(threadVal["frame.addr"].GetString(), nullptr, 16);
}
catch (...)
{
}
}
threads.emplace_back(tid, pc);
LogDebug("Added thread with id: %u", tid);
} catch(const std::exception& e) {
LogError("Failed to parse thread entry: %s", e.what());
} catch(...) {
LogError("Unknown error parsing thread entry");
}
}
}
// Fallback: Check if we have thread info directly in the payload (older GDB versions)
else if (result.payload.find("threads") != std::string::npos) {
threads.emplace_back(1);
LogDebug("Added fallback thread with id: 1");
}
else {
LogError("No threads list in thread-info response. Payload: %s", result.payload.c_str());
return;
}
std::unique_lock cacheLock(m_cacheMutex);
m_cachedThreads = threads;
LogDebug("Updated thread list cache with %zu threads", threads.size());
}
void GdbMiAdapter::UpdateAllRegisters() {
if (m_registerNames.empty()) {
LogError("Cannot update registers: register names list is empty");
return;
}
auto result = m_mi->SendCommand("-data-list-register-values r");
if (result.command != "done") {
LogError("Failed to get register values: %s", result.fullLine.c_str());
return;
}
std::unordered_map<std::string, DebugRegister> regs;
auto gdbmiregisters = MiValue::Parse(result.payload);
if (!gdbmiregisters.IsDict() || !gdbmiregisters["register-values"].IsList())
{
LogError("No register-values in response. Payload: %s", result.payload.c_str());
return;
}
for (size_t i = 0; i < gdbmiregisters["register-values"].size(); i++)
{
try {
auto gdbmi_reg = gdbmiregisters["register-values"][i];
auto reg_idx = std::stoul(gdbmi_reg["number"].GetString(), 0, 10);
auto reg_value = ParseGdbValue(gdbmi_reg["value"].GetString());
if (reg_idx < m_registerNames.size())
{
std::string name = m_registerNames[reg_idx];
if (!name.empty())
{
regs[name] = DebugRegister(name, reg_value, 0, reg_idx);
}
}
} catch (...) {
LogWarn("Failed to parse register value at index %zu", i);
}
}
std::unique_lock cacheLock(m_cacheMutex);
m_cachedRegisters = regs;
LogInfo("Updated register cache with %zu registers", regs.size());
}
void GdbMiAdapter::UpdateStackFrames(uint32_t tid) {
if (GetActiveThreadId() != tid) {
SetActiveThreadId(tid);
}
auto result = m_mi->SendCommand("-stack-list-frames");
if (result.command != "done") {
LogError("Failed to get stack frames: %s", result.fullLine.c_str());
return;
}
std::vector<DebugFrame> frames;
auto gdbmi_frames = MiValue::Parse(result.payload);
for (size_t i = 0; i < gdbmi_frames["stack"].size(); ++i)
{
try {
auto parsed_frame = gdbmi_frames["stack"][i];
auto debug_frame = DebugFrame(i,
std::stoull(parsed_frame["frame"]["addr"].GetString(), 0, 16),
0,
0,
parsed_frame["frame"]["func"].GetString(),
0,
"n/a");
frames.push_back(debug_frame);
} catch (...) {
LogWarn("Failed to parse stack frame %zu", i);
}
}
std::unique_lock cacheLock(m_cacheMutex);
m_cachedFrames[tid] = frames;
LogInfo("Updated stack frames cache with %zu frames for thread %u", frames.size(), tid);
}
void GdbMiAdapter::AsyncRecordHandler(const MiRecord& record)
{
if (record.command == "stopped")
{
// LogDebug(" stopped event");
m_lastStopReason = GetStopReason(record);
// Update TID (optional, not holding the event mutex)
auto value = MiValue::Parse(record.payload);
if (value.Exists("thread-id"))
{
try {
m_lastStopTid = std::stoi(value["thread-id"].GetString());
m_currentTid = m_lastStopTid;
} catch(...) { LogError("GDBMI: error parsing thread-id"); }
}
// Update target state BEFORE posting events
m_targetRunningAtomic.store(false, std::memory_order_release);
// Check if the process has exited
if (m_lastStopReason == ProcessExited)
{
// Parse exit code if available
if (value.Exists("exit-code"))
{
try {
m_exitCode = std::stoull(value["exit-code"].GetString(), nullptr, 0);
} catch(...) {
LogWarn("Failed to parse exit code");
m_exitCode = 0;
}
}
else
{
m_exitCode = 0;
}
// Post target exited event
DebuggerEvent dbgevt;
dbgevt.type = TargetExitedEventType;
dbgevt.data.exitData.exitCode = m_exitCode;
PostDebuggerEvent(dbgevt);
m_eventCV.notify_all();
}
else
{
// Normal stop - kick a background refresh so we don't block the reader
ScheduleStateRefresh();
m_eventCV.notify_all();
}
}
else if (record.command == "running")
{
// LogDebug(" running event");
InvalidateCache();
m_targetRunningAtomic.store(true, std::memory_order_release);
DebuggerEvent event;
event.type = ResumeEventType;
PostDebuggerEvent(event);
m_eventCV.notify_all();
}
else if (record.command == "error")
{
LogError("GDBMI: %s", record.payload.c_str());
}
else if (record.type == '~' || record.type == '@' || record.type == '&' || record.type == '=')
{ // Console stream output
std::string message;
std::string raw = record.command;
if (!record.payload.empty())
raw += "," + record.payload;
if (raw.length() > 2 && raw.front() == '"' && raw.back() == '"')
raw = raw.substr(1, raw.length() - 2);
for (size_t i = 0; i < raw.length(); ++i) {
if (raw[i] == '\\' && i + 1 < raw.length()) {
switch (raw[i+1]) {
case 'n': message += '\n'; break;
case 'r': message += '\r'; break;
case 't': message += '\t'; break;
case '"': message += '"'; break;
case '\\': message += '\\'; break;
default: message += raw[i+1]; break;
}
i++;
} else {
message += raw[i];
}
}
// Buffer console output if capture is enabled (for console commands)
// When buffering, we DON'T post events - the caller will get the buffered output
bool shouldPostEvent = true;
{
std::unique_lock lock(m_consoleBufferMutex);
if (m_captureConsoleOutput && record.type == '~')
{
m_consoleOutputBuffer += message;
shouldPostEvent = false; // Don't post events for buffered output
}
}
// Only post event if we're not buffering this output
if (shouldPostEvent)
{
DebuggerEvent event;
event.type = BackendMessageEventType;
event.data.messageData.message = message;
PostDebuggerEvent(event);
}
}
}
void GdbMiAdapter::ScheduleStateRefresh()
{
// dispatch off-thread to avoid reader blocking
if (!m_connected || m_targetRunningAtomic) return;
std::thread([this]{
// Serialize MI traffic with m_gdbCommandMutex (not the reader/event mutex)?
{
std::unique_lock lock(m_gdbCommandMutex);
UpdateThreadList();
UpdateAllRegisters();
UpdateStackFrames(m_currentTid);
// Apply any pending breakpoints that were added while target was running
// or couldn't be resolved earlier (modules not loaded yet)
ApplyBreakpoints();
ApplyPendingHardwareBreakpoints();
}
DebuggerEvent ev;
ev.type = AdapterStoppedEventType;
ev.data.targetStoppedData.reason = m_lastStopReason;
PostDebuggerEvent(ev);
}).detach();
}
DebugStopReason GdbMiAdapter::GetStopReason(const MiRecord& record)
{
auto value = MiValue::Parse(record.payload);
if (value.Exists("reason"))
{
const std::string& reason = value["reason"].GetString();
if (reason == "breakpoint-hit")
return Breakpoint;
if (reason == "end-stepping-range")
return SingleStep;
if (reason == "exited-normally" || reason == "exited")
return ProcessExited;
if (reason == "signal-received")
return SignalInt;
}
return UnknownReason;
}
bool GdbMiAdapter::RunMonitorCommand(const std::string& command) const
{
if (!m_mi) return false;
// Monitor commands don't use MI syntax, they use the console interpreter
auto result = m_mi->SendCommand("-interpreter-exec console \"monitor " + command + "\"");
// The result is usually printed to the console stream ('~' records), which is hard to
// capture synchronously. For now, we assume it worked if we get a 'done' back.
// A better implementation would buffer console output between commands.
return (result.command == "done");
}
bool GdbMiAdapter::StartGdbAndDetectArch(const std::string& gdbPath, const std::string& inputFile, const std::string& symbolFile)
{
// Get architecture and register setup
LogInfo("Detecting target architecture...");
// Try multiple methods to detect architecture since $arch may return "void" on embedded targets
std::string detectedArch;
// Method 1: Try "show architecture" via console command (most reliable)
std::string archOutput = InvokeBackendCommand("show architecture");
if (!archOutput.empty() && archOutput != "error, transport not ready")
{
LogInfo("Architecture output from 'show architecture': %s", archOutput.c_str());
// Parse output like: "The target architecture is set automatically (currently i386:x86-64)"
// or "The target architecture is set to \"i386:x86-64\"."
if (archOutput.find("x86-64") != std::string::npos || archOutput.find("x86_64") != std::string::npos)
{
detectedArch = "x86_64";
LogInfo("Detected x86_64 from 'show architecture'");
}
else if (archOutput.find("i386") != std::string::npos && archOutput.find("x86-64") == std::string::npos)
{
detectedArch = "x86";
LogInfo("Detected x86 from 'show architecture'");
}
else if (archOutput.find("aarch64") != std::string::npos || archOutput.find("arm64") != std::string::npos)
{
detectedArch = "aarch64";
LogInfo("Detected aarch64 from 'show architecture'");
}
else if (archOutput.find("armv7") != std::string::npos)
{
detectedArch = "armv7-m";
LogInfo("Detected armv7-m from 'show architecture'");
}
else if (archOutput.find("arm") != std::string::npos)
{
detectedArch = "arm";
LogInfo("Detected ARM from 'show architecture'");
}
}
// Method 2: Try $arch (may return "void" on some targets)
if (detectedArch.empty())
{
LogInfo("Method 1 failed, trying $arch...");
auto archResult = m_mi->SendCommand("-data-evaluate-expression $arch");
if (archResult.command == "done")
{
auto value = MiValue::Parse(archResult.payload);
std::string archStr = value["value"].GetString();
// Remove quotes if present
if (archStr.length() >= 2 && archStr.front() == '"' && archStr.back() == '"')
{
archStr = archStr.substr(1, archStr.length() - 2);
}
LogInfo("Raw architecture string from $arch: %s", archStr.c_str());
if (archStr != "void" && !archStr.empty())
{
detectedArch = archStr;
LogInfo("Detected architecture from $arch: %s", archStr.c_str());
}
}
}
// Detect reverse debugging / TTD support by querying GDB's knowledge of the
// remote server's capabilities from the initial qSupported handshake.
//
// IMPORTANT: We must NOT send a raw qSupported packet via "maintenance packet" because
// this re-negotiates the GDB remote protocol mid-session, causing gdbserver to reset its
// internal register description state. After re-negotiation, gdbserver may lose knowledge
// of registers (e.g. AVX ymm0h), and subsequent register reads will crash it.
//
// Instead, we query GDB's cached knowledge of the 'bc' (reverse-continue) and 'bs'
// (reverse-step) packet support, which was negotiated during -target-select.
m_canReverseContinue = false;
m_canReverseStep = false;
{
std::string bcStatus = InvokeBackendCommand("show remote reverse-continue-packet");
std::string bsStatus = InvokeBackendCommand("show remote reverse-step-packet");
// Output: 'Support for the 'bc' packet ... is "auto", currently enabled.'
if (!bcStatus.empty() && bcStatus.find("currently enabled") != std::string::npos)
m_canReverseContinue = true;
if (!bsStatus.empty() && bsStatus.find("currently enabled") != std::string::npos)
m_canReverseStep = true;
if (m_canReverseContinue && m_canReverseStep)
LogInfo("Reverse debugging support detected (TTD enabled)");
else
LogInfo("No reverse debugging support detected");
}
// Fetch register list - needed for Method 3 if architecture still not detected,
// and also needed later for populating m_registerNames
auto regListResult = m_mi->SendCommand("-data-list-register-names");
// Method 3: If previous methods failed, try to detect from register names
if (detectedArch.empty())
{
LogInfo("Methods 1 & 2 failed, trying register-based detection...");
// Get register names first to help with architecture detection
if (regListResult.command == "done")
{
LogDebug("Register names for architecture detection: %s", regListResult.payload.c_str());
// Check for ARM Cortex-M registers (common in embedded)
if (regListResult.payload.find("r0") != std::string::npos && regListResult.payload.find("sp") != std::string::npos && regListResult.payload.find("lr") != std::string::npos && regListResult.payload.find("pc") != std::string::npos)
{
// Check for specific ARM Cortex-M registers
if (regListResult.payload.find("xpsr") != std::string::npos || regListResult.payload.find("primask") != std::string::npos || regListResult.payload.find("faultmask") != std::string::npos)
{
detectedArch = "armv7-m"; // Cortex-M
LogInfo("Detected ARM Cortex-M architecture from registers");
}
else
{
detectedArch = "arm"; // Generic ARM
LogInfo("Detected generic ARM architecture from registers");
}
}
// Check for x86/x86_64 registers
else if (regListResult.payload.find("rax") != std::string::npos)
{
detectedArch = "x86_64";
LogInfo("Detected x86_64 architecture from registers");
}
else if (regListResult.payload.find("eax") != std::string::npos)
{
detectedArch = "x86";
LogInfo("Detected x86 (32-bit) architecture from registers");
}
}
}
// Set the final architecture
m_remoteArch = detectedArch;
LogInfo("Final detected remote architecture: %s", m_remoteArch.c_str());
// Get register names (regListResult already fetched above)
if (regListResult.command == "done")
{
LogDebug("Register names response: %s", regListResult.payload.c_str());
auto value = MiValue::Parse(regListResult.payload);
// Check for register-names in different possible locations
if (value.Exists("register-names"))
{
m_registerNames.clear();
for (const auto& regVal : value["register-names"].GetList())
m_registerNames.push_back(regVal.GetString());
LogInfo("Found %zu registers in register-names list", m_registerNames.size());
}
else
{
LogError("No register-names in response. Payload: %s", regListResult.payload.c_str());
}
}
else
{
LogError("Failed to get register names: %s", regListResult.fullLine.c_str());
// Fallback for common embedded architectures
if (m_remoteArch.find("arm") != std::string::npos)
{
LogInfo("Using ARM register fallback");
m_registerNames = { "r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "sp", "lr", "pc", "xpsr" };
}
}
return true;
}
bool GdbMiAdapter::Connect(const std::string& server, uint32_t port) {
auto settings = GetAdapterSettings();
BNSettingsScope scope = SettingsResourceScope;
auto data = GetData();
auto gdbPath = settings->Get<std::string>("gdb.path", data, &scope);
scope = SettingsResourceScope;
auto symbolFile = settings->Get<std::string>("gdb.symbolFile", data, &scope);
scope = SettingsResourceScope;
auto inputFile = settings->Get<std::string>("common.inputFile", data, &scope);
scope = SettingsResourceScope;
auto ipAddress = settings->Get<std::string>("connect.ipAddress", data, &scope);
scope = SettingsResourceScope;
auto serverPort = static_cast<uint32_t>(settings->Get<uint64_t>("connect.port", data, &scope));
if (ipAddress.empty() || serverPort == 0)
{
LogError("Missing connection settings for restart.");
return false;
}
m_connected = false;
m_isLocalSession = false;
if (gdbPath.empty()) return false;
if (inputFile.empty()) inputFile = symbolFile;
m_mi = std::make_unique<GdbMiConnector>(gdbPath, inputFile);
// Set up async callback BEFORE starting GDB to avoid race conditions
m_mi->SetAsyncCallback([this](const MiRecord& record){ this->AsyncRecordHandler(record); });
if (!m_mi->Start()) return false;
m_mi->SendCommand("-gdb-set mi-async on");
m_mi->SendCommand("-gdb-set pagination off");
m_mi->SendCommand("-gdb-set confirm off");
m_mi->SendCommand("-enable-frame-filters");
m_mi->SendCommand("-interpreter-exec console \"add-symbol-file "+symbolFile+"\"");
m_mi->SendCommand("-file-exec-file " + inputFile);
// TODO: we should offer an option on whether or not to connect in extended mode
std::string connectCmd = "-target-select remote " + ipAddress + ":" + std::to_string(serverPort);
auto result = m_mi->SendCommand(connectCmd, 1000);
m_connected = (result.command == "connected");
if (!m_connected)
{
LogError("Failed to connect to target");
m_mi->Stop();
m_mi.reset();
return false;
}
if (!StartGdbAndDetectArch(gdbPath, inputFile, symbolFile))
return false;
// AFTER we are connected and stopped, populate the cache for the first time.
LogInfo("Populating initial state cache...");
ScheduleStateRefresh();
LogInfo("Applying breakpoints...");
ApplyBreakpoints();
ApplyPendingHardwareBreakpoints();
return true;
}
bool GdbMiAdapter::Execute(const std::string& path, const LaunchConfigurations& configs)
{
return ExecuteWithArgs(path, "", "", configs);
}
bool GdbMiAdapter::ExecuteWithArgs(const std::string& path, const std::string& args,
const std::string& workingDir, const LaunchConfigurations& configs)
{
InvalidateCache();
auto settings = GetAdapterSettings();
BNSettingsScope scope = SettingsResourceScope;
auto data = GetData();
auto gdbPath = settings->Get<std::string>("gdb.path", data, &scope);
scope = SettingsResourceScope;
auto symbolFile = settings->Get<std::string>("gdb.symbolFile", data, &scope);
scope = SettingsResourceScope;
auto inputFile = settings->Get<std::string>("common.inputFile", data, &scope);
scope = SettingsResourceScope;
auto executablePath = settings->Get<std::string>("launch.executablePath", data, &scope);
scope = SettingsResourceScope;
auto workingDirectory = settings->Get<std::string>("launch.workingDirectory", data, &scope);
scope = SettingsResourceScope;
auto commandLineArgs = settings->Get<std::string>("launch.commandLineArguments", data, &scope);
// Use settings values, fall back to function parameters
if (executablePath.empty())
executablePath = path;
if (workingDirectory.empty())
workingDirectory = workingDir;
if (commandLineArgs.empty())
commandLineArgs = args;
if (gdbPath.empty())
{
LogError("GDB path is not configured");
return false;
}
if (executablePath.empty())
{
LogError("No executable path specified for local debugging");
return false;
}
m_connected = false;
m_isLocalSession = true;
if (inputFile.empty()) inputFile = executablePath;
// Check if the executable path is a UDB recording file (.undo)
// For recordings, don't pass the file as GDB's target executable argument
bool isUndoRecording = (executablePath.size() >= 5 &&
executablePath.substr(executablePath.size() - 5) == ".undo");
std::string gdbTargetArg = isUndoRecording ? "" : inputFile;
m_mi = std::make_unique<GdbMiConnector>(gdbPath, gdbTargetArg);
// Set up async callback BEFORE starting GDB to avoid race conditions
m_mi->SetAsyncCallback([this](const MiRecord& record){ this->AsyncRecordHandler(record); });
if (!m_mi->Start())
{
LogError("Failed to start GDB process");
return false;
}
m_mi->SendCommand("-gdb-set mi-async on");
m_mi->SendCommand("-gdb-set pagination off");
m_mi->SendCommand("-gdb-set confirm off");
m_mi->SendCommand("-enable-frame-filters");
if (isUndoRecording)
{
// UDB recording: use "uload" to load the trace file.
// After uload, the target is already stopped at the beginning of the recording.
auto uloadResult = m_mi->SendCommand(
"-interpreter-exec console \"uload " + executablePath + "\"", 30000);
if (uloadResult.command != "done")
{
LogError("Failed to load UDB recording: %s", uloadResult.fullLine.c_str());
m_mi->Stop();
m_mi.reset();
return false;
}
// Load separate symbol file if specified
if (!symbolFile.empty())
m_mi->SendCommand("-interpreter-exec console \"add-symbol-file " + symbolFile + "\"");
m_connected = true;
if (!StartGdbAndDetectArch(gdbPath, inputFile, symbolFile))
{
m_connected = false;
m_mi->Stop();
m_mi.reset();
return false;
}
// UDB recording is already stopped after uload, just populate state
LogInfo("UDB recording loaded, populating initial state...");
ScheduleStateRefresh();
ApplyBreakpoints();
ApplyPendingHardwareBreakpoints();
}
else
{
// Normal local executable: load and run it
auto fileResult = m_mi->SendCommand("-file-exec-and-symbols " + executablePath);
if (fileResult.command != "done")
{
LogError("Failed to load executable: %s", fileResult.fullLine.c_str());
m_mi->Stop();
m_mi.reset();
return false;
}
// Load separate symbol file if specified
if (!symbolFile.empty() && symbolFile != executablePath)
m_mi->SendCommand("-interpreter-exec console \"add-symbol-file " + symbolFile + "\"");
// Set working directory if specified
if (!workingDirectory.empty())
m_mi->SendCommand("-environment-cd " + workingDirectory);
// Set command line arguments if specified
if (!commandLineArgs.empty())
m_mi->SendCommand("-exec-arguments " + commandLineArgs);
// Apply breakpoints before running so entry breakpoints work
LogInfo("Applying breakpoints before launch...");
m_connected = true;
if (!StartGdbAndDetectArch(gdbPath, inputFile, symbolFile))
{
m_connected = false;
m_mi->Stop();
m_mi.reset();
return false;
}
ApplyBreakpoints();
ApplyPendingHardwareBreakpoints();
// Launch the target with -exec-run, which starts the inferior and stops at the first
// breakpoint (or runs to completion if none are set). The --start flag stops at main.
auto runResult = m_mi->SendCommand("-exec-run --start", 5000);
if (runResult.command != "running" && runResult.command != "done")
{
LogError("Failed to launch target: %s", runResult.fullLine.c_str());
m_connected = false;
m_mi->Stop();
m_mi.reset();
return false;
}
}
return true;
}
bool GdbMiAdapter::Attach(uint32_t pid) {
InvalidateCache();
auto settings = GetAdapterSettings();
BNSettingsScope scope = SettingsResourceScope;
auto data = GetData();
auto server = settings->Get<std::string>("connect.ipAddress", data, &scope);
scope = SettingsResourceScope;
auto port = static_cast<uint32_t>(settings->Get<uint64_t>("connect.port", data, &scope));
if (!server.empty() && port != 0)
return Connect(server, port);
LogError("Missing connection settings for attach.");
return false;
}
std::vector<DebugProcess> GdbMiAdapter::GetProcessList() { LogWarn("GdbMiAdapter::GetProcessList not implemented"); return {}; }
bool GdbMiAdapter::SuspendThread(uint32_t) { LogWarn("GdbMiAdapter::SuspendThread not implemented"); return false; }
bool GdbMiAdapter::ResumeThread(uint32_t) { LogWarn("GdbMiAdapter::ResumeThread not implemented"); return false; }
void GdbMiAdapter::Stop()
{
try
{
if (m_mi && m_mi->IsRunning())
{
LogDebug("GDB MI connector stopping...");
m_mi->SetAsyncCallback(nullptr);
m_mi->Stop();
m_mi.reset();
LogDebug("GDB MI connector stopped.");
}
}
catch (const std::exception& e)
{
LogError("Exception during GDB MI adapter stop: %s", e.what());
}
catch (...)
{
LogError("Unknown exception during GDB MI adapter stop");
}
// Clear all cached data
InvalidateCache();
// Reset target state
m_targetRunningAtomic.store(false, std::memory_order_release);
m_connected = false;
}
bool GdbMiAdapter::Quit()
{
if (m_mi && m_connected) InvokeBackendCommand("kill");
m_connected = false;
m_targetRunningAtomic.store(false);
DebuggerEvent dbgevt;
dbgevt.type = TargetExitedEventType;
PostDebuggerEvent(dbgevt);
Stop();
return true;
}
bool GdbMiAdapter::Detach() {
if (m_mi && m_connected) m_mi->SendCommand("-target-detach");
m_connected = false;
m_targetRunningAtomic.store(false);
DebuggerEvent dbgevt;
dbgevt.type = DetachedEventType;
PostDebuggerEvent(dbgevt);
Stop();
return true;
}
std::vector<DebugThread> GdbMiAdapter::GetThreadList() {
std::unique_lock lock(m_cacheMutex);
return m_cachedThreads;
}
std::unordered_map<std::string, DebugRegister> GdbMiAdapter::ReadAllRegisters() {
std::unique_lock lock(m_cacheMutex);
return m_cachedRegisters;
}
DebugRegister GdbMiAdapter::ReadRegister(const std::string& reg) {
std::unique_lock lock(m_cacheMutex);
if (m_cachedRegisters.contains(reg)) return m_cachedRegisters[reg];
LogWarn("GdbMiAdapter::ReadRegister failed to retrieve '%s'", reg.c_str());
return {};
}
std::vector<DebugFrame> GdbMiAdapter::GetFramesOfThread(uint32_t tid) {
std::unique_lock lock(m_cacheMutex);
if (m_cachedFrames.contains(tid))
{
return m_cachedFrames[tid];
}
// If not cached, return an empty list for now and trigger a background refresh.
// The UI will be updated once the data is available via an event.
if (!m_targetRunningAtomic)
{
ScheduleStateRefresh();
}
return {};
}
uint32_t GdbMiAdapter::GetActiveThreadId() const { return m_currentTid; }
DebugThread GdbMiAdapter::GetActiveThread() const {
auto self = const_cast<GdbMiAdapter*>(this);
uint64_t pc = self->GetInstructionOffset();
return DebugThread(m_currentTid, pc);
}
bool GdbMiAdapter::SetActiveThreadId(uint32_t tid) {
if (!m_mi) return false;
auto result = m_mi->SendCommand("-thread-select " + std::to_string(tid));
if (result.command == "done") {
m_currentTid = tid;
return true;
}
return false;
}
bool GdbMiAdapter::SetActiveThread(const DebugThread& thread) { return SetActiveThreadId(thread.m_tid); }
DebugBreakpoint GdbMiAdapter::AddBreakpoint(std::uintptr_t address, unsigned long breakpoint_type) {
if (!m_mi) { return {}; }
LogDebug("-break-insert -h *0x%" PRIx64, (uint64_t)address);
auto result = m_mi->SendCommand(fmt::format("-break-insert -h *0x{:x}", address));
if (result.command == "done") {
DebuggerEvent evt;
evt.type = BackendMessageEventType;
evt.data.messageData.message = result.payload;
PostDebuggerEvent(evt);
return DebugBreakpoint{address, 0, true};
}
LogWarn("Failed to set BP at 0x%" PRIx64, (uint64_t)address);
return {};
}
DebugBreakpoint GdbMiAdapter::AddBreakpoint(const ModuleNameAndOffset& address, unsigned long breakpoint_type) {
if (!m_mi)
{
// Not connected yet - add to pending list
if (std::ranges::find(m_pendingBreakpoints, address) == m_pendingBreakpoints.end())
m_pendingBreakpoints.push_back(address);
return {};
}
// Try to resolve the module base address
uint64_t base{};
if (GetModuleBase(address.module, base))
{
// Module is loaded - resolve to absolute address
uint64_t addr = base + address.offset;
return AddBreakpoint(addr, breakpoint_type);
}
else
{
// Module not loaded yet - add to pending list for deferred application
if (std::ranges::find(m_pendingBreakpoints, address) == m_pendingBreakpoints.end())
m_pendingBreakpoints.push_back(address);
return {};
}
}