summaryrefslogtreecommitdiffstats
path: root/process.cpp
blob: 21cfb556cc3839b14d516cdca822bf7d258cfe75 (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
#include "process.h"
#include <QCoreApplication>
#include <unistd.h>
#include <QDebug>
#include <QFile>
#include <QSocketNotifier>
#include <sys/socket.h>
#include <signal.h>
#include <fcntl.h>
#include <QFileInfo>

static int pipefd[2];

static void signalhandler(int)
{
    write(pipefd[1], " ", 1);
}

static bool analyzeBinary(const QString &binary)
{
    QFileInfo fi(binary);
    if (!fi.exists()) {
        printf("Binary does not exist.\n");
        return false;
    }
    if (!fi.isFile()) {
        printf("Binary is not a file.\n");
        return false;
    }
    if (!fi.isReadable()) {
        printf("Binary is not readable.\n");
        return false;
    }
    if (!fi.isExecutable()) {
        printf("Binary is not executable.\n");
        return false;
    }

    if (fi.size() < 4) {
        printf("Binary is smaller than 4 bytes.\n");
        return false;
    }

    QFile f(binary);
    if (!f.open(QFile::ReadOnly)) {
        printf("Could not open binary to analyze.\n");
        return false;
    }

    QByteArray elfHeader = f.read(4);
    f.close();

    if (elfHeader.size() < 4) {
        printf("Failed to read ELF header.\n");
        return false;
    }

    if (elfHeader != QByteArray::fromHex("7f454C46")) { // 0x7f ELF
        printf("Binary is not an ELF file.\n");
        return false;
    }

    return true;
}

Process::Process()
    : QObject(0)
    , mProcess(new QProcess(this))
    , mDebuggee(0)
    , mDebug(false)
{
    mProcess->setProcessChannelMode(QProcess::SeparateChannels);
    connect(mProcess, SIGNAL(readyReadStandardError()), this, SLOT(readyReadStandardError()));
    connect(mProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readyReadStandardOutput()));
    connect(mProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(finished(int, QProcess::ExitStatus)));
    connect(mProcess, SIGNAL(error(QProcess::ProcessError)), this, SLOT(error(QProcess::ProcessError)));
    connect(mProcess, SIGNAL(finished(int, QProcess::ExitStatus)), qApp, SLOT(quit()));

    if (pipe2(pipefd, O_CLOEXEC) != 0)
        qWarning("Could not create pipe");

    QSocketNotifier *n = new QSocketNotifier(pipefd[0], QSocketNotifier::Read, this);
    connect(n, SIGNAL(activated(int)), this, SLOT(stop()));

    signal(SIGINT, signalhandler);
    signal(SIGTERM, signalhandler);
    signal(SIGHUP, signalhandler);
    signal(SIGPIPE, signalhandler);
}

Process::~Process()
{
    close(pipefd[0]);
    close(pipefd[1]);
}

void Process::readyReadStandardOutput()
{
    QByteArray b = mProcess->readAllStandardOutput();
    write(1, b.constData(), b.size());

    if (mConfig.flags.testFlag(Config::PrintDebugMessages))
        qDebug() << b;
}

void Process::readyReadStandardError()
{
    QByteArray b = mProcess->readAllStandardError();
    if (mDebug) {
        int index = b.indexOf(" created; pid = ");
        if (index >= 0) {
            mDebuggee = QString::fromLatin1(b.mid(index+16)).toUInt();
        }
        mDebug = false; // only search once
    }
    write(2, b.constData(), b.size());

    if (mConfig.flags.testFlag(Config::PrintDebugMessages))
        qDebug() << b;
}

void Process::setDebug()
{
    mDebug = true;
}

void Process::error(QProcess::ProcessError error)
{
    switch (error) {
    case QProcess::FailedToStart:
        printf("Failed to start\n");
        analyzeBinary(mBinary);
        break;
    case QProcess::Crashed:
        printf("Crashed\n");
        break;
    case QProcess::Timedout:
        printf("Timedout\n");
        break;
    case QProcess::WriteError:
        printf("Write error\n");
        break;
    case QProcess::ReadError:
        printf("Read error\n");
        break;
    case QProcess::UnknownError:
        printf("Unknown error\n");
        break;
    }
    qApp->quit();
}

void Process::finished(int exitCode, QProcess::ExitStatus exitStatus)
{
    if (exitStatus == QProcess::NormalExit)
        qDebug() << "Process exited with exitcode" << exitCode;
    else
        qDebug() << "Process stopped";
}

void Process::startup(QStringList args)
{
    QProcessEnvironment pe = QProcessEnvironment::systemEnvironment();

    foreach (const QString &key, mConfig.env.keys()) {
        qDebug() << key << mConfig.env.value(key);
        pe.insert(key, mConfig.env.value(key));
    }
    if (!mConfig.base.isEmpty())
        pe.insert(QLatin1String("B2QT_BASE"), mConfig.base);
    if (!mConfig.platform.isEmpty())
        pe.insert(QLatin1String("B2QT_PLATFORM"), mConfig.platform);

    args.append(mConfig.args);

    mProcess->setProcessEnvironment(pe);
    mBinary = args.first();
    args.removeFirst();
    qDebug() << mBinary << args;
    mProcess->start(mBinary, args);
}

void Process::start(const QStringList &args)
{
    startup(args);
}

void Process::stop()
{
    if (mProcess->state() == QProcess::QProcess::NotRunning) {
        qDebug() << "No process running";
        qApp->exit();
        return;
    }

    if (mDebuggee != 0) {
        qDebug() << "Kill debuggee " << mDebuggee;
        if (kill(mDebuggee, SIGKILL) != 0)
            perror("Could not kill debugee");
    }
    if (kill(-getpid(), SIGTERM) != 0)
        perror("Could not kill process group");

    mProcess->terminate();
    if (!mProcess->waitForFinished())
        mProcess->kill();
}

void Process::incomingConnection(int i)
{
    accept(i, NULL, NULL);
    stop();
}

void Process::setSocketNotifier(QSocketNotifier *s)
{
    connect(s, SIGNAL(activated(int)), this, SLOT(incomingConnection(int)));
}

void Process::setConfig(const Config &config)
{
    mConfig = config;
}