File: debugsession.cpp

package info (click to toggle)
kdevelop 4%3A5.6.2-4
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 57,892 kB
  • sloc: cpp: 278,773; javascript: 3,558; python: 3,385; sh: 1,317; ansic: 689; xml: 273; php: 95; makefile: 40; lisp: 13; sed: 12
file content (329 lines) | stat: -rw-r--r-- 12,390 bytes parent folder | download
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
/*
 * GDB Debugger Support
 *
 * Copyright 1999-2001 John Birch <jbb@kdevelop.org>
 * Copyright 2001 by Bernd Gehrmann <bernd@kdevelop.org>
 * Copyright 2006 Vladimir Prus <ghost@cs.msu.su>
 * Copyright 2007 Hamish Rodda <rodda@kde.org>
 * Copyright 2009 Niko Sams <niko.sams@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this program; if not, write to the
 * Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */

#include "debugsession.h"

#include "debuglog.h"
#include "debuggerplugin.h"
#include "gdb.h"
#include "gdbbreakpointcontroller.h"
#include "gdbframestackmodel.h"
#include "mi/micommand.h"
#include "stty.h"
#include "variablecontroller.h"

#include <debugger/breakpoint/breakpoint.h>
#include <debugger/breakpoint/breakpointmodel.h>
#include <execute/iexecuteplugin.h>
#include <interfaces/icore.h>
#include <interfaces/idebugcontroller.h>
#include <interfaces/ilaunchconfiguration.h>
#include <interfaces/iuicontroller.h>
#include <sublime/message.h>
#include <util/environmentprofilelist.h>

#include <KLocalizedString>
#include <KShell>

#include <QApplication>
#include <QDir>
#include <QFileInfo>
#include <QStandardPaths>
#include <QGuiApplication>
#include <QRegularExpression>
#include <QVersionNumber>

using namespace KDevMI::GDB;
using namespace KDevMI::MI;
using namespace KDevelop;

DebugSession::DebugSession(CppDebuggerPlugin *plugin)
    : MIDebugSession(plugin)
{
    m_breakpointController = new BreakpointController(this);
    m_variableController = new VariableController(this);
    m_frameStackModel = new GdbFrameStackModel(this);

    if (m_plugin) m_plugin->setupToolViews();
}

DebugSession::~DebugSession()
{
    if (m_plugin) m_plugin->unloadToolViews();
}

void DebugSession::setAutoDisableASLR(bool enable)
{
    m_autoDisableASLR = enable;
}

BreakpointController *DebugSession::breakpointController() const
{
    return m_breakpointController;
}

VariableController *DebugSession::variableController() const
{
    return m_variableController;
}

GdbFrameStackModel *DebugSession::frameStackModel() const
{
    return m_frameStackModel;
}

GdbDebugger *DebugSession::createDebugger() const
{
    return new GdbDebugger;
}

void DebugSession::initializeDebugger()
{
    //addCommand(new GDBCommand(GDBMI::EnableTimings, "yes"));

    addCommand(new CliCommand(MI::GdbShow, QStringLiteral("version"), this, &DebugSession::handleVersion));

    // This makes gdb pump a variable out on one line.
    addCommand(MI::GdbSet, QStringLiteral("width 0"));
    addCommand(MI::GdbSet, QStringLiteral("height 0"));

    addCommand(MI::SignalHandle, QStringLiteral("SIG32 pass nostop noprint"));
    addCommand(MI::SignalHandle, QStringLiteral("SIG41 pass nostop noprint"));
    addCommand(MI::SignalHandle, QStringLiteral("SIG42 pass nostop noprint"));
    addCommand(MI::SignalHandle, QStringLiteral("SIG43 pass nostop noprint"));

    addCommand(MI::EnablePrettyPrinting);

    addCommand(MI::GdbSet, QStringLiteral("charset UTF-8"));
    addCommand(MI::GdbSet, QStringLiteral("print sevenbit-strings off"));

    QString fileName = QStandardPaths::locate(QStandardPaths::GenericDataLocation,
                                              QStringLiteral("kdevgdb/printers/gdbinit"));
    if (!fileName.isEmpty()) {
        QFileInfo fileInfo(fileName);
        QString quotedPrintersPath = fileInfo.dir().path()
                                             .replace(QLatin1Char('\\'), QLatin1String("\\\\"))
                                             .replace(QLatin1Char('"'), QLatin1String("\\\""));
        addCommand(MI::NonMI,
                   QStringLiteral("python sys.path.insert(0, \"%0\")").arg(quotedPrintersPath));
        addCommand(MI::NonMI, QLatin1String("source ") + fileName);
    }

    // GDB can't disable ASLR on CI server.
    addCommand(MI::GdbSet,
               QStringLiteral("disable-randomization %1").arg(m_autoDisableASLR ? QLatin1String("on") : QLatin1String("off")));

    qCDebug(DEBUGGERGDB) << "Initialized GDB";
}

void DebugSession::configInferior(ILaunchConfiguration *cfg, IExecutePlugin *iexec, const QString &)
{
    // Read Configuration values
    KConfigGroup grp = cfg->config();
    bool breakOnStart = grp.readEntry(KDevMI::Config::BreakOnStartEntry, false);
    bool displayStaticMembers = grp.readEntry(Config::StaticMembersEntry, false);
    bool asmDemangle = grp.readEntry(Config::DemangleNamesEntry, true);

    if (breakOnStart) {
        BreakpointModel* m = ICore::self()->debugController()->breakpointModel();
        bool found = false;
        const auto breakpoints = m->breakpoints();
        for (Breakpoint* b : breakpoints) {
            if (b->location() == QLatin1String("main")) {
                found = true;
                break;
            }
        }
        if (!found) {
            m->addCodeBreakpoint(QStringLiteral("main"));
        }
    }
    // Needed so that breakpoint widget has a chance to insert breakpoints.
    // FIXME: a bit hacky, as we're really not ready for new commands.
    setDebuggerStateOn(s_dbgBusy);
    raiseEvent(debugger_ready);

    if (displayStaticMembers) {
        addCommand(MI::GdbSet, QStringLiteral("print static-members on"));
    } else {
        addCommand(MI::GdbSet, QStringLiteral("print static-members off"));
    }

    if (asmDemangle) {
        addCommand(MI::GdbSet, QStringLiteral("print asm-demangle on"));
    } else {
        addCommand(MI::GdbSet, QStringLiteral("print asm-demangle off"));
    }

    // Set the environment variables
    const EnvironmentProfileList environmentProfiles(KSharedConfig::openConfig());
    QString envProfileName = iexec->environmentProfileName(cfg);
    if (envProfileName.isEmpty()) {
        qCWarning(DEBUGGERGDB) << i18n("No environment profile specified, looks like a broken "
                                       "configuration, please check run configuration '%1'. "
                                       "Using default environment profile.", cfg->name());
        envProfileName = environmentProfiles.defaultProfileName();
    }
    const auto& envvars = environmentProfiles.createEnvironment(envProfileName, {});
    for (const auto& envvar : envvars) {
        addCommand(GdbSet, QLatin1String("environment ") + envvar);
    }

    qCDebug(DEBUGGERGDB) << "Per inferior configuration done";
}

bool DebugSession::execInferior(KDevelop::ILaunchConfiguration *cfg, IExecutePlugin *, const QString &executable)
{
    qCDebug(DEBUGGERGDB) << "Executing inferior";

    KConfigGroup grp = cfg->config();
    QUrl configGdbScript = grp.readEntry(Config::RemoteGdbConfigEntry, QUrl());
    QUrl runShellScript = grp.readEntry(Config::RemoteGdbShellEntry, QUrl());
    QUrl runGdbScript = grp.readEntry(Config::RemoteGdbRunEntry, QUrl());

    // handle remote debug
    if (configGdbScript.isValid()) {
        addCommand(MI::NonMI, QLatin1String("source ") + KShell::quoteArg(configGdbScript.toLocalFile()));
    }

    // FIXME: have a check box option that controls remote debugging
    if (runShellScript.isValid()) {
        // Special for remote debug, the remote inferior is started by this shell script
        QByteArray tty(m_tty->getSlave().toLatin1());
        QByteArray options = QByteArray(">") + tty + QByteArray("  2>&1 <") + tty;

        auto *proc = new QProcess;
        const QStringList arguments{
            QStringLiteral("-c"),
            KShell::quoteArg(runShellScript.toLocalFile()) + QLatin1Char(' ') + KShell::quoteArg(executable) + QString::fromLatin1(options),
        };

        qCDebug(DEBUGGERGDB) << "starting sh" << arguments;
        proc->start(QStringLiteral("sh"), arguments);
        //PORTING TODO QProcess::DontCare);
    }

    if (runGdbScript.isValid()) {
        // Special for remote debug, gdb script at run is requested, to connect to remote inferior

        // Race notice: wait for the remote gdbserver/executable
        // - but that might be an issue for this script to handle...

        // Note: script could contain "run" or "continue"

        // Future: the shell script should be able to pass info (like pid)
        // to the gdb script...

        addCommand(new SentinelCommand([this, runGdbScript]() {
            breakpointController()->initSendBreakpoints();

            breakpointController()->setDeleteDuplicateBreakpoints(true);
            qCDebug(DEBUGGERGDB) << "Running gdb script " << KShell::quoteArg(runGdbScript.toLocalFile());

            addCommand(MI::NonMI, QLatin1String("source ") + KShell::quoteArg(runGdbScript.toLocalFile()),
                       [this](const MI::ResultRecord&) {
                           breakpointController()->setDeleteDuplicateBreakpoints(false);
                       },
                       CmdMaybeStartsRunning);
            raiseEvent(connected_to_program);
        }, CmdMaybeStartsRunning));
    } else {
        // normal local debugging
        addCommand(MI::FileExecAndSymbols, KShell::quoteArg(executable),
                   this, &DebugSession::handleFileExecAndSymbols,
                   CmdHandlesError);
        raiseEvent(connected_to_program);

        addCommand(new SentinelCommand([this]() {
            breakpointController()->initSendBreakpoints();
            addCommand(MI::ExecRun, QString(), CmdMaybeStartsRunning);
        }, CmdMaybeStartsRunning));
    }
    return true;
}

bool DebugSession::loadCoreFile(KDevelop::ILaunchConfiguration*,
                                const QString& debugee, const QString& corefile)
{
    addCommand(MI::FileExecAndSymbols, debugee,
               this, &DebugSession::handleFileExecAndSymbols,
               CmdHandlesError);
    raiseEvent(connected_to_program);

    addCommand(NonMI, QLatin1String("core ") + corefile,
               this, &DebugSession::handleCoreFile,
               CmdHandlesError);
    return true;
}

void DebugSession::handleVersion(const QStringList& s)
{
    const auto response = s.value(0);
    qCDebug(DEBUGGERGDB) << response;
    // minimal version is 7.0,0
    QRegularExpression rx(QStringLiteral("([0-9]+)\\.([0-9]+)(\\.([0-9]+))?"));
    const auto match = rx.match(response);
    if (!match.hasMatch() || QVersionNumber::fromString(match.capturedRef(0).toString()) < QVersionNumber(7, 0, 0)) {
        if (!qobject_cast<QGuiApplication*>(qApp))  {
            //for unittest
            qFatal("You need a graphical application.");
        }

        const QString messageText = i18n("<b>You need gdb 7.0.0 or higher.</b><br />"
                                         "You are using: %1",
                                         response);
        auto* message = new Sublime::Message(messageText, Sublime::Message::Error);
        ICore::self()->uiController()->postMessage(message);
        stopDebugger();
    }
}

void DebugSession::handleFileExecAndSymbols(const ResultRecord& r)
{
    if (r.reason == QLatin1String("error")) {
        const QString messageText =
            i18n("<b>Could not start debugger:</b><br />")+
                 r[QStringLiteral("msg")].literal();
        auto* message = new Sublime::Message(messageText, Sublime::Message::Error);
        ICore::self()->uiController()->postMessage(message);
        stopDebugger();
    }
}

void DebugSession::handleCoreFile(const ResultRecord& r)
{
    if (r.reason != QLatin1String("error")) {
        setDebuggerStateOn(s_programExited | s_core);
    } else {
        const QString messageText =
            i18n("<b>Failed to load core file</b>"
                 "<p>Debugger reported the following error:"
                 "<p><tt>%1",
                 r[QStringLiteral("msg")].literal());
        auto* message = new Sublime::Message(messageText, Sublime::Message::Error);
        ICore::self()->uiController()->postMessage(message);
        stopDebugger();
    }
}