Skip to content

Commit de51657

Browse files
committed
Fix windows and linux child process lifetime protection
1 parent 200ffb3 commit de51657

7 files changed

Lines changed: 168 additions & 0 deletions

File tree

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
// SPDX-FileCopyrightText: Team OpenVPI
2+
// SPDX-License-Identifier: Apache-2.0
3+
4+
#include "ChildProcess.h"
5+
6+
#if defined(Q_OS_WIN)
7+
# include <cstddef>
8+
# include <memory>
9+
#elif defined(Q_OS_LINUX)
10+
# include <signal.h>
11+
# include <sys/prctl.h>
12+
# include <unistd.h>
13+
# include <cerrno>
14+
#endif
15+
16+
#include <QLoggingCategory>
17+
#include <QProcess>
18+
#include <QString>
19+
20+
#if defined(Q_OS_WIN)
21+
# include <qt_windows.h>
22+
#endif
23+
24+
namespace Core {
25+
26+
#if defined(Q_OS_WIN)
27+
Q_STATIC_LOGGING_CATEGORY(lcChildProcess, "diffscope.core.childprocess")
28+
29+
namespace {
30+
31+
struct ChildProcessJob {
32+
HANDLE m_handle{};
33+
STARTUPINFOEXW m_startupInfo{};
34+
std::unique_ptr<std::byte[]> m_attributeStorage;
35+
36+
~ChildProcessJob() {
37+
if (m_startupInfo.lpAttributeList)
38+
DeleteProcThreadAttributeList(m_startupInfo.lpAttributeList);
39+
if (m_handle)
40+
CloseHandle(m_handle);
41+
}
42+
};
43+
44+
bool reportWindowsError(const char *operation, QString *errorMessage) {
45+
const auto error = GetLastError();
46+
qCWarning(lcChildProcess) << operation << "failed with error" << error;
47+
if (errorMessage) {
48+
wchar_t buffer[1024]{};
49+
const auto length = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, error, 0, buffer, sizeof(buffer) / sizeof(buffer[0]), nullptr);
50+
const auto message = length ? QString::fromWCharArray(buffer, length).trimmed() : QString::number(error);
51+
*errorMessage = QString::fromLatin1(operation) + QStringLiteral(": ") + message;
52+
}
53+
return false;
54+
}
55+
56+
}
57+
#endif
58+
59+
bool configureChildProcess(QProcess *process, QString *errorMessage) {
60+
Q_ASSERT(process);
61+
Q_ASSERT(process->state() == QProcess::NotRunning);
62+
if (errorMessage)
63+
errorMessage->clear();
64+
#if defined(Q_OS_WIN)
65+
auto job = std::make_shared<ChildProcessJob>();
66+
job->m_handle = CreateJobObjectW(nullptr, nullptr);
67+
if (!job->m_handle)
68+
return reportWindowsError("CreateJobObjectW", errorMessage);
69+
70+
JOBOBJECT_EXTENDED_LIMIT_INFORMATION limits{};
71+
limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
72+
if (!SetInformationJobObject(job->m_handle, JobObjectExtendedLimitInformation, &limits, sizeof(limits)))
73+
return reportWindowsError("SetInformationJobObject", errorMessage);
74+
75+
SIZE_T attributeSize{};
76+
InitializeProcThreadAttributeList(nullptr, 1, 0, &attributeSize);
77+
if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
78+
return reportWindowsError("InitializeProcThreadAttributeList", errorMessage);
79+
job->m_attributeStorage = std::make_unique<std::byte[]>(attributeSize);
80+
auto attributes = reinterpret_cast<LPPROC_THREAD_ATTRIBUTE_LIST>(job->m_attributeStorage.get());
81+
if (!InitializeProcThreadAttributeList(attributes, 1, 0, &attributeSize))
82+
return reportWindowsError("InitializeProcThreadAttributeList", errorMessage);
83+
job->m_startupInfo.lpAttributeList = attributes;
84+
if (!UpdateProcThreadAttribute(attributes, 0, PROC_THREAD_ATTRIBUTE_JOB_LIST, &job->m_handle, sizeof(job->m_handle), nullptr, nullptr))
85+
return reportWindowsError("UpdateProcThreadAttribute", errorMessage);
86+
87+
process->setCreateProcessArgumentsModifier([job](QProcess::CreateProcessArguments *arguments) {
88+
job->m_startupInfo.StartupInfo = *arguments->startupInfo;
89+
job->m_startupInfo.StartupInfo.cb = sizeof(STARTUPINFOEXW);
90+
arguments->startupInfo = &job->m_startupInfo.StartupInfo;
91+
arguments->flags |= EXTENDED_STARTUPINFO_PRESENT;
92+
});
93+
#elif defined(Q_OS_LINUX)
94+
const auto parentPid = getpid();
95+
process->setChildProcessModifier([process, parentPid] {
96+
if (prctl(PR_SET_PDEATHSIG, static_cast<unsigned long>(SIGKILL), 0UL, 0UL, 0UL) == -1)
97+
process->failChildProcessModifier("prctl(PR_SET_PDEATHSIG)", errno);
98+
if (getppid() != parentPid)
99+
process->failChildProcessModifier("getppid", ESRCH);
100+
});
101+
#else
102+
Q_UNUSED(process)
103+
#endif
104+
return true;
105+
}
106+
107+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
// SPDX-FileCopyrightText: Team OpenVPI
2+
// SPDX-License-Identifier: Apache-2.0
3+
4+
#ifndef DIFFSCOPE_COREPLUGIN_CHILDPROCESS_H
5+
#define DIFFSCOPE_COREPLUGIN_CHILDPROCESS_H
6+
7+
#include <coreplugin/coreglobal.h>
8+
9+
class QProcess;
10+
class QString;
11+
12+
namespace Core {
13+
14+
// Configures a stopped process to terminate on parent exit on Windows and Linux. Returns whether configuration succeeded.
15+
// Replaces the platform-specific process modifier and retains Windows resources until reconfiguration or destruction.
16+
// Linux protection applies to the direct child and the lifetime of the thread that starts it.
17+
// Returns true without changes on other platforms. Reports configuration failures through errorMessage if provided.
18+
CORE_EXPORT bool configureChildProcess(QProcess *process, QString *errorMessage = nullptr);
19+
20+
}
21+
22+
#endif // DIFFSCOPE_COREPLUGIN_CHILDPROCESS_H

