-
-
Notifications
You must be signed in to change notification settings - Fork 340
Expand file tree
/
Copy pathDebugger.cpp
More file actions
3642 lines (3046 loc) · 122 KB
/
Debugger.cpp
File metadata and controls
3642 lines (3046 loc) · 122 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
/*
* Copyright (C) 2006 - 2025 Evan Teran <evan.teran@gmail.com>
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "Debugger.h"
#include "ArchProcessor.h"
#include "CommentServer.h"
#include "Configuration.h"
#include "DebuggerInternal.h"
#include "DialogAbout.h"
#include "DialogArguments.h"
#include "DialogAttach.h"
#include "DialogBreakpoints.h"
#include "DialogMemoryRegions.h"
#include "DialogOpenProgram.h"
#include "DialogOptions.h"
#include "DialogPlugins.h"
#include "DialogThreads.h"
#include "Expression.h"
#include "IAnalyzer.h"
#include "IBinary.h"
#include "IBreakpoint.h"
#include "IDebugEvent.h"
#include "IDebugger.h"
#include "IPlugin.h"
#include "IProcess.h"
#include "IThread.h"
#include "Instruction.h"
#include "MemoryRegions.h"
#include "QHexView"
#include "RecentFileManager.h"
#include "RegionBuffer.h"
#include "RegisterViewModelBase.h"
#include "SessionError.h"
#include "SessionManager.h"
#include "State.h"
#include "Symbol.h"
#include "SymbolManager.h"
#include "Theme.h"
#include "edb.h"
#if defined(Q_OS_LINUX)
#include "linker.h"
#endif
#include <QCloseEvent>
#include <QDateTime>
#include <QDesktopServices>
#include <QDesktopWidget>
#include <QDir>
#include <QDragEnterEvent>
#include <QDropEvent>
#include <QFileDialog>
#include <QFileInfo>
#include <QHBoxLayout>
#include <QInputDialog>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonParseError>
#include <QLabel>
#include <QMessageBox>
#include <QMimeData>
#include <QScreen>
#include <QSettings>
#include <QShortcut>
#include <QSplitter>
#include <QStringListModel>
#include <QTimer>
#include <QToolButton>
#include <QUrl>
#include <QVector>
#include <QtDebug>
#include <clocale>
#include <cstring>
#include <memory>
#include <random>
#if defined(Q_OS_UNIX)
#include <csignal>
#endif
#include <sys/stat.h>
#include <sys/types.h>
#if defined(Q_OS_LINUX) || defined(Q_OS_OPENBSD) || defined(Q_OS_FREEBSD)
#include <fcntl.h>
#include <unistd.h>
#endif
namespace {
QPlainTextEdit *logger_instance = nullptr;
constexpr quint64 initial_bp_tag = Q_UINT64_C(0x494e4954494e5433); // "INITINT3" in hex
constexpr quint64 stepover_bp_tag = Q_UINT64_C(0x535445504f564552); // "STEPOVER" in hex
constexpr quint64 run_to_cursor_tag = Q_UINT64_C(0x474f544f48455245); // "GOTOHERE" in hex
#ifdef Q_OS_LINUX
constexpr quint64 ld_loader_tag = Q_UINT64_C(0x4c49424556454e54); // "LIBEVENT" in hex
#endif
template <class Addr>
void handle_library_event(IProcess *process, edb::address_t debug_pointer) {
#ifdef Q_OS_LINUX
edb::linux_struct::r_debug<Addr> dynamic_info;
const bool ok = (process->readBytes(debug_pointer, &dynamic_info, sizeof(dynamic_info)) == sizeof(dynamic_info));
if (ok) {
// NOTE(eteran): at least on my system, the name of
// what is being loaded is either in
// r8 or r13 depending on which event
// we are looking at.
// TODO(eteran): find a way to get the name reliably
switch (dynamic_info.r_state) {
case edb::linux_struct::r_debug<Addr>::RT_CONSISTENT:
// TODO(eteran): enable this once we are confident
#if 0
edb::v1::memory_regions().sync();
#endif
break;
case edb::linux_struct::r_debug<Addr>::RT_ADD:
// qDebug("LIBRARY LOAD EVENT");
break;
case edb::linux_struct::r_debug<Addr>::RT_DELETE:
// qDebug("LIBRARY UNLOAD EVENT");
break;
}
}
#else
Q_UNUSED(process)
Q_UNUSED(debug_pointer)
#endif
}
template <class Addr>
edb::address_t find_linker_hook_address(IProcess *process, edb::address_t debug_pointer) {
#ifdef Q_OS_LINUX
edb::linux_struct::r_debug<Addr> dynamic_info;
const bool ok = process->readBytes(debug_pointer, &dynamic_info, sizeof(dynamic_info));
if (ok) {
return edb::address_t::fromZeroExtended(dynamic_info.r_brk);
}
#else
Q_UNUSED(process)
Q_UNUSED(debug_pointer)
#endif
return edb::address_t(0);
}
//--------------------------------------------------------------------------
// Name: is_instruction_ret
//--------------------------------------------------------------------------
bool is_instruction_ret(edb::address_t address) {
uint8_t buffer[edb::Instruction::MaxSize];
if (const int size = edb::v1::get_instruction_bytes(address, buffer)) {
edb::Instruction inst(buffer, buffer + size, address);
return is_ret(inst);
}
return false;
}
class RunUntilRet : public IDebugEventHandler {
Q_DECLARE_TR_FUNCTIONS(RunUntilRet)
public:
//--------------------------------------------------------------------------
// Name: RunUntilRet
//--------------------------------------------------------------------------
RunUntilRet() {
edb::v1::add_debug_event_handler(this);
}
//--------------------------------------------------------------------------
// Name: ~RunUntilRet
//--------------------------------------------------------------------------
~RunUntilRet() override {
edb::v1::remove_debug_event_handler(this);
try {
for (const auto &bp : ownBreakpoints_) {
if (!bp.second.expired()) {
edb::v1::debugger_core->removeBreakpoint(bp.first);
}
}
} catch (...) {
EDB_PRINT_AND_DIE("unexpected exception occurred");
}
}
//--------------------------------------------------------------------------
// Name: pass_back_to_debugger
// Desc: Makes the previous handler the event handler again and deletes this.
//--------------------------------------------------------------------------
virtual edb::EventStatus pass_back_to_debugger() {
delete this;
return edb::DEBUG_NEXT_HANDLER;
}
//--------------------------------------------------------------------------
// Name: handle_event
//--------------------------------------------------------------------------
// TODO: Need to handle stop/pause button
edb::EventStatus handleEvent(const std::shared_ptr<IDebugEvent> &event) override {
if (!event->isTrap()) {
return pass_back_to_debugger();
}
if (IProcess *process = edb::v1::debugger_core->process()) {
std::shared_ptr<IThread> thread = process->currentThread();
if (!thread) {
return pass_back_to_debugger();
}
State state;
thread->getState(&state);
edb::address_t address = state.instructionPointer();
IDebugEvent::TRAP_REASON trap_reason = event->trapReason();
IDebugEvent::REASON reason = event->reason();
qDebug() << QStringLiteral("Event at address 0x%1").arg(address, 0, 16);
/*
* An IDebugEvent::TRAP_BREAKPOINT can happen for the following reasons:
* 1. We hit a user-set breakpoint.
* 2. We hit an internal breakpoint due to our RunUntilRet algorithm.
* 3. We hit a syscall (this shouldn't be; it may be a ptrace bug).
* 4. We have exited in some form or another.
* First check for exit, then breakpoint (user-set, then internal; adjust for RIP in both cases),
* then finally for the syscall bug.
*/
if (trap_reason == IDebugEvent::TRAP_BREAKPOINT) {
qDebug() << "Trap breakpoint";
// Take care of exit/terminated conditions; address == 0 may suffice to catch all, but not 100% sure.
if (reason == IDebugEvent::EVENT_EXITED || reason == IDebugEvent::EVENT_TERMINATED || address == 0) {
qDebug() << "The process is no longer running.";
return pass_back_to_debugger();
}
// Check the previous byte for 0xcc to see if it was an actual breakpoint
std::shared_ptr<IBreakpoint> bp = edb::v1::find_triggered_breakpoint(address);
// If there was a bp there, then we hit a block terminator as part of our RunUntilRet
// algorithm, or it is a user-set breakpoint.
if (bp && bp->enabled()) { // Isn't it always enabled if trap_reason is breakpoint, anyway?
const edb::address_t prev_address = bp->address();
bp->hit();
// Adjust RIP since 1st byte was replaced with 0xcc and we are now 1 byte after it.
state.setInstructionPointer(prev_address);
thread->setState(state);
address = prev_address;
// If it wasn't internal, it was a user breakpoint. Pass back to Debugger.
if (!bp->internal()) {
qDebug() << "Previous was not an internal breakpoint.";
return pass_back_to_debugger();
}
qDebug() << "Previous was an internal breakpoint.";
bp->disable();
edb::v1::debugger_core->removeBreakpoint(bp->address());
} else {
// No breakpoint if it was a syscall; continue.
return edb::DEBUG_CONTINUE;
}
}
// If we are on our ret (or the instr after?), then ret.
if (address == returnAddress_) {
qDebug() << QStringLiteral("On our terminator at 0x%1").arg(address, 0, 16);
if (is_instruction_ret(address)) {
qDebug() << "Found ret; passing back to debugger";
return pass_back_to_debugger();
}
// If not a ret, then step so we can find the next block terminator.
qDebug() << "Not ret. Single-stepping";
return edb::DEBUG_CONTINUE_STEP;
}
// If we stepped (either because it was the first event or because we hit a jmp/jcc),
// then find the next block terminator and edb::DEBUG_CONTINUE.
// TODO: What if we started on a ret? Set bp, then the proc runs away?
uint8_t buffer[edb::Instruction::MaxSize];
while (const int size = edb::v1::get_instruction_bytes(address, buffer)) {
// Get the instruction
edb::Instruction inst(buffer, buffer + size, 0);
qDebug() << QStringLiteral("Scanning for terminator at 0x%1: found %2").arg(address, 0, 16).arg(inst.mnemonic().c_str());
// Check if it's a proper block terminator (ret/jmp/jcc/hlt)
if (inst) {
if (is_terminator(inst)) {
qDebug() << QStringLiteral("Found terminator %1 at 0x%2").arg(QString(inst.mnemonic().c_str())).arg(address, 0, 16);
// If we already had a breakpoint there, then just continue.
if (std::shared_ptr<IBreakpoint> bp = edb::v1::debugger_core->findBreakpoint(address)) {
qDebug() << QStringLiteral("Already a breakpoint at terminator 0x%1").arg(address, 0, 16);
return edb::DEBUG_CONTINUE;
}
// Otherwise, attempt to set a breakpoint there and continue.
if (std::shared_ptr<IBreakpoint> bp = edb::v1::debugger_core->addBreakpoint(address)) {
ownBreakpoints_.emplace_back(address, bp);
qDebug() << QStringLiteral("Setting breakpoint at terminator 0x%1").arg(address, 0, 16);
bp->setInternal(true);
bp->setOneTime(true); // If the 0xcc get's rm'd on next event, then
// don't set it one time; we'll handle it manually
returnAddress_ = address;
return edb::DEBUG_CONTINUE;
}
QMessageBox::critical(edb::v1::debugger_ui,
tr("Error running until return"),
tr("Failed to set breakpoint on a block terminator at address %1.").arg(address.toPointerString()));
return pass_back_to_debugger();
}
} else {
// Invalid instruction or some other problem. Pass it back to the debugger.
QMessageBox::critical(edb::v1::debugger_ui,
tr("Error running until return"),
tr("Failed to disassemble instruction at address %1.").arg(address.toPointerString()));
return pass_back_to_debugger();
}
address += inst.byteSize();
}
// If we end up out here, we've got bigger problems. Pass it back to the debugger.
QMessageBox::critical(edb::v1::debugger_ui,
tr("Error running until return"),
tr("Stepped outside the loop, address=%1.").arg(address.toPointerString()));
return pass_back_to_debugger();
}
qDebug() << "The process is no longer running.";
return pass_back_to_debugger();
}
private:
std::vector<std::pair<edb::address_t, std::weak_ptr<IBreakpoint>>> ownBreakpoints_;
edb::address_t lastCallReturn_ = 0;
edb::address_t returnAddress_ = 0;
};
}
//------------------------------------------------------------------------------
// Name: Debugger
// Desc:
//------------------------------------------------------------------------------
Debugger::Debugger(QWidget *parent)
: QMainWindow(parent),
ttyProc_(new QProcess(this)),
argumentsDialog_(new DialogArguments),
timer_(new QTimer(this)),
recentFileManager_(new RecentFileManager(this)),
stackViewInfo_(nullptr),
commentServer_(std::make_shared<CommentServer>()) {
setupUi();
// connect the timer to the debug event
connect(timer_, &QTimer::timeout, this, &Debugger::nextDebugEvent);
// create a context menu for the tab bar as well
connect(tabWidget_, &TabWidget::customContextMenuRequested, this, &Debugger::tabContextMenu);
// CPU Shortcuts
gotoAddressAction_ = createAction(tr("&Goto Expression..."), QKeySequence(tr("Ctrl+G")), &Debugger::gotoTriggered);
editCommentAction_ = createAction(tr("Add &Comment..."), QKeySequence(tr(";")), &Debugger::mnuCPUEditComment);
toggleBreakpointAction_ = createAction(tr("&Toggle Breakpoint"), QKeySequence(tr("F2")), &Debugger::mnuCPUToggleBreakpoint);
conditionalBreakpointAction_ = createAction(tr("Add &Conditional Breakpoint"), QKeySequence(tr("Shift+F2")), &Debugger::mnuCPUAddConditionalBreakpoint);
runToThisLineAction_ = createAction(tr("R&un to this Line"), QKeySequence(tr("F4")), &Debugger::mnuCPURunToThisLine);
runToLinePassAction_ = createAction(tr("Run to this Line (Pass Signal To Application)"), QKeySequence(tr("Shift+F4")), &Debugger::mnuCPURunToThisLinePassSignal);
editBytesAction_ = createAction(tr("Binary &Edit..."), QKeySequence(tr("Ctrl+E")), &Debugger::mnuModifyBytes);
fillWithZerosAction_ = createAction(tr("&Fill with 00's"), QKeySequence(), &Debugger::mnuCPUFillZero);
fillWithNOPsAction_ = createAction(tr("Fill with &NOPs"), QKeySequence(), &Debugger::mnuCPUFillNop);
setAddressLabelAction_ = createAction(tr("Set &Label..."), QKeySequence(tr(":")), &Debugger::mnuCPULabelAddress);
followConstantInDumpAction_ = createAction(tr("Follow Constant In &Dump"), QKeySequence(), &Debugger::mnuCPUFollowInDump);
followConstantInStackAction_ = createAction(tr("Follow Constant In &Stack"), QKeySequence(), &Debugger::mnuCPUFollowInStack);
followAction_ = createAction(tr("&Follow"), QKeySequence(tr("Return")), [this]() {
QWidget *const widget = QApplication::focusWidget();
if (qobject_cast<QDisassemblyView *>(widget)) {
mnuCPUFollow();
} else {
auto event = new QKeyEvent(QEvent::KeyPress, Qt::Key_Enter, Qt::NoModifier);
QCoreApplication::postEvent(widget, event);
}
});
// these get updated when we attach/run a new process, so it's OK to hard code them here
#if defined(EDB_X86_64)
setRIPAction_ = createAction(tr("&Set %1 to this Instruction").arg("RIP"), QKeySequence(tr("Ctrl+*")), &Debugger::mnuCPUSetEIP);
gotoRIPAction_ = createAction(tr("&Goto %1").arg("RIP"), QKeySequence(tr("*")), &Debugger::mnuCPUJumpToEIP);
#elif defined(EDB_X86)
setRIPAction_ = createAction(tr("&Set %1 to this Instruction").arg("EIP"), QKeySequence(tr("Ctrl+*")), &Debugger::mnuCPUSetEIP);
gotoRIPAction_ = createAction(tr("&Goto %1").arg("EIP"), QKeySequence(tr("*")), &Debugger::mnuCPUJumpToEIP);
#elif defined(EDB_ARM32) || defined(EDB_ARM64)
setRIPAction_ = createAction(tr("&Set %1 to this Instruction").arg("PC"), QKeySequence(tr("Ctrl+*")), &Debugger::mnuCPUSetEIP);
gotoRIPAction_ = createAction(tr("&Goto %1").arg("PC"), QKeySequence(tr("*")), &Debugger::mnuCPUJumpToEIP);
#else
#error "This doesn't initialize actions and will lead to crash"
#endif
// Data Dump Shortcuts
dumpFollowInCPUAction_ = createAction(tr("Follow Address In &CPU"), QKeySequence(), &Debugger::mnuDumpFollowInCPU);
dumpFollowInDumpAction_ = createAction(tr("Follow Address In &Dump"), QKeySequence(), &Debugger::mnuDumpFollowInDump);
dumpFollowInStackAction_ = createAction(tr("Follow Address In &Stack"), QKeySequence(), &Debugger::mnuDumpFollowInStack);
dumpSaveToFileAction_ = createAction(tr("&Save To File"), QKeySequence(), &Debugger::mnuDumpSaveToFile);
// Register View Shortcuts
registerFollowInDumpAction_ = createAction(tr("&Follow In Dump"), QKeySequence(), &Debugger::mnuRegisterFollowInDump);
registerFollowInDumpTabAction_ = createAction(tr("&Follow In Dump (New Tab)"), QKeySequence(), &Debugger::mnuRegisterFollowInDumpNewTab);
registerFollowInStackAction_ = createAction(tr("&Follow In Stack"), QKeySequence(), &Debugger::mnuRegisterFollowInStack);
// Stack View Shortcuts
stackFollowInCPUAction_ = createAction(tr("Follow Address In &CPU"), QKeySequence(), &Debugger::mnuStackFollowInCPU);
stackFollowInDumpAction_ = createAction(tr("Follow Address In &Dump"), QKeySequence(), &Debugger::mnuStackFollowInDump);
stackFollowInStackAction_ = createAction(tr("Follow Address In &Stack"), QKeySequence(), &Debugger::mnuStackFollowInStack);
// these get updated when we attach/run a new process, so it's OK to hard code them here
#if defined(EDB_X86_64)
stackGotoRSPAction_ = createAction(tr("Goto %1").arg("RSP"), QKeySequence(), &Debugger::mnuStackGotoESP);
stackGotoRBPAction_ = createAction(tr("Goto %1").arg("RBP"), QKeySequence(), &Debugger::mnuStackGotoEBP);
stackPushAction_ = createAction(tr("&Push %1").arg("QWORD"), QKeySequence(), &Debugger::mnuStackPush);
stackPopAction_ = createAction(tr("P&op %1").arg("QWORD"), QKeySequence(), &Debugger::mnuStackPop);
#elif defined(EDB_X86)
stackGotoRSPAction_ = createAction(tr("Goto %1").arg("ESP"), QKeySequence(), &Debugger::mnuStackGotoESP);
stackGotoRBPAction_ = createAction(tr("Goto %1").arg("EBP"), QKeySequence(), &Debugger::mnuStackGotoEBP);
stackPushAction_ = createAction(tr("&Push %1").arg("DWORD"), QKeySequence(), &Debugger::mnuStackPush);
stackPopAction_ = createAction(tr("P&op %1").arg("DWORD"), QKeySequence(), &Debugger::mnuStackPop);
#elif defined(EDB_ARM32)
stackGotoRSPAction_ = createAction(tr("Goto %1").arg("SP"), QKeySequence(), &Debugger::mnuStackGotoESP);
stackGotoRBPAction_ = createAction(tr("Goto %1").arg("FP"), QKeySequence(), &Debugger::mnuStackGotoEBP);
stackGotoRBPAction_->setDisabled(true); // FIXME(ARM): this just stubs it out since it likely won't really work
stackPushAction_ = createAction(tr("&Push %1").arg("DWORD"), QKeySequence(), &Debugger::mnuStackPush);
stackPushAction_->setDisabled(true); // FIXME(ARM): this just stubs it out since it likely won't really work
stackPopAction_ = createAction(tr("P&op %1").arg("DWORD"), QKeySequence(), &Debugger::mnuStackPop);
stackPopAction_->setDisabled(true); // FIXME(ARM): this just stubs it out since it likely won't really work
#elif defined(EDB_ARM64)
stackGotoRSPAction_ = createAction(tr("Goto %1").arg("SP"), QKeySequence(), &Debugger::mnuStackGotoESP);
stackGotoRSPAction_->setDisabled(true); // FIXME(ARM): this just stubs it out since it likely won't really work
stackGotoRBPAction_ = createAction(tr("Goto %1").arg("FP"), QKeySequence(), &Debugger::mnuStackGotoEBP);
stackGotoRBPAction_->setDisabled(true); // FIXME(ARM): this just stubs it out since it likely won't really work
stackPushAction_ = createAction(tr("&Push %1").arg("QWORD"), QKeySequence(), &Debugger::mnuStackPush);
stackPushAction_->setDisabled(true); // FIXME(ARM): this just stubs it out since it likely won't really work
stackPopAction_ = createAction(tr("P&op %1").arg("QWORD"), QKeySequence(), &Debugger::mnuStackPop);
stackPopAction_->setDisabled(true); // FIXME(ARM): this just stubs it out since it likely won't really work
#else
#error "This doesn't initialize actions and will lead to crash"
#endif
// set these to have no meaningful "data" (yet)
followConstantInDumpAction_->setData(qlonglong(0));
followConstantInStackAction_->setData(qlonglong(0));
setAcceptDrops(true);
// setup the list model for instruction details list
listModel_ = new QStringListModel(this);
listView_->setModel(listModel_);
// setup the recent file manager
ui.action_Recent_Files->setMenu(recentFileManager_->createMenu());
connect(recentFileManager_, &RecentFileManager::fileSelected, this, &Debugger::openFile);
// make us the default event handler
edb::v1::add_debug_event_handler(this);
// enable the arch processor
#if 0
ui.registerList->setModel(&edb::v1::arch_processor().get_register_view_model());
edb::v1::arch_processor().setup_register_view();
#endif
// default the working directory to ours
workingDirectory_ = QDir().absolutePath();
// let the plugins setup their menus
finishPluginSetup();
// Make sure number formatting and reading code behaves predictably when using standard C++ facilities.
// NOTE: this should only be done after the plugins have finished loading, since some dynamic libraries
// (e.g. libkdecore), which are indirectly loaded by the plugins, re-set locale to "" once again. (This
// first time is QApplication.)
std::setlocale(LC_NUMERIC, "C");
}
//------------------------------------------------------------------------------
// Name: ~Debugger
// Desc:
//------------------------------------------------------------------------------
Debugger::~Debugger() {
for (QObject *plugin : edb::v1::plugin_list()) {
if (auto p = qobject_cast<IPlugin *>(plugin)) {
p->fini();
}
}
// kill our xterm and wait for it to die
ttyProc_->kill();
ttyProc_->waitForFinished(3000);
edb::v1::remove_debug_event_handler(this);
}
template <class F>
QAction *Debugger::createAction(const QString &text, const QKeySequence &keySequence, F func) {
auto action = new QAction(text, this);
action->setShortcut(keySequence);
addAction(action);
connect(action, &QAction::triggered, this, func);
return action;
}
//------------------------------------------------------------------------------
// Name: updateMenuState
// Desc:
//------------------------------------------------------------------------------
void Debugger::updateMenuState(GuiState state) {
switch (state) {
case Paused:
ui.actionRun_Until_Return->setEnabled(true);
ui.action_Restart->setEnabled(true);
ui.action_Run->setEnabled(true);
ui.action_Pause->setEnabled(false);
ui.action_Step_Into->setEnabled(true);
ui.action_Step_Over->setEnabled(true);
ui.actionStep_Out->setEnabled(true);
ui.action_Step_Into_Pass_Signal_To_Application->setEnabled(true);
ui.action_Step_Over_Pass_Signal_To_Application->setEnabled(true);
ui.action_Run_Pass_Signal_To_Application->setEnabled(true);
ui.action_Detach->setEnabled(true);
ui.action_Kill->setEnabled(true);
tabCreate_->setEnabled(true);
status_->setText(tr("paused"));
status_->repaint();
break;
case Running:
ui.actionRun_Until_Return->setEnabled(false);
ui.action_Restart->setEnabled(false);
ui.action_Run->setEnabled(false);
ui.action_Pause->setEnabled(true);
ui.action_Step_Into->setEnabled(false);
ui.action_Step_Over->setEnabled(false);
ui.actionStep_Out->setEnabled(false);
ui.action_Step_Into_Pass_Signal_To_Application->setEnabled(false);
ui.action_Step_Over_Pass_Signal_To_Application->setEnabled(false);
ui.action_Run_Pass_Signal_To_Application->setEnabled(false);
ui.action_Detach->setEnabled(true);
ui.action_Kill->setEnabled(true);
tabCreate_->setEnabled(true);
status_->setText(tr("running"));
status_->repaint();
break;
case Terminated:
ui.actionRun_Until_Return->setEnabled(false);
ui.action_Restart->setEnabled(recentFileManager_->entryCount() > 0);
ui.action_Run->setEnabled(false);
ui.action_Pause->setEnabled(false);
ui.action_Step_Into->setEnabled(false);
ui.action_Step_Over->setEnabled(false);
ui.actionStep_Out->setEnabled(false);
ui.action_Step_Into_Pass_Signal_To_Application->setEnabled(false);
ui.action_Step_Over_Pass_Signal_To_Application->setEnabled(false);
ui.action_Run_Pass_Signal_To_Application->setEnabled(false);
ui.action_Detach->setEnabled(false);
ui.action_Kill->setEnabled(false);
tabCreate_->setEnabled(false);
status_->setText(tr("terminated"));
status_->repaint();
break;
}
guiState_ = state;
}
//------------------------------------------------------------------------------
// Name: createTty
// Desc: creates a TTY object for our command line I/O
//------------------------------------------------------------------------------
QString Debugger::createTty() {
QString result_tty = ttyFile_;
#if defined(Q_OS_LINUX) || defined(Q_OS_OPENBSD) || defined(Q_OS_FREEBSD)
// we attempt to reuse an open output window
if (edb::v1::config().tty_enabled && ttyProc_->state() != QProcess::Running) {
const QString command = edb::v1::config().tty_command;
if (!command.isEmpty()) {
// ok, creating a new one...
// first try to get a 'unique' filename, i would love to use a system
// temp file API... but there doesn't seem to be one which will create
// a pipe...only ordinary files!
std::random_device rd;
std::mt19937 mt(rd());
const auto temp_pipe = QStringLiteral("%1/edb_temp_file_%2_%3").arg(QDir::tempPath()).arg(mt()).arg(getpid());
// make sure it isn't already there, and then make the pipe
::unlink(qPrintable(temp_pipe));
::mkfifo(qPrintable(temp_pipe), S_IRUSR | S_IWUSR);
// this is a basic shell script which will output the tty to a file (the pipe),
// ignore kill sigs, close all standard IO, and then just hang
const auto shell_script = QString(
"tty > %1;"
"trap \"\" INT QUIT TSTP;"
"exec<&-; exec>&-;"
"while :; do sleep 3600; done")
.arg(temp_pipe);
// parse up the command from the options, white space delimited
QStringList proc_args = edb::v1::parse_command_line(command);
const QString tty_command = proc_args.takeFirst().trimmed();
// start constructing the arguments for the term
const QFileInfo command_info(tty_command);
if (command_info.fileName() == "gnome-terminal") {
// NOTE(eteran): gnome-terminal at some point dropped support for -e
// in favor of using "everything after --"
// See issue: https://github.com/eteran/edb-debugger/issues/774
proc_args << "--hide-menubar"
<< "--title" << tr("edb output")
<< "--";
} else if (command_info.fileName() == "xfce4-terminal") {
proc_args << "--hide-menubar"
<< "--title" << tr("edb output")
<< "--hold"
<< "-x";
} else if (command_info.fileName() == "konsole") {
proc_args << "--hide-menubar"
<< "--title" << tr("edb output")
<< "--nofork"
<< "--hold"
<< "-e";
} else {
proc_args << "-title" << tr("edb output")
<< "-hold"
<< "-e";
}
proc_args << "sh"
<< "-c" << QStringLiteral("%1").arg(shell_script);
qDebug() << "Running Terminal: " << tty_command;
qDebug() << "Terminal Args: " << proc_args;
// make the tty process object and connect it's death signal to our cleanup
connect(ttyProc_, SIGNAL(finished(int, QProcess::ExitStatus)), SLOT(ttyProcFinished(int, QProcess::ExitStatus)));
ttyProc_->start(tty_command, proc_args);
if (ttyProc_->waitForStarted(3000)) {
// try to read from the pipe, but with a 2 second timeout
int fd = open(qPrintable(temp_pipe), O_RDWR);
if (fd != -1) {
fd_set set;
FD_ZERO(&set); // clear the set
FD_SET(fd, &set); // add our file descriptor to the set
struct timeval timeout;
timeout.tv_sec = 2;
timeout.tv_usec = 0;
char buf[256] = {};
const int rv = select(fd + 1, &set, nullptr, nullptr, &timeout);
switch (rv) {
case -1:
qDebug() << "An error occurred while attempting to get the TTY of the terminal sub-process";
break;
case 0:
qDebug() << "A Timeout occurred while attempting to get the TTY of the terminal sub-process";
break;
default:
if (read(fd, buf, sizeof(buf)) != -1) {
result_tty = QString(buf).trimmed();
}
break;
}
::close(fd);
}
} else {
qDebug().nospace() << "Could not launch the desired terminal [" << tty_command << "], please check that it exists and you have proper permissions.";
}
// cleanup, god i wish there was an easier way than this!
::unlink(qPrintable(temp_pipe));
}
}
#endif
qDebug() << "Terminal process has TTY: " << result_tty;
return result_tty;
}
//------------------------------------------------------------------------------
// Name: ttyProcFinished
// Desc: cleans up the data associated with a TTY when the terminal dies
//------------------------------------------------------------------------------
void Debugger::ttyProcFinished(int exit_code, QProcess::ExitStatus exit_status) {
Q_UNUSED(exit_code)
Q_UNUSED(exit_status)
ttyFile_.clear();
}
//------------------------------------------------------------------------------
// Name: currentTab
// Desc:
//------------------------------------------------------------------------------
int Debugger::currentTab() const {
return tabWidget_->currentIndex();
}
//------------------------------------------------------------------------------
// Name: currentDataViewInfo
// Desc:
//------------------------------------------------------------------------------
std::shared_ptr<DataViewInfo> Debugger::currentDataViewInfo() const {
return dataRegions_[currentTab()];
}
//------------------------------------------------------------------------------
// Name: setDebuggerCaption
// Desc: sets the caption part to also show the application name and pid
//------------------------------------------------------------------------------
void Debugger::setDebuggerCaption(const QString &appname) {
if (IProcess *process = edb::v1::debugger_core->process()) {
setWindowTitle(tr("edb - %1 [%2]").arg(appname).arg(process->pid()));
} else {
setWindowTitle(tr("edb"));
}
}
//------------------------------------------------------------------------------
// Name: deleteDataTab
// Desc:
//------------------------------------------------------------------------------
void Debugger::deleteDataTab() {
const int current = currentTab();
// get a pointer to the info we need (before removing it from the list!)
// this seems redundant to current_data_view_info(), but we need the
// index too, so may as well waste one line to avoid duplicate work
std::shared_ptr<DataViewInfo> info = dataRegions_[current];
// remove it from the list
dataRegions_.remove(current);
// remove the tab associated with it
tabWidget_->removeTab(current);
}
//------------------------------------------------------------------------------
// Name: createDataTab
// Desc:
//------------------------------------------------------------------------------
void Debugger::createDataTab() {
const int current = currentTab();
// duplicate the current region
auto new_data_view = std::make_shared<DataViewInfo>((current != -1) ? dataRegions_[current]->region : nullptr);
auto hexview = std::make_shared<QHexView>();
Theme theme = Theme::load();
QColor addressForegroundColor = theme.text[Theme::Address].foreground().color();
QColor alternatingByteColor = theme.text[Theme::AlternatingByte].foreground().color();
QColor nonPrintableTextColor = theme.text[Theme::NonPrintingCharacter].foreground().color();
hexview->setAddressColor(addressForegroundColor);
hexview->setAlternateWordColor(alternatingByteColor);
hexview->setNonPrintableTextColor(nonPrintableTextColor);
// QColor coldZoneColor_ = Qt::gray;
// QColor lineColor_ = Qt::black;
new_data_view->view = hexview;
// setup the context menu
hexview->setContextMenuPolicy(Qt::CustomContextMenu);
connect(hexview.get(), &QHexView::customContextMenuRequested, this, &Debugger::mnuDumpContextMenu);
// show the initial data for this new view
if (new_data_view->region) {
hexview->setAddressOffset(new_data_view->region->start());
} else {
hexview->setAddressOffset(0);
}
// NOTE(eteran): for issue #522, allow comments in data view when single word width
hexview->setCommentServer(commentServer_.get());
hexview->setData(new_data_view->stream.get());
const Configuration &config = edb::v1::config();
// set the default view options
hexview->setShowAddress(config.data_show_address);
hexview->setShowHexDump(config.data_show_hex);
hexview->setShowAsciiDump(config.data_show_ascii);
hexview->setShowComments(config.data_show_comments);
hexview->setRowWidth(config.data_row_width);
hexview->setWordWidth(config.data_word_width);
hexview->setShowAddressSeparator(config.show_address_separator);
// Setup data views according to debuggee bitness
if (edb::v1::debuggeeIs64Bit()) {
hexview->setAddressSize(QHexView::Address64);
} else {
hexview->setAddressSize(QHexView::Address32);
}
// set the default font
QFont dump_font;
dump_font.fromString(config.data_font);
hexview->setFont(dump_font);
dataRegions_.push_back(new_data_view);
// create the tab!
if (new_data_view->region) {
tabWidget_->addTab(hexview.get(), tr("%1-%2").arg(
edb::v1::format_pointer(new_data_view->region->start()),
edb::v1::format_pointer(new_data_view->region->end())));
} else {
tabWidget_->addTab(hexview.get(), tr("%1-%2").arg(
edb::v1::format_pointer(edb::address_t(0)),
edb::v1::format_pointer(edb::address_t(0))));
}
tabWidget_->setCurrentIndex(tabWidget_->count() - 1);
}
//------------------------------------------------------------------------------
// Name: finish_plugin_setup
// Desc: finalizes plugin setup by adding each to the menu, we can do this now
// that we have a GUI widget to attach it to
//------------------------------------------------------------------------------
void Debugger::finishPluginSetup() {
// call the init function for each plugin, this is done after
// ALL plugins are loaded in case there are inter-plugin dependencies
for (QObject *plugin : edb::v1::plugin_list()) {
if (auto p = qobject_cast<IPlugin *>(plugin)) {
p->init();
}
}
// setup the menu for all plugins that which to do so
QPointer<DialogOptions> options = qobject_cast<DialogOptions *>(edb::v1::dialog_options());
for (QObject *plugin : edb::v1::plugin_list()) {
if (auto p = qobject_cast<IPlugin *>(plugin)) {
if (QMenu *const menu = p->menu(this)) {
ui.menu_Plugins->addMenu(menu);
}
if (QWidget *const options_page = p->optionsPage()) {
if (options) {
options->addOptionsPage(options_page);
}
}
// setup the shortcuts for these actions
const QList<QAction *> register_actions = p->registerContextMenu();
const QList<QAction *> cpu_actions = p->cpuContextMenu();
const QList<QAction *> stack_actions = p->stackContextMenu();
const QList<QAction *> data_actions = p->dataContextMenu();
const QList<QAction *> actions = register_actions + cpu_actions + stack_actions + data_actions;
for (QAction *action : actions) {
QKeySequence shortcut = action->shortcut();
if (!shortcut.isEmpty()) {
connect(new QShortcut(shortcut, this), &QShortcut::activated, action, &QAction::trigger);
}
}
}
}
}
//------------------------------------------------------------------------------
// Name: getGotoExpression
// Desc:
//------------------------------------------------------------------------------
Result<edb::address_t, QString> Debugger::getGotoExpression() {
std::optional<edb::address_t> address = edb::v2::get_expression_from_user(tr("Goto Expression"), tr("Expression:"));
if (address) {
return *address;
}
return make_unexpected(tr("No Address"));
}
//------------------------------------------------------------------------------
// Name: getFollowRegister
// Desc:
//------------------------------------------------------------------------------
Result<edb::reg_t, QString> Debugger::getFollowRegister() const {
const Register reg = activeRegister();
if (!reg || reg.bitSize() > 8 * sizeof(edb::address_t)) {
return make_unexpected(tr("No Value"));
}
return reg.valueAsAddress();
}
//------------------------------------------------------------------------------
// Name: gotoTriggered
// Desc:
//------------------------------------------------------------------------------
void Debugger::gotoTriggered() {
QWidget *const widget = QApplication::focusWidget();
if (auto hexview = qobject_cast<QHexView *>(widget)) {
if (hexview == stackView_.get()) {
mnuStackGotoAddress();
} else {
mnuDumpGotoAddress();
}
} else if (qobject_cast<QDisassemblyView *>(widget)) {
mnuCPUJumpToAddress();
}
}
//------------------------------------------------------------------------------
// Name: setupUi
// Desc: creates the UI
//------------------------------------------------------------------------------
void Debugger::setupUi() {
// setup the global pointers as early as possible.
// NOTE: this should never be changed after this point
// NOTE: this is important that this happens BEFORE any components which
// read settings as it could end up being a memory leak (and therefore never
// calling it's destructor which writes the settings to disk!).
edb::v1::debugger_ui = this;
ui.setupUi(this);
splitter_ = new QSplitter(this);
splitter_->setObjectName(QLatin1String("mainSplitter"));
splitter_->setOrientation(Qt::Vertical);
{
logger_ = new QPlainTextEdit(this);
logger_->setObjectName(QLatin1String("logView"));
logger_->setReadOnly(true);
QFont font("monospace");
font.setStyleHint(QFont::TypeWriter);
logger_->setFont(font);
logger_->setWordWrapMode(QTextOption::WrapMode::NoWrap);
logger_->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
logger_instance = logger_;
qInstallMessageHandler([](QtMsgType type, const QMessageLogContext &, const QString &message) {
const QString text = [type, &message]() {
switch (type) {
case QtDebugMsg:
return tr("DEBUG %1").arg(message);
case QtInfoMsg:
return tr("INFO %1").arg(message);
case QtWarningMsg:
return tr("WARN %1").arg(message);
case QtCriticalMsg:
return tr("ERROR %1").arg(message);
case QtFatalMsg:
return tr("FATAL %1").arg(message);
default:
Q_UNREACHABLE();
}
}();
logger_instance->appendPlainText(text);
std::cerr << message.toUtf8().constData() << "\n"; // this may be useful as a crash log
});
auto toolButton = static_cast<QToolButton *>(ui.toolBar->widgetForAction(ui.action_Debug_Logger));
toolButton->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
connect(ui.action_Debug_Logger, &QAction::triggered, this, [this](bool checked) {
logger_->setVisible(checked);
});