-
Notifications
You must be signed in to change notification settings - Fork 801
/
gdbengine.cpp
5208 lines (4669 loc) · 193 KB
/
gdbengine.cpp
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) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0
#include "gdbengine.h"
#include <debugger/breakhandler.h>
#include <debugger/debuggeractions.h>
#include <debugger/debuggercore.h>
#include <debugger/debuggerinternalconstants.h>
#include <debugger/debuggermainwindow.h>
#include <debugger/debuggerprotocol.h>
#include <debugger/debuggersourcepathmappingwidget.h>
#include <debugger/debuggertooltipmanager.h>
#include <debugger/debuggertr.h>
#include <debugger/disassembleragent.h>
#include <debugger/disassemblerlines.h>
#include <debugger/logwindow.h>
#include <debugger/memoryagent.h>
#include <debugger/moduleshandler.h>
#include <debugger/procinterrupt.h>
#include <debugger/registerhandler.h>
#include <debugger/shared/hostutils.h>
#include <debugger/sourcefileshandler.h>
#include <debugger/sourceutils.h>
#include <debugger/stackhandler.h>
#include <debugger/terminal.h>
#include <debugger/threadshandler.h>
#include <coreplugin/icore.h>
#include <coreplugin/messagebox.h>
#include <projectexplorer/devicesupport/idevice.h>
#include <projectexplorer/project.h>
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/projectmanager.h>
#include <projectexplorer/taskhub.h>
#include <utils/algorithm.h>
#include <utils/environment.h>
#include <utils/hostosinfo.h>
#include <utils/qtcprocess.h>
#include <utils/processinterface.h>
#include <utils/qtcassert.h>
#include <utils/stringutils.h>
#include <utils/temporaryfile.h>
#include <QDirIterator>
#include <QGuiApplication>
#include <QJsonArray>
#include <QMessageBox>
#include <QProcess>
#include <QPushButton>
#include <QRegularExpression>
using namespace Core;
using namespace ProjectExplorer;
using namespace Utils;
namespace Debugger::Internal {
enum { debugPending = 0 };
#define PENDING_DEBUG(s) do { if (debugPending) qDebug() << s; } while (0)
#define CB(callback) [this](const DebuggerResponse &r) { callback(r); }
#define CHECK_STATE(s) do { checkState(s, __FILE__, __LINE__); } while (0)
static int ¤tToken()
{
static int token = 0;
return token;
}
static bool isMostlyHarmlessMessage(const QStringView msg)
{
return msg == u"warning: GDB: Failed to set controlling terminal: "
"Inappropriate ioctl for device\\n"
|| msg == u"warning: GDB: Failed to set controlling terminal: "
"Invalid argument\\n";
}
static QMessageBox *showMessageBox(QMessageBox::Icon icon,
const QString &title, const QString &text,
QMessageBox::StandardButtons buttons)
{
auto mb = new QMessageBox(icon, title, text, buttons, ICore::dialogParent());
mb->setAttribute(Qt::WA_DeleteOnClose);
mb->setTextInteractionFlags(Qt::TextSelectableByMouse);
mb->show();
return mb;
}
enum class TracepointCaptureType
{
Address,
Caller,
Callstack,
FilePos,
Function,
Pid,
ProcessName,
Tick,
Tid,
ThreadName,
Expression
};
struct TracepointCaptureData
{
TracepointCaptureType type;
QVariant expression;
int start;
int end;
};
const char tracepointCapturePropertyName[] = "GDB.TracepointCapture";
const char notCompatibleMessage[] = "is not compatible with target architecture";
///////////////////////////////////////////////////////////////////////
//
// GdbEngine
//
///////////////////////////////////////////////////////////////////////
GdbEngine::GdbEngine()
{
m_gdbProc.setProcessMode(ProcessMode::Writer);
setObjectName("GdbEngine");
setDebuggerName("GDB");
m_gdbOutputCodec = QTextCodec::codecForLocale();
m_inferiorOutputCodec = QTextCodec::codecForLocale();
m_commandTimer.setSingleShot(true);
connect(&m_commandTimer, &QTimer::timeout,
this, &GdbEngine::commandTimeout);
DebuggerSettings &s = settings();
connect(&s.autoDerefPointers, &BaseAspect::changed,
this, &GdbEngine::reloadLocals);
connect(s.createFullBacktrace.action(), &QAction::triggered,
this, &GdbEngine::createFullBacktrace);
connect(&s.useDebuggingHelpers, &BaseAspect::changed,
this, &GdbEngine::reloadLocals);
connect(&s.useDynamicType, &BaseAspect::changed,
this, &GdbEngine::reloadLocals);
connect(&m_gdbProc, &Process::started,
this, &GdbEngine::handleGdbStarted);
connect(&m_gdbProc, &Process::done,
this, &GdbEngine::handleGdbDone);
connect(&m_gdbProc, &Process::readyReadStandardOutput,
this, &GdbEngine::readGdbStandardOutput);
connect(&m_gdbProc, &Process::readyReadStandardError,
this, &GdbEngine::readGdbStandardError);
// Output
connect(&m_outputCollector, &OutputCollector::byteDelivery,
this, &GdbEngine::readDebuggeeOutput);
}
GdbEngine::~GdbEngine()
{
// Prevent sending error messages afterwards.
disconnect();
}
QString GdbEngine::failedToStartMessage()
{
return Tr::tr("The gdb process failed to start.");
}
// Parse "~:gdb: unknown target exception 0xc0000139 at 0x77bef04e\n"
// and return an exception message
static QString msgWinException(const QString &data, unsigned *exCodeIn = nullptr)
{
if (exCodeIn)
*exCodeIn = 0;
const int exCodePos = data.indexOf("0x");
const int blankPos = exCodePos != -1 ? data.indexOf(' ', exCodePos + 1) : -1;
const int addressPos = blankPos != -1 ? data.indexOf("0x", blankPos + 1) : -1;
if (addressPos < 0)
return Tr::tr("An exception was triggered.");
const unsigned exCode = data.mid(exCodePos, blankPos - exCodePos).toUInt(nullptr, 0);
if (exCodeIn)
*exCodeIn = exCode;
const quint64 address = data.mid(addressPos).trimmed().toULongLong(nullptr, 0);
QString rc;
QTextStream str(&rc);
str << Tr::tr("An exception was triggered:") << ' ';
formatWindowsException(exCode, address, 0, 0, 0, str);
str << '.';
return rc;
}
static bool isNameChar(int c)
{
// could be 'stopped' or 'shlibs-added'
return (c >= 'a' && c <= 'z') || c == '-';
}
static bool contains(const QString &message, const QString &pattern, int size)
{
const int s = message.size();
if (s < size)
return false;
const int pos = message.indexOf(pattern);
if (pos == -1)
return false;
const bool beginFits = pos == 0 || message.at(pos - 1) == '\n';
const bool endFits = pos + size == s || message.at(pos + size) == '\n';
return beginFits && endFits;
}
static bool isGdbConnectionError(const QString &message)
{
// Handle messages gdb client produces when the target exits (gdbserver)
//
// we get this as response either to a specific command, e.g.
// 31^error,msg="Remote connection closed"
// or as informative output:
// &Remote connection closed
const char msg1[] = "Remote connection closed";
const char msg2[] = "Remote communication error. Target disconnected.: No error.";
const char msg3[] = "Quit";
return contains(message, msg1, sizeof(msg1) - 1)
|| contains(message, msg2, sizeof(msg2) - 1)
|| contains(message, msg3, sizeof(msg3) - 1);
}
void GdbEngine::handleResponse(const QString &buff)
{
showMessage(buff, LogOutput);
if (buff.isEmpty() || buff == "(gdb) ")
return;
DebuggerOutputParser parser(buff);
const int token = parser.readInt();
// Next char decides kind of response.
switch (parser.readChar().unicode()) {
case '*':
case '+':
case '=': {
const QStringView asyncClass = parser.readString(isNameChar);
GdbMi result;
while (!parser.isAtEnd()) {
GdbMi data;
if (!parser.isCurrent(',')) {
// happens on archer where we get
// 23^running <NL> *running,thread-id="all" <NL> (gdb)
result.m_type = GdbMi::Tuple;
break;
}
parser.advance(); // skip ','
data.parseResultOrValue(parser);
if (data.isValid()) {
//qDebug() << "parsed result:" << data.toString();
result.addChild(data);
result.m_type = GdbMi::Tuple;
}
}
handleAsyncOutput(asyncClass, result);
break;
}
case '~': {
QString data = parser.readCString();
if (data.startsWith("bridgemessage={")) {
// It's already logged.
break;
}
if (data.startsWith("interpreterresult={")) {
GdbMi allData;
allData.fromStringMultiple(data);
DebuggerResponse response;
response.resultClass = ResultDone;
response.data = allData["interpreterresult"];
response.token = allData["token"].toInt();
handleResultRecord(&response);
break;
}
if (data.startsWith("interpreterasync={")) {
GdbMi allData;
allData.fromStringMultiple(data);
QString asyncClass = allData["asyncclass"].data();
if (asyncClass == "breakpointmodified")
handleInterpreterBreakpointModified(allData["interpreterasync"]);
break;
}
if (data.startsWith("tracepointhit={")) {
GdbMi allData;
allData.fromStringMultiple(data);
handleTracepointHit(allData["tracepointhit"]);
break;
}
if (data.startsWith("tracepointmodified=")) {
GdbMi allData;
allData.fromStringMultiple(data);
handleTracepointModified(allData["tracepointmodified"]);
break;
}
m_pendingConsoleStreamOutput += data;
// Fragile, but it's all we have.
if (data.contains("\nNo more reverse-execution history.\n"))
handleBeginOfRecordingReached();
// Show some messages to give the impression something happens.
if (data.startsWith("Reading symbols from ")) {
showStatusMessage(Tr::tr("Reading %1...").arg(data.mid(21)), 1000);
progressPing();
} else if (data.startsWith("[New ") || data.startsWith("[Thread ")) {
if (data.endsWith('\n'))
data.chop(1);
progressPing();
showStatusMessage(data, 1000);
} else if (data.startsWith("gdb: unknown target exception 0x")) {
// [Windows, most likely some DLL/Entry point not found]:
// "gdb: unknown target exception 0xc0000139 at 0x77bef04e"
// This may be fatal and cause the target to exit later
unsigned exCode;
m_lastWinException = msgWinException(data, &exCode);
showMessage(m_lastWinException, LogMisc);
const Task::TaskType type = isFatalWinException(exCode) ? Task::Error : Task::Warning;
TaskHub::addTask(Task(type, m_lastWinException, {}, -1,
Constants::TASK_CATEGORY_DEBUGGER_RUNTIME));
}
break;
}
case '@': {
QString data = parser.readCString();
QString msg = data.left(data.size() - 1);
showMessage(msg, AppOutput);
break;
}
case '&': {
QString data = parser.readCString();
// On Windows, the contents seem to depend on the debugger
// version and/or OS version used.
if (data.startsWith("warning:")) {
showMessage(data.mid(9), AppStuff); // Cut "warning: "
if (data.contains(notCompatibleMessage))
m_ignoreNextTrap = true;
} else if (data.startsWith("Error while mapping")) {
m_detectTargetIncompat = true;
} else if (m_detectTargetIncompat && data.contains(notCompatibleMessage)) {
m_detectTargetIncompat = false;
m_ignoreNextTrap = true;
}
m_pendingLogStreamOutput += data;
if (isGdbConnectionError(data)) {
notifyInferiorExited();
break;
}
break;
}
case '^': {
DebuggerResponse response;
response.token = token;
const QStringView resultClass = parser.readString(isNameChar);
if (resultClass == u"done")
response.resultClass = ResultDone;
else if (resultClass == u"running")
response.resultClass = ResultRunning;
else if (resultClass == u"connected")
response.resultClass = ResultConnected;
else if (resultClass == u"error")
response.resultClass = ResultError;
else if (resultClass == u"exit")
response.resultClass = ResultExit;
else
response.resultClass = ResultUnknown;
if (!parser.isAtEnd()) {
if (parser.isCurrent(',')) {
parser.advance();
response.data.parseTuple_helper(parser);
response.data.m_type = GdbMi::Tuple;
response.data.m_name = "data";
} else {
// Archer has this.
response.data.m_type = GdbMi::Tuple;
response.data.m_name = "data";
}
}
response.logStreamOutput = m_pendingLogStreamOutput;
response.consoleStreamOutput = m_pendingConsoleStreamOutput;
m_pendingLogStreamOutput.clear();
m_pendingConsoleStreamOutput.clear();
if (response.data.data().isEmpty())
response.data.fromString(response.consoleStreamOutput);
handleResultRecord(&response);
break;
}
default: {
qDebug() << "UNKNOWN RESPONSE TYPE '" << parser.current() << "'. BUFFER: "
<< parser.buffer();
break;
}
}
if (settings().logTimeStamps())
showMessage(QString("Output handled"));
}
void GdbEngine::handleAsyncOutput(const QStringView asyncClass, const GdbMi &result)
{
if (asyncClass == u"stopped") {
if (m_inUpdateLocals) {
showMessage("UNEXPECTED *stopped NOTIFICATION IGNORED", LogWarning);
} else {
handleStopResponse(result);
m_pendingLogStreamOutput.clear();
m_pendingConsoleStreamOutput.clear();
}
} else if (asyncClass == u"running") {
if (m_inUpdateLocals) {
showMessage("UNEXPECTED *running NOTIFICATION IGNORED", LogWarning);
} else {
GdbMi threads = result["thread-id"];
threadsHandler()->notifyRunning(threads.data());
if (runParameters().toolChainAbi.os() == Abi::WindowsOS) {
// NOTE: Each created thread spits out a *running message. We completely ignore them
// on Windows, and handle only numbered responses
// FIXME: Breakpoints on Windows are exceptions which are thrown in newly
// created threads so we have to filter out the running threads messages when
// we request a stop.
} else if (state() == InferiorRunOk || state() == EngineSetupRequested) {
// We get multiple *running after thread creation and in Windows terminals.
showMessage(QString("NOTE: INFERIOR STILL RUNNING IN STATE %1.").
arg(DebuggerEngine::stateName(state())));
} else {
notifyInferiorRunOk();
}
}
} else if (asyncClass == u"library-loaded") {
// Archer has 'id="/usr/lib/libdrm.so.2",
// target-name="/usr/lib/libdrm.so.2",
// host-name="/usr/lib/libdrm.so.2",
// symbols-loaded="0"
// id="/lib/i386-linux-gnu/libc.so.6"
// target-name="/lib/i386-linux-gnu/libc.so.6"
// host-name="/lib/i386-linux-gnu/libc.so.6"
// symbols-loaded="0",thread-group="i1"
QString id = result["id"].data();
if (!id.isEmpty())
showStatusMessage(Tr::tr("Library %1 loaded.").arg(id), 1000);
progressPing();
Module module;
module.startAddress = 0;
module.endAddress = 0;
module.hostPath = Utils::FilePath::fromUserInput(result["host-name"].data());
const QString target = result["target-name"].data();
module.modulePath = runParameters().inferior.command.executable().withNewPath(target);
module.moduleName = module.hostPath.baseName();
modulesHandler()->updateModule(module);
} else if (asyncClass == u"library-unloaded") {
// Archer has 'id="/usr/lib/libdrm.so.2",
// target-name="/usr/lib/libdrm.so.2",
// host-name="/usr/lib/libdrm.so.2"
QString id = result["id"].data();
const QString target = result["target-name"].data();
modulesHandler()->removeModule(runParameters().inferior.command.executable().withNewPath(target));
progressPing();
showStatusMessage(Tr::tr("Library %1 unloaded.").arg(id), 1000);
} else if (asyncClass == u"thread-group-added") {
// 7.1-symbianelf has "{id="i1"}"
} else if (asyncClass == u"thread-group-started") {
// Archer had only "{id="28902"}" at some point of 6.8.x.
// *-started seems to be standard in 7.1, but in early
// 7.0.x, there was a *-created instead.
progressPing();
// 7.1.50 has thread-group-started,id="i1",pid="3529"
QString id = result["id"].data();
showStatusMessage(Tr::tr("Thread group %1 created.").arg(id), 1000);
notifyInferiorPid(result["pid"].toProcessHandle());
handleThreadGroupCreated(result);
} else if (asyncClass == u"thread-created") {
//"{id="1",group-id="28902"}"
QString id = result["id"].data();
showStatusMessage(Tr::tr("Thread %1 created.").arg(id), 1000);
ThreadData thread;
thread.id = id;
thread.groupId = result["group-id"].data();
threadsHandler()->updateThread(thread);
} else if (asyncClass == u"thread-group-exited") {
// Archer has "{id="28902"}"
QString id = result["id"].data();
showStatusMessage(Tr::tr("Thread group %1 exited.").arg(id), 1000);
handleThreadGroupExited(result);
} else if (asyncClass == u"thread-exited") {
//"{id="1",group-id="28902"}"
QString id = result["id"].data();
QString groupid = result["group-id"].data();
showStatusMessage(Tr::tr("Thread %1 in group %2 exited.")
.arg(id).arg(groupid), 1000);
threadsHandler()->removeThread(id);
} else if (asyncClass == u"thread-selected") {
QString id = result["id"].data();
showStatusMessage(Tr::tr("Thread %1 selected.").arg(id), 1000);
//"{id="2"}"
} else if (asyncClass == u"breakpoint-modified") {
// New in FSF gdb since 2011-04-27.
// "{bkpt={number="3",type="breakpoint",disp="keep",
// enabled="y",addr="<MULTIPLE>",times="1",
// original-location="\\",simple_gdbtest_app.cpp\\":135"},
// {number="3.1",enabled="y",addr="0x0805ff68",
// func="Vector<int>::Vector(int)",
// file="simple_gdbtest_app.cpp",
// fullname="/data/...line="135"},{number="3.2"...}}.."
// Note the leading comma in original-location. Filter it out.
// We don't need the field anyway.
QString ba = result.toString();
ba = '[' + ba.mid(6, ba.size() - 7) + ']';
const int pos1 = ba.indexOf(",original-location");
const int pos2 = ba.indexOf("\":", pos1 + 2);
const int pos3 = ba.indexOf('"', pos2 + 2);
ba.remove(pos1, pos3 - pos1 + 1);
GdbMi res;
res.fromString(ba);
const FilePath &fileRoot = runParameters().projectSourceDirectory;
BreakHandler *handler = breakHandler();
Breakpoint bp;
for (const GdbMi &bkpt : res) {
const QString nr = bkpt["number"].data();
if (nr.contains('.')) {
// A sub-breakpoint.
QTC_ASSERT(bp, continue);
SubBreakpoint loc = bp->findOrCreateSubBreakpoint(nr);
loc->params.updateFromGdbOutput(bkpt, fileRoot);
loc->params.type = bp->type();
} else {
// A primary breakpoint.
bp = handler->findBreakpointByResponseId(nr);
if (bp)
bp->updateFromGdbOutput(bkpt, fileRoot);
}
}
if (bp)
bp->adjustMarker();
} else if (asyncClass == u"breakpoint-created") {
// "{bkpt={number="1",type="breakpoint",disp="del",enabled="y",
// addr="<PENDING>",pending="main",times="0",
// original-location="main"}}" -- or --
// {bkpt={number="2",type="hw watchpoint",disp="keep",enabled="y",
// what="*0xbfffed48",times="0",original-location="*0xbfffed48"}}
BreakHandler *handler = breakHandler();
for (const GdbMi &bkpt : result) {
const QString nr = bkpt["number"].data();
BreakpointParameters br;
br.type = BreakpointByFileAndLine;
br.updateFromGdbOutput(bkpt, runParameters().projectSourceDirectory);
handler->handleAlienBreakpoint(nr, br);
}
} else if (asyncClass == u"breakpoint-deleted") {
// "breakpoint-deleted" "{id="1"}"
// New in FSF gdb since 2011-04-27.
const QString nr = result["id"].data();
// This also triggers when a temporary breakpoint is hit.
// We do not really want that, as this loses all information.
// FIXME: Use a special marker for this case?
// if (!bp.isOneShot()) ... is not sufficient.
// It keeps temporary "Jump" breakpoints alive.
breakHandler()->removeAlienBreakpoint(nr);
} else if (asyncClass == u"cmd-param-changed") {
// New since 2012-08-09
// "{param="debug remote",value="1"}"
} else if (asyncClass == u"memory-changed") {
// New since 2013
// "{thread-group="i1",addr="0x0918a7a8",len="0x10"}"
} else if (asyncClass == u"tsv-created") {
// New since 2013-02-06
} else if (asyncClass == u"tsv-modified") {
// New since 2013-02-06
} else {
qDebug() << "IGNORED ASYNC OUTPUT"
<< asyncClass << result.toString();
}
}
void GdbEngine::readGdbStandardError()
{
QString err = QString::fromUtf8(m_gdbProc.readAllRawStandardError());
showMessage("UNEXPECTED GDB STDERR: " + err);
if (err == "Undefined command: \"bb\". Try \"help\".\n")
return;
if (err.startsWith("BFD: reopening"))
return;
qWarning() << "Unexpected GDB stderr:" << err;
}
void GdbEngine::readDebuggeeOutput(const QByteArray &ba)
{
const QString msg = m_inferiorOutputCodec->toUnicode(ba.constData(), ba.size(),
&m_inferiorOutputCodecState);
if (msg.startsWith("&\"") && isMostlyHarmlessMessage(QStringView{msg}.mid(2, msg.size() - 4)))
showMessage("Mostly harmless terminal warning suppressed.", LogWarning);
else
showMessage(msg, AppStuff);
}
void GdbEngine::readGdbStandardOutput()
{
m_commandTimer.start(); // Restart timer.
int newstart = 0;
int scan = m_inbuffer.size();
QByteArray out = m_gdbProc.readAllRawStandardOutput();
m_inbuffer.append(out);
// This can trigger when a dialog starts a nested event loop.
if (m_busy)
return;
while (newstart < m_inbuffer.size()) {
int start = newstart;
int end = m_inbuffer.indexOf('\n', scan);
if (end < 0) {
m_inbuffer.remove(0, start);
return;
}
newstart = end + 1;
scan = newstart;
if (end == start)
continue;
if (m_inbuffer.at(end - 1) == '\r') {
--end;
if (end == start)
continue;
}
m_busy = true;
QString msg = m_gdbOutputCodec->toUnicode(m_inbuffer.constData() + start, end - start,
&m_gdbOutputCodecState);
handleResponse(msg);
m_busy = false;
}
m_inbuffer.clear();
}
void GdbEngine::interruptInferior()
{
// A core never runs, so this cannot be called.
QTC_ASSERT(!isCoreEngine(), return);
CHECK_STATE(InferiorStopRequested);
if (usesExecInterrupt()) {
runCommand({"-exec-interrupt"});
} else {
showStatusMessage(Tr::tr("Stop requested..."), 5000);
showMessage("TRYING TO INTERRUPT INFERIOR");
// Ctrl+C events are only handled properly for console applications on Windows
// when gdb debugs a GUI application the CTRL+C events are not handled
if (HostOsInfo::isWindowsHost() && !m_isQnxGdb) {
IDevice::ConstPtr dev = device();
QTC_ASSERT(dev, notifyInferiorStopFailed(); return);
DeviceProcessSignalOperation::Ptr signalOperation = dev->signalOperation();
QTC_ASSERT(signalOperation, notifyInferiorStopFailed(); return);
connect(signalOperation.get(), &DeviceProcessSignalOperation::finished,
this, [this, signalOperation](const QString &error) {
if (error.isEmpty()) {
showMessage("Interrupted " + QString::number(inferiorPid()));
notifyInferiorStopOk();
} else {
showMessage(error, LogError);
notifyInferiorStopFailed();
}
});
signalOperation->setDebuggerCommand(runParameters().debugger.command.executable());
signalOperation->interruptProcess(inferiorPid());
} else {
interruptInferior2();
}
}
}
void GdbEngine::runCommand(const DebuggerCommand &command)
{
const int token = ++currentToken();
DebuggerCommand cmd = command;
if (cmd.function.isEmpty()) {
showMessage(QString("EMPTY FUNCTION RUN, TOKEN: %1 ARGS: %2")
.arg(token).arg(cmd.args.toString()));
QTC_ASSERT(false, return);
}
if (!m_gdbProc.isRunning()) {
showMessage(QString("NO GDB PROCESS RUNNING, CMD IGNORED: %1 %2")
.arg(cmd.function).arg(state()));
if (cmd.callback) {
DebuggerResponse response;
response.resultClass = ResultError;
cmd.callback(response);
}
return;
}
if (cmd.flags & (NeedsTemporaryStop|NeedsFullStop)) {
showMessage("RUNNING NEEDS-STOP COMMAND " + cmd.function);
const bool wantContinue = bool(cmd.flags & NeedsTemporaryStop);
cmd.flags &= ~(NeedsTemporaryStop|NeedsFullStop);
if (state() == InferiorStopRequested) {
if (cmd.flags & LosesChild) {
notifyInferiorIll();
return;
}
showMessage("CHILD ALREADY BEING INTERRUPTED. STILL HOPING.");
// Calling shutdown() here breaks all situations where two
// NeedsStop commands are issued in quick succession.
m_onStop.append(cmd, wantContinue);
return;
}
if (state() == InferiorRunOk) {
showStatusMessage(Tr::tr("Stopping temporarily."), 1000);
m_onStop.append(cmd, wantContinue);
setState(InferiorStopRequested);
interruptInferior();
return;
}
if (state() != InferiorStopOk)
showMessage("UNSAFE STATE FOR QUEUED COMMAND. EXECUTING IMMEDIATELY");
}
if (!(cmd.flags & Discardable))
++m_nonDiscardableCount;
bool isPythonCommand = true;
if ((cmd.flags & NativeCommand) || cmd.function.contains('-') || cmd.function.contains(' '))
isPythonCommand = false;
if (isPythonCommand) {
cmd.arg("token", token);
cmd.function = "python theDumper." + cmd.function + "(" + cmd.argsToPython() + ")";
}
QTC_ASSERT(m_gdbProc.isRunning(), return);
cmd.postTime = QTime::currentTime().msecsSinceStartOfDay();
m_commandForToken[token] = cmd;
m_flagsForToken[token] = cmd.flags;
if (cmd.flags & ConsoleCommand)
cmd.function = "-interpreter-exec console \"" + cmd.function + '"';
cmd.function = QString::number(token) + cmd.function;
showMessage(cmd.function.left(100), LogInput);
if (m_scheduledTestResponses.contains(token)) {
// Fake response for test cases.
QString buffer = m_scheduledTestResponses.value(token);
buffer.replace("@TOKEN@", QString::number(token));
m_scheduledTestResponses.remove(token);
showMessage(QString("FAKING TEST RESPONSE (TOKEN: %2, RESPONSE: %3)")
.arg(token).arg(buffer));
QMetaObject::invokeMethod(this, [this, buffer] { handleResponse(buffer); });
} else {
m_gdbProc.write(cmd.function + "\r\n");
if (command.flags & NeedsFlush) {
// We don't need the response or result here, just want to flush
// anything that's still on the gdb side.
m_gdbProc.write({"p 0\n"});
}
// Start Watchdog.
const int watchDogMilliSecs = settings().gdbWatchdogTimeout() * 1000;
m_commandTimer.setInterval(watchDogMilliSecs);
// The process can die for external reason between the "-gdb-exit" was
// sent and a response could be retrieved. We don't want the watchdog
// to bark in that case since the only possible outcome is a dead
// process anyway.
if (!cmd.function.endsWith("-gdb-exit"))
m_commandTimer.start();
//if (cmd.flags & LosesChild)
// notifyInferiorIll();
}
}
void GdbEngine::commandTimeout()
{
const QList<int> keys = Utils::sorted(m_commandForToken.keys());
bool killIt = false;
for (int key : keys) {
const DebuggerCommand &cmd = m_commandForToken.value(key);
killIt = true;
showMessage(QString::number(key) + ": " + cmd.function);
}
QStringList commands;
for (const DebuggerCommand &cmd : std::as_const(m_commandForToken))
commands << QString("\"%1\"").arg(cmd.function);
if (killIt) {
showMessage(QString("TIMED OUT WAITING FOR GDB REPLY. "
"COMMANDS STILL IN PROGRESS: ") + commands.join(", "));
int timeOut = m_commandTimer.interval();
//m_commandTimer.stop();
const QString msg = Tr::tr("The gdb process has not responded "
"to a command within %n seconds. This could mean it is stuck "
"in an endless loop or taking longer than expected to perform "
"the operation.\nYou can choose between waiting "
"longer or aborting debugging.", nullptr, timeOut / 1000);
QMessageBox *mb = showMessageBox(QMessageBox::Critical,
Tr::tr("GDB Not Responding"), msg,
QMessageBox::Ok | QMessageBox::Cancel);
mb->button(QMessageBox::Cancel)->setText(Tr::tr("Give GDB More Time"));
mb->button(QMessageBox::Ok)->setText(Tr::tr("Stop Debugging"));
if (mb->exec() == QMessageBox::Ok) {
showMessage("KILLING DEBUGGER AS REQUESTED BY USER");
// This is an undefined state, so we just pull the emergency brake.
m_gdbProc.kill();
notifyEngineShutdownFinished();
} else {
showMessage("CONTINUE DEBUGGER AS REQUESTED BY USER");
}
} else {
showMessage(QString("\nNON-CRITICAL TIMEOUT\nCOMMANDS STILL IN PROGRESS: ")
+ commands.join(", "));
}
}
void GdbEngine::handleResultRecord(DebuggerResponse *response)
{
//qDebug() << "TOKEN:" << response->token
// << " ACCEPTABLE:" << m_oldestAcceptableToken;
//qDebug() << "\nRESULT" << response->token << response->toString();
int token = response->token;
if (token <= 0)
return;
if (!m_commandForToken.contains(token)) {
// In theory this should not happen (rather the error should be
// reported in the "first" response to the command) in practice it
// does. We try to handle a few situations we are aware of gracefully.
// Ideally, this code should not be present at all.
showMessage(QString("COOKIE FOR TOKEN %1 ALREADY EATEN (%2). "
"TWO RESPONSES FOR ONE COMMAND?").arg(token).
arg(stateName(state())));
if (response->resultClass == ResultError) {
QString msg = response->data["msg"].data();
if (msg == "Cannot find new threads: generic error") {
// Handle a case known to occur on Linux/gdb 6.8 when debugging moc
// with helpers enabled. In this case we get a second response with
// msg="Cannot find new threads: generic error"
showMessage("APPLYING WORKAROUND #1");
AsynchronousMessageBox::critical(Tr::tr("Executable Failed"), msg);
showStatusMessage(Tr::tr("Process failed to start."));
//shutdown();
notifyInferiorIll();
} else if (msg == "\"finish\" not meaningful in the outermost frame.") {
// Handle a case known to appear on GDB 6.4 symbianelf when
// the stack is cut due to access to protected memory.
//showMessage("APPLYING WORKAROUND #2");
notifyInferiorStopOk();
} else if (msg.startsWith("Cannot find bounds of current function")) {
// Happens when running "-exec-next" in a function for which
// there is no debug information. Divert to "-exec-next-step"
showMessage("APPLYING WORKAROUND #3");
notifyInferiorStopOk();
executeStepOver(true);
} else if (msg.startsWith("Couldn't get registers: No such process.")) {
// Happens on archer-tromey-python 6.8.50.20090910-cvs
// There might to be a race between a process shutting down
// and library load messages.
showMessage("APPLYING WORKAROUND #4");
notifyInferiorStopOk();
//notifyInferiorIll();
//showStatusMessage(Tr::tr("Executable failed: %1").arg(msg));
//shutdown();
//AsynchronousMessageBox::critical(Tr::tr("Executable Failed"), msg);
} else if (msg.contains("Cannot insert breakpoint")) {
// For breakpoints set by address to non-existent addresses we
// might get something like "6^error,msg="Warning:\nCannot insert
// breakpoint 3.\nError accessing memory address 0x34592327:
// Input/output error.\nCannot insert breakpoint 4.\nError
// accessing memory address 0x34592335: Input/output error.\n".
// This should not stop us from proceeding.
// Most notably, that happens after a "6^running" and "*running"
// We are probably sitting at _start and can't proceed as
// long as the breakpoints are enabled.
// FIXME: Should we silently disable the offending breakpoints?
showMessage("APPLYING WORKAROUND #5");
AsynchronousMessageBox::critical(Tr::tr("Setting Breakpoints Failed"), msg);
QTC_CHECK(state() == InferiorRunOk);
notifyInferiorSpontaneousStop();
notifyEngineIll();
} else if (msg.startsWith("Process record: failed to record execution log.")) {
// Reverse execution recording failed. Full message is something like
// ~"Process record does not support instruction 0xfae64 at address 0x7ffff7dec6f8.\n"
notifyInferiorSpontaneousStop();
handleRecordingFailed();
} else if (msg.startsWith("Target multi-thread does not support this command.")) {
notifyInferiorSpontaneousStop();
handleRecordingFailed();
} else if (isGdbConnectionError(msg)) {
notifyInferiorExited();
} else {
// Windows: Some DLL or some function not found. Report
// the exception now in a box.
if (msg.startsWith("During startup program exited with"))
notifyInferiorExited();
else if (msg.contains("Command aborted."))
notifyInferiorSpontaneousStop();
QString logMsg;
if (!m_lastWinException.isEmpty())
logMsg = m_lastWinException + '\n';
logMsg += msg;
AsynchronousMessageBox::critical(Tr::tr("Executable Failed"), logMsg);
showStatusMessage(Tr::tr("Executable failed: %1").arg(logMsg));
}
}
return;
}
DebuggerCommand cmd = m_commandForToken.take(token);
const int flags = m_flagsForToken.take(token);
if (settings().logTimeStamps()) {
showMessage(QString("Response time: %1: %2 s")
.arg(cmd.function)
.arg(QTime::fromMSecsSinceStartOfDay(cmd.postTime).msecsTo(QTime::currentTime()) / 1000.),
LogTime);
}
if (response->token < m_oldestAcceptableToken && (flags & Discardable)) {
//showMessage(_("### SKIPPING OLD RESULT") + response.toString());
return;
}
bool isExpectedResult =
(response->resultClass == ResultError) // Can always happen.
|| (response->resultClass == ResultRunning && (flags & RunRequest))
|| (response->resultClass == ResultExit && (flags & ExitRequest))
|| (response->resultClass == ResultDone);
// ResultDone can almost "always" happen. Known examples are:
// (response->resultClass == ResultDone && cmd.function == "continue")
// Happens with some incarnations of gdb 6.8 for "jump to line"
// (response->resultClass == ResultDone && cmd.function.startsWith("jump"))
// (response->resultClass == ResultDone && cmd.function.startsWith("detach"))
// Happens when stepping finishes very quickly and issues *stopped and ^done
// instead of ^running and *stopped
// (response->resultClass == ResultDone && (cmd.flags & RunRequest));
if (!isExpectedResult) {
const DebuggerRunParameters &rp = runParameters();
Abi abi = rp.toolChainAbi;
if (abi.os() == Abi::WindowsOS
&& cmd.function.startsWith("attach")
&& (rp.startMode == AttachToLocalProcess || terminal()))
{
// Ignore spurious 'running' responses to 'attach'.
} else {
QString rsp = DebuggerResponse::stringFromResultClass(response->resultClass);
rsp = "UNEXPECTED RESPONSE '" + rsp + "' TO COMMAND '" + cmd.function + "'";
qWarning("%s", qPrintable(rsp));
showMessage(rsp);
}
}
if (!(flags & Discardable))
--m_nonDiscardableCount;
m_inUpdateLocals = (flags & InUpdateLocals);
if (cmd.callback)
cmd.callback(*response);
PENDING_DEBUG("MISSING TOKENS: " << m_commandForToken.keys());
if (m_commandForToken.isEmpty())
m_commandTimer.stop();
}
bool GdbEngine::acceptsDebuggerCommands() const
{
return true;