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

IJHack / QtPass / 44942146864

21 Nov 2026 07:40PM UTC coverage: 94.705% (+0.007%) from 94.698%
44942146864

push

github

web-flow
Pull before edit: stop after 30 seconds (#2296)

* Pull before edit: stop after 30 seconds

With automatic pull on, editPassword() runs GitPull_b() on the GUI thread,
and both backends waited for git without a deadline. A remote that never
answered froze the window, and with it the panel and clipboard autoclear
timers, until git gave up, which it may never do.

GitPull_b() takes a deadline; the window passes Pass::kBlockingPullMs
(30 s). Past it git is stopped, and the status bar says the pull did not
finish and that the entry is edited as it is here.

Scan finding ANT-2026-OVSRX5SC.

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

* Executor: stop a blocking run's whole process group

stopBlocking() signalled only the process QtPass started. pass is a shell
script: at the pull's deadline the script stopped, and the git it ran went
on pulling into the store while the entry was being edited.

Each child already leads a session and process group of its own (setsid,
detachFromTerminal()). On Unix, send SIGTERM and SIGKILL to the group too,
and wait for the group to empty before returning; a group id cannot be
reused while a process is left in it. This holds for every blocking run
that is stopped, cancelled or timed out.

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

---------

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

38 of 44 new or added lines in 5 files covered. (86.36%)

9533 of 10066 relevant lines covered (94.7%)

2533.31 hits per line

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

95.91
/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 <QStringDecoder>
9
#include <QThread>
10
#include <algorithm>
11
#include <climits>
12
#include <utility>
13

14
#include "qtpasslogging.h"
15

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

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

31
Executor::Executor(QObject *parent) : QObject(parent) {
446 ✔
32
  connect(&m_process, &QProcess::finished, this, &Executor::onProcessFinished);
446 ✔
33
  connect(&m_process, &QProcess::started, this, &Executor::starting);
446 ✔
34
}
446 ✔
35

36
Executor::~Executor() { m_process.blockSignals(true); }
893 ✔
37

38
void Executor::detachFromTerminal(QProcess &process) {
2,292 ✔
39
#if defined(Q_OS_UNIX) && QT_VERSION >= QT_VERSION_CHECK(6, 7, 0)
40
  // A child inherits QtPass's controlling terminal when QtPass was started
41
  // from one. git (HTTPS credentials) and ssh (key passphrase, host key) then
42
  // prompt on that /dev/tty, and as the queue runs one command at a time,
43
  // every decrypt and save waits behind a prompt nobody sees: QtPass looks
44
  // frozen. In a session of its own the child has no terminal, so git and
45
  // ssh use SSH_ASKPASS/GIT_ASKPASS when set and otherwise fail with an
46
  // error QtPass shows. GIT_TERMINAL_PROMPT=0 is not set on top: without a
47
  // tty git has nothing to prompt on, and some credential helpers read it as
48
  // "no interaction at all" and would skip their own dialogs.
49
  //
50
  // gpg is unaffected: pinentry is started by gpg-agent, which finds the
51
  // terminal through GPG_TTY (set by the user's shell) or the tty on gpg's
52
  // stdin, here always a pipe. pass is a shell script running that gpg and
53
  // git, so the same holds for it.
54
  //
55
  // Signal dispositions are left alone (no ResetSignalHandlers): exec()
56
  // already resets caught signals, and QtPass sets no SIG_IGN of its own, so
57
  // that flag would only undo what QtPass's own parent chose (nohup, say).
58
  // Terminal signals (Ctrl+C, the SIGHUP of a closed terminal) now reach
59
  // QtPass but not the child; the children are short-lived and, with no
60
  // terminal, cannot sit waiting for input.
61
  QProcess::UnixProcessParameters params = process.unixProcessParameters();
2,292 ✔
62
  params.flags |= QProcess::UnixProcessFlag::CreateNewSession;
63
  process.setUnixProcessParameters(params);
2,292 ✔
64
#else
65
  Q_UNUSED(process);
66
#endif
67
}
2,292 ✔
68

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

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

73
void Executor::startProcess(QProcess &process, const QString &app,
2,286 ✔
74
                            const QStringList &args) {
75
  detachFromTerminal(process);
2,286 ✔
76
#ifdef Q_OS_UNIX
77
  // In the child, between fork and exec: umask() is async-signal-safe.
78
  if (const int mask = g_childUmask.load(); mask >= 0) {
2,286 ✔
79
    process.setChildProcessModifier(
1 ✔
80
        [mask] { ::umask(static_cast<mode_t>(mask)); });
1 ✔
81
  }
82
#endif
83
  if (const auto wsl = parseWslCommand(app)) {
2,286 ✔
84
    process.start(wsl->launcher, wsl->argv(args));
18 ✔
85
  } else {
86
    process.start(resolveExecutable(app), args);
4,554 ✔
87
  }
88
}
2,286 ✔
89

90
auto Executor::resolveExecutable(const QString &app) -> QString {
2,283 ✔
91
  if (app.isEmpty() || QDir::isAbsolutePath(app)) {
4,565 ✔
92
    return app;
93
  }
94
  const QDir appDir(QCoreApplication::applicationDirPath());
65 ✔
95
  QStringList candidates{QDir::cleanPath(appDir.absoluteFilePath(app))};
260 ✔
96
#ifdef Q_OS_WIN
97
  candidates << QDir::cleanPath(
98
      appDir.absoluteFilePath(app + QStringLiteral(".exe")));
99
#endif
100
  for (const QString &candidate : std::as_const(candidates)) {
127 ✔
101
    // A stray non-executable file of that name must not mask PATH.
102
    const QFileInfo info(candidate);
65 ✔
103
    if (info.isFile() && info.isExecutable()) {
65 ✔
104
      return candidate;
105
    }
106
  }
65 ✔
107
  return app;
108
}
130 ✔
109

110
auto Executor::WslCommand::argv(const QStringList &args) const -> QStringList {
35 ✔
111
  return options + QStringList{QStringLiteral("--exec"), command} + args;
140 ✔
112
}
113

114
auto Executor::WslCommand::with(const QString &program) const -> WslCommand {
12 ✔
115
  return {launcher, options, program};
12 ✔
116
}
117

118
auto Executor::parseWslCommand(const QString &app)
4,305 ✔
119
    -> std::optional<WslCommand> {
120
  const QStringList parts = QProcess::splitCommand(app);
4,305 ✔
121
  if (parts.size() < 2) {
4,305 ✔
122
    return std::nullopt;
4,260 ✔
123
  }
124
  // The file name after the last separator of either kind: a Windows path
125
  // has to be recognised as such wherever the parser runs.
126
  const QString &launcher = parts.first();
127
  const qsizetype separator = std::max(launcher.lastIndexOf(QLatin1Char('/')),
45 ✔
128
                                       launcher.lastIndexOf(QLatin1Char('\\')));
45 ✔
129
  const QString launcherName = launcher.mid(separator + 1);
45 ✔
130
  const bool isWsl =
131
      launcherName.compare(QLatin1String("wsl"), Qt::CaseInsensitive) == 0 ||
58 ✔
132
      launcherName.compare(QLatin1String("wsl.exe"), Qt::CaseInsensitive) == 0;
13 ✔
133
  if (!isWsl) {
134
    return std::nullopt;
3 ✔
135
  }
136
  WslCommand wsl;
42 ✔
137
#ifdef Q_OS_WIN
138
  // A bare wsl or wsl.exe in any case is looked up on PATH as `wsl`; a path
139
  // stays as is.
140
  wsl.launcher = separator < 0 ? QStringLiteral("wsl") : launcher;
141
#else
142
  // QtPass running inside WSL reaches wsl.exe through interop under exactly
143
  // that name; nothing says `wsl` resolves too, so start what was written.
144
  wsl.launcher = launcher;
42 ✔
145
#endif
146
  // wsl.exe options that take a value; anything else starting with `-` is a
147
  // flag. A user-written -e/--exec is dropped, argv() always adds one.
148
  static const QStringList valued{
149
      QStringLiteral("-d"),   QStringLiteral("--distribution"),
2 ✔
150
      QStringLiteral("-u"),   QStringLiteral("--user"),
2 ✔
151
      QStringLiteral("--cd"), QStringLiteral("--shell-type")};
56 ✔
152
  qsizetype i = 1;
153
  for (; i < parts.size() && parts.at(i).startsWith(QLatin1Char('-')); ++i) {
59 ✔
154
    const QString &option = parts.at(i);
155
    if (option == QLatin1String("-e") || option == QLatin1String("--exec")) {
18 ✔
156
      continue;
7 ✔
157
    }
158
    if (valued.contains(option)) {
11 ✔
159
      if (i + 1 >= parts.size()) {
11 ✔
160
        return std::nullopt;
1 ✔
161
      }
162
      wsl.options << option << parts.at(++i);
163
    } else {
164
      wsl.options << option;
165
    }
166
  }
167
  // Exactly one program. More is a shell command line (`sh -c "..."`),
168
  // which is what --exec exists to keep out.
169
  if (i != parts.size() - 1) {
41 ✔
170
    return std::nullopt;
6 ✔
171
  }
172
  wsl.command = parts.at(i);
35 ✔
173
  return wsl;
174
}
42 ✔
175

176
auto Executor::wslExecArgs(const QString &command, const QStringList &args)
2 ✔
177
    -> QStringList {
178
  return WslCommand{QStringLiteral("wsl"), {}, command}.argv(args);
2 ✔
179
}
180

181
auto Executor::translatePathForWsl(const QString &path, const QString &exe)
1,568 ✔
182
    -> QString {
183
  QString normalizedPath = QDir::cleanPath(path);
1,568 ✔
184
  const auto wsl = parseWslCommand(exe);
1,568 ✔
185
  if (!wsl) {
1,568 ✔
186
    return normalizedPath;
1,564 ✔
187
  }
188
  QString wslPath;
4 ✔
189
  const auto wslpath = wsl->with(QStringLiteral("wslpath"));
8 ✔
190
  const int rc = executeBlocking(wslpath.launcher,
4 ✔
191
                                 wslpath.argv({normalizedPath}), &wslPath);
12 ✔
192
  // Only the line end wslpath prints: white space at the end of the path is
193
  // the name's own ("team " beside "team", a folder named " "), and trimmed
194
  // it made git remove or move the neighbour, or the whole store.
195
  QString translated = wslPath;
196
  if (translated.endsWith(QLatin1Char('\n'))) {
4 ✔
197
    translated.chop(1);
4 ✔
198
  }
199
  if (translated.endsWith(QLatin1Char('\r'))) {
4 ✔
200
    translated.chop(1);
×
201
  }
202
  return (rc == 0 && !translated.isEmpty()) ? translated : normalizedPath;
4 ✔
203
}
4 ✔
204

205
void Executor::executeNext() {
835 ✔
206
  if (running || m_execQueue.isEmpty()) {
835 ✔
207
    return;
431 ✔
208
  }
209
  // A copy, and marked running, before anyone hears of it: a slot on
210
  // dequeuing() that queues more cannot invalidate it or start it a second
211
  // time, and one that calls cancelNext() cannot drop it.
212
  const ExecQueueItem i = m_execQueue.head();
414 ✔
213
  running = true;
414 ✔
214
  emit dequeuing(i.id, true);
414 ✔
215

216
  // An empty executable never emits finished(); dropping it wedged the queue
217
  // (#1682). Fail it like a failed-to-start process so the queue drains.
218
  if (i.app.isEmpty()) {
414 ✔
219
    qCDebug(lcQtPass) << "No executable set for:" << i.id;
5 ✔
220
    const int failedId = i.id;
5 ✔
221
    running = false;
5 ✔
222
    m_execQueue.dequeue();
5 ✔
223
    ++m_pendingErrors;
5 ✔
224
    QMetaObject::invokeMethod(
5 ✔
225
        this,
226
        [this, failedId]() {
5 ✔
227
          emit error(failedId, -1, QString(),
10 ✔
228
                     tr("No executable configured for this command"));
5 ✔
229
          --m_pendingErrors;
5 ✔
230
          postDrainedIfIdle();
5 ✔
231
        },
5 ✔
232
        Qt::QueuedConnection);
233
    executeNext();
5 ✔
234
    return;
235
  }
236

237
  // Always set it: an item without a directory runs in the application's
238
  // cwd, not wherever the previous item happened to run.
239
  m_process.setWorkingDirectory(i.workingDir);
409 ✔
240
  startProcess(m_process, i.app, i.args);
409 ✔
241

242
  // A failed start never emits finished(), so `running` would stall the queue
243
  // and waiters (the keygen dialog) would hang. The emit is queued so it does
244
  // not re-enter KeygenDialog::done(), still on the stack; -1 goes through
245
  // Pass::finished's non-zero error gate.
246
  if (!m_process.waitForStarted(-1)) {
409 ✔
247
    qCDebug(lcQtPass) << "Process failed to start:" << i.id << " " << i.app;
5 ✔
248
    const int failedId = i.id;
5 ✔
249
    const QString failedApp = i.app;
250
    m_process.closeWriteChannel();
5 ✔
251
    running = false;
5 ✔
252
    m_execQueue.dequeue();
5 ✔
253
    ++m_pendingErrors;
5 ✔
254
    QMetaObject::invokeMethod(
5 ✔
255
        this,
256
        [this, failedId, failedApp]() {
10 ✔
257
          emit error(failedId, -1, QString(),
15 ✔
258
                     tr("Failed to start %1").arg(failedApp));
10 ✔
259
          --m_pendingErrors;
5 ✔
260
          postDrainedIfIdle();
5 ✔
261
        },
5 ✔
262
        Qt::QueuedConnection);
263
    executeNext();
5 ✔
264
    return;
265
  }
266

267
  if (!i.input.isEmpty()) {
404 ✔
268
    QByteArray data = i.input.toUtf8();
269
    if (m_process.write(data) != data.length()) {
105 ✔
270
      qCDebug(lcQtPass) << "Not all data written to process:" << i.id << " "
×
271
                        << i.app;
×
272
    }
273
  }
274
  m_process.closeWriteChannel();
404 ✔
275
}
414 ✔
276

277
void Executor::execute(int id, const QString &app, const QStringList &args,
85 ✔
278
                       bool readStdout, bool readStderr) {
279
  execute(id, QString(), app, args, QString(), readStdout, readStderr);
170 ✔
280
}
85 ✔
281

282
void Executor::execute(int id, const QString &workDir, const QString &app,
2 ✔
283
                       const QStringList &args, bool readStdout,
284
                       bool readStderr) {
285
  execute(id, workDir, app, args, QString(), readStdout, readStderr);
2 ✔
286
}
2 ✔
287

288
void Executor::execute(int id, const QString &app, const QStringList &args,
1 ✔
289
                       QString input, bool readStdout, bool readStderr) {
290
  execute(id, QString(), app, args, std::move(input), readStdout, readStderr);
2 ✔
291
}
1 ✔
292

293
void Executor::execute(int id, const QString &workDir, const QString &app,
427 ✔
294
                       const QStringList &args, QString input, bool readStdout,
295
                       bool readStderr) {
296
  // Queue even an empty executable: executeNext() reports it (#1682).
297
  // startProcess resolves the executable, as on the blocking path.
298
  m_execQueue.push_back(
427 ✔
299
      {id, app, args, std::move(input), readStdout, readStderr, workDir});
300
  executeNext();
427 ✔
301
}
1,281 ✔
302

303
// UTF-8 first; on a decoding error fall back to the system encoding.
304
// lossless, when given, says whether the text encodes back to exactly these
305
// bytes: what writing it to gpg or pass (toUtf8(), as every writer here
306
// does) would store. Not for bytes that are not UTF-8 (each became U+FFFD,
307
// or on Windows a code-page character), nor for a leading byte order mark,
308
// which the decoder drops without an error. A literal U+FFFD, as older
309
// QtPass versions left in such entries, does encode back.
310
static auto decodeAssumingUtf8(const QByteArray &in, bool *lossless = nullptr)
2,379 ✔
311
    -> QString {
312
  // Stateless: a truncated trailing byte becomes a replacement character
313
  // instead of being held back for a continuation that never comes.
314
  auto converter =
2,379 ✔
315
      QStringDecoder(QStringDecoder::Utf8, QStringDecoder::Flag::Stateless);
316
  QString out = converter(in);
2,379 ✔
317
  if (converter.hasError()) {
2,379 ✔
318
    auto fallback =
4 ✔
319
        QStringDecoder(QStringDecoder::System, QStringDecoder::Flag::Stateless);
320
    out = fallback(in);
8 ✔
321
  }
322
  if (lossless != nullptr) {
2,379 ✔
323
    *lossless = out.toUtf8() == in;
348 ✔
324
  }
325
  return out;
2,379 ✔
326
}
327

328
// Returns an error code rather than throwing, matching QtPass's error
329
// handling elsewhere.
330
namespace {
331

332
#ifdef Q_OS_UNIX
333
/**
334
 * @brief Wait up to @p ms for every process in group @p group to exit.
335
 * @param group A process group id; the child's own pid, as it leads a
336
 *        session of its own (Executor::detachFromTerminal()).
337
 * @param ms Most milliseconds to wait.
338
 * @return true once the group is empty.
339
 */
340
auto waitForGroup(pid_t group, int ms) -> bool {
17 ✔
341
  QDeadlineTimer deadline(ms);
17 ✔
342
  // kill(-group, 0) fails with ESRCH once no process is left in it; while
343
  // one is, no new process can be given that id.
344
  while (::kill(-group, 0) == 0) {
23 ✔
345
    if (deadline.hasExpired()) {
6 ✔
346
      return false;
347
    }
348
    QThread::msleep(10);
6 ✔
349
  }
350
  return true;
351
}
352
#endif
353

354
/**
355
 * @brief Stop a running @p process from the thread that owns it:
356
 * terminate(), then kill() if it is still running after a grace period,
357
 * then at most one more grace period for it to exit.
358
 * A console gpg ignores terminate() on Windows (WM_CLOSE), hence the kill.
359
 *
360
 * On Unix the whole process group gets the signals and is waited for: pass
361
 * is a shell script, and the git it runs would otherwise go on pulling into
362
 * the store after the run was reported stopped.
363
 */
364
void stopBlocking(QProcess &process) {
17 ✔
365
#ifdef Q_OS_UNIX
366
  const auto group = static_cast<pid_t>(process.processId());
17 ✔
367
  const auto signalGroup = [group](int signal) {
20 ✔
368
    if (group > 0) {
20 ✔
369
      ::kill(-group, signal);
20 ✔
370
    }
371
  };
37 ✔
372
  signalGroup(SIGTERM);
17 ✔
373
#endif
374
  process.terminate();
17 ✔
375
  if (!process.waitForFinished(kBlockingKillGraceMs)) {
17 ✔
376
#ifdef Q_OS_UNIX
377
    signalGroup(SIGKILL);
3 ✔
378
#endif
379
    process.kill();
3 ✔
380
    // SIGKILL cannot be ignored, but a child in uninterruptible sleep (a
381
    // hung NFS or FUSE mount) dies only when the kernel lets it. Wait one
382
    // more grace period, not forever: the run is reported as failed either
383
    // way, and a blocking run then lasts at most its timeout plus twice the
384
    // grace.
385
    if (!process.waitForFinished(kBlockingKillGraceMs)) {
3 ✔
NEW
386
      qCWarning(lcQtPass) << "Process still running after kill():"
×
NEW
387
                          << process.program();
×
388
    }
389
  }
390
#ifdef Q_OS_UNIX
391
  if (group > 0 && !waitForGroup(group, kBlockingKillGraceMs)) {
17 ✔
NEW
392
    signalGroup(SIGKILL);
×
NEW
393
    if (!waitForGroup(group, kBlockingKillGraceMs)) {
×
NEW
394
      qCWarning(lcQtPass) << "Processes started by" << process.program()
×
NEW
395
                          << "still running after kill()";
×
396
    }
397
  }
398
#endif
399
}
17 ✔
400

401
/**
402
 * @brief What is left of @p deadline, as QProcess's wait functions take it:
403
 * -1 for none.
404
 */
405
auto msecsLeft(const QDeadlineTimer &deadline) -> int {
3,084 ✔
406
  if (deadline.isForever()) {
3,084 ✔
407
    return -1;
408
  }
409
  return static_cast<int>(
410
      std::clamp<qint64>(deadline.remainingTime(), 0, INT_MAX));
112 ✔
411
}
412

413
/**
414
 * @brief Wait for @p process to finish, stopping it when @p cancel is set
415
 * or @p deadline passes.
416
 *
417
 * Polls the flag; every QProcess call, terminate()/kill() included, stays on
418
 * this thread, so another thread can never act on an exited process (or a
419
 * pid the OS has since reused).
420
 * @return false when it was cancelled or ran out of time.
421
 */
422
auto waitOrCancel(QProcess &process, const std::atomic_bool *cancel,
1,821 ✔
423
                  const QDeadlineTimer &deadline) -> bool {
424
  if (cancel == nullptr) {
1,821 ✔
425
    // waitForFinished() can also fail (a poll error) with the child still
426
    // running; that is not completion either. Stop it rather than report
427
    // it done.
428
    if (!process.waitForFinished(msecsLeft(deadline)) &&
1,209 ✔
429
        process.state() != QProcess::NotRunning) {
5 ✔
430
      stopBlocking(process);
5 ✔
431
      return false;
5 ✔
432
    }
433
    return true;
1,199 ✔
434
  }
435
  while (!process.waitForFinished(
1,302 ✔
436
      deadline.isForever()
437
          ? kBlockingCancelPollMs
438
          : qMin(kBlockingCancelPollMs, msecsLeft(deadline)))) {
3 ✔
439
    if (process.state() == QProcess::NotRunning) {
46 ✔
440
      return true;
441
    }
442
    if (cancel->load() || deadline.hasExpired()) {
58 ✔
443
      stopBlocking(process);
12 ✔
444
      return false;
12 ✔
445
    }
446
  }
447
  return true;
448
}
449

450
} // namespace
451

452
auto Executor::runBlocking(QProcess &process, const QString &app,
1,615 ✔
453
                           const QStringList &args, const QString &input,
454
                           QString *process_out, QString *process_err,
455
                           const std::atomic_bool *cancel, int timeoutMs)
456
    -> int {
457
  QByteArray out;
1,615 ✔
458
  const int rc = runBlockingRaw(process, app, args, input.toUtf8(),
3,230 ✔
459
                                process_out != nullptr ? &out : nullptr,
460
                                process_err, cancel, timeoutMs);
461
  if (process_out != nullptr) {
1,615 ✔
462
    *process_out = decodeAssumingUtf8(out);
2,924 ✔
463
  }
464
  return rc;
1,615 ✔
465
}
466

467
auto Executor::runBlockingRaw(QProcess &process, const QString &app,
1,885 ✔
468
                              const QStringList &args, const QByteArray &input,
469
                              QByteArray *process_out, QString *process_err,
470
                              const std::atomic_bool *cancel, int timeoutMs)
471
    -> int {
472
  if (cancel != nullptr && cancel->load())
1,885 ✔
473
    return -1;
474
  const QDeadlineTimer deadline = timeoutMs < 0
475
                                      ? QDeadlineTimer(QDeadlineTimer::Forever)
1,877 ✔
476
                                      : QDeadlineTimer(timeoutMs);
1,877 ✔
477
  startProcess(process, app, args);
1,877 ✔
478
  if (!process.waitForStarted(msecsLeft(deadline))) {
1,877 ✔
479
    qCDebug(lcQtPass) << "Process failed to start:" << app;
56 ✔
480
    if (process.state() != QProcess::NotRunning) {
56 ✔
481
      stopBlocking(process);
×
482
    }
483
    return -1;
56 ✔
484
  }
485
  if (!input.isEmpty()) {
1,821 ✔
486
    if (process.write(input) != input.length()) {
319 ✔
487
      qCDebug(lcQtPass) << "Not all input written:" << app;
×
488
    }
489
  }
490
  // Always close stdin so a child blocking on EOF doesn't hang.
491
  process.closeWriteChannel();
1,821 ✔
492
  if (!waitOrCancel(process, cancel, deadline)) {
1,821 ✔
493
    return -1;
494
  }
495
  // Read before judging the exit: a process that crashed may have said why,
496
  // as the queued path (onProcessFinished) keeps it too.
497
  if (process_out != nullptr) {
1,804 ✔
498
    *process_out = process.readAllStandardOutput();
3,162 ✔
499
  }
500
  if (process_err != nullptr) {
1,804 ✔
501
    *process_err = decodeAssumingUtf8(process.readAllStandardError());
480 ✔
502
  }
503
  return process.exitStatus() == QProcess::NormalExit ? process.exitCode() : -1;
1,804 ✔
504
}
505

506
auto Executor::executeBlockingRaw(QProcess &process, const QString &app,
270 ✔
507
                                  const QStringList &args,
508
                                  const QByteArray &input,
509
                                  QByteArray *process_out, QString *process_err,
510
                                  const std::atomic_bool *cancel, int timeoutMs)
511
    -> int {
512
  return runBlockingRaw(process, app, args, input, process_out, process_err,
270 ✔
513
                        cancel, timeoutMs);
270 ✔
514
}
515

516
auto Executor::executeBlocking(const QString &app, const QStringList &args,
318 ✔
517
                               const QString &input, QString *process_out,
518
                               QString *process_err) -> int {
519
  QProcess internal;
318 ✔
520
  return runBlocking(internal, app, args, input, process_out, process_err);
636 ✔
521
}
318 ✔
522

523
auto Executor::executeBlocking(QProcess &process, const QString &app,
1,261 ✔
524
                               const QStringList &args, const QString &input,
525
                               QString *process_out, QString *process_err,
526
                               const std::atomic_bool *cancel, int timeoutMs)
527
    -> int {
528
  return runBlocking(process, app, args, input, process_out, process_err,
1,261 ✔
529
                     cancel, timeoutMs);
1,261 ✔
530
}
531

532
auto Executor::executeBlocking(const QString &app, const QStringList &args,
281 ✔
533
                               QString *process_out, QString *process_err)
534
    -> int {
535
  return executeBlocking(app, args, QString(), process_out, process_err);
562 ✔
536
}
537

538
auto Executor::executeBlocking(const QProcessEnvironment &env,
36 ✔
539
                               const QString &app, const QStringList &args,
540
                               QString *process_out, QString *process_err)
541
    -> int {
542
  QProcess process;
36 ✔
543
  process.setProcessEnvironment(env);
36 ✔
544
  return runBlocking(process, app, args, QString(), process_out, process_err);
72 ✔
545
}
36 ✔
546

547
void Executor::setEnvironment(const QProcessEnvironment &env) {
789 ✔
548
  m_process.setProcessEnvironment(env);
789 ✔
549
}
789 ✔
550

551
auto Executor::environment() const -> QProcessEnvironment {
127 ✔
552
  return m_process.processEnvironment();
127 ✔
553
}
554

555
// Also -1 while the head is already running: that one is not cancelled.
556
auto Executor::cancelNext() -> int {
15 ✔
557
  if (running || m_execQueue.isEmpty()) {
15 ✔
558
    return -1;
559
  }
560
  const int id = m_execQueue.dequeue().id;
11 ✔
561
  // As in executeNext(): while the signal is out, a slot's cancelNext()
562
  // drops nothing and its execute() only queues. Nothing is started here
563
  // afterwards: the caller (ImitatePass dropping the rest of a failed
564
  // transaction from its completion handler) may cancel again, and the
565
  // queue moves on when that handler returns (onProcessFinished()).
566
  running = true;
11 ✔
567
  emit dequeuing(id, false);
11 ✔
568
  running = false;
11 ✔
569
  return id;
11 ✔
570
}
571

572
void Executor::onProcessFinished(int exitCode,
398 ✔
573
                                 QProcess::ExitStatus exitStatus) {
574
  ExecQueueItem i = m_execQueue.dequeue();
575
  running = false;
398 ✔
576
  auto [output, err] = collectOutput(i, exitCode);
398 ✔
577
  if (exitStatus == QProcess::NormalExit) {
398 ✔
578
    if (exitCode != 0) {
397 ✔
579
      qCDebug(lcQtPass) << i.app << "exited with" << exitCode << err;
47 ✔
580
    }
581
    emit finished(i.id, exitCode, output, err);
397 ✔
582
    m_outputLossless = true;
397 ✔
583
  } else {
584
    // A signal-killed process usually leaves stderr empty; without this the
585
    // password pane would show nothing at all for the failure.
586
    if (err.trimmed().isEmpty()) {
1 ✔
587
      err = tr("%1 crashed or was killed").arg(i.app);
2 ✔
588
    }
589
    // Qt leaves exitCode undefined after a CrashExit (the signal number on
590
    // Unix), and Pass::finished gates on it: 0 would pass as success and 1
591
    // as grep's "no matches". Report -1, like the failed-to-start path.
592
    emit error(i.id, -1, output, err);
1 ✔
593
    m_outputLossless = true;
1 ✔
594
  }
595
  executeNext();
398 ✔
596
  postDrainedIfIdle();
398 ✔
597
}
398 ✔
598

599
void Executor::postDrainedIfIdle() {
408 ✔
600
  // One check at a time, run after what is emitted now; it fires only once
601
  // nothing runs or waits and every posted error() of a failed start is
602
  // out (the last of those posts the check again).
603
  if (m_drainCheckPosted) {
408 ✔
604
    return;
605
  }
606
  m_drainCheckPosted = true;
404 ✔
607
  QMetaObject::invokeMethod(
404 ✔
608
      this,
609
      [this]() {
404 ✔
610
        m_drainCheckPosted = false;
347 ✔
611
        if (isIdle() && m_pendingErrors == 0) {
144 ✔
612
          emit drained();
144 ✔
613
        }
614
      },
347 ✔
615
      Qt::QueuedConnection);
616
}
617

618
auto Executor::collectOutput(const ExecQueueItem &item, int exitCode)
398 ✔
619
    -> std::pair<QString, QString> {
620
  QString output;
398 ✔
621
  QString err;
398 ✔
622
  m_outputLossless = true;
398 ✔
623
  if (item.readStdout) {
398 ✔
624
    output = decodeAssumingUtf8(m_process.readAllStandardOutput(),
696 ✔
625
                                &m_outputLossless);
626
  }
627
  if (item.readStderr || exitCode != 0) {
398 ✔
628
    err = decodeAssumingUtf8(m_process.readAllStandardError());
658 ✔
629
  }
630
  return {output, err};
398 ✔
631
}
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