• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

IJHack / QtPass / 45670038354

25 Nov 2026 05:56PM UTC coverage: 94.806% (-0.007%) from 94.813%
45670038354

push

github

web-flow
Executor: keep the first and last 32 KiB of a command's stderr (#2337)

Both the queued and the blocking path read stderr whole once the
command ended, with no bound. gpg writes a line per packet it rejects
and Git one per ref, so an entry or a repository someone else made
could fill gigabytes, held in memory and then shown in the output pane.

Executor::CappedOutput keeps the first and the last kMaxStderrBytes / 2
(64 KiB in all), with a line saying how many bytes were left out
between; the cuts fall on whole UTF-8 characters. Both paths read
stderr as it arrives, so it does not pile up in QProcess's buffer, and
stdout nobody asked for is read and dropped the same way. Wanted stdout
is kept whole: a decrypt must be lossless, and gpg's --max-output
bounds it.

What decides on gpg's records no longer reads the capped text:
CappedOutput counts complete "[GNUPG:]" lines by keyword as they
arrive, the Executor hands the counts on through lastStatusCounts(),
and RealPass judges a re-encryption by them, so a large store's
END_ENCRYPTION lines are all counted. ImitatePass::getKeysFromFile()
lists an entry's recipients from gpg's ENC_TO status lines on stdout
(--status-fd=1), read whole, instead of its -v messages on stderr.

Scan: ANT-2026-VQGRD45V

Signed-off-by: Anne Jan Brouwer <brouwer@annejan.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

117 of 120 new or added lines in 4 files covered. (97.5%)

3 existing lines in 1 file now uncovered.

10131 of 10686 relevant lines covered (94.81%)

21942.38 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

96.06
/src/executor.cpp
1
// SPDX-FileCopyrightText: 2016 Anne Jan Brouwer
2
// SPDX-License-Identifier: GPL-3.0-or-later
3
#include "executor.h"
4
#include <QCoreApplication>
5
#include <QDeadlineTimer>
6
#include <QDir>
7
#include <QFileInfo>
8
#include <QScopeGuard>
9
#include <QStringDecoder>
10
#include <QThread>
11
#include <algorithm>
12
#include <climits>
13
#include <utility>
14

15
#include "qtpasslogging.h"
16

17
#ifdef Q_OS_UNIX
18
#include <csignal>
19
#include <sys/stat.h>
20
#endif
21

22
namespace {
23
/// Executor::setChildUmask(); negative for none.
24
std::atomic_int g_childUmask{-1};
25
/// How often a cancellable blocking run re-checks its cancel flag.
26
constexpr int kBlockingCancelPollMs = 100;
27
/// Grace between terminate() and kill() once a blocking run is cancelled;
28
/// gpg and git exit on SIGTERM well within this.
29
constexpr int kBlockingKillGraceMs = 1000;
30
} // namespace
31

32
Executor::Executor(QObject *parent) : QObject(parent) {
480 ✔
33
  connect(&m_process, &QProcess::finished, this, &Executor::onProcessFinished);
480 ✔
34
  connect(&m_process, &QProcess::started, this, &Executor::starting);
480 ✔
35
  // Read as it arrives, so what QProcess buffers stays small: stderr into
36
  // the cap, stdout nobody asked for into nothing.
37
  connect(&m_process, &QProcess::readyReadStandardError, this,
480 ✔
38
          [this]() { m_stderr.append(m_process.readAllStandardError()); });
4,560 ✔
39
  connect(&m_process, &QProcess::readyReadStandardOutput, this, [this]() {
480 ✔
40
    if (m_discardStdout) {
162 ✔
41
      m_process.readAllStandardOutput();
4 ✔
42
    }
43
  });
162 ✔
44
}
480 ✔
45

46
namespace {
47

48
/**
49
 * @brief Length of a UTF-8 sequence from its lead byte.
50
 * @param lead The first byte.
51
 * @return 1 to 4, or 0 for a continuation byte.
52
 */
53
auto utf8SequenceLength(unsigned char lead) -> int {
16 ✔
54
  if (lead < 0x80) {
16 ✔
55
    return 1;
56
  }
57
  if ((lead & 0xC0) == 0x80) {
2 ✔
58
    return 0;
59
  }
60
  if ((lead & 0xE0) == 0xC0) {
2 ✔
61
    return 2;
62
  }
NEW
63
  if ((lead & 0xF0) == 0xE0) {
×
NEW
64
    return 3;
×
65
  }
66
  return 4;
67
}
68

69
} // namespace
70

71
void Executor::CappedOutput::countStatus(const QByteArray &line) {
268,645 ✔
72
  static const QByteArray prefix = QByteArrayLiteral("[GNUPG:] ");
268,647 ✔
73
  if (!line.startsWith(prefix)) {
268,645 ✔
74
    return;
249,336 ✔
75
  }
76
  QByteArray keyword = line.mid(prefix.size());
19,309 ✔
77
  keyword.truncate(keyword.indexOf(' ') < 0 ? keyword.size()
23,461 ✔
78
                                            : keyword.indexOf(' '));
79
  if (keyword.endsWith('\r')) {
80
    keyword.chop(1);
6,001 ✔
81
  }
82
  const QString key = QString::fromLatin1(keyword);
83
  if (m_status.contains(key) || m_status.size() < kMaxStatusKeywords) {
19,518 ✔
84
    ++m_status[key];
19,304 ✔
85
  }
86
}
87

