aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/valgrind/callgrindengine.cpp
blob: 99d948c2482e82a7fd3c1a79d778d3093216630d (plain)
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
// 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 "callgrindengine.h"

#include "valgrindsettings.h"

#include <valgrind/callgrind/callgrindparser.h>
#include <valgrind/valgrindrunner.h>
#include <valgrind/valgrindtr.h>

#include <debugger/analyzer/analyzermanager.h>

#include <utils/filepath.h>
#include <utils/filestreamermanager.h>
#include <utils/process.h>
#include <utils/qtcassert.h>
#include <utils/temporaryfile.h>

#include <QDebug>

#define CALLGRIND_CONTROL_DEBUG 0

using namespace ProjectExplorer;
using namespace Valgrind::Callgrind;
using namespace Utils;

namespace Valgrind {
namespace Internal {

const char CALLGRIND_CONTROL_BINARY[] = "callgrind_control";

void setupCallgrindRunner(CallgrindToolRunner *);

CallgrindToolRunner::CallgrindToolRunner(RunControl *runControl)
    : ValgrindToolRunner(runControl)
{
    setId("CallgrindToolRunner");

    connect(&m_runner, &ValgrindRunner::valgrindStarted, this, [this](qint64 pid) {
        m_pid = pid;
    });
    connect(&m_runner, &ValgrindRunner::finished, this, [this] {
        triggerParse();
        emit parserDataReady(this);
    });
    connect(&m_parser, &Callgrind::Parser::parserDataReady, this, [this] {
        emit parserDataReady(this);
    });

    m_valgrindRunnable = runControl->runnable();

    static int fileCount = 100;
    m_valgrindOutputFile = runControl->workingDirectory() / QString("callgrind.out.f%1").arg(++fileCount);

    setupCallgrindRunner(this);
}

CallgrindToolRunner::~CallgrindToolRunner()
{
    cleanupTempFile();
}

QStringList CallgrindToolRunner::toolArguments() const
{
    QStringList arguments = {"--tool=callgrind"};

    if (m_settings.enableCacheSim.value())
        arguments << "--cache-sim=yes";

    if (m_settings.enableBranchSim.value())
        arguments << "--branch-sim=yes";

    if (m_settings.collectBusEvents.value())
        arguments << "--collect-bus=yes";

    if (m_settings.collectSystime.value())
        arguments << "--collect-systime=yes";

    if (m_markAsPaused)
        arguments << "--instr-atstart=no";

    // add extra arguments
    if (!m_argumentForToggleCollect.isEmpty())
        arguments << m_argumentForToggleCollect;

    arguments << "--callgrind-out-file=" + m_valgrindOutputFile.path();

    arguments << ProcessArgs::splitArgs(m_settings.callgrindArguments.value(), HostOsInfo::hostOs());

    return arguments;
}

QString CallgrindToolRunner::progressTitle() const
{
    return Tr::tr("Profiling");
}

void CallgrindToolRunner::start()
{
    const FilePath executable = runControl()->commandLine().executable();
    appendMessage(Tr::tr("Profiling %1").arg(executable.toUserOutput()), NormalMessageFormat);
    return ValgrindToolRunner::start();
}

void CallgrindToolRunner::setPaused(bool paused)
{
    if (m_markAsPaused == paused)
        return;

    m_markAsPaused = paused;

    // call controller only if it is attached to a valgrind process
    if (paused)
        pause();
    else
        unpause();
}

void CallgrindToolRunner::setToggleCollectFunction(const QString &toggleCollectFunction)
{
    if (toggleCollectFunction.isEmpty())
        return;

    m_argumentForToggleCollect = "--toggle-collect=" + toggleCollectFunction;
}

Callgrind::ParseData *CallgrindToolRunner::takeParserData()
{
    return m_parser.takeData();
}

void CallgrindToolRunner::showStatusMessage(const QString &message)
{
    Debugger::showPermanentStatusMessage(message);
}

static QString toOptionString(CallgrindToolRunner::Option option)
{
    /* callgrind_control help from v3.9.0

    Options:
    -h --help        Show this help text
    --version        Show version
    -s --stat        Show statistics
    -b --back        Show stack/back trace
    -e [<A>,...]     Show event counters for <A>,... (default: all)
    --dump[=<s>]     Request a dump optionally using <s> as description
    -z --zero        Zero all event counters
    -k --kill        Kill
    --instr=<on|off> Switch instrumentation state on/off
    */

    switch (option) {
        case CallgrindToolRunner::Dump:
            return QLatin1String("--dump");
        case CallgrindToolRunner::ResetEventCounters:
            return QLatin1String("--zero");
        case CallgrindToolRunner::Pause:
            return QLatin1String("--instr=off");
        case CallgrindToolRunner::UnPause:
            return QLatin1String("--instr=on");
        default:
            return QString(); // never reached
    }
}

void CallgrindToolRunner::run(Option option)
{
    if (m_controllerProcess) {
        showStatusMessage(Tr::tr("Previous command has not yet finished."));
        return;
    }

    // save back current running operation
    m_lastOption = option;

    m_controllerProcess.reset(new Process);

    switch (option) {
        case CallgrindToolRunner::Dump:
            showStatusMessage(Tr::tr("Dumping profile data..."));
            break;
        case CallgrindToolRunner::ResetEventCounters:
            showStatusMessage(Tr::tr("Resetting event counters..."));
            break;
        case CallgrindToolRunner::Pause:
            showStatusMessage(Tr::tr("Pausing instrumentation..."));
            break;
        case CallgrindToolRunner::UnPause:
            showStatusMessage(Tr::tr("Unpausing instrumentation..."));
            break;
        default:
            break;
    }

#if CALLGRIND_CONTROL_DEBUG
    m_controllerProcess->setProcessChannelMode(QProcess::ForwardedChannels);
#endif
    connect(m_controllerProcess.get(), &Process::done,
            this, &CallgrindToolRunner::controllerProcessDone);

    const FilePath control =
            m_valgrindRunnable.command.executable().withNewPath(CALLGRIND_CONTROL_BINARY);
    m_controllerProcess->setCommand({control, {toOptionString(option), QString::number(m_pid)}});
    m_controllerProcess->setWorkingDirectory(m_valgrindRunnable.workingDirectory);
    m_controllerProcess->setEnvironment(m_valgrindRunnable.environment);
    m_controllerProcess->start();
}

void CallgrindToolRunner::controllerProcessDone()
{
    const QString error = m_controllerProcess->errorString();
    const ProcessResult result = m_controllerProcess->result();

    m_controllerProcess.release()->deleteLater();

    if (result != ProcessResult::FinishedWithSuccess) {
        showStatusMessage(Tr::tr("An error occurred while trying to run %1: %2").arg(CALLGRIND_CONTROL_BINARY).arg(error));
        qWarning() << "Controller exited abnormally:" << error;
        return;
    }

    // this call went fine, we might run another task after this
    switch (m_lastOption) {
        case ResetEventCounters:
            // lets dump the new reset profiling info
            run(Dump);
            return;
        case Pause:
            m_paused = true;
            break;
        case Dump:
            showStatusMessage(Tr::tr("Callgrind dumped profiling info"));
            triggerParse();
            break;
        case UnPause:
            m_paused = false;
            showStatusMessage(Tr::tr("Callgrind unpaused."));
            break;
        default:
            break;
    }

    m_lastOption = Unknown;
}

void CallgrindToolRunner::triggerParse()
{
    cleanupTempFile();
    {
        TemporaryFile dataFile("callgrind.out");
        if (!dataFile.open()) {
            showStatusMessage(Tr::tr("Failed opening temp file..."));
            return;
        }
        m_hostOutputFile = FilePath::fromString(dataFile.fileName());
    }

    const auto afterCopy = [this](expected_str<void> res) {
        QTC_ASSERT_EXPECTED(res, return);
        showStatusMessage(Tr::tr("Parsing Profile Data..."));
        m_parser.parse(m_hostOutputFile);
    };
    // TODO: Store the handle and cancel on CallgrindToolRunner destructor?
    // TODO: Should d'tor of context object cancel the running task?
    FileStreamerManager::copy(m_valgrindOutputFile, m_hostOutputFile, this, afterCopy);
}

void CallgrindToolRunner::cleanupTempFile()
{
    if (!m_hostOutputFile.isEmpty() && m_hostOutputFile.exists())
        m_hostOutputFile.removeFile();

    m_hostOutputFile.clear();
}

} // Internal
} // Valgrind