crashhandler.cpp 10.3 KB
Newer Older
1
/****************************************************************************
2
**
3 4
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
5
**
Tobias Hunger's avatar
Tobias Hunger committed
6
** This file is part of Qt Creator.
7
**
Tobias Hunger's avatar
Tobias Hunger committed
8 9 10 11
** 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
12 13 14
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
15
**
16 17 18 19 20 21 22
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** 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-3.0.html.
23
**
Tobias Hunger's avatar
Tobias Hunger committed
24
****************************************************************************/
25 26 27 28 29 30

#include "crashhandler.h"
#include "crashhandlerdialog.h"
#include "backtracecollector.h"
#include "utils.h"

31
#include <utils/environment.h>
32
#include <utils/fileutils.h>
33

34 35 36
#include <QApplication>
#include <QDebug>
#include <QDesktopServices>
37
#include <QDir>
38 39 40 41
#include <QFile>
#include <QRegExp>
#include <QTextStream>
#include <QUrl>
42
#include <QVector>
43 44 45 46 47 48 49 50

#include <stdio.h>
#include <stdlib.h>

#include <errno.h>
#include <unistd.h>

#include <sys/types.h>
51
#include <sys/wait.h>
52 53 54

static const char FileDistroInformation[] = "/etc/lsb-release";
static const char FileKernelVersion[] = "/proc/version";
55
static const char QtCreatorExecutable[] = "qtcreator";
56 57 58 59 60 61 62 63 64 65 66

static QString collectLinuxDistributionInfo()
{
    return QString::fromLatin1(fileContents(QLatin1String(FileDistroInformation)));
}

static QString collectKernelVersionInfo()
{
    return QString::fromLatin1(fileContents(QLatin1String(FileKernelVersion)));
}

67 68
// Convience class for interacting with exec() family of functions.
class CExecList : public QVector<char *>
69 70
{
public:
71 72 73 74 75 76
    CExecList(const QStringList &list)
    {
        foreach (const QString &item, list)
            append(qstrdup(item.toLatin1().data()));
        append(0);
    }
77

78
    ~CExecList()
79
    {
80 81
        for (int i = 0; i < size(); ++i)
            delete[] value(i);
82
    }
83 84 85 86 87
};

class CrashHandlerPrivate
{
public:
88
    CrashHandlerPrivate(pid_t pid, const QString &signalName, CrashHandler *crashHandler)
89
        : pid(pid),
90
          creatorInPath(Utils::Environment::systemEnvironment().searchInPath(QLatin1String(QtCreatorExecutable))),
91
          dialog(crashHandler, signalName) {}
92 93

    const pid_t pid;
94
    const Utils::FileName creatorInPath; // Backup debugger.
95 96 97 98

    BacktraceCollector backtraceCollector;
    CrashHandlerDialog dialog;

99 100
    QStringList restartAppCommandLine;
    QStringList restartAppEnvironment;
101 102
};

103 104
CrashHandler::CrashHandler(pid_t pid, const QString &signalName, QObject *parent)
    : QObject(parent), d(new CrashHandlerPrivate(pid, signalName, this))
105
{
106 107 108 109 110
    connect(&d->backtraceCollector, &BacktraceCollector::error, this, &CrashHandler::onError);
    connect(&d->backtraceCollector, &BacktraceCollector::backtraceChunk,
            this, &CrashHandler::onBacktraceChunk);
    connect(&d->backtraceCollector, &BacktraceCollector::backtrace,
            this, &CrashHandler::onBacktraceFinished);
111 112 113 114

    d->dialog.appendDebugInfo(collectKernelVersionInfo());
    d->dialog.appendDebugInfo(collectLinuxDistributionInfo());

115 116 117 118 119 120 121
    if (!collectRestartAppData()) {
        d->dialog.disableRestartAppCheckBox();
        if (d->creatorInPath.isEmpty())
            d->dialog.disableDebugAppButton();
    }

    d->dialog.show();
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
}

CrashHandler::~CrashHandler()
{
    delete d;
}

void CrashHandler::run()
{
    d->backtraceCollector.run(d->pid);
}

void CrashHandler::onError(const QString &errorMessage)
{
    d->dialog.setToFinalState();

    QTextStream(stderr) << errorMessage;
139
    const QString text = QLatin1String("A problem occurred providing the backtrace. "
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
        "Please make sure to have the debugger \"gdb\" installed.\n");
    d->dialog.appendDebugInfo(text);
    d->dialog.appendDebugInfo(errorMessage);
}

void CrashHandler::onBacktraceChunk(const QString &chunk)
{
    d->dialog.appendDebugInfo(chunk);
}

void CrashHandler::onBacktraceFinished(const QString &backtrace)
{
    d->dialog.setToFinalState();

    // Select first line of relevant thread.

    // Example debugger output:
    // ...
    // [Current thread is 1 (Thread 0x7f1c33c79780 (LWP 975))]
    // ...
    // Thread 1 (Thread 0x7f1c33c79780 (LWP 975)):
    // ...
162
    QRegExp rx(QLatin1String("\\[Current thread is (\\d+)"));
163 164 165 166 167 168 169 170 171 172
    const int pos = rx.indexIn(backtrace);
    if (pos == -1)
        return;
    const QString threadNumber = rx.cap(1);
    const QString textToSelect = QString::fromLatin1("Thread %1").arg(threadNumber);
    d->dialog.selectLineWithContents(textToSelect);
}

void CrashHandler::openBugTracker()
{
173
    QDesktopServices::openUrl(QUrl(QLatin1String(URL_BUGTRACKER)));
174 175 176 177 178 179
}

bool CrashHandler::collectRestartAppData()
{
    const QString procDir = QString::fromLatin1("/proc/%1").arg(d->pid);

180
    // Get command line.
181 182 183 184
    // man 5 proc: /proc/[pid]/cmdline
    // The command-line arguments appear in this file as a set of strings separated by
    // null bytes ('\0'), with a further null byte after the last string.
    const QString procCmdFileName = procDir + QLatin1String("/cmdline");
185 186
    QList<QByteArray> commandLine = fileContents(procCmdFileName).split('\0');
    if (commandLine.size() < 2) {
187 188 189
        qWarning("%s: Unexpected format in file '%s'.\n", Q_FUNC_INFO, qPrintable(procCmdFileName));
        return false;
    }
190 191 192 193 194
    commandLine.removeLast();
    foreach (const QByteArray &item, commandLine)
        d->restartAppCommandLine.append(QString::fromLatin1(item));

    // Get environment.
195
    // man 5 proc: /proc/[pid]/environ
196
    // The entries are separated by null bytes ('\0'), and there may be a null byte at the end.
197
    const QString procEnvFileName = procDir + QLatin1String("/environ");
198 199
    QList<QByteArray> environment = fileContents(procEnvFileName).split('\0');
    if (environment.isEmpty()) {
200 201 202
        qWarning("%s: Unexpected format in file '%s'.\n", Q_FUNC_INFO, qPrintable(procEnvFileName));
        return false;
    }
203 204 205 206
    if (environment.last().isEmpty())
        environment.removeLast();
    foreach (const QByteArray &item, environment)
        d->restartAppEnvironment.append(QString::fromLatin1(item));
207 208 209 210

    return true;
}

211
void CrashHandler::runCommand(QStringList commandLine, QStringList environment, WaitMode waitMode)
212 213 214 215 216 217 218 219 220 221 222 223 224 225
{
    // TODO: If QTBUG-2284 is resolved, use QProcess::startDetached() here.
    // We can't use QProcess::startDetached because of bug
    //
    //      QTBUG-2284
    //      QProcess::startDetached does not support setting an environment for the new process
    //
    // therefore, we use fork-exec.

    pid_t pid = fork();
    switch (pid) {
    case -1: // error
        qFatal("%s: fork() failed.", Q_FUNC_INFO);
        break;
226 227 228 229 230 231 232 233 234 235 236 237 238
    case 0: { // child
        CExecList argv(commandLine);
        CExecList envp(environment);
        qDebug("Running\n");
        for (int i = 0; argv[i]; ++i)
            qDebug("   %s", argv[i]);
        if (!environment.isEmpty()) {
            qDebug("\nwith environment:\n");
            for (int i = 0; envp[i]; ++i)
                qDebug("   %s", envp[i]);
        }

        // The standards pipes must be open, otherwise the application will
239 240 241 242 243 244 245 246
        // receive a SIGPIPE as soon as these are used.
        if (freopen("/dev/null", "r", stdin) == 0)
            qFatal("%s: freopen() failed for stdin: %s.\n", Q_FUNC_INFO, strerror(errno));
        if (freopen("/dev/null", "w", stdout) == 0)
            qFatal("%s: freopen() failed for stdout: %s.\n", Q_FUNC_INFO, strerror(errno));
        if (freopen("/dev/null", "w", stderr) == 0)
            qFatal("%s: freopen() failed for stderr: %s.\n.", Q_FUNC_INFO, strerror(errno));

247
        if (environment.isEmpty())
248
            execvp(argv[0], argv.data());
249
        else
250
            execvpe(argv[0], argv.data(), envp.data());
251
        _exit(EXIT_FAILURE);
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
    } default: // parent
        if (waitMode == WaitForExit) {
            while (true) {
                int status;
                if (waitpid(pid, &status, 0) == -1) {
                    if (errno == EINTR) // Signal handler of QProcess for SIGCHLD was triggered.
                        continue;
                    perror("waitpid() failed unexpectedly");
                }
                if (WIFEXITED(status)) {
                    qDebug("Child exited with exit code %d.", WEXITSTATUS(status));
                    break;
                } else if (WIFSIGNALED(status)) {
                    qDebug("Child terminated by signal %d.", WTERMSIG(status));
                    break;
                }
            }
        }
270 271 272
        break;
    }
}
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294

void CrashHandler::restartApplication()
{
    runCommand(d->restartAppCommandLine, d->restartAppEnvironment, DontWaitForExit);
}

void CrashHandler::debugApplication()
{
    // User requested to debug the app while our debugger is running.
    if (d->backtraceCollector.isRunning()) {
        if (!d->dialog.runDebuggerWhileBacktraceNotFinished())
            return;
        if (d->backtraceCollector.isRunning()) {
            d->backtraceCollector.disconnect();
            d->backtraceCollector.kill();
            d->dialog.setToFinalState();
            d->dialog.appendDebugInfo(tr("\n\nCollecting backtrace aborted by user."));
            QCoreApplication::processEvents(); // Show the last appended output immediately.
        }
    }

    // Prepare command.
295
    QString executable = d->creatorInPath.toString();
296
    if (executable.isEmpty() && !d->restartAppCommandLine.isEmpty())
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
        executable = d->restartAppCommandLine.at(0);
    const QStringList commandLine = QStringList()
            << executable
            << QLatin1String("-debug")
            << QString::number(d->pid);

    QStringList environment;
    if (!d->restartAppEnvironment.isEmpty())
        environment = d->restartAppEnvironment;

    // The UI is blocked/frozen anyway, so hide the dialog while debugging.
    d->dialog.hide();
    runCommand(commandLine, environment, WaitForExit);
    d->dialog.show();
}