88
void Executor::CappedOutput::append(const QByteArray &chunk) {
5,176 ✔
89
  // Status records, whole lines at a time, before the text is cut.
90
  qsizetype start = 0;
91
  for (qsizetype end = chunk.indexOf('\n'); end >= 0;
273,821 ✔
92
       start = end + 1, end = chunk.indexOf('\n', start)) {
268,645 ✔
93
    if (!m_lineTooLong &&
268,645 ✔
94
        m_line.size() + (end - start) <= kMaxStatusLineBytes) {
268,644 ✔
95
      m_line.append(chunk.constData() + start, end - start);
537,286 ✔
96
      countStatus(m_line);
268,643 ✔
97
    }
98
    m_line.clear();
268,645 ✔
99
    m_lineTooLong = false;
268,645 ✔
100
  }
101
  if (!m_lineTooLong) {
5,176 ✔
102
    if (m_line.size() + (chunk.size() - start) > kMaxStatusLineBytes) {
5,097 ✔
103
      m_line.clear();
2 ✔
104
      m_lineTooLong = true;
2 ✔
105
    } else {
106
      m_line.append(chunk.constData() + start, chunk.size() - start);
9,494 ✔
107
    }
108
  }
109

110
  constexpr qsizetype half = kMaxStderrBytes / 2;
111
  qsizetype from = 0;
112
  if (m_head.size() < half) {
5,176 ✔
113
    from = qMin(half - m_head.size(), chunk.size());
1,629 ✔
114
    m_head.append(chunk.constData(), from);
2,568 ✔
115
  }
116
  if (from == chunk.size()) {
5,176 ✔
117
    return;
118
  }
119
  m_tail.append(chunk.constData() + from, chunk.size() - from);
7,096 ✔
120
  if (m_tail.size() > half) {
3,548 ✔
121
    const qsizetype excess = m_tail.size() - half;
3,156 ✔
122
    m_dropped += excess;
3,156 ✔
123
    m_tail.remove(0, excess);
3,156 ✔
124
  }
125
}
126

127
// When bytes were left out, the head may end and the tail begin in the
128
// middle of a character: both are cut back to whole ones, so the text
129
// still decodes as UTF-8 rather than falling back to another encoding.
130
auto Executor::CappedOutput::take() -> QByteArray {
1,149 ✔
131
  QByteArray all;
1,149 ✔
132
  if (m_dropped == 0) {
1,149 ✔
133
    all = m_head + m_tail;
2,282 ✔
134
  } else {
135
    QByteArray head = m_head;
136
    qsizetype chopped = 0;
137
    for (qsizetype back = 1; back <= qMin<qsizetype>(4, head.size()); ++back) {
8 ✔
138
      const int length = utf8SequenceLength(
8 ✔
139
          static_cast<unsigned char>(head.at(head.size() - back)));
8 ✔
140
      if (length != 0) {
8 ✔
141
        if (length > back) {
8 ✔
142
          chopped = back;
143
          head.chop(back);
1 ✔
144
        }
145
        break;
146
      }
147
    }
148
    qsizetype start = 0;
149
    while (start < m_tail.size() &&
8 ✔
150
           utf8SequenceLength(static_cast<unsigned char>(m_tail.at(start))) ==
8 ✔
151
               0) {
NEW
152
      ++start;
×
153
    }
154
    all = head + QByteArrayLiteral("\n[... ") +
16 ✔
155
          QByteArray::number(m_dropped + chopped + start) +
24 ✔
156
          QByteArrayLiteral(" bytes left out ...]\n") + m_tail.mid(start);
24 ✔
157
  }
158
  m_head.clear();
1,149 ✔
159
  m_tail.clear();
1,149 ✔
160
  m_dropped = 0;
1,149 ✔
161
  // A last line without a line end is a record too.
162
  if (!m_lineTooLong && !m_line.isEmpty()) {
1,149 ✔
163
    countStatus(m_line);
2 ✔
164
  }
165
  m_line.clear();
1,149 ✔
166
  m_lineTooLong = false;
1,149 ✔
167
  return all;
1,149 ✔
168
}
169

170
Executor::~Executor() { m_process.blockSignals(true); }
961 ✔
171

