summaryrefslogtreecommitdiffstats
path: root/app/main.cpp
blob: f058a059ebf32aee768ef28c7a19b9567c4df253 (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
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
/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd
** All rights reserved.
** For any questions to The Qt Company, please use contact form at http://www.qt.io/contact-us
**
** This file is part of the Qt Enterprise Perf Profiler Add-on.
**
** GNU General Public License Usage
** This file may be used under the terms of the GNU General Public License
** version 3 as published by the Free Software Foundation and appearing in
** the file LICENSE.GPLv3 included in the packaging of this file. Please
** review the following information to ensure the GNU General Public License
** requirements will be met: https://www.gnu.org/licenses/gpl.html.
**
** If you have questions regarding the use of this file, please use
** contact form at http://www.qt.io/contact-us
**
****************************************************************************/

#include "perfheader.h"
#include "perfattributes.h"
#include "perffeatures.h"
#include "perfdata.h"
#include "perfunwind.h"
#include "perfregisterinfo.h"
#include "perfstdin.h"

#include <QFile>
#include <QDir>
#include <QDebug>
#include <QtEndian>
#include <QCoreApplication>
#include <QCommandLineParser>
#include <QScopedPointer>
#include <QAbstractSocket>
#include <QTcpSocket>
#include <limits>

#ifdef Q_OS_WIN
#include <io.h>
#include <fcntl.h>
#endif

enum ErrorCodes {
    NoError,
    TcpSocketError,
    CannotOpen,
    BadMagic,
    HeaderError,
    DataError,
    MissingData,
    InvalidOption
};

class PerfTcpSocket : public QTcpSocket {
    Q_OBJECT
public:
    PerfTcpSocket(QCoreApplication *app);

public slots:
    void readingFinished();
    void processError(QAbstractSocket::SocketError error);

private:
    bool reading;
};

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);
    app.setApplicationName(QLatin1String("perfparser"));
    app.setApplicationVersion(QLatin1String("4.4"));

    QCommandLineParser parser;
    parser.setApplicationDescription(QLatin1String("Perf data parser and unwinder."));
    parser.addHelpOption();
    parser.addVersionOption();

    QCommandLineOption input(QLatin1String("input"),
                             QCoreApplication::translate(
                                 "main", "Read perf data from <file> instead of stdin."),
                             QLatin1String("file"));
    parser.addOption(input);

    QCommandLineOption host(QLatin1String("host"),
                            QCoreApplication::translate(
                                "main", "Read perf data from remote <host> instead of stdin."),
                            QLatin1String("host"));
    parser.addOption(host);

    QCommandLineOption port(QLatin1String("port"),
                            QCoreApplication::translate(
                              "main", "When reading from remote host, connect to <port> (default: "
                                      "9327)."),
                            QLatin1String("port"),
                            QLatin1String("9327"));
    parser.addOption(port);

    QCommandLineOption output(QLatin1String("output"),
                              QCoreApplication::translate(
                                  "main", "Write b2qt data to <file> instead of stdout."),
                              QLatin1String("file"));
    parser.addOption(output);

    QCommandLineOption sysroot(QLatin1String("sysroot"),
                               QCoreApplication::translate(
                                   "main", "Look for system libraries in <path> (default: %1).")
                               .arg(QDir::rootPath()),
                               QLatin1String("path"),
                               QDir::rootPath());
    parser.addOption(sysroot);

    const auto defaultDebug = QString::fromLatin1("%1usr%1lib%1debug%2%3%1.debug%2.debug")
            .arg(QDir::separator(), QDir::listSeparator(), QDir::homePath());
    QCommandLineOption debug(QLatin1String("debug"),
                             QCoreApplication::translate(
                                 "main",
                                 "Look for debug information in <path>. "
                                 "You can specify multiple paths separated by ':'. "
                                 "Relative paths are relative to the original file's path. "
                                 "The default is: <sysroot>%1 .").arg(defaultDebug),
                             QLatin1String("path"), defaultDebug);
    parser.addOption(debug);

    QCommandLineOption extra(QLatin1String("extra"),
                             QCoreApplication::translate(
                                 "main", "Look for additional libraries in <path> (default: .)."),
                             QLatin1String("path"));
    parser.addOption(extra);

    QCommandLineOption appPath(QLatin1String("app"),
                               QCoreApplication::translate(
                                   "main", "Look for application binary in <path> (default: .)."),
                               QLatin1String("path"));
    parser.addOption(appPath);

    const auto defaultArch =
            PerfRegisterInfo::s_defaultArchitecture != PerfRegisterInfo::ARCH_INVALID
            ? QLatin1String(PerfRegisterInfo::s_archNames[PerfRegisterInfo::s_defaultArchitecture])
            : QString();

    QCommandLineOption arch(QLatin1String("arch"),
                            QCoreApplication::translate(
                                "main",
                                "Set the fallback architecture, in case the architecture is not "
                                "given in the data itself, to <arch>. "
                                "The default is: %1").arg(defaultArch),
                            QLatin1String("arch"),
                            defaultArch);
    parser.addOption(arch);

    const auto defaultKallsyms = QString::fromLatin1("%1proc%1kallsyms").arg(QDir::separator());
    QCommandLineOption kallsymsPath(QLatin1String("kallsyms"),
                                    QCoreApplication::translate(
                                        "main", "Path to kallsyms mapping to resolve kernel "
                                        "symbols. The default is: <sysroot>%1 .")
                                    .arg(defaultKallsyms), QLatin1String("path"), defaultKallsyms);
    parser.addOption(kallsymsPath);

    QCommandLineOption printStats(QLatin1String("print-stats"),
                               QCoreApplication::translate(
                                   "main", "Print statistics instead of converting the data."));
    parser.addOption(printStats);

    QCommandLineOption bufferSize(QLatin1String("buffer-size"),
                                  QCoreApplication::translate(
                                   "main", "Size of event buffer in kilobytes. This influences how"
                                   " many events get buffered before they get sorted by time and "
                                   " then analyzed. Increase this value when your perf.data file"
                                   " was recorded with a large buffer value (perf record -m)."
                                   " Pass 0 to buffer events until a FINISHED_ROUND event is "
                                   " encountered. Default value is 10MB"),
                                   QLatin1String("buffer-size"), QLatin1String("10240"));
    parser.addOption(bufferSize);

    QCommandLineOption maxFrames(QLatin1String("max-frames"),
                                  QCoreApplication::translate(
                                   "main", "Maximum number of frames that will be unwound."
                                   " Set the value to -1 to unwind as many frames as possible."
                                   " Beware that this can then potentially lead to infinite loops "
                                   " when the stack got corrupted. Default value is 64."),
                                   QLatin1String("max-frames"), QLatin1String("64"));
    parser.addOption(maxFrames);

    parser.process(app);

    QScopedPointer<QFile> outfile;
    if (parser.isSet(output)) {
        outfile.reset(new QFile(parser.value(output)));
        if (!outfile->open(QIODevice::WriteOnly))
            return CannotOpen;
    } else {
        outfile.reset(new QFile);
#ifdef Q_OS_WIN
        _setmode(fileno(stdout), O_BINARY);
#endif
        if (!outfile->open(stdout, QIODevice::WriteOnly))
            return CannotOpen;
    }

    QScopedPointer<QIODevice> infile;
    if (parser.isSet(host)) {
        PerfTcpSocket *socket = new PerfTcpSocket(&app);
        infile.reset(socket);
    } else {
        if (parser.isSet(input))
            infile.reset(new QFile(parser.value(input)));
        else
            infile.reset(new PerfStdin);
    }

    bool ok = false;
    uint maxEventBufferSize = parser.value(bufferSize).toUInt(&ok) * 1024;
    if (!ok) {
        qWarning() << "Failed to parse buffer-size argument. Expected unsigned integer, got:"
                   << parser.value(bufferSize);
        return InvalidOption;
    }

    int maxFramesValue = parser.value(maxFrames).toInt(&ok);
    if (!ok) {
        qWarning() << "Failed to parse max-frames argument. Expected integer, got:"
                   << parser.value(maxFrames);
        return InvalidOption;
    }

    PerfUnwind unwind(outfile.data(), parser.value(sysroot), parser.isSet(debug) ?
                          parser.value(debug) : parser.value(sysroot) + parser.value(debug),
                      parser.value(extra), parser.value(appPath), parser.isSet(kallsymsPath)
                        ? parser.value(kallsymsPath)
                        : parser.value(sysroot) + parser.value(kallsymsPath),
                      parser.isSet(printStats), maxEventBufferSize, maxFramesValue);

    PerfHeader header(infile.data());
    PerfAttributes attributes;
    PerfFeatures features;
    PerfData data(infile.data(), &unwind, &header, &attributes);

    features.setArchitecture(parser.value(arch).toLatin1());

    QObject::connect(&header, &PerfHeader::finished, [&]() {
        if (!header.isPipe()) {
            const qint64 filePos = infile->pos();
            if (!attributes.read(infile.data(), &header)) {
                qWarning() << "Failed to read attributes";
                qApp->exit(DataError);
                return;
            }
            if (!features.read(infile.data(), &header)) {
                qWarning() << "Failed to read features";
                qApp->exit(DataError);
                return;
            }
            infile->seek(filePos);

            // first send features, as it may contain better event descriptions
            unwind.features(features);

            const auto& attrs = attributes.attributes();
            for (auto it = attrs.begin(), end = attrs.end(); it != end; ++it) {
                unwind.attr(PerfRecordAttr(it.value(), {it.key()}));
            }
        }

        const QByteArray &featureArch = features.architecture();
        for (uint i = 0; i < PerfRegisterInfo::ARCH_INVALID; ++i) {
            if (featureArch.startsWith(PerfRegisterInfo::s_archNames[i])) {
                unwind.setArchitecture(static_cast<PerfRegisterInfo::Architecture>(i));
                break;
            }
        }

        if (unwind.architecture() == PerfRegisterInfo::ARCH_INVALID) {
            qWarning() << "No information about CPU architecture found. Cannot unwind.";
            qApp->exit(MissingData);
            return;
        }

        QObject::connect(infile.data(), &QIODevice::readyRead, &data, &PerfData::read);
        if (infile->bytesAvailable() > 0)
            data.read();
    });

    QObject::connect(&header, &PerfHeader::error, []() {
        qApp->exit(HeaderError);
    });

    QObject::connect(&data, &PerfData::finished, []() {
        qApp->exit(NoError);
    });

    QObject::connect(&data, &PerfData::error, []() {
        qApp->exit(DataError);
    });

    if (parser.isSet(host)) {
        PerfTcpSocket *socket = static_cast<PerfTcpSocket *>(infile.data());
        QObject::connect(socket, &QTcpSocket::disconnected, &data, &PerfData::finishReading);
        QObject::connect(&data, &PerfData::finished, socket, &PerfTcpSocket::readingFinished);
        socket->connectToHost(parser.value(host), parser.value(port).toUShort(),
                              QIODevice::ReadOnly);
    } else {
        if (!infile->open(QIODevice::ReadOnly))
            return CannotOpen;
        QMetaObject::invokeMethod(&header, "read", Qt::QueuedConnection);
    }

    return app.exec();
}


void PerfTcpSocket::processError(QAbstractSocket::SocketError error)
{
    if (reading) {
        qWarning() << "socket error" << error << errorString();
        qApp->exit(TcpSocketError);
    } // Otherwise ignore the error. We don't need the socket anymore
}


PerfTcpSocket::PerfTcpSocket(QCoreApplication *app) : QTcpSocket(app), reading(true)
{
    connect(this, SIGNAL(error(QAbstractSocket::SocketError)),
            this, SLOT(processError(QAbstractSocket::SocketError)));
}

void PerfTcpSocket::readingFinished()
{
    reading = false;
}

#include "main.moc"