‎src/plugins/libresvipformatconverter/internal/LibreSVIPManager.cpp‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@
4949
#include <SVSCraftQuick/MessageBox.h>
5050

5151
#include <appinstall/InstallationManager.h>
52+
#include <coreplugin/ChildProcess.h>
5253
#include <coreplugin/CoreInterface.h>
5354
#include <coreplugin/NotificationMessage.h>
5455

@@ -521,6 +522,10 @@ namespace LibreSVIPFormatConverter::Internal {
521522

522523
stopProcess(true);
523524
m_process = new QProcess(this);
525+
if (!Core::configureChildProcess(m_process, &result.errorMessage)) {
526+
stopProcess(true);
527+
return result;
528+
}
524529
m_process->setProcessChannelMode(QProcess::MergedChannels);
525530
m_process->setWorkingDirectory(canonicalInfo.absolutePath());
526531
m_process->start(canonicalPath, {QStringLiteral("rpc"), QStringLiteral("server")});
@@ -817,6 +822,11 @@ namespace LibreSVIPFormatConverter::Internal {
817822

818823
stopProcess(true);
819824
m_process = new QProcess(this);
825+
if (!Core::configureChildProcess(m_process, &result.errorMessage)) {
826+
stopProcess(true);
827+
m_busy = false;
828+
return result;
829+
}
820830
m_process->setProcessChannelMode(QProcess::MergedChannels);
821831
m_process->setWorkingDirectory(QFileInfo(m_executablePath).absolutePath());
822832
m_process->start(m_executablePath, {QStringLiteral("rpc"), QStringLiteral("server")});

‎src/plugins/synth/internal/dssp/DsspDeviceCatalog.cpp‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@
1010
#include <QProcess>
1111
#include <QTimer>
1212

13+
#include <coreplugin/ChildProcess.h>
14+
1315
namespace Synth::Internal {
1416

1517
DsspDeviceCatalog::DsspDeviceCatalog(QObject *parent) : QObject(parent), m_timer(new QTimer(this)) {
@@ -106,6 +108,11 @@ namespace Synth::Internal {
106108
const bool success = status == QProcess::NormalExit && exitCode == 0 && readDevices(process->readAllStandardOutput());
107109
complete(process, success, success ? QString{} : tr("Could not read execution devices from DiffSinger Synthesis Program."));
108110
});
111+
QString errorMessage;
112+
if (!Core::configureChildProcess(process, &errorMessage)) {
113+
complete(process, false, errorMessage);
114+
return;
115+
}
109116
m_timer->start();
110117
Q_EMIT changed();
111118
process->start(executablePath, {QStringLiteral("dump-devices")}, QIODevice::ReadOnly);

‎src/plugins/synth/internal/dssp/DsspServerManager.cpp‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
#include <SVSCraftQuick/MessageBox.h>
2323

2424
#include <appinstall/InstallationManager.h>
25+
#include <coreplugin/ChildProcess.h>
2526
#include <coreplugin/CoreInterface.h>
2627
#include <coreplugin/NotificationMessage.h>
2728

@@ -55,6 +56,11 @@ namespace Synth::Internal {
5556
product.catalogUrl = QUrl(QString::fromUtf8(DIFFSCOPE_DSSP_CATALOG_URL));
5657
product.probeVersion = [](const QString &path, QObject *context, AppInstall::VersionResultHandler finished) -> AppInstall::VersionProbeCancellation {
5758
auto process = new QProcess(context);
59+
if (!Core::configureChildProcess(process)) {
60+
delete process;
61+
finished({});
62+
return {};
63+
}
5864
process->setStandardErrorFile(QProcess::nullDevice());
5965
QObject::connect(process, &QProcess::errorOccurred, context, [finished](QProcess::ProcessError error) {
6066
if (error == QProcess::FailedToStart)
@@ -470,6 +476,11 @@ namespace Synth::Internal {
470476
}
471477

472478
void DsspServerManager::launch(const QVariantMap &device) {
479+
QString errorMessage;
480+
if (!Core::configureChildProcess(m_process, &errorMessage)) {
481+
fail(errorMessage);
482+
return;
483+
}
473484
QStringList arguments{
474485
QStringLiteral("serve"),
475486
QStringLiteral("--host"), m_startConfiguration.host,

‎src/plugins/synth/internal/packagemanager/PackageManagerSettings.cpp‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
#include <CoreApi/runtimeinterface.h>
1919

2020
#include <appinstall/InstallationManager.h>
21+
#include <coreplugin/ChildProcess.h>
2122

2223
#include <synth/internal/DsspServerManager.h>
2324
#include <synth/internal/PackageManagerUtils.h>
@@ -45,6 +46,11 @@ namespace Synth::Internal {
4546
product.catalogUrl = QUrl(QString::fromUtf8(DIFFSCOPE_DSPM_CATALOG_URL));
4647
product.probeVersion = [](const QString &path, QObject *context, AppInstall::VersionResultHandler finished) -> AppInstall::VersionProbeCancellation {
4748
auto process = new QProcess(context);
49+
if (!Core::configureChildProcess(process)) {
50+
delete process;
51+
finished({});
52+
return {};
53+
}
4854
process->setStandardErrorFile(QProcess::nullDevice());
4955
QObject::connect(process, &QProcess::errorOccurred, context, [finished](QProcess::ProcessError error) {
5056
if (error == QProcess::FailedToStart)

‎src/plugins/synth/internal/packagemanager/PackageManagerUtils.cpp‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@
1818
#include <QVariant>
1919
#include <QtGlobal>
2020

21+
#include <coreplugin/ChildProcess.h>
22+
2123
namespace Synth::Internal {
2224

2325
Q_STATIC_LOGGING_CATEGORY(lcPackageManagerUtils, "diffscope.synth.utils")
@@ -84,6 +86,9 @@ namespace Synth::Internal {
8486
return result;
8587
}
8688

89+
if (!Core::configureChildProcess(&process, &result.errorMessage))
90+
return result;
91+
8792
process.setProgram(executablePath);
8893
process.setArguments(arguments);
8994

0 commit comments

Comments
 (0)