172
void Executor::detachFromTerminal(QProcess &process) {
2,320 ✔
173
#if defined(Q_OS_UNIX) && QT_VERSION >= QT_VERSION_CHECK(6, 7, 0)
174
  // A child inherits QtPass's controlling terminal when QtPass was started
175
  // from one. git (HTTPS credentials) and ssh (key passphrase, host key) then
176
  // prompt on that /dev/tty, and as the queue runs one command at a time,
177
  // every decrypt and save waits behind a prompt nobody sees: QtPass looks
178
  // frozen. In a session of its own the child has no terminal, so git and
179
  // ssh use SSH_ASKPASS/GIT_ASKPASS when set and otherwise fail with an
180
  // error QtPass shows. GIT_TERMINAL_PROMPT=0 is not set on top: without a
181
  // tty git has nothing to prompt on, and some credential helpers read it as
182
  // "no interaction at all" and would skip their own dialogs.
183
  //
184
  // gpg is unaffected: pinentry is started by gpg-agent, which finds the
185
  // terminal through GPG_TTY (set by the user's shell) or the tty on gpg's
186
  // stdin, here always a pipe. pass is a shell script running that gpg and
187
  // git, so the same holds for it.
188
  //
189
  // Signal dispositions are left alone (no ResetSignalHandlers): exec()
190
  // already resets caught signals, and QtPass sets no SIG_IGN of its own, so
191
  // that flag would only undo what QtPass's own parent chose (nohup, say).
192
  // Terminal signals (Ctrl+C, the SIGHUP of a closed terminal) now reach
193
  // QtPass but not the child; the children are short-lived and, with no
194
  // terminal, cannot sit waiting for input.
195
  QProcess::UnixProcessParameters params = process.unixProcessParameters();
2,320 ✔
196
  params.flags |= QProcess::UnixProcessFlag::CreateNewSession;
197
  process.setUnixProcessParameters(params);
2,320 ✔
198
#else
199
  Q_UNUSED(process);
200
#endif
201
}
2,320 ✔
202

203
void Executor::setChildUmask(int mask) { g_childUmask.store(mask); }
5 ✔
204

205
auto Executor::childUmask() -> int { return g_childUmask.load(); }
30 ✔
206

207
void Executor::startProcess(QProcess &process, const QString &app,
2,314 ✔
208
                            const QStringList &args) {
209
  detachFromTerminal(process);
2,314 ✔
210
#ifdef Q_OS_UNIX
211
  // In the child, between fork and exec: umask() is async-signal-safe.
212
  if (const int mask = g_childUmask.load(); mask >= 0) {
2,314 ✔
213
    process.setChildProcessModifier(
1 ✔
214
        [mask] { ::umask(static_cast<mode_t>(mask)); });
1 ✔
215
  }
216
#endif
217
  if (const auto wsl = parseWslCommand(app)) {
2,314 ✔
218
    process.start(wsl->launcher, wsl->argv(args));
18 ✔
219
  } else {
220
    process.start(resolveExecutable(app), args);
4,610 ✔
221
  }
222
}
2,314 ✔
223

224
auto Executor::resolveExecutable(const QString &app) -> QString {
2,311 ✔
225
  if (app.isEmpty() || QDir::isAbsolutePath(app)) {
4,621 ✔
226
    return app;
227
  }
228
  const QDir appDir(QCoreApplication::applicationDirPath());
72 ✔
229
  QStringList candidates{QDir::cleanPath(appDir.absoluteFilePath(app))};
288 ✔
230
#ifdef Q_OS_WIN
231
  candidates << QDir::cleanPath(
232
      appDir.absoluteFilePath(app + QStringLiteral(".exe")));
233
#endif
234
  for (const QString &candidate : std::as_const(candidates)) {
141 ✔
235
    // A stray non-executable file of that name must not mask PATH.
236
    const QFileInfo info(candidate);
72 ✔
237
    if (info.isFile() && info.isExecutable()) {
72 ✔
238
      return candidate;
239
    }
240
  }
72 ✔
241
  return app;
242
}
144 ✔
243

244
auto Executor::WslCommand::argv(const QStringList &args) const -> QStringList {
35 ✔
245
  return options + QStringList{QStringLiteral("--exec"), command} + args;
140 ✔
246
}
247

248
auto Executor::WslCommand::with(const QString &program) const -> WslCommand {
12 ✔
249
  return {launcher, options, program};
12 ✔
250
}
251

252
auto Executor::parseWslCommand(const QString &app)
3,956 ✔
253
    -> std::optional<WslCommand> {
254
  const QStringList parts = QProcess::splitCommand(app);
3,956 ✔
255
  if (parts.size() < 2) {
3,956 ✔
256
    return std::nullopt;
3,911 ✔
257
  }
258
  // The file name after the last separator of either kind: a Windows path
259
  // has to be recognised as such wherever the parser runs.
260
  const QString &launcher = parts.first();
261
  const qsizetype separator = std::max(launcher.lastIndexOf(QLatin1Char('/')),
45 ✔
262
                                       launcher.lastIndexOf(QLatin1Char('\\')));
45 ✔
263
  const QString launcherName = launcher.mid(separator + 1);
264
  const bool isWsl =
265
      launcherName.compare(QLatin1String("wsl"), Qt::CaseInsensitive) == 0 ||
58 ✔
266
      launcherName.compare(QLatin1String("wsl.exe"), Qt::CaseInsensitive) == 0;
13 ✔
267
  if (!isWsl) {
268
    return std::nullopt;
3 ✔
269
  }
270
  WslCommand wsl;
42 ✔
271
#ifdef Q_OS_WIN
272
  // A bare wsl or wsl.exe in any case is looked up on PATH as `wsl`; a path
273
  // stays as is.
274
  wsl.launcher = separator < 0 ? QStringLiteral("wsl") : launcher;
275
#else
276
  // QtPass running inside WSL reaches wsl.exe through interop under exactly
277
  // that name; nothing says `wsl` resolves too, so start what was written.
278
  wsl.launcher = launcher;
42 ✔
279
#endif
280
  // wsl.exe options that take a value; anything else starting with `-` is a
281
  // flag. A user-written -e/--exec is dropped, argv() always adds one.
282
  static const QStringList valued{
283
      QStringLiteral("-d"),   QStringLiteral("--distribution"),
2 ✔
284
      QStringLiteral("-u"),   QStringLiteral("--user"),
2 ✔
285
      QStringLiteral("--cd"), QStringLiteral("--shell-type")};
58 ✔
286
  qsizetype i = 1;
287
  for (; i < parts.size() && parts.at(i).startsWith(QLatin1Char('-')); ++i) {
59 ✔
288
    const QString &option = parts.at(i);
289
    if (option == QLatin1String("-e") || option == QLatin1String("--exec")) {
18 ✔
290
      continue;
7 ✔
291
    }
292
    if (valued.contains(option)) {
11 ✔
293
      if (i + 1 >= parts.size()) {
11 ✔
294
        return std::nullopt;
1 ✔
295
      }
296
      wsl.options << option << parts.at(++i);
297
    } else {
298
      wsl.options << option;
299
    }
300
  }
301
  // Exactly one program. More is a shell command line (`sh -c "..."`),
302
  // which is what --exec exists to keep out.
303
  if (i != parts.size() - 1) {
41 ✔
304
    return std::nullopt;
6 ✔
305
  }
306
  wsl.command = parts.at(i);
35 ✔
307
  return wsl;
308
}
42 ✔
309

310
auto Executor::wslExecArgs(const QString &command, const QStringList &args)
2 ✔
311
    -> QStringList {
312
  return WslCommand{QStringLiteral("wsl"), {}, command}.argv(args);
2 ✔
313
}
314

315
auto Executor::translatePathForWsl(const QString &path, const QString &exe)
1,147 ✔
316
    -> QString {
317
  QString normalizedPath = QDir::cleanPath(path);
1,147 ✔
318
  const auto wsl = parseWslCommand(exe);
1,147 ✔
319
  if (!wsl) {
1,147 ✔
320
    return normalizedPath;
1,143 ✔
321
  }
322
  QString wslPath;
4 ✔
323
  const auto wslpath = wsl->with(QStringLiteral("wslpath"));
8 ✔
324
  const int rc = executeBlocking(wslpath.launcher,
4 ✔
325
                                 wslpath.argv({normalizedPath}), &wslPath);
12 ✔
326
  // Only the line end wslpath prints: white space at the end of the path is
327
  // the name's own ("team " beside "team", a folder named " "), and trimmed
328
  // it made git remove or move the neighbour, or the whole store.
329
  QString translated = wslPath;
330
  if (translated.endsWith(QLatin1Char('\n'))) {
4 ✔
331
    translated.chop(1);
4 ✔
332
  }
333
  if (translated.endsWith(QLatin1Char('\r'))) {
4 ✔
334
    translated.chop(1);
×
335
  }
336
  return (rc == 0 && !translated.isEmpty()) ? translated : normalizedPath;
4 ✔
337
}
4 ✔
338

339
void Executor::executeNext() {
868 ✔
340
  if (running || m_execQueue.isEmpty()) {
868 ✔
341
    return;
447 ✔
342
  }
343
  // A copy, and marked running, before anyone hears of it: a slot on
344
  // dequeuing() that queues more cannot invalidate it or start it a second
345
  // time, and one that calls cancelNext() cannot drop it.
346
  const ExecQueueItem i = m_execQueue.head();
431 ✔
347
  running = true;
431 ✔
348
  emit dequeuing(i.id, true);
431 ✔
349

350
  // An empty executable never emits finished(); dropping it wedged the queue
351
  // (#1682). Fail it like a failed-to-start process so the queue drains.
352
  if (i.app.isEmpty()) {
431 ✔
353
    qCDebug(lcQtPass) << "No executable set for:" << i.id;
5 ✔
354
    const int failedId = i.id;
5 ✔
355
    running = false;
5 ✔
356
    m_execQueue.dequeue();
5 ✔
357
    ++m_pendingErrors;
5 ✔
358
    QMetaObject::invokeMethod(
5 ✔
359
        this,
360
        [this, failedId]() {
5 ✔
361
          emit error(failedId, -1, QString(),
10 ✔
362
                     tr("No executable configured for this command"));
5 ✔
363
          --m_pendingErrors;
5 ✔
364
          postDrainedIfIdle();
5 ✔
365
        },
5 ✔
366
        Qt::QueuedConnection);
367
    executeNext();
5 ✔
368
    return;
369
  }
370

371
  // Always set it: an item without a directory runs in the application's
372
  // cwd, not wherever the previous item happened to run.
373
  m_process.setWorkingDirectory(i.workingDir);
426 ✔
374
  m_stderr.clear();
426 ✔
375
  m_discardStdout = !i.readStdout;
426 ✔
376
  startProcess(m_process, i.app, i.args);
426 ✔
377

378
  // A failed start never emits finished(), so `running` would stall the queue
379
  // and waiters (the keygen dialog) would hang. The emit is queued so it does
380
  // not re-enter KeygenDialog::done(), still on the stack; -1 goes through
381
  // Pass::finished's non-zero error gate.
382
  if (!m_process.waitForStarted(-1)) {
426 ✔
383
    qCDebug(lcQtPass) << "Process failed to start:" << i.id << " " << i.app;
5 ✔
384
    const int failedId = i.id;
5 ✔
385
    const QString failedApp = i.app;
386
    m_process.closeWriteChannel();
5 ✔
387
    running = false;
5 ✔
388
    m_execQueue.dequeue();
5 ✔
389
    ++m_pendingErrors;
5 ✔
390
    QMetaObject::invokeMethod(
5 ✔
391
        this,
392
        [this, failedId, failedApp]() {
10 ✔
393
          emit error(failedId, -1, QString(),
15 ✔
394
                     tr("Failed to start %1").arg(failedApp));
10 ✔
395
          --m_pendingErrors;
5 ✔
396
          postDrainedIfIdle();
5 ✔
397
        },
5 ✔
398
        Qt::QueuedConnection);
399
    executeNext();
5 ✔
400
    return;
401
  }
402

403
  if (!i.input.isEmpty()) {
421 ✔
404
    QByteArray data = i.input.toUtf8();
405
    if (m_process.write(data) != data.length()) {
110 ✔
406
      qCDebug(lcQtPass) << "Not all data written to process:" << i.id << " "
×
407
                        << i.app;
×
408
    }
409
  }
410
  m_process.closeWriteChannel();
421 ✔
411
}
431 ✔
412

413
void Executor::execute(int id, const QString &app, const QStringList &args,
87 ✔
414
                       bool readStdout, bool readStderr) {
415
  execute(id, QString(), app, args, QString(), readStdout, readStderr);
174 ✔
416
}
87 ✔
417

418
void Executor::execute(int id, const QString &workDir, const QString &app,
2 ✔
419
                       const QStringList &args, bool readStdout,
420
                       bool readStderr) {
421
  execute(id, workDir, app, args, QString(), readStdout, readStderr);
2 ✔
422
}
2 ✔
423

424
void Executor::execute(int id, const QString &app, const QStringList &args,
1 ✔
425
                       QString input, bool readStdout, bool readStderr) {
426
  execute(id, QString(), app, args, std::move(input), readStdout, readStderr);
2 ✔
427
}
1 ✔
428

429
void Executor::execute(int id, const QString &workDir, const QString &app,
444 ✔
430
                       const QStringList &args, QString input, bool readStdout,
431
                       bool readStderr) {
432
  // Queue even an empty executable: executeNext() reports it (#1682).
433
  // startProcess resolves the executable, as on the blocking path.
434
  m_execQueue.push_back(
444 ✔
435
      {id, app, args, std::move(input), readStdout, readStderr, workDir});
436
  executeNext();
444 ✔
437
}
1,332 ✔
438

439
// UTF-8 first; on a decoding error fall back to the system encoding.
440
// lossless, when given, says whether the text encodes back to exactly these
441
// bytes: what writing it to gpg or pass (toUtf8(), as every writer here
442
// does) would store. Not for bytes that are not UTF-8 (each became U+FFFD,
443
// or on Windows a code-page character), nor for a leading byte order mark,
444
// which the decoder drops without an error. A literal U+FFFD, as older
445
// QtPass versions left in such entries, does encode back.
446
static auto decodeAssumingUtf8(const QByteArray &in, bool *lossless = nullptr)
2,457 ✔
447
    -> QString {
448
  // Stateless: a truncated trailing byte becomes a replacement character
449
  // instead of being held back for a continuation that never comes.
450
  auto converter =
2,457 ✔
451
      QStringDecoder(QStringDecoder::Utf8, QStringDecoder::Flag::Stateless);
452
  QString out = converter(in);
2,457 ✔
453
  if (converter.hasError()) {
2,457 ✔
454
    auto fallback =
4 ✔
455
        QStringDecoder(QStringDecoder::System, QStringDecoder::Flag::Stateless);
456
    out = fallback(in);
8 ✔
457
  }
458
  if (lossless != nullptr) {
2,457 ✔
459
    *lossless = out.toUtf8() == in;
362 ✔
460
  }
461
  return out;
2,457 ✔
462
}
463

464
auto Executor::decodeText(const QByteArray &bytes) -> QString {
432 ✔
465
  return decodeAssumingUtf8(bytes);
432 ✔
466
}
467

468
// Returns an error code rather than throwing, matching QtPass's error
469
// handling elsewhere.
470
namespace {
471

472
#ifdef Q_OS_UNIX
473
/**
474
 * @brief Wait up to @p ms for every process in group @p group to exit.
475
 * @param group A process group id; the child's own pid, as it leads a
476
 *        session of its own (Executor::detachFromTerminal()).
477
 * @param ms Most milliseconds to wait.
478
 * @return true once the group is empty.
479
 */
480
auto waitForGroup(pid_t group, int ms) -> bool {
18 ✔
481
  QDeadlineTimer deadline(ms);
18 ✔
482
  // kill(-group, 0) fails with ESRCH once no process is left in it; while
483
  // one is, no new process can be given that id.
484
  while (::kill(-group, 0) == 0) {
25 ✔
485
    if (deadline.hasExpired()) {
7 ✔
486
      return false;
487
    }
488
    QThread::msleep(10);
7 ✔
489
  }
490
  return true;
491
}
492
#endif
493

494
/**
495
 * @brief Stop a running @p process from the thread that owns it:
496
 * terminate(), then kill() if it is still running after a grace period,
497
 * then at most one more grace period for it to exit.
498
 * A console gpg ignores terminate() on Windows (WM_CLOSE), hence the kill.
499
 *
500
 * On Unix the whole process group gets the signals and is waited for: pass
501
 * is a shell script, and the git it runs would otherwise go on pulling into
502
 * the store after the run was reported stopped.
503
 */
504
void stopBlocking(QProcess &process) {
18 ✔
505
#ifdef Q_OS_UNIX
506
  const auto group = static_cast<pid_t>(process.processId());
18 ✔
507
  const auto signalGroup = [group](int signal) {
21 ✔
508
    if (group > 0) {
21 ✔
509
      ::kill(-group, signal);
21 ✔
510
    }
511
  };
39 ✔
512
  signalGroup(SIGTERM);
18 ✔
513
#endif
514
  process.terminate();
18 ✔
515
  if (!process.waitForFinished(kBlockingKillGraceMs)) {
18 ✔
516
#ifdef Q_OS_UNIX
517
    signalGroup(SIGKILL);
3 ✔
518
#endif
519
    process.kill();
3 ✔
520
    // SIGKILL cannot be ignored, but a child in uninterruptible sleep (a
521
    // hung NFS or FUSE mount) dies only when the kernel lets it. Wait one
522
    // more grace period, not forever: the run is reported as failed either
523
    // way, and a blocking run then lasts at most its timeout plus twice the
524
    // grace.
525
    if (!process.waitForFinished(kBlockingKillGraceMs)) {
3 ✔
526
      qCWarning(lcQtPass) << "Process still running after kill():"
×
527
                          << process.program();
×
528
    }
529
  }
530
#ifdef Q_OS_UNIX
531
  if (group > 0 && !waitForGroup(group, kBlockingKillGraceMs)) {
18 ✔
532
    signalGroup(SIGKILL);
×
533
    if (!waitForGroup(group, kBlockingKillGraceMs)) {
×
534
      qCWarning(lcQtPass) << "Processes started by" << process.program()
×
535
                          << "still running after kill()";
×
536
    }
537
  }
538
#endif
539
}
18 ✔
540

541
/**
542
 * @brief What is left of @p deadline, as QProcess's wait functions take it:
543
 * -1 for none.
544
 */
545
auto msecsLeft(const QDeadlineTimer &deadline) -> int {
3,105 ✔
546
  if (deadline.isForever()) {
3,105 ✔
547
    return -1;
548
  }
549
  return static_cast<int>(
550
      std::clamp<qint64>(deadline.remainingTime(), 0, INT_MAX));
146 ✔
551
}
552

553
/**
554
 * @brief Wait for @p process to finish, stopping it when @p cancel is set
555
 * or @p deadline passes.
556
 *
557
 * Polls the flag; every QProcess call, terminate()/kill() included, stays on
558
 * this thread, so another thread can never act on an exited process (or a
559
 * pid the OS has since reused).
560
 * @return false when it was cancelled or ran out of time.
561
 */
562
auto waitOrCancel(QProcess &process, const std::atomic_bool *cancel,
1,833 ✔
563
                  const QDeadlineTimer &deadline) -> bool {
564
  if (cancel == nullptr) {
1,833 ✔
565
    // waitForFinished() can also fail (a poll error) with the child still
566
    // running; that is not completion either. Stop it rather than report
567
    // it done.
568
    if (!process.waitForFinished(msecsLeft(deadline)) &&
1,220 ✔
569
        process.state() != QProcess::NotRunning) {
6 ✔
570
      stopBlocking(process);
6 ✔
571
      return false;
6 ✔
572
    }
573
    return true;
1,208 ✔
574
  }
575
  while (!process.waitForFinished(
1,308 ✔
576
      deadline.isForever()
577
          ? kBlockingCancelPollMs
578
          : qMin(kBlockingCancelPollMs, msecsLeft(deadline)))) {
3 ✔
579
    if (process.state() == QProcess::NotRunning) {
47 ✔
580
      return true;
581
    }
582
    if (cancel->load() || deadline.hasExpired()) {
59 ✔
583
      stopBlocking(process);
12 ✔
584
      return false;
12 ✔
585
    }
586
  }
587
  return true;
588
}
589

590
} // namespace
591

592
auto Executor::runBlocking(QProcess &process, const QString &app,
1,192 ✔
593
                           const QStringList &args, const QString &input,
594
                           QString *process_out, QString *process_err,
595
                           const std::atomic_bool *cancel, int timeoutMs)
596
    -> int {
597
  QByteArray out;
1,192 ✔
598
  const int rc = runBlockingRaw(process, app, args, input.toUtf8(),
2,384 ✔
599
                                process_out != nullptr ? &out : nullptr,
600
                                process_err, cancel, timeoutMs);
601
  if (process_out != nullptr) {
1,192 ✔
602
    *process_out = decodeAssumingUtf8(out);
2,074 ✔
603
  }
604
  return rc;
1,192 ✔
605
}
606

607
auto Executor::runBlockingRaw(QProcess &process, const QString &app,
1,896 ✔
608
                              const QStringList &args, const QByteArray &input,
609
                              QByteArray *process_out, QString *process_err,
610
                              const std::atomic_bool *cancel, int timeoutMs)
611
    -> int {
612
  if (cancel != nullptr && cancel->load())
1,896 ✔
613
    return -1;
614
  const QDeadlineTimer deadline = timeoutMs < 0
615
                                      ? QDeadlineTimer(QDeadlineTimer::Forever)
1,888 ✔
616
                                      : QDeadlineTimer(timeoutMs);
1,888 ✔
617
  // Read as it arrives (QProcess emits these from inside its waitFor*()
618
  // calls too), so neither channel piles up in QProcess's buffers: stderr
619
  // into the cap, stdout nobody asked for into nothing. Wanted stdout is
620
  // kept whole, as a decrypt must be lossless; gpg's --max-output bounds it.
621
  CappedOutput err;
1,888 ✔
622
  const QMetaObject::Connection errReader = QObject::connect(
623
      &process, &QProcess::readyReadStandardError,
624
      [&process, &err]() { err.append(process.readAllStandardError()); });
5,704 ✔
625
  const QMetaObject::Connection outDropper =
626
      process_out != nullptr
627
          ? QMetaObject::Connection()
1,888 ✔
628
          : QObject::connect(&process, &QProcess::readyReadStandardOutput,
629
                             [&process]() { process.readAllStandardOutput(); });
2,100 ✔
630
  const auto disconnectReaders = qScopeGuard([&errReader, &outDropper]() {
1,888 ✔
631
    QObject::disconnect(errReader);
1,888 ✔
632
    QObject::disconnect(outDropper);
1,888 ✔
633
  });
1,888 ✔
634
  startProcess(process, app, args);
1,888 ✔
635
  if (!process.waitForStarted(msecsLeft(deadline))) {
1,888 ✔
636
    qCDebug(lcQtPass) << "Process failed to start:" << app;
55 ✔
637
    if (process.state() != QProcess::NotRunning) {
55 ✔
638
      stopBlocking(process);
×
639
    }
640
    return -1;
55 ✔
641
  }
642
  if (!input.isEmpty()) {
1,833 ✔
643
    if (process.write(input) != input.length()) {
764 ✔
644
      qCDebug(lcQtPass) << "Not all input written:" << app;
×
645
    }
646
  }
647
  // Always close stdin so a child blocking on EOF doesn't hang.
648
  process.closeWriteChannel();
1,833 ✔
649
  if (!waitOrCancel(process, cancel, deadline)) {
1,833 ✔
650
    return -1;
651
  }
652
  // Read before judging the exit: a process that crashed may have said why,
653
  // as the queued path (onProcessFinished) keeps it too.
654
  if (process_out != nullptr) {
1,815 ✔
655
    *process_out = process.readAllStandardOutput();
3,180 ✔
656
  }
657
  if (process_err != nullptr) {
1,815 ✔
658
    err.append(process.readAllStandardError());
281 ✔
659
    *process_err = decodeAssumingUtf8(err.take());
562 ✔
660
  }
661
  return process.exitStatus() == QProcess::NormalExit ? process.exitCode() : -1;
1,815 ✔
662
}
1,888 ✔
663

664
auto Executor::executeBlockingRaw(QProcess &process, const QString &app,
704 ✔
665
                                  const QStringList &args,
666
                                  const QByteArray &input,
667
                                  QByteArray *process_out, QString *process_err,
668
                                  const std::atomic_bool *cancel, int timeoutMs)
669
    -> int {
670
  return runBlockingRaw(process, app, args, input, process_out, process_err,
704 ✔
671
                        cancel, timeoutMs);
704 ✔
672
}
673

674
auto Executor::executeBlocking(const QString &app, const QStringList &args,
302 ✔
675
                               const QString &input, QString *process_out,
676
                               QString *process_err) -> int {
677
  QProcess internal;
302 ✔
678
  return runBlocking(internal, app, args, input, process_out, process_err);
604 ✔
679
}
302 ✔
680

681
auto Executor::executeBlocking(QProcess &process, const QString &app,
854 ✔
682
                               const QStringList &args, const QString &input,
683
                               QString *process_out, QString *process_err,
684
                               const std::atomic_bool *cancel, int timeoutMs)
685
    -> int {
686
  return runBlocking(process, app, args, input, process_out, process_err,
854 ✔
687
                     cancel, timeoutMs);
854 ✔
688
}
689

690
auto Executor::executeBlocking(const QString &app, const QStringList &args,
270 ✔
691
                               QString *process_out, QString *process_err)
692
    -> int {
693
  return executeBlocking(app, args, QString(), process_out, process_err);
540 ✔
694
}
695

696
auto Executor::executeBlocking(const QProcessEnvironment &env,
36 ✔
697
                               const QString &app, const QStringList &args,
698
                               QString *process_out, QString *process_err)
699
    -> int {
700
  QProcess process;
36 ✔
701
  process.setProcessEnvironment(env);
36 ✔
702
  return runBlocking(process, app, args, QString(), process_out, process_err);
72 ✔
703
}
36 ✔
704

705
void Executor::setEnvironment(const QProcessEnvironment &env) {
831 ✔
706
  m_process.setProcessEnvironment(env);
831 ✔
707
}
831 ✔
708

709
auto Executor::environment() const -> QProcessEnvironment {
132 ✔
710
  return m_process.processEnvironment();
132 ✔
711
}
712

713
// Also -1 while the head is already running: that one is not cancelled.
714
auto Executor::cancelNext() -> int {
15 ✔
715
  if (running || m_execQueue.isEmpty()) {
15 ✔
716
    return -1;
717
  }
718
  const int id = m_execQueue.dequeue().id;
11 ✔
719
  // As in executeNext(): while the signal is out, a slot's cancelNext()
720
  // drops nothing and its execute() only queues. Nothing is started here
721
  // afterwards: the caller (ImitatePass dropping the rest of a failed
722
  // transaction from its completion handler) may cancel again, and the
723
  // queue moves on when that handler returns (onProcessFinished()).
724
  running = true;
11 ✔
725
  emit dequeuing(id, false);
11 ✔
726
  running = false;
11 ✔
727
  return id;
11 ✔
728
}
729

730
void Executor::onProcessFinished(int exitCode,
414 ✔
731
                                 QProcess::ExitStatus exitStatus) {
732
  ExecQueueItem i = m_execQueue.dequeue();
733
  running = false;
414 ✔
734
  auto [output, err] = collectOutput(i, exitCode);
414 ✔
735
  if (exitStatus == QProcess::NormalExit) {
414 ✔
736
    if (exitCode != 0) {
413 ✔
737
      qCDebug(lcQtPass) << i.app << "exited with" << exitCode << err;
48 ✔
738
    }
739
    emit finished(i.id, exitCode, output, err);
413 ✔
740
    m_outputLossless = true;
413 ✔
741
    m_lastStatus.clear();
413 ✔
742
  } else {
743
    // A signal-killed process usually leaves stderr empty; without this the
744
    // password pane would show nothing at all for the failure.
745
    if (err.trimmed().isEmpty()) {
1 ✔
746
      err = tr("%1 crashed or was killed").arg(i.app);
2 ✔
747
    }
748
    // Qt leaves exitCode undefined after a CrashExit (the signal number on
749
    // Unix), and Pass::finished gates on it: 0 would pass as success and 1
750
    // as grep's "no matches". Report -1, like the failed-to-start path.
751
    emit error(i.id, -1, output, err);
1 ✔
752
    m_outputLossless = true;
1 ✔
753
    m_lastStatus.clear();
1 ✔
754
  }
755
  executeNext();
414 ✔
756
  postDrainedIfIdle();
414 ✔
757
}
414 ✔
758

759
void Executor::postDrainedIfIdle() {
424 ✔
760
  // One check at a time, run after what is emitted now; it fires only once
761
  // nothing runs or waits and every posted error() of a failed start is
762
  // out (the last of those posts the check again).
763
  if (m_drainCheckPosted) {
424 ✔
764
    return;
765
  }
766
  m_drainCheckPosted = true;
420 ✔
767
  QMetaObject::invokeMethod(
420 ✔
768
      this,
769
      [this]() {
420 ✔
770
        m_drainCheckPosted = false;
363 ✔
771
        if (isIdle() && m_pendingErrors == 0) {
158 ✔
772
          emit drained();
158 ✔
773
        }
774
      },
363 ✔
775
      Qt::QueuedConnection);
776
}
777

778
auto Executor::collectOutput(const ExecQueueItem &item, int exitCode)
414 ✔
779
    -> std::pair<QString, QString> {
780
  QString output;
414 ✔
781
  QString err;
414 ✔
782
  m_outputLossless = true;
414 ✔
783
  if (item.readStdout) {
414 ✔
784
    output = decodeAssumingUtf8(m_process.readAllStandardOutput(),
724 ✔
785
                                &m_outputLossless);
786
  }
787
  m_stderr.append(m_process.readAllStandardError());
414 ✔
788
  const QByteArray errBytes = m_stderr.take();
414 ✔
789
  m_lastStatus = m_stderr.statusCounts();
414 ✔
790
  if (item.readStderr || exitCode != 0) {
414 ✔
791
    err = decodeAssumingUtf8(errBytes);
690 ✔
792
  }
793
  return {output, err};
414 ✔
794
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc