lldbengine.cpp 40.6 KB
Newer Older
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
/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "lldbengine.h"

32
33
34
#include <debugger/debuggeractions.h>
#include <debugger/debuggercore.h>
#include <debugger/debuggerdialogs.h>
Fawzi Mohamed's avatar
Fawzi Mohamed committed
35
#include <debugger/debuggerinternalconstants.h>
36
37
38
39
40
#include <debugger/debuggerplugin.h>
#include <debugger/debuggerprotocol.h>
#include <debugger/debuggerstartparameters.h>
#include <debugger/debuggerstringutils.h>
#include <debugger/debuggertooltipmanager.h>
41

42
43
44
45
46
47
48
49
50
#include <debugger/breakhandler.h>
#include <debugger/disassemblerlines.h>
#include <debugger/moduleshandler.h>
#include <debugger/registerhandler.h>
#include <debugger/stackhandler.h>
#include <debugger/sourceutils.h>
#include <debugger/threadshandler.h>
#include <debugger/watchhandler.h>
#include <debugger/watchutils.h>
51
52

#include <utils/qtcassert.h>
53
#include <utils/savedaction.h>
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

#include <texteditor/itexteditor.h>
#include <coreplugin/idocument.h>
#include <coreplugin/icore.h>

#include <QDateTime>
#include <QDebug>
#include <QDir>
#include <QFileInfo>
#include <QTimer>
#include <QVariant>

#include <QApplication>
#include <QMessageBox>
#include <QToolTip>

namespace Debugger {
namespace Internal {

///////////////////////////////////////////////////////////////////////
//
// LldbEngine
//
///////////////////////////////////////////////////////////////////////

LldbEngine::LldbEngine(const DebuggerStartParameters &startParameters)
    : DebuggerEngine(startParameters)
{
82
    m_lastAgentId = 0;
hjk's avatar
hjk committed
83
    m_lastToken = 0;
84
    setObjectName(QLatin1String("LldbEngine"));
85
86
87
88
89
90
91
92
93
94
95

    connect(debuggerCore()->action(AutoDerefPointers), SIGNAL(valueChanged(QVariant)),
            SLOT(updateLocals()));
    connect(debuggerCore()->action(CreateFullBacktrace), SIGNAL(triggered()),
            SLOT(updateAll()));
    connect(debuggerCore()->action(UseDebuggingHelpers), SIGNAL(valueChanged(QVariant)),
            SLOT(updateLocals()));
    connect(debuggerCore()->action(UseDynamicType), SIGNAL(valueChanged(QVariant)),
            SLOT(updateLocals()));
    connect(debuggerCore()->action(IntelFlavor), SIGNAL(valueChanged(QVariant)),
            SLOT(updateAll()));
96
97
98
99
100
}

LldbEngine::~LldbEngine()
{}

hjk's avatar
hjk committed
101
void LldbEngine::executeDebuggerCommand(const QString &command, DebuggerLanguages)
102
{
hjk's avatar
hjk committed
103
    runCommand(Command("executeDebuggerCommand").arg("command", command));
104
105
}

hjk's avatar
hjk committed
106
void LldbEngine::runCommand(const Command &command)
107
108
{
    QTC_ASSERT(m_lldbProc.state() == QProcess::Running, notifyEngineIll());
hjk's avatar
hjk committed
109
110
    ++m_lastToken;
    QByteArray token = QByteArray::number(m_lastToken);
111
112
    QByteArray cmd = "{\"cmd\":\"" + command.function + "\","
        + command.args + "\"token\":" + token + "}\n";
hjk's avatar
hjk committed
113
    showMessage(_(token + cmd), LogInput);
114
    m_lldbProc.write(cmd);
115
116
117
118
119
}

void LldbEngine::shutdownInferior()
{
    QTC_ASSERT(state() == InferiorShutdownRequested, qDebug() << state());
120
    runCommand(Command("shutdownInferior"));
121
122
123
124
125
126
127
128
129
130
131
}

void LldbEngine::shutdownEngine()
{
    QTC_ASSERT(state() == EngineShutdownRequested, qDebug() << state());
    m_lldbProc.kill();
}

void LldbEngine::setupEngine()
{
    QTC_ASSERT(state() == EngineSetupRequested, qDebug() << state());
Fawzi Mohamed's avatar
Fawzi Mohamed committed
132
133
134
135
136
137
    if (startParameters().remoteSetupNeeded) {
        notifyEngineRequestRemoteSetup();
    } else {
        startLldb();
    }
}
138

Fawzi Mohamed's avatar
Fawzi Mohamed committed
139
140
void LldbEngine::startLldb()
{
141
    m_lldbCmd = startParameters().debuggerCommand;
142
143
144
145
146
147
148
149
150
151
    connect(&m_lldbProc, SIGNAL(error(QProcess::ProcessError)),
        SLOT(handleLldbError(QProcess::ProcessError)));
    connect(&m_lldbProc, SIGNAL(finished(int,QProcess::ExitStatus)),
        SLOT(handleLldbFinished(int,QProcess::ExitStatus)));
    connect(&m_lldbProc, SIGNAL(readyReadStandardOutput()),
        SLOT(readLldbStandardOutput()));
    connect(&m_lldbProc, SIGNAL(readyReadStandardError()),
        SLOT(readLldbStandardError()));

    connect(this, SIGNAL(outputReady(QByteArray)),
152
        SLOT(handleResponse(QByteArray)), Qt::QueuedConnection);
153

154
155
156
157
    QStringList args;
    args.append(_("-i"));
    args.append(Core::ICore::resourcePath() + _("/debugger/lldbbridge.py"));
    args.append(m_lldbCmd);
Andre Hartmann's avatar
Andre Hartmann committed
158
    showMessage(_("STARTING LLDB ") + args.join(QLatin1String(" ")));
159
    m_lldbProc.setEnvironment(startParameters().environment.toStringList());
Eike Ziller's avatar
Eike Ziller committed
160
161
    if (!startParameters().workingDirectory.isEmpty())
        m_lldbProc.setWorkingDirectory(startParameters().workingDirectory);
162

163
    m_lldbProc.start(_("python"), args);
164
165

    if (!m_lldbProc.waitForStarted()) {
166
        const QString msg = tr("Unable to start LLDB \"%1\": %2")
167
            .arg(m_lldbCmd, m_lldbProc.errorString());
168
169
        notifyEngineSetupFailed();
        showMessage(_("ADAPTER START FAILED"));
170
        if (!msg.isEmpty())
171
            Core::ICore::showWarningWithOptions(tr("Adapter start failed."), msg);
172
173
174
175
176
    }
}

void LldbEngine::setupInferior()
{
177
178
179
    const DebuggerStartParameters &sp = startParameters();
    Command cmd("setupInferior");
    cmd.arg("executable", QFileInfo(sp.executable).absoluteFilePath());
Fawzi Mohamed's avatar
Fawzi Mohamed committed
180
    cmd.arg("startMode", sp.startMode); // directly relying on this is brittle wrt. insertions, so check it here
181
    cmd.arg("processArgs", sp.processArgs);
Fawzi Mohamed's avatar
Fawzi Mohamed committed
182
183
184
    cmd.arg("attachPid", ((sp.startMode == AttachCrashedExternal || sp.startMode == AttachExternal)
                          ? sp.attachPID : 0));
    cmd.arg("sysRoot", sp.sysRoot);
Fawzi Mohamed's avatar
Fawzi Mohamed committed
185
186
    cmd.arg("remoteChannel", ((sp.startMode == AttachToRemoteProcess
                               || sp.startMode == AttachToRemoteServer)
Fawzi Mohamed's avatar
Fawzi Mohamed committed
187
                              ? sp.remoteChannel : QString()));
188
    cmd.arg("platform", sp.platform);
189
    runCommand(cmd);
190
    requestUpdateWatchers();
191
    updateLocals(); // update display options
192
193
194
195
196
}

void LldbEngine::runEngine()
{
    QTC_ASSERT(state() == EngineRunRequested, qDebug() << state());
197

hjk's avatar
hjk committed
198
199
    Command cmd("handleBreakpoints");
    if (attemptBreakpointSynchronizationHelper(&cmd)) {
200
        runEngine2();
hjk's avatar
hjk committed
201
202
203
204
    } else {
        cmd.arg("continuation", "runEngine2");
        runCommand(cmd);
    }
205
206
207
208
}

void LldbEngine::runEngine2()
{
209
    showStatusMessage(tr("Running requested..."), 5000);
210
    runCommand("runEngine");
211
212
213
214
215
}

void LldbEngine::interruptInferior()
{
    showStatusMessage(tr("Interrupt requested..."), 5000);
216
    runCommand("interruptInferior");
217
218
}

219
220
221
222
void LldbEngine::executeStep()
{
    resetLocation();
    notifyInferiorRunRequested();
223
    runCommand("executeStep");
224
225
}

226
227
228
229
void LldbEngine::executeStepI()
{
    resetLocation();
    notifyInferiorRunRequested();
230
    runCommand("executeStepI");
231
232
233
234
235
236
}

void LldbEngine::executeStepOut()
{
    resetLocation();
    notifyInferiorRunRequested();
237
    runCommand("executeStepOut");
238
239
240
241
242
243
}

void LldbEngine::executeNext()
{
    resetLocation();
    notifyInferiorRunRequested();
244
    runCommand("executeNext");
245
246
247
248
249
250
}

void LldbEngine::executeNextI()
{
    resetLocation();
    notifyInferiorRunRequested();
251
    runCommand("executeNextI");
252
253
254
255
256
257
}

void LldbEngine::continueInferior()
{
    resetLocation();
    notifyInferiorRunRequested();
258
    runCommand("continueInferior");
259
260
}

261
void LldbEngine::handleResponse(const QByteArray &response)
262
{
263
264
    GdbMi all;
    all.fromStringMultiple(response);
265

266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
    foreach (const GdbMi &item, all.children()) {
        const QByteArray name = item.name();
        if (name == "data")
            refreshLocals(item);
        else if (name == "stack")
            refreshStack(item);
        else if (name == "registers")
            refreshRegisters(item);
        else if (name == "threads")
            refreshThreads(item);
        else if (name == "typeinfo")
            refreshTypeInfo(item);
        else if (name == "state")
            refreshState(item);
        else if (name == "location")
            refreshLocation(item);
        else if (name == "modules")
            refreshModules(item);
284
285
        else if (name == "symbols")
            refreshSymbols(item);
286
287
        else if (name == "bkpts")
            refreshBreakpoints(item);
288
289
        else if (name == "output")
            refreshOutput(item);
290
291
        else if (name == "disassembly")
            refreshDisassembly(item);
292
293
        else if (name == "memory")
            refreshMemory(item);
294
295
296
297
298
299
300
301
302
        else if (name == "continuation")
            runContinuation(item);
    }
}

void LldbEngine::runContinuation(const GdbMi &data)
{
    const QByteArray target = data.data();
    QMetaObject::invokeMethod(this, target, Qt::QueuedConnection);
303
304
}

305
306
void LldbEngine::executeRunToLine(const ContextData &data)
{
307
308
    resetLocation();
    notifyInferiorRunRequested();
hjk's avatar
hjk committed
309
310
    runCommand(Command("executeRunToLine")
        .arg("file", data.fileName).arg("line", data.address));
311
312
313
314
}

void LldbEngine::executeRunToFunction(const QString &functionName)
{
315
316
    resetLocation();
    notifyInferiorRunRequested();
hjk's avatar
hjk committed
317
    runCommand(Command("executeRunToFunction").arg("function", functionName));
318
319
320
321
}

void LldbEngine::executeJumpToLine(const ContextData &data)
{
322
323
    resetLocation();
    notifyInferiorRunRequested();
hjk's avatar
hjk committed
324
325
    runCommand(Command("executeJumpToLine")
        .arg("file", data.fileName).arg("line", data.address));
326
327
328
329
330
331
332
333
}

void LldbEngine::activateFrame(int frameIndex)
{
    resetLocation();
    if (state() != InferiorStopOk && state() != InferiorUnrunnable)
        return;

hjk's avatar
hjk committed
334
    runCommand(Command("activateFrame").arg("index", frameIndex));
335
336
337
338
}

void LldbEngine::selectThread(ThreadId threadId)
{
hjk's avatar
hjk committed
339
    runCommand(Command("selectThread").arg("id", threadId.raw()));
340
341
342
343
344
345
346
347
}

bool LldbEngine::acceptsBreakpoint(BreakpointModelId id) const
{
    return breakHandler()->breakpointData(id).isCppBreakpoint()
        && startParameters().startMode != AttachCore;
}

hjk's avatar
hjk committed
348
bool LldbEngine::attemptBreakpointSynchronizationHelper(Command *cmd)
349
350
351
{
    BreakHandler *handler = breakHandler();

352
353
354
355
356
357
358
359
360
361
362
363
364
    foreach (BreakpointModelId id, handler->unclaimedBreakpointIds()) {
        // Take ownership of the breakpoint. Requests insertion.
        if (acceptsBreakpoint(id)) {
            showMessage(_("TAKING OWNERSHIP OF BREAKPOINT %1 IN STATE %2")
                .arg(id.toString()).arg(handler->state(id)));
            handler->setEngine(id, this);
        } else {
            showMessage(_("BREAKPOINT %1 IN STATE %2 IS NOT ACCEPTABLE")
                .arg(id.toString()).arg(handler->state(id)));
        }
    }

    bool done = true;
hjk's avatar
hjk committed
365
    cmd->beginList("bkpts");
366
367
    foreach (BreakpointModelId id, handler->engineBreakpointIds(this)) {
        const BreakpointResponse &response = handler->response(id);
368
369
        const BreakpointState bpState = handler->state(id);
        switch (bpState) {
370
371
372
373
374
375
        case BreakpointNew:
            // Should not happen once claimed.
            QTC_CHECK(false);
            break;
        case BreakpointInsertRequested:
            done = false;
hjk's avatar
hjk committed
376
377
378
379
380
            cmd->beginGroup()
                    .arg("operation", "add")
                    .arg("modelid", id.toByteArray())
                    .arg("type", handler->type(id))
                    .arg("ignorecount", handler->ignoreCount(id))
381
                    .arg("condition", handler->condition(id).toHex())
hjk's avatar
hjk committed
382
383
384
385
386
                    .arg("function", handler->functionName(id).toUtf8())
                    .arg("oneshot", handler->isOneShot(id))
                    .arg("enabled", handler->isEnabled(id))
                    .arg("file", handler->fileName(id).toUtf8())
                    .arg("line", handler->lineNumber(id))
387
388
                    .arg("address", handler->address(id))
                    .arg("expression", handler->expression(id))
hjk's avatar
hjk committed
389
                    .endGroup();
390
391
392
393
            handler->notifyBreakpointInsertProceeding(id);
            break;
        case BreakpointChangeRequested:
            done = false;
hjk's avatar
hjk committed
394
395
396
397
398
399
            cmd->beginGroup()
                    .arg("operation", "change")
                    .arg("modelid", id.toByteArray())
                    .arg("lldbid", response.id.toByteArray())
                    .arg("type", handler->type(id))
                    .arg("ignorecount", handler->ignoreCount(id))
400
                    .arg("condition", handler->condition(id).toHex())
hjk's avatar
hjk committed
401
402
403
404
405
                    .arg("function", handler->functionName(id).toUtf8())
                    .arg("oneshot", handler->isOneShot(id))
                    .arg("enabled", handler->isEnabled(id))
                    .arg("file", handler->fileName(id).toUtf8())
                    .arg("line", handler->lineNumber(id))
406
407
                    .arg("address", handler->address(id))
                    .arg("expression", handler->expression(id))
hjk's avatar
hjk committed
408
                    .endGroup();
409
410
411
412
            handler->notifyBreakpointChangeProceeding(id);
            break;
        case BreakpointRemoveRequested:
            done = false;
hjk's avatar
hjk committed
413
414
415
416
417
            cmd->beginGroup()
                    .arg("operation", "remove")
                    .arg("modelid", id.toByteArray())
                    .arg("lldbid", response.id.toByteArray())
                    .endGroup();
418
419
420
421
422
423
424
            handler->notifyBreakpointRemoveProceeding(id);
            break;
        case BreakpointChangeProceeding:
        case BreakpointInsertProceeding:
        case BreakpointRemoveProceeding:
        case BreakpointInserted:
        case BreakpointDead:
425
            QTC_ASSERT(false, qDebug() << "UNEXPECTED STATE" << bpState << "FOR BP " << id);
426
427
            break;
        default:
428
            QTC_ASSERT(false, qDebug() << "UNKNOWN STATE" << bpState << "FOR BP" << id);
429
430
        }
    }
hjk's avatar
hjk committed
431
    cmd->endList();
432
433
434
435
436
437
438
439
440
441
    return done;
}

void LldbEngine::attemptBreakpointSynchronization()
{
    showMessage(_("ATTEMPT BREAKPOINT SYNCHRONIZATION"));
    if (!stateAcceptsBreakpointChanges()) {
        showMessage(_("BREAKPOINT SYNCHRONIZATION NOT POSSIBLE IN CURRENT STATE"));
        return;
    }
442

hjk's avatar
hjk committed
443
444
    Command cmd("handleBreakpoints");
    if (!attemptBreakpointSynchronizationHelper(&cmd)) {
445
        showMessage(_("BREAKPOINTS ARE NOT FULLY SYNCHRONIZED"));
hjk's avatar
hjk committed
446
        runCommand(cmd);
447
448
449
450
    } else {
        showMessage(_("BREAKPOINTS ARE SYNCHRONIZED"));
    }
}
451

452
void LldbEngine::updateBreakpointData(const GdbMi &bkpt, bool added)
453
454
{
    BreakHandler *handler = breakHandler();
455
    BreakpointModelId id = BreakpointModelId(bkpt["modelid"].data());
456
    BreakpointResponse response = handler->response(id);
457
    BreakpointResponseId rid = BreakpointResponseId(bkpt["lldbid"].data());
458
459
460
461
    if (added)
        response.id = rid;
    QTC_CHECK(response.id == rid);
    response.address = 0;
462
463
    response.enabled = bkpt["enabled"].toInt();
    response.ignoreCount = bkpt["ignorecount"].toInt();
464
    response.condition = QByteArray::fromHex(bkpt["condition"].data());
465
    response.hitCount = bkpt["hitcount"].toInt();
466
467
468

    if (added) {
        // Added.
469
        GdbMi locations = bkpt["locations"];
470
471
472
        const int numChild = locations.children().size();
        if (numChild > 1) {
            foreach (const GdbMi &location, locations.children()) {
473
                const int locid = location["locid"].toInt();
474
                BreakpointResponse sub;
475
                sub.id = BreakpointResponseId(rid.majorPart(), locid);
476
                sub.type = response.type;
477
                sub.address = location["addr"].toAddress();
478
                sub.functionName = location["func"].toUtf8();
479
480
481
482
                handler->insertSubBreakpoint(id, sub);
            }
        } else if (numChild == 1) {
            const GdbMi location = locations.childAt(0);
483
            response.address = location["addr"].toAddress();
484
            response.functionName = location["func"].toUtf8();
485
486
487
488
489
490
491
492
493
494
495
496
        } else {
            QTC_CHECK(false);
        }
        handler->setResponse(id, response);
        handler->notifyBreakpointInsertOk(id);
    } else {
        // Changed.
        handler->setResponse(id, response);
        handler->notifyBreakpointChangeOk(id);
    }
}

497
void LldbEngine::refreshDisassembly(const GdbMi &data)
498
499
500
{
    DisassemblerLines result;

501
    int cookie = data["cookie"].toInt();
502
503
504
505
    QPointer<DisassemblerAgent> agent = m_disassemblerAgents.key(cookie);
    if (!agent.isNull()) {
        foreach (const GdbMi &line, data["lines"].children()) {
            DisassemblerLine dl;
506
            dl.address = line["address"].toAddress();
507
508
            dl.data = line["inst"].toUtf8();
            dl.function = line["func-name"].toUtf8();
509
            dl.offset = line["offset"].toInt();
510
511
512
            QByteArray comment = line["comment"].data();
            if (!comment.isEmpty())
                dl.data += QString::fromUtf8(" # " + comment);
513
514
515
            result.appendLine(dl);
        }
        agent->setContents(result);
516
    }
517
}
518

519
520
void LldbEngine::refreshMemory(const GdbMi &data)
{
521
    int cookie = data["cookie"].toInt();
522
    qulonglong addr = data["address"].toAddress();
523
524
525
526
527
528
529
    QPointer<MemoryAgent> agent = m_memoryAgents.key(cookie);
    if (!agent.isNull()) {
        QPointer<QObject> token = m_memoryAgentTokens.value(cookie);
        QTC_ASSERT(!token.isNull(), return);
        QByteArray ba = QByteArray::fromHex(data["contents"].data());
        agent->addLazyData(token.data(), addr, ba);
    }
530
531
}

532
533
534
535
536
537
538
539
540
541
542
543
void LldbEngine::refreshOutput(const GdbMi &output)
{
    QByteArray channel = output["channel"].data();
    QByteArray data = QByteArray::fromHex(output["data"].data());
    LogChannel ch = AppStuff;
    if (channel == "stdout")
        ch = AppOutput;
    else if (channel == "stderr")
        ch = AppError;
    showMessage(QString::fromUtf8(data), ch);
}

544
void LldbEngine::refreshBreakpoints(const GdbMi &bkpts)
545
{
546
    BreakHandler *handler = breakHandler();
hjk's avatar
hjk committed
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
    foreach (const GdbMi &bkpt, bkpts.children()) {
        QByteArray op = bkpt["operation"].data();
        if (op == "added") {
            BreakpointModelId id = BreakpointModelId(bkpt["modelid"].data());
            QTC_CHECK(handler->state(id) == BreakpointInsertProceeding);
            updateBreakpointData(bkpt, true);
        } else if (op == "changed") {
            BreakpointModelId id = BreakpointModelId(bkpt["modelid"].data());
            QTC_CHECK(handler->state(id) == BreakpointChangeProceeding);
            updateBreakpointData(bkpt, false);
        } else if (op == "removed") {
            BreakpointModelId id = BreakpointModelId(bkpt["modelid"].data());
            QTC_CHECK(handler->state(id) == BreakpointRemoveProceeding);
            handler->notifyBreakpointRemoveOk(id);
        }
562
    }
563
564
565
566
567
568
569
570
571
572
573
574
575
}

void LldbEngine::loadSymbols(const QString &moduleName)
{
    Q_UNUSED(moduleName)
}

void LldbEngine::loadAllSymbols()
{
}

void LldbEngine::reloadModules()
{
576
    runCommand("listModules");
577
578
}

579
void LldbEngine::refreshModules(const GdbMi &modules)
580
{
581
582
    Modules mods;
    foreach (const GdbMi &item, modules.children()) {
583
        Module module;
584
585
        module.modulePath = item["file"].toUtf8();
        module.moduleName = item["name"].toUtf8();
586
        module.symbolsRead = Module::UnknownReadState;
587
        module.startAddress = item["loaded_addr"].toAddress();
588
        module.endAddress = 0; // FIXME: End address not easily available.
589
        mods.append(module);
590
    }
591
    modulesHandler()->setModules(mods);
592
593
594
595
}

void LldbEngine::requestModuleSymbols(const QString &moduleName)
{
596
    runCommand(Command("listSymbols").arg("module", moduleName));
597
598
}

599
void LldbEngine::refreshSymbols(const GdbMi &symbols)
600
{
601
    QString moduleName = symbols["module"].toUtf8();
602
603
604
    Symbols syms;
    foreach (const GdbMi &item, symbols["symbols"].children()) {
        Symbol symbol;
605
606
607
608
609
        symbol.address = item["address"].toUtf8();
        symbol.name = item["name"].toUtf8();
        symbol.state = item["state"].toUtf8();
        symbol.section = item["section"].toUtf8();
        symbol.demangled = item["demangled"].toUtf8();
610
611
612
        syms.append(symbol);
    }
   debuggerCore()->showModuleSymbols(moduleName, syms);
613
614
}

615

616
617
618
619
620
621
622
623
624
625
626
627
628
//////////////////////////////////////////////////////////////////////
//
// Tooltip specific stuff
//
//////////////////////////////////////////////////////////////////////

static WatchData m_toolTip;
static QPoint m_toolTipPos;
static QHash<QString, WatchData> m_toolTipCache;

bool LldbEngine::setToolTipExpression(const QPoint &mousePos,
    TextEditor::ITextEditor *editor, const DebuggerToolTipContext &ctx)
{
629
630
    Q_UNUSED(mousePos);
    Q_UNUSED(editor);
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

    if (state() != InferiorStopOk) {
        //SDEBUG("SUPPRESSING DEBUGGER TOOLTIP, INFERIOR NOT STOPPED");
        return false;
    }
    // Check mime type and get expression (borrowing some C++ - functions)
    const QString javaPythonMimeType =
        QLatin1String("application/javascript");
    if (!editor->document() || editor->document()->mimeType() != javaPythonMimeType)
        return false;

    int line;
    int column;
    QString exp = cppExpressionAt(editor, ctx.position, &line, &column);

/*
    if (m_toolTipCache.contains(exp)) {
        const WatchData & data = m_toolTipCache[exp];
        q->watchHandler()->removeChildren(data.iname);
        insertData(data);
        return;
    }
*/

    QToolTip::hideText();
    if (exp.isEmpty() || exp.startsWith(QLatin1Char('#')))  {
        QToolTip::hideText();
        return false;
    }

    if (!hasLetterOrNumber(exp)) {
662
        QToolTip::showText(m_toolTipPos, tr("\"%1\" contains no identifier.").arg(exp));
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
        return true;
    }

    if (exp.startsWith(QLatin1Char('"')) && exp.endsWith(QLatin1Char('"'))) {
        QToolTip::showText(m_toolTipPos, tr("String literal %1").arg(exp));
        return true;
    }

    if (exp.startsWith(QLatin1String("++")) || exp.startsWith(QLatin1String("--")))
        exp.remove(0, 2);

    if (exp.endsWith(QLatin1String("++")) || exp.endsWith(QLatin1String("--")))
        exp.remove(0, 2);

    if (exp.startsWith(QLatin1Char('<')) || exp.startsWith(QLatin1Char('[')))
        return false;

    if (hasSideEffects(exp)) {
        QToolTip::showText(m_toolTipPos,
682
            tr("Cowardly refusing to evaluate expression \"%1\" "
683
               "with potential side effects.").arg(exp));
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
        return true;
    }

#if 0
    //if (status() != InferiorStopOk)
    //    return;

    // FIXME: 'exp' can contain illegal characters
    m_toolTip = WatchData();
    m_toolTip.exp = exp;
    m_toolTip.name = exp;
    m_toolTip.iname = tooltipIName;
    insertData(m_toolTip);
#endif
    return false;
}

701
702
703
704
void LldbEngine::updateAll()
{
    updateLocals();
}
705
706
707
708
709
710
711

//////////////////////////////////////////////////////////////////////
//
// Watch specific stuff
//
//////////////////////////////////////////////////////////////////////

712
713
void LldbEngine::assignValueInDebugger(const Internal::WatchData *data,
    const QString &expression, const QVariant &value)
714
{
715
716
717
718
719
    Q_UNUSED(data);
    Command cmd("assignValue");
    cmd.arg("exp", expression.toLatin1().toHex());
    cmd.arg("value", value.toString().toLatin1().toHex());
    runCommand(cmd);
720
721
722
723
724
725
}

void LldbEngine::updateWatchData(const WatchData &data, const WatchUpdateFlags &flags)
{
    Q_UNUSED(data);
    Q_UNUSED(flags);
726
727
728
729
730
    updateLocals();
}

void LldbEngine::updateLocals()
{
731
    WatchHandler *handler = watchHandler();
732

hjk's avatar
hjk committed
733
    //requestUpdateWatchers();
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
    Command cmd("updateData");
    cmd.arg("expanded", handler->expansionRequests());
    cmd.arg("typeformats", handler->typeFormatRequests());
    cmd.arg("formats", handler->individualFormatRequests());

//    const QString fileName = stackHandler()->currentFrame().file;
//    if (!fileName.isEmpty()) {
//        const QString function = stackHandler()->currentFrame().function;
//        typedef DebuggerToolTipManager::ExpressionInamePair ExpressionInamePair;
//        typedef DebuggerToolTipManager::ExpressionInamePairs ExpressionInamePairs;

//        // Re-create tooltip items that are not filters on existing local variables in
//        // the tooltip model.
//        ExpressionInamePairs toolTips = DebuggerToolTipManager::instance()
//                ->treeWidgetExpressions(fileName, objectName(), function);

//        const QString currentExpression = tooltipExpression();
//        if (!currentExpression.isEmpty()) {
//            int currentIndex = -1;
//            for (int i = 0; i < toolTips.size(); ++i) {
//                if (toolTips.at(i).first == currentExpression) {
//                    currentIndex = i;
//                    break;
//                }
//            }
//            if (currentIndex < 0)
//                toolTips.push_back(ExpressionInamePair(currentExpression, tooltipIName(currentExpression)));
//        }

//        foreach (const ExpressionInamePair &p, toolTips) {
//            if (p.second.startsWith("tooltip")) {
//                QHash<QByteArray, QByteArray> hash;
//                hash["exp"] = p.first.toLatin1();
//                hash["id"] = p.second;
//                watcherData.append(Command::toData(hash));
//            }
//        }
//    }

    const static bool alwaysVerbose = !qgetenv("QTC_DEBUGGER_PYTHON_VERBOSE").isEmpty();
hjk's avatar
hjk committed
775
    cmd.arg("passexceptions", alwaysVerbose);
776
777
778
779
780
781
782
783
    cmd.arg("fancy", debuggerCore()->boolSetting(UseDebuggingHelpers));
    cmd.arg("autoderef", debuggerCore()->boolSetting(AutoDerefPointers));
    cmd.arg("dyntype", debuggerCore()->boolSetting(UseDynamicType));
    //cmd.arg("partial", ??)
    //cmd.arg("tooltipOnly", ??)
    //cmd.arg("resultvarname", m_resultVarName);

    runCommand(cmd);
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
}

void LldbEngine::handleLldbError(QProcess::ProcessError error)
{
    qDebug() << "HANDLE LLDB ERROR";
    showMessage(_("HANDLE LLDB ERROR"));
    switch (error) {
    case QProcess::Crashed:
        break; // will get a processExited() as well
    // impossible case QProcess::FailedToStart:
    case QProcess::ReadError:
    case QProcess::WriteError:
    case QProcess::Timedout:
    default:
        //setState(EngineShutdownRequested, true);
        m_lldbProc.kill();
Leena Miettinen's avatar
Leena Miettinen committed
800
        showMessageBox(QMessageBox::Critical, tr("LLDB I/O Error"),
801
802
803
804
805
806
807
808
809
                       errorMessage(error));
        break;
    }
}

QString LldbEngine::errorMessage(QProcess::ProcessError error) const
{
    switch (error) {
        case QProcess::FailedToStart:
Leena Miettinen's avatar
Leena Miettinen committed
810
            return tr("The LLDB process failed to start. Either the "
811
                "invoked program \"%1\" is missing, or you may have insufficient "
812
                "permissions to invoke the program.")
813
                .arg(m_lldbCmd);
814
        case QProcess::Crashed:
Leena Miettinen's avatar
Leena Miettinen committed
815
            return tr("The LLDB process crashed some time after starting "
816
817
818
819
820
821
822
                "successfully.");
        case QProcess::Timedout:
            return tr("The last waitFor...() function timed out. "
                "The state of QProcess is unchanged, and you can try calling "
                "waitFor...() again.");
        case QProcess::WriteError:
            return tr("An error occurred when attempting to write "
Leena Miettinen's avatar
Leena Miettinen committed
823
                "to the LLDB process. For example, the process may not be running, "
824
825
826
827
828
                "or it may have closed its input channel.");
        case QProcess::ReadError:
            return tr("An error occurred when attempting to read from "
                "the Lldb process. For example, the process may not be running.");
        default:
829
            return tr("An unknown error in the Lldb process occurred.") + QLatin1Char(' ');
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
    }
}

void LldbEngine::handleLldbFinished(int code, QProcess::ExitStatus type)
{
    qDebug() << "LLDB FINISHED";
    showMessage(_("LLDB PROCESS FINISHED, status %1, code %2").arg(type).arg(code));
    notifyEngineSpontaneousShutdown();
}

void LldbEngine::readLldbStandardError()
{
    QByteArray err = m_lldbProc.readAllStandardError();
    qDebug() << "\nLLDB STDERR" << err;
    //qWarning() << "Unexpected lldb stderr:" << err;
845
    showMessage(_(err), LogError);
846
847
    if (!err.startsWith("warning:"))
        m_lldbProc.kill();
848
849
850
851
852
}

void LldbEngine::readLldbStandardOutput()
{
    QByteArray out = m_lldbProc.readAllStandardOutput();
853
    showMessage(_("Lldb stdout: " + out));
854
    m_inbuffer.append(out);
855
    while (true) {
856
        int pos = m_inbuffer.indexOf("@\n");
857
858
859
        if (pos == -1)
            break;
        QByteArray response = m_inbuffer.left(pos).trimmed();
860
        m_inbuffer = m_inbuffer.mid(pos + 2);
861
862
863
864
        emit outputReady(response);
    }
}

865
void LldbEngine::requestUpdateWatchers()
866
{
867
    QHashIterator<QByteArray, int> it(WatchHandler::watcherNames());
868
869
870
871
    QList<QByteArray> watcherData;
    while (it.hasNext()) {
        it.next();
        QHash<QByteArray, QByteArray> hash;
872
873
        hash["iname"] = "\"watch." + QByteArray::number(it.value()) + '"';
        hash["exp"] = '"' + it.key().toHex() + '"';
874
        watcherData.append(Command::toData(hash));
875
    }
876
    Command cmd("setWatchers");
877
    cmd.args.append("\"watchers\":" + Command::toData(watcherData) + ',');
878
    runCommand(cmd);
879
880
}

881
882
883
884
void LldbEngine::refreshLocals(const GdbMi &vars)
{
    //const bool partial = response.cookie.toBool();
    WatchHandler *handler = watchHandler();
885
    handler->resetValueCache();
886
887
888
889
890
891
892
893
894
895
    QList<WatchData> list;

    //if (!partial) {
        list.append(*handler->findData("local"));
        list.append(*handler->findData("watch"));
        list.append(*handler->findData("return"));
    //}

    foreach (const GdbMi &child, vars.children()) {
        WatchData dummy;
896
897
        dummy.iname = child["iname"].data();
        GdbMi wname = child["wname"];
898
        if (wname.isValid()) {
899
900
901
            // Happens (only) for watched expressions.
            dummy.exp = QByteArray::fromHex(wname.data());
            dummy.name = QString::fromUtf8(dummy.exp);
902
        } else {
903
            dummy.name = child["name"].toUtf8();
904
        }
905
906
907
908
909
910
911
912
913
914
915
        parseWatchData(handler->expandedINames(), dummy, child, &list);
    }
    handler->insertData(list);
 }

void LldbEngine::refreshStack(const GdbMi &stack)
{
    //if (!partial)
    //    emit stackFrameCompleted();
    StackHandler *handler = stackHandler();
    StackFrames frames;
916
    foreach (const GdbMi &item, stack["frames"].children()) {
917
        StackFrame frame;
918
        frame.level = item["level"].toInt();
919
920
921
        frame.file = item["file"].toUtf8();
        frame.function = item["func"].toUtf8();
        frame.from = item["func"].toUtf8();
922
        frame.line = item["line"].toInt();
923
        frame.address = item["addr"].toAddress();
924
925
926
        frame.usable = QFileInfo(frame.file).isReadable();
        frames.append(frame);
    }
927
    bool canExpand = stack["hasmore"].toInt();
928
929
    debuggerCore()->action(ExpandStack)->setEnabled(canExpand);
    handler->setFrames(frames);
930
931
932

    int index = stack["current-frame"].toInt();
    handler->setCurrentIndex(index);
933
934
935
936
937
938
939
940
}

void LldbEngine::refreshRegisters(const GdbMi &registers)
{
    RegisterHandler *handler = registerHandler();
    Registers regs;
    foreach (const GdbMi &item, registers.children()) {
        Register reg;
941
942
        reg.name = item["name"].data();
        reg.value = item["value"].data();
943
        //reg.type = item["type"].data();
944
945
946
947
948
        regs.append(reg);
    }
    //handler->setRegisters(registers);
    handler->setAndMarkRegisters(regs);
}
949
950
951
952
953
954
955
956
957

void LldbEngine::refreshThreads(const GdbMi &threads)
{
    ThreadsHandler *handler = threadsHandler();
    handler->updateThreads(threads);
    if (!handler->currentThread().isValid()) {
        ThreadId other = handler->threadAt(0);
        if (other.isValid())
            selectThread(other);
958
    }
959
    updateViews(); // Adjust Threads combobox.
hjk's avatar
hjk committed
960
961
}

962
void LldbEngine::refreshTypeInfo(const GdbMi &typeInfo)
hjk's avatar
hjk committed
963
{
964
965
    if (typeInfo.type() == GdbMi::List) {
//        foreach (const GdbMi &s, typeInfo.children()) {
966
967
//            const GdbMi name = s["name"];
//            const GdbMi size = s["size"];
968
969
970
971
972
973
974
975
976
977
978
//            if (name.isValid() && size.isValid())
//                m_typeInfoCache.insert(QByteArray::fromBase64(name.data()),
//                                       TypeInfo(size.data().toUInt()));
//        }
    }
//    for (int i = 0; i != list.size(); ++i) {
//        const TypeInfo ti = m_typeInfoCache.value(list.at(i).type);
//        if (ti.size)
//            list[i].size = ti.size;
//    }
}
hjk's avatar
hjk committed
979

980
981
void LldbEngine::refreshState(const GdbMi &reportedState)
{
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
    QByteArray newState = reportedState.data();
    if (newState == "running")
        notifyInferiorRunOk();
    else if (newState == "inferiorrunfailed")
        notifyInferiorRunFailed();
    else if (newState == "stopped")
        notifyInferiorSpontaneousStop();
    else if (newState == "inferiorstopok")
        notifyInferiorStopOk();
    else if (newState == "inferiorstopfailed")
        notifyInferiorStopFailed();
    else if (newState == "enginesetupok")
        notifyEngineSetupOk();
    else if (newState == "enginesetupfailed")
        notifyEngineSetupFailed();
    else if (newState == "stopped")
        notifyInferiorSpontaneousStop();
    else if (newState == "inferiorsetupok")
        notifyInferiorSetupOk();
hjk's avatar
hjk committed
1001
    else if (newState == "enginerunandinferiorrunok")
1002
        notifyEngineRunAndInferiorRunOk();
hjk's avatar
hjk committed
1003
1004
    else if (newState == "enginerunandinferiorstopok")
        notifyEngineRunAndInferiorStopOk();
1005
1006
1007
1008
1009
1010
1011
1012
    else if (newState == "inferiorshutdownok")
        notifyInferiorShutdownOk();
    else if (newState == "inferiorshutdownfailed")
        notifyInferiorShutdownFailed();
    else if (newState == "engineshutdownok")
        notifyEngineShutdownOk();
    else if (newState == "engineshutdownfailed")
        notifyEngineShutdownFailed();
hjk's avatar
hjk committed
1013
1014
    else if (newState == "inferiorexited")
        notifyInferiorExited();
1015
1016
}

1017
1018
void LldbEngine::refreshLocation(const GdbMi &reportedLocation)
{
1019
1020
1021
1022
1023
1024
1025
1026
1027
    if (debuggerCore()->boolSetting(OperateByInstruction)) {
        Location loc(reportedLocation["addr"].toAddress());
        loc.setNeedsMarker(true);
        gotoLocation(loc);
    } else {
        QString file = reportedLocation["file"].toUtf8();
        int line = reportedLocation["line"].toInt();
        gotoLocation(Location(file, line));
    }
1028
1029
}

1030
1031
void LldbEngine::reloadRegisters()
{
1032
    runCommand("reportRegisters");
1033
1034
}

1035
1036
void LldbEngine::fetchDisassembler(DisassemblerAgent *agent)
{
1037
1038
1039
1040
1041
1042
    QPointer<DisassemblerAgent> p(agent);
    int id = m_disassemblerAgents.value(p, -1);
    if (id == -1) {
        id = ++m_lastAgentId;
        m_disassemblerAgents.insert(p, id);
    }
hjk's avatar
hjk committed
1043
    runCommand(Command("disassemble").arg("cookie", id));
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
}


void LldbEngine::fetchMemory(MemoryAgent *agent, QObject *editorToken,
        quint64 addr, quint64 length)
{
    int id = m_memoryAgents.value(agent, -1);
    if (id == -1) {
        id = ++m_lastAgentId;
        m_memoryAgents.insert(agent, id);
    }
1055
    m_memoryAgentTokens.insert(id, editorToken);
1056
    runCommand(Command("fetchMemory")
hjk's avatar
hjk committed
1057
1058
1059
               .arg("address", addr)
               .arg("length", length)
               .arg("cookie", id));
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
}

void LldbEngine::changeMemory(MemoryAgent *agent, QObject *editorToken,
        quint64 addr, const QByteArray &data)
{
    int id = m_memoryAgents.value(agent, -1);
    if (id == -1) {
        id = ++m_lastAgentId;
        m_memoryAgents.insert(agent, id);
        m_memoryAgentTokens.insert(id, editorToken);
    }
hjk's avatar
hjk committed
1071
1072
1073
1074
    runCommand(Command("writeMemory")
               .arg("address", addr)
               .arg("data", data.toHex())
               .arg("cookie", id));
1075
1076
}

1077
1078
1079
void LldbEngine::setRegisterValue(int regnr, const QString &value)
{
    Register reg = registerHandler()->registers().at(regnr);
hjk's avatar
hjk committed
1080
    runCommand(Command("setRegister").arg("name", reg.name).arg("value", value));
1081
1082
1083
}


1084
1085
bool LldbEngine::hasCapability(unsigned cap) const
{
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
    if (cap & (ReverseSteppingCapability
        | AutoDerefPointersCapability
        | DisassemblerCapability
        | RegisterCapability
        | ShowMemoryCapability
        | JumpToLineCapability
        | ReloadModuleCapability
        | ReloadModuleSymbolsCapability
        | BreakOnThrowAndCatchCapability
        | BreakConditionCapability
        | TracePointCapability
        | ReturnFromFunctionCapability
        | CreateFullBacktraceCapability
        | WatchpointByAddressCapability
        | WatchpointByExpressionCapability
        | AddWatcherCapability
        | WatchWidgetsCapability
        | ShowModuleSymbolsCapability
        | ShowModuleSectionsCapability
        | CatchCapability
        | OperateByInstructionCapability
        | RunToLineCapability
        | WatchComplexExpressionsCapability
        | MemoryAddressCapability))
        return true;

    if (startParameters().startMode == AttachCore)
        return false;

    //return cap == SnapshotCapability;
    return false;
1117
1118
1119
1120
1121
1122
1123
}

DebuggerEngine *createLldbEngine(const DebuggerStartParameters &startParameters)
{
    return new LldbEngine(startParameters);
}

Fawzi Mohamed's avatar
Fawzi Mohamed committed
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
void LldbEngine::notifyEngineRemoteSetupDone(int portOrPid, int qmlPort)
{
    QTC_ASSERT(state() == EngineSetupRequested, qDebug() << state());
    DebuggerEngine::notifyEngineRemoteSetupDone(portOrPid, qmlPort);

    if (qmlPort != -1)
        startParameters().qmlServerPort = qmlPort;
    if (portOrPid != -1) {
        if (startParameters().startMode == AttachExternal) {
            startParameters().attachPID = portOrPid;
        } else {
            QString &rc = startParameters().remoteChannel;
            const int sepIndex = rc.lastIndexOf(QLatin1Char(':'));
Fawzi Mohamed's avatar
Fawzi Mohamed committed
1137
            if (sepIndex != -1)
Fawzi Mohamed's avatar
Fawzi Mohamed committed
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
                rc.replace(sepIndex + 1, rc.count() - sepIndex - 1,
                           QString::number(portOrPid));
        }
    }
    startLldb();
}

void LldbEngine::notifyEngineRemoteSetupFailed(const QString &reason)
{
    QTC_ASSERT(state() == EngineSetupRequested, qDebug() << state());
    DebuggerEngine::notifyEngineRemoteSetupFailed(reason);
    showMessage(_("ADAPTER START FAILED"));
    if (!reason.isEmpty()) {
        const QString title = tr("Adapter start failed");
        Core::ICore::showWarningWithOptions(title, reason);
    }
    notifyEngineSetupFailed();
}
hjk's avatar
hjk committed
1156
1157
1158
1159
1160
1161
1162

///////////////////////////////////////////////////////////////////////
//
// Command
//
///////////////////////////////////////////////////////////////////////

1163
const LldbEngine::Command &LldbEngine::Command::argHelper(const char *name, const QByteArray &data) const
hjk's avatar
hjk committed
1164
{
1165
    args.append('"');
hjk's avatar
hjk committed
1166
    args.append(name);
1167
    args.append("\":");
1168
1169
    args.append(data);
    args.append(",");
hjk's avatar
hjk committed
1170
1171
1172
    return *this;
}

1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
QByteArray LldbEngine::Command::toData(const QList<QByteArray> &value)
{
    QByteArray res;
    foreach (const QByteArray &item, value) {
        if (!res.isEmpty())
            res.append(',');
        res += item;
    }
    return '[' + res + ']';
}

QByteArray LldbEngine::Command::toData(const QHash<QByteArray, QByteArray> &value)
{
    QByteArray res;
    QHashIterator<QByteArray, QByteArray> it(value);
    while (it.hasNext()) {
        it.next();
        if (!res.isEmpty())
            res.append(',');
1192
        res += '"' + it.key() + "\":" + it.value();
1193
1194
1195
1196
    }
    return '{' + res + '}';
}

1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
const LldbEngine::Command &LldbEngine::Command::arg(const char *name, int value) const
{
    return argHelper(name, QByteArray::number(value));
}

const LldbEngine::Command &LldbEngine::Command::arg(const char *name, qlonglong value) const
{
    return argHelper(name, QByteArray::number(value));
}

const LldbEngine::Command &LldbEngine::Command::arg(const char *name, qulonglong value) const
{
    return argHelper(name, QByteArray::number(value));
}

hjk's avatar
hjk committed
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
const LldbEngine::Command &LldbEngine::Command::arg(const char *name, const QString &value) const
{
    return arg(name, value.toUtf8().data());
}

const LldbEngine::Command &LldbEngine::Command::arg(const char *name, const QByteArray &value) const
{
    return arg(name, value.data());
}

const LldbEngine::Command &LldbEngine::Command::arg(const char *name, const char *value) const
{
1224
    args.append('"');
hjk's avatar
hjk committed
1225
    args.append(name);
1226
    args.append("\":\"");
hjk's avatar
hjk committed
1227
    args.append(value);
1228
    args.append("\",");
hjk's avatar
hjk committed
1229
1230
1231
1232
1233
1234
    return *this;
}

const LldbEngine::Command &LldbEngine::Command::beginList(const char *name) const
{
    if (name) {
1235
        args += '"';
hjk's avatar
hjk committed
1236
        args += name;
1237
        args += "\":";
hjk's avatar
hjk committed
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
    }
    args += '[';
    return *this;
}

void LldbEngine::Command::endList() const
{
    if (args.endsWith(','))
        args.chop(1);
    args += "],";
}

const LldbEngine::Command &LldbEngine::Command::beginGroup(const char *name) const
{
    if (name) {
1253
        args += '"';
hjk's avatar
hjk committed
1254
        args += name;
1255
        args += "\":";
hjk's avatar
hjk committed
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
    }
    args += '{';
    return *this;
}

void LldbEngine::Command::endGroup() const
{
    if (args.endsWith(','))
        args.chop(1);
    args += "},";
}