summaryrefslogtreecommitdiff
path: root/src/env.cpp
diff options
context:
space:
mode:
authorMikaël Capelle <capelle.mikael@gmail.com>2022-05-17 11:47:01 +0200
committerMikaël Capelle <capelle.mikael@gmail.com>2023-07-09 17:20:40 +0200
commitd13f6bb870cdda71257f665367be8ef9fca86255 (patch)
tree52e214718478f1e52856572f5aa1a2ac58537f9f /src/env.cpp
parent86bb01ba9eac879d3685c439ac9da0028bc4bc80 (diff)
Apply clang-format.
Diffstat (limited to 'src/env.cpp')
-rw-r--r--src/env.cpp529
1 files changed, 224 insertions, 305 deletions
diff --git a/src/env.cpp b/src/env.cpp
index 818ce8fb..9e67ef88 100644
--- a/src/env.cpp
+++ b/src/env.cpp
@@ -1,10 +1,10 @@
#include "env.h"
+#include "envdump.h"
#include "envmetrics.h"
#include "envmodule.h"
#include "envsecurity.h"
#include "envshortcut.h"
#include "envwindows.h"
-#include "envdump.h"
#include "settings.h"
#include "shared/util.h"
#include <log.h>
@@ -15,8 +15,7 @@ namespace env
using namespace MOBase;
-Console::Console()
- : m_hasConsole(false), m_in(nullptr), m_out(nullptr), m_err(nullptr)
+Console::Console() : m_hasConsole(false), m_in(nullptr), m_out(nullptr), m_err(nullptr)
{
// try to attach to parent
if (!AttachConsole(ATTACH_PARENT_PROCESS)) {
@@ -63,11 +62,9 @@ Console::~Console()
}
}
-
-ModuleNotification::ModuleNotification(QObject* o, std::function<void (Module)> f)
- : m_cookie(nullptr), m_object(o), m_f(std::move(f))
-{
-}
+ModuleNotification::ModuleNotification(QObject* o, std::function<void(Module)> f)
+ : m_cookie(nullptr), m_object(o), m_f(std::move(f))
+{}
ModuleNotification::~ModuleNotification()
{
@@ -75,9 +72,7 @@ ModuleNotification::~ModuleNotification()
return;
}
- typedef NTSTATUS NTAPI LdrUnregisterDllNotificationType(
- PVOID Cookie
- );
+ typedef NTSTATUS NTAPI LdrUnregisterDllNotificationType(PVOID Cookie);
LibraryPtr ntdll(LoadLibraryW(L"ntdll.dll"));
@@ -86,8 +81,9 @@ ModuleNotification::~ModuleNotification()
return;
}
- auto* LdrUnregisterDllNotification = reinterpret_cast<LdrUnregisterDllNotificationType*>(
- GetProcAddress(ntdll.get(), "LdrUnregisterDllNotification"));
+ auto* LdrUnregisterDllNotification =
+ reinterpret_cast<LdrUnregisterDllNotificationType*>(
+ GetProcAddress(ntdll.get(), "LdrUnregisterDllNotification"));
if (!LdrUnregisterDllNotification) {
log::error("LdrUnregisterDllNotification not found in ntdll.dll");
@@ -123,23 +119,23 @@ void ModuleNotification::fire(QString path, std::size_t fileSize)
// so this queues the callback in the main thread
if (m_f) {
- QMetaObject::invokeMethod(m_object, [path, fileSize, f=m_f] {
- f(Module(path, fileSize));
- }, Qt::QueuedConnection);
+ QMetaObject::invokeMethod(
+ m_object,
+ [path, fileSize, f = m_f] {
+ f(Module(path, fileSize));
+ },
+ Qt::QueuedConnection);
}
}
-
-Environment::Environment()
-{
-}
+Environment::Environment() {}
// anchor
Environment::~Environment() = default;
const std::vector<Module>& Environment::loadedModules() const
{
- if (m_modules.empty()){
+ if (m_modules.empty()) {
m_modules = getLoadedModules();
}
@@ -190,24 +186,19 @@ QString Environment::timezone() const
}
auto offsetString = [](int o) {
- return
- QString("%1%2:%3")
- .arg(o < 0 ? "" : "+")
- .arg(QString::number(o / 60), 2, QChar::fromLatin1('0'))
- .arg(QString::number(o % 60), 2, QChar::fromLatin1('0'));
+ return QString("%1%2:%3")
+ .arg(o < 0 ? "" : "+")
+ .arg(QString::number(o / 60), 2, QChar::fromLatin1('0'))
+ .arg(QString::number(o % 60), 2, QChar::fromLatin1('0'));
};
- const auto stdName = QString::fromWCharArray(tz.StandardName);
+ const auto stdName = QString::fromWCharArray(tz.StandardName);
const auto stdOffset = -(tz.Bias + tz.StandardBias);
- const auto std = QString("%1, %2")
- .arg(stdName)
- .arg(offsetString(stdOffset));
+ const auto std = QString("%1, %2").arg(stdName).arg(offsetString(stdOffset));
- const auto dstName = QString::fromWCharArray(tz.DaylightName);
+ const auto dstName = QString::fromWCharArray(tz.DaylightName);
const auto dstOffset = -(tz.Bias + tz.DaylightBias);
- const auto dst = QString("%1, %2")
- .arg(dstName)
- .arg(offsetString(dstOffset));
+ const auto dst = QString("%1, %2").arg(dstName).arg(offsetString(dstOffset));
QString s;
@@ -220,57 +211,55 @@ QString Environment::timezone() const
return s;
}
-std::unique_ptr<ModuleNotification> Environment::onModuleLoaded(
- QObject* o, std::function<void (Module)> f)
+std::unique_ptr<ModuleNotification>
+Environment::onModuleLoaded(QObject* o, std::function<void(Module)> f)
{
- typedef struct _UNICODE_STRING {
+ typedef struct _UNICODE_STRING
+ {
USHORT Length;
USHORT MaximumLength;
- PWSTR Buffer;
+ PWSTR Buffer;
} UNICODE_STRING, *PUNICODE_STRING;
typedef const PUNICODE_STRING PCUNICODE_STRING;
- typedef struct _LDR_DLL_LOADED_NOTIFICATION_DATA {
- ULONG Flags; //Reserved.
- PCUNICODE_STRING FullDllName; //The full path name of the DLL module.
- PCUNICODE_STRING BaseDllName; //The base file name of the DLL module.
- PVOID DllBase; //A pointer to the base address for the DLL in memory.
- ULONG SizeOfImage; //The size of the DLL image, in bytes.
+ typedef struct _LDR_DLL_LOADED_NOTIFICATION_DATA
+ {
+ ULONG Flags; // Reserved.
+ PCUNICODE_STRING FullDllName; // The full path name of the DLL module.
+ PCUNICODE_STRING BaseDllName; // The base file name of the DLL module.
+ PVOID DllBase; // A pointer to the base address for the DLL in memory.
+ ULONG SizeOfImage; // The size of the DLL image, in bytes.
} LDR_DLL_LOADED_NOTIFICATION_DATA, *PLDR_DLL_LOADED_NOTIFICATION_DATA;
- typedef struct _LDR_DLL_UNLOADED_NOTIFICATION_DATA {
- ULONG Flags; //Reserved.
- PCUNICODE_STRING FullDllName; //The full path name of the DLL module.
- PCUNICODE_STRING BaseDllName; //The base file name of the DLL module.
- PVOID DllBase; //A pointer to the base address for the DLL in memory.
- ULONG SizeOfImage; //The size of the DLL image, in bytes.
+ typedef struct _LDR_DLL_UNLOADED_NOTIFICATION_DATA
+ {
+ ULONG Flags; // Reserved.
+ PCUNICODE_STRING FullDllName; // The full path name of the DLL module.
+ PCUNICODE_STRING BaseDllName; // The base file name of the DLL module.
+ PVOID DllBase; // A pointer to the base address for the DLL in memory.
+ ULONG SizeOfImage; // The size of the DLL image, in bytes.
} LDR_DLL_UNLOADED_NOTIFICATION_DATA, *PLDR_DLL_UNLOADED_NOTIFICATION_DATA;
- typedef union _LDR_DLL_NOTIFICATION_DATA {
+ typedef union _LDR_DLL_NOTIFICATION_DATA
+ {
LDR_DLL_LOADED_NOTIFICATION_DATA Loaded;
LDR_DLL_UNLOADED_NOTIFICATION_DATA Unloaded;
} LDR_DLL_NOTIFICATION_DATA, *PLDR_DLL_NOTIFICATION_DATA;
typedef VOID CALLBACK LDR_DLL_NOTIFICATION_FUNCTION(
- ULONG NotificationReason,
- const PLDR_DLL_NOTIFICATION_DATA NotificationData,
- PVOID Context
- );
+ ULONG NotificationReason, const PLDR_DLL_NOTIFICATION_DATA NotificationData,
+ PVOID Context);
typedef LDR_DLL_NOTIFICATION_FUNCTION* PLDR_DLL_NOTIFICATION_FUNCTION;
typedef NTSTATUS NTAPI LdrRegisterDllNotificationType(
- ULONG Flags,
- PLDR_DLL_NOTIFICATION_FUNCTION NotificationFunction,
- PVOID Context,
- PVOID *Cookie
- );
+ ULONG Flags, PLDR_DLL_NOTIFICATION_FUNCTION NotificationFunction, PVOID Context,
+ PVOID * Cookie);
- const ULONG LDR_DLL_NOTIFICATION_REASON_LOADED = 1;
+ const ULONG LDR_DLL_NOTIFICATION_REASON_LOADED = 1;
const ULONG LDR_DLL_NOTIFICATION_REASON_UNLOADED = 2;
-
// loading ntdll.dll, the function will be found with GetProcAddress()
LibraryPtr ntdll(LoadLibraryW(L"ntdll.dll"));
@@ -280,33 +269,32 @@ std::unique_ptr<ModuleNotification> Environment::onModuleLoaded(
}
auto* LdrRegisterDllNotification = reinterpret_cast<LdrRegisterDllNotificationType*>(
- GetProcAddress(ntdll.get(), "LdrRegisterDllNotification"));
+ GetProcAddress(ntdll.get(), "LdrRegisterDllNotification"));
if (!LdrRegisterDllNotification) {
log::error("LdrRegisterDllNotification not found in ntdll.dll");
return {};
}
-
auto context = std::make_unique<ModuleNotification>(o, f);
void* cookie = nullptr;
- auto OnDllLoaded = [](ULONG reason, const PLDR_DLL_NOTIFICATION_DATA data, void* context) {
+ auto OnDllLoaded = [](ULONG reason, const PLDR_DLL_NOTIFICATION_DATA data,
+ void* context) {
if (reason == LDR_DLL_NOTIFICATION_REASON_LOADED) {
if (data && data->Loaded.FullDllName) {
if (context) {
static_cast<ModuleNotification*>(context)->fire(
- QString::fromWCharArray(
- data->Loaded.FullDllName->Buffer,
- data->Loaded.FullDllName->Length / sizeof(wchar_t)),
- data->Loaded.SizeOfImage);
+ QString::fromWCharArray(data->Loaded.FullDllName->Buffer,
+ data->Loaded.FullDllName->Length /
+ sizeof(wchar_t)),
+ data->Loaded.SizeOfImage);
}
}
}
};
- const auto r = LdrRegisterDllNotification(
- 0, OnDllLoaded, context.get(), &cookie);
+ const auto r = LdrRegisterDllNotification(0, OnDllLoaded, context.get(), &cookie);
if (r != 0) {
log::error("failed to register for module notifications, error {}", r);
@@ -356,9 +344,8 @@ void Environment::dump(const Settings& s) const
}
const auto r = metrics().desktopGeometry();
- log::debug(
- "desktop geometry: ({},{})-({},{})",
- r.left(), r.top(), r.right(), r.bottom());
+ log::debug("desktop geometry: ({},{})-({},{})", r.left(), r.top(), r.right(),
+ r.bottom());
dumpDisks(s);
}
@@ -379,11 +366,8 @@ void Environment::dumpDisks(const Settings& s) const
// remember
rootPaths.insert(si.rootPath());
- log::debug(
- " . {} free={} MB{}",
- si.rootPath(),
- (si.bytesFree() / 1000 / 1000),
- (si.isReadOnly() ? " (readonly)" : ""));
+ log::debug(" . {} free={} MB{}", si.rootPath(), (si.bytesFree() / 1000 / 1000),
+ (si.isReadOnly() ? " (readonly)" : ""));
};
log::debug("drives:");
@@ -398,7 +382,6 @@ void Environment::dumpDisks(const Settings& s) const
dump(QCoreApplication::applicationDirPath());
}
-
QString path()
{
return get("PATH");
@@ -426,19 +409,17 @@ void setPath(const QString& s)
QString get(const QString& name)
{
std::size_t bufferSize = 4000;
- auto buffer = std::make_unique<wchar_t[]>(bufferSize);
+ auto buffer = std::make_unique<wchar_t[]>(bufferSize);
- DWORD realSize = ::GetEnvironmentVariableW(
- name.toStdWString().c_str(),
- buffer.get(), static_cast<DWORD>(bufferSize));
+ DWORD realSize = ::GetEnvironmentVariableW(name.toStdWString().c_str(), buffer.get(),
+ static_cast<DWORD>(bufferSize));
if (realSize > bufferSize) {
bufferSize = realSize;
- buffer = std::make_unique<wchar_t[]>(bufferSize);
+ buffer = std::make_unique<wchar_t[]>(bufferSize);
- realSize = ::GetEnvironmentVariableW(
- name.toStdWString().c_str(),
- buffer.get(), static_cast<DWORD>(bufferSize));
+ realSize = ::GetEnvironmentVariableW(name.toStdWString().c_str(), buffer.get(),
+ static_cast<DWORD>(bufferSize));
}
if (realSize == 0) {
@@ -446,9 +427,8 @@ QString get(const QString& name)
// don't log if not found
if (e != ERROR_ENVVAR_NOT_FOUND) {
- log::error(
- "failed to get environment variable '{}', {}",
- name, formatSystemMessage(e));
+ log::error("failed to get environment variable '{}', {}", name,
+ formatSystemMessage(e));
}
return {};
@@ -462,16 +442,12 @@ void set(const QString& n, const QString& v)
::SetEnvironmentVariableW(n.toStdWString().c_str(), v.toStdWString().c_str());
}
-
-Service::Service(QString name)
- : Service(std::move(name), StartType::None, Status::None)
-{
-}
+Service::Service(QString name) : Service(std::move(name), StartType::None, Status::None)
+{}
Service::Service(QString name, StartType st, Status s)
- : m_name(std::move(name)), m_startType(st), m_status(s)
-{
-}
+ : m_name(std::move(name)), m_startType(st), m_status(s)
+{}
const QString& Service::name() const
{
@@ -496,29 +472,27 @@ Service::Status Service::status() const
QString Service::toString() const
{
return QString("service '%1', start=%2, status=%3")
- .arg(m_name)
- .arg(env::toString(m_startType))
- .arg(env::toString(m_status));
+ .arg(m_name)
+ .arg(env::toString(m_startType))
+ .arg(env::toString(m_status));
}
-
QString toString(Service::StartType st)
{
using ST = Service::StartType;
- switch (st)
- {
- case ST::None:
- return "none";
+ switch (st) {
+ case ST::None:
+ return "none";
- case ST::Disabled:
- return "disabled";
+ case ST::Disabled:
+ return "disabled";
- case ST::Enabled:
- return "enabled";
+ case ST::Enabled:
+ return "enabled";
- default:
- return QString("unknown %1").arg(static_cast<int>(st));
+ default:
+ return QString("unknown %1").arg(static_cast<int>(st));
}
}
@@ -526,19 +500,18 @@ QString toString(Service::Status st)
{
using S = Service::Status;
- switch (st)
- {
- case S::None:
- return "none";
+ switch (st) {
+ case S::None:
+ return "none";
- case S::Stopped:
- return "stopped";
+ case S::Stopped:
+ return "stopped";
- case S::Running:
- return "running";
+ case S::Running:
+ return "running";
- default:
- return QString("unknown %1").arg(static_cast<int>(st));
+ default:
+ return QString("unknown %1").arg(static_cast<int>(st));
}
}
@@ -550,9 +523,8 @@ Service::StartType getServiceStartType(SC_HANDLE s, const QString& name)
const auto e = GetLastError();
if (e != ERROR_INSUFFICIENT_BUFFER) {
- log::error(
- "QueryServiceConfig() for size for '{}' failed, {}",
- name, GetLastError());
+ log::error("QueryServiceConfig() for size for '{}' failed, {}", name,
+ GetLastError());
return Service::StartType::None;
}
@@ -560,41 +532,33 @@ Service::StartType getServiceStartType(SC_HANDLE s, const QString& name)
const auto size = needed;
MallocPtr<QUERY_SERVICE_CONFIG> config(
- static_cast<QUERY_SERVICE_CONFIG*>(std::malloc(size)));
+ static_cast<QUERY_SERVICE_CONFIG*>(std::malloc(size)));
if (!QueryServiceConfig(s, config.get(), size, &needed)) {
const auto e = GetLastError();
- log::error(
- "QueryServiceConfig() for '{}' failed", name, formatSystemMessage(e));
+ log::error("QueryServiceConfig() for '{}' failed", name, formatSystemMessage(e));
return Service::StartType::None;
}
+ switch (config->dwStartType) {
+ case SERVICE_AUTO_START: // fall-through
+ case SERVICE_BOOT_START:
+ case SERVICE_DEMAND_START:
+ case SERVICE_SYSTEM_START: {
+ return Service::StartType::Enabled;
+ }
- switch (config->dwStartType)
- {
- case SERVICE_AUTO_START: // fall-through
- case SERVICE_BOOT_START:
- case SERVICE_DEMAND_START:
- case SERVICE_SYSTEM_START:
- {
- return Service::StartType::Enabled;
- }
-
- case SERVICE_DISABLED:
- {
- return Service::StartType::Disabled;
- }
+ case SERVICE_DISABLED: {
+ return Service::StartType::Disabled;
+ }
- default:
- {
- log::error(
- "unknown service start type {} for '{}'",
- config->dwStartType, name);
+ default: {
+ log::error("unknown service start type {} for '{}'", config->dwStartType, name);
- return Service::StartType::None;
- }
+ return Service::StartType::None;
+ }
}
}
@@ -606,9 +570,8 @@ Service::Status getServiceStatus(SC_HANDLE s, const QString& name)
const auto e = GetLastError();
if (e != ERROR_INSUFFICIENT_BUFFER) {
- log::error(
- "QueryServiceStatusEx() for size for '{}' failed, {}",
- name, GetLastError());
+ log::error("QueryServiceStatusEx() for size for '{}' failed, {}", name,
+ GetLastError());
return Service::Status::None;
}
@@ -616,56 +579,47 @@ Service::Status getServiceStatus(SC_HANDLE s, const QString& name)
const auto size = needed;
MallocPtr<SERVICE_STATUS_PROCESS> status(
- static_cast<SERVICE_STATUS_PROCESS*>(std::malloc(size)));
+ static_cast<SERVICE_STATUS_PROCESS*>(std::malloc(size)));
const auto r = QueryServiceStatusEx(
- s, SC_STATUS_PROCESS_INFO, reinterpret_cast<BYTE*>(status.get()),
- size, &needed);
+ s, SC_STATUS_PROCESS_INFO, reinterpret_cast<BYTE*>(status.get()), size, &needed);
if (!r) {
const auto e = GetLastError();
- log::error(
- "QueryServiceStatusEx() failed for '{}', {}",
- name, formatSystemMessage(e));
+ log::error("QueryServiceStatusEx() failed for '{}', {}", name,
+ formatSystemMessage(e));
return Service::Status::None;
}
+ switch (status->dwCurrentState) {
+ case SERVICE_START_PENDING: // fall-through
+ case SERVICE_CONTINUE_PENDING:
+ case SERVICE_RUNNING: {
+ return Service::Status::Running;
+ }
- switch (status->dwCurrentState)
- {
- case SERVICE_START_PENDING: // fall-through
- case SERVICE_CONTINUE_PENDING:
- case SERVICE_RUNNING:
- {
- return Service::Status::Running;
- }
-
- case SERVICE_STOPPED: // fall-through
- case SERVICE_STOP_PENDING:
- case SERVICE_PAUSE_PENDING:
- case SERVICE_PAUSED:
- {
- return Service::Status::Stopped;
- }
+ case SERVICE_STOPPED: // fall-through
+ case SERVICE_STOP_PENDING:
+ case SERVICE_PAUSE_PENDING:
+ case SERVICE_PAUSED: {
+ return Service::Status::Stopped;
+ }
- default:
- {
- log::error(
- "unknown service status {} for '{}'",
- status->dwCurrentState, name);
+ default: {
+ log::error("unknown service status {} for '{}'", status->dwCurrentState, name);
- return Service::Status::None;
- }
+ return Service::Status::None;
+ }
}
}
Service getService(const QString& name)
{
// service manager
- const LocalPtr<SC_HANDLE> scm(OpenSCManager(
- NULL, NULL, SERVICE_QUERY_STATUS | SERVICE_QUERY_CONFIG));
+ const LocalPtr<SC_HANDLE> scm(
+ OpenSCManager(NULL, NULL, SERVICE_QUERY_STATUS | SERVICE_QUERY_CONFIG));
if (!scm) {
const auto e = GetLastError();
@@ -674,9 +628,8 @@ Service getService(const QString& name)
}
// service
- const LocalPtr<SC_HANDLE> s(OpenService(
- scm.get(), name.toStdWString().c_str(),
- SERVICE_QUERY_STATUS | SERVICE_QUERY_CONFIG));
+ const LocalPtr<SC_HANDLE> s(OpenService(scm.get(), name.toStdWString().c_str(),
+ SERVICE_QUERY_STATUS | SERVICE_QUERY_CONFIG));
if (!s) {
const auto e = GetLastError();
@@ -685,20 +638,19 @@ Service getService(const QString& name)
}
const auto startType = getServiceStartType(s.get(), name);
- const auto status = getServiceStatus(s.get(), name);
+ const auto status = getServiceStatus(s.get(), name);
return {name, startType, status};
}
-
std::optional<QString> getAssocString(const QFileInfo& file, ASSOCSTR astr)
{
const auto ext = L"." + file.suffix().toStdWString();
// getting buffer size
DWORD bufferSize = 0;
- auto r = AssocQueryStringW(
- ASSOCF_INIT_IGNOREUNKNOWN, astr, ext.c_str(), L"open", nullptr, &bufferSize);
+ auto r = AssocQueryStringW(ASSOCF_INIT_IGNOREUNKNOWN, astr, ext.c_str(), L"open",
+ nullptr, &bufferSize);
// returns S_FALSE when giving back the buffer size, so that's actually the
// expected return value
@@ -707,9 +659,8 @@ std::optional<QString> getAssocString(const QFileInfo& file, ASSOCSTR astr)
if (r == HRESULT_FROM_WIN32(ERROR_NO_ASSOCIATION)) {
log::error("file '{}' has no associated executable", file.absoluteFilePath());
} else {
- log::error(
- "can't get buffer size for AssocQueryStringW(), {}",
- formatSystemMessage(r));
+ log::error("can't get buffer size for AssocQueryStringW(), {}",
+ formatSystemMessage(r));
}
return {};
}
@@ -718,13 +669,12 @@ std::optional<QString> getAssocString(const QFileInfo& file, ASSOCSTR astr)
auto buffer = std::make_unique<wchar_t[]>(bufferSize + 1);
std::fill(buffer.get(), buffer.get() + bufferSize + 1, 0);
- r = AssocQueryStringW(
- ASSOCF_INIT_IGNOREUNKNOWN, astr, ext.c_str(), L"open", buffer.get(), &bufferSize);
+ r = AssocQueryStringW(ASSOCF_INIT_IGNOREUNKNOWN, astr, ext.c_str(), L"open",
+ buffer.get(), &bufferSize);
if (FAILED(r)) {
- log::error(
- "failed to get exe associated with '{}', {}",
- file.suffix(), formatSystemMessage(r));
+ log::error("failed to get exe associated with '{}', {}", file.suffix(),
+ formatSystemMessage(r));
return {};
}
@@ -751,7 +701,7 @@ QString formatCommandLine(const QFileInfo& targetInfo, const QString& cmd)
// first one is the filename
const auto wpath = targetInfo.absoluteFilePath().toStdWString();
- args[0] = reinterpret_cast<DWORD_PTR>(wpath.c_str());
+ args[0] = reinterpret_cast<DWORD_PTR>(wpath.c_str());
// remaining are ""
std::fill(args.begin() + 1, args.end(), reinterpret_cast<DWORD_PTR>(L""));
@@ -761,20 +711,17 @@ QString formatCommandLine(const QFileInfo& targetInfo, const QString& cmd)
const auto wcmd = cmd.toStdWString();
- const auto n = ::FormatMessageW(
- FORMAT_MESSAGE_ALLOCATE_BUFFER |
- FORMAT_MESSAGE_ARGUMENT_ARRAY |
- FORMAT_MESSAGE_FROM_STRING,
- wcmd.c_str(), 0, 0,
- reinterpret_cast<LPWSTR>(&buffer),
- 0, reinterpret_cast<va_list*>(&args[0]));
+ const auto n =
+ ::FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_ARGUMENT_ARRAY |
+ FORMAT_MESSAGE_FROM_STRING,
+ wcmd.c_str(), 0, 0, reinterpret_cast<LPWSTR>(&buffer), 0,
+ reinterpret_cast<va_list*>(&args[0]));
- if (n == 0 || !buffer){
+ if (n == 0 || !buffer) {
const auto e = GetLastError();
- log::error(
- "failed to format command line '{}' with path '{}', {}",
- cmd, targetInfo.absoluteFilePath(), formatSystemMessage(e));
+ log::error("failed to format command line '{}' with path '{}', {}", cmd,
+ targetInfo.absoluteFilePath(), formatSystemMessage(e));
return {};
}
@@ -788,12 +735,12 @@ QString formatCommandLine(const QFileInfo& targetInfo, const QString& cmd)
std::pair<QString, QString> splitExeAndArguments(const QString& cmd)
{
int exeBegin = 0;
- int exeEnd = -1;
+ int exeEnd = -1;
- if (cmd[0] == '"'){
+ if (cmd[0] == '"') {
// surrounded by double-quotes, so find the next one
exeBegin = 1;
- exeEnd = cmd.indexOf('"', exeBegin);
+ exeEnd = cmd.indexOf('"', exeBegin);
if (exeEnd == -1) {
log::error("missing terminating double-quote in command line '{}'", cmd);
@@ -807,7 +754,7 @@ std::pair<QString, QString> splitExeAndArguments(const QString& cmd)
}
}
- QString exe = cmd.mid(exeBegin, exeEnd - exeBegin).trimmed();
+ QString exe = cmd.mid(exeBegin, exeEnd - exeBegin).trimmed();
QString args = cmd.mid(exeEnd + 1).trimmed();
return {std::move(exe), std::move(args)};
@@ -815,9 +762,8 @@ std::pair<QString, QString> splitExeAndArguments(const QString& cmd)
Association getAssociation(const QFileInfo& targetInfo)
{
- log::debug(
- "getting association for '{}', extension is '.{}'",
- targetInfo.absoluteFilePath(), targetInfo.suffix());
+ log::debug("getting association for '{}', extension is '.{}'",
+ targetInfo.absoluteFilePath(), targetInfo.suffix());
const auto cmd = getAssocString(targetInfo, ASSOCSTR_COMMAND);
if (!cmd) {
@@ -828,9 +774,8 @@ Association getAssociation(const QFileInfo& targetInfo)
QString formattedCmd = formatCommandLine(targetInfo, *cmd);
if (formattedCmd.isEmpty()) {
- log::error(
- "command line associated with '{}' is empty",
- targetInfo.absoluteFilePath());
+ log::error("command line associated with '{}' is empty",
+ targetInfo.absoluteFilePath());
return {};
}
@@ -847,7 +792,6 @@ Association getAssociation(const QFileInfo& targetInfo)
return {QFileInfo(p.first), *cmd, p.second};
}
-
struct RegistryKeyCloser
{
using pointer = HKEY;
@@ -866,10 +810,9 @@ RegistryKeyPtr openRegistryKey(HKEY parent, const wchar_t* name)
{
HKEY subkey = 0;
- auto r = ::RegOpenKeyExW(
- parent, name,
- 0, KEY_SET_VALUE|KEY_ENUMERATE_SUB_KEYS|KEY_QUERY_VALUE,
- &subkey);
+ auto r = ::RegOpenKeyExW(parent, name, 0,
+ KEY_SET_VALUE | KEY_ENUMERATE_SUB_KEYS | KEY_QUERY_VALUE,
+ &subkey);
if (r != ERROR_SUCCESS) {
return {};
@@ -880,12 +823,12 @@ RegistryKeyPtr openRegistryKey(HKEY parent, const wchar_t* name)
bool keyHasValues(HKEY key)
{
- auto name = std::make_unique<wchar_t[]>(1000 + 1);
+ auto name = std::make_unique<wchar_t[]>(1000 + 1);
DWORD nameSize = 1000;
// note that RegEnumValueW() also enumerates the default value if it exists
- auto r = ::RegEnumValueW(
- key, 0, name.get(), &nameSize, nullptr, nullptr, nullptr, nullptr);
+ auto r = ::RegEnumValueW(key, 0, name.get(), &nameSize, nullptr, nullptr, nullptr,
+ nullptr);
if (r != ERROR_NO_MORE_ITEMS) {
return true;
@@ -895,18 +838,17 @@ bool keyHasValues(HKEY key)
return false;
}
-bool forEachSubKey(HKEY key, std::function<bool (const wchar_t* name)> f)
+bool forEachSubKey(HKEY key, std::function<bool(const wchar_t* name)> f)
{
- auto name = std::make_unique<wchar_t[]>(1000 + 1);
+ auto name = std::make_unique<wchar_t[]>(1000 + 1);
DWORD nameSize = 1000;
DWORD i = 0;
// something would be really wrong if it had more than 100 keys
- while (i < 100)
- {
- auto r = ::RegEnumKeyExW(
- key, i, name.get(), &nameSize, nullptr, nullptr, nullptr, nullptr);
+ while (i < 100) {
+ auto r = ::RegEnumKeyExW(key, i, name.get(), &nameSize, nullptr, nullptr, nullptr,
+ nullptr);
if (r == ERROR_NO_MORE_ITEMS) {
// no more subkeys
@@ -991,8 +933,7 @@ void deleteRegistryKeyIfEmpty(const QString& name)
bool registryValueExists(const QString& keyName, const QString& valueName)
{
- auto key = openRegistryKey(
- HKEY_CURRENT_USER, keyName.toStdWString().c_str());
+ auto key = openRegistryKey(HKEY_CURRENT_USER, keyName.toStdWString().c_str());
if (!key) {
return false;
@@ -1000,25 +941,22 @@ bool registryValueExists(const QString& keyName, const QString& valueName)
DWORD type = 0;
- auto r = ::RegQueryValueExW(
- key.get(), valueName.toStdWString().c_str(),
- nullptr, &type, nullptr, nullptr);
+ auto r = ::RegQueryValueExW(key.get(), valueName.toStdWString().c_str(), nullptr,
+ &type, nullptr, nullptr);
return (r == ERROR_SUCCESS);
}
-
// returns the filename of the given process or the current one
//
-std::filesystem::path processPath(HANDLE process=INVALID_HANDLE_VALUE)
+std::filesystem::path processPath(HANDLE process = INVALID_HANDLE_VALUE)
{
// double the buffer size 10 times
const int MaxTries = 10;
DWORD bufferSize = MAX_PATH;
- for (int tries=0; tries<MaxTries; ++tries)
- {
+ for (int tries = 0; tries < MaxTries; ++tries) {
auto buffer = std::make_unique<wchar_t[]>(bufferSize + 1);
std::fill(buffer.get(), buffer.get() + bufferSize + 1, 0);
@@ -1063,7 +1001,7 @@ std::filesystem::path processPath(HANDLE process=INVALID_HANDLE_VALUE)
return {};
}
-std::wstring processFilename(HANDLE process=INVALID_HANDLE_VALUE)
+std::wstring processFilename(HANDLE process = INVALID_HANDLE_VALUE)
{
const auto p = processPath(process);
if (p.empty()) {
@@ -1092,9 +1030,8 @@ DWORD findOtherPid()
// same one
auto filename = processFilename();
if (filename.empty()) {
- std::wcerr
- << L"can't get current process filename, defaulting to "
- << defaultName << L"\n";
+ std::wcerr << L"can't get current process filename, defaulting to " << defaultName
+ << L"\n";
filename = defaultName;
} else {
@@ -1115,25 +1052,23 @@ DWORD findOtherPid()
}
}
- std::wclog
- << L"no process with this filename\n"
- << L"MO may not be running, or it may be running as administrator\n"
- << L"you can try running this again as administrator\n";
+ std::wclog << L"no process with this filename\n"
+ << L"MO may not be running, or it may be running as administrator\n"
+ << L"you can try running this again as administrator\n";
return 0;
}
std::wstring tempDir()
{
- const DWORD bufferSize = MAX_PATH + 1;
+ const DWORD bufferSize = MAX_PATH + 1;
wchar_t buffer[bufferSize + 1] = {};
const auto written = GetTempPathW(bufferSize, buffer);
if (written == 0) {
const auto e = GetLastError();
- std::wcerr
- << L"failed to get temp path, " << formatSystemMessage(e) << L"\n";
+ std::wcerr << L"failed to get temp path, " << formatSystemMessage(e) << L"\n";
return {};
}
@@ -1144,13 +1079,10 @@ std::wstring tempDir()
std::wstring safeVersion()
{
- try
- {
+ try {
// this can throw
return MOShared::createVersionInfo().displayString(3).toStdWString() + L"-";
- }
- catch(...)
- {
+ } catch (...) {
return {};
}
}
@@ -1162,32 +1094,28 @@ HandlePtr tempFile(const std::wstring dir)
// UTC time and date will be in the filename
const auto now = std::time(0);
- const auto tm = std::gmtime(&now);
+ const auto tm = std::gmtime(&now);
// "ModOrganizer-YYYYMMDDThhmmss.dmp", with a possible "-i" appended, where
// i can go until MaxTries
std::wostringstream oss;
- oss
- << L"ModOrganizer-" << safeVersion()
- << std::setw(4) << (1900 + tm->tm_year)
- << std::setw(2) << std::setfill(L'0') << (tm->tm_mon + 1)
- << std::setw(2) << std::setfill(L'0') << tm->tm_mday << "T"
- << std::setw(2) << std::setfill(L'0') << tm->tm_hour
- << std::setw(2) << std::setfill(L'0') << tm->tm_min
- << std::setw(2) << std::setfill(L'0') << tm->tm_sec;
+ oss << L"ModOrganizer-" << safeVersion() << std::setw(4) << (1900 + tm->tm_year)
+ << std::setw(2) << std::setfill(L'0') << (tm->tm_mon + 1) << std::setw(2)
+ << std::setfill(L'0') << tm->tm_mday << "T" << std::setw(2) << std::setfill(L'0')
+ << tm->tm_hour << std::setw(2) << std::setfill(L'0') << tm->tm_min << std::setw(2)
+ << std::setfill(L'0') << tm->tm_sec;
const std::wstring prefix = oss.str();
- const std::wstring ext = L".dmp";
+ const std::wstring ext = L".dmp";
// first path to try, without counter in it
std::wstring path = dir + L"\\" + prefix + ext;
- for (int i=0; i<MaxTries; ++i) {
+ for (int i = 0; i < MaxTries; ++i) {
std::wclog << L"trying file '" << path << L"'\n";
- HandlePtr h (CreateFileW(
- path.c_str(), GENERIC_WRITE, 0, nullptr,
- CREATE_NEW, FILE_ATTRIBUTE_NORMAL, nullptr));
+ HandlePtr h(CreateFileW(path.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_NEW,
+ FILE_ATTRIBUTE_NORMAL, nullptr));
if (h.get() != INVALID_HANDLE_VALUE) {
// worked
@@ -1198,8 +1126,7 @@ HandlePtr tempFile(const std::wstring dir)
if (e != ERROR_FILE_EXISTS) {
// probably no write access
- std::wcerr
- << L"failed to create dump file, " << formatSystemMessage(e) << L"\n";
+ std::wcerr << L"failed to create dump file, " << formatSystemMessage(e) << L"\n";
return {};
}
@@ -1243,7 +1170,6 @@ HandlePtr dumpFile(const wchar_t* dir)
return {};
}
-
CoreDumpTypes coreDumpTypeFromString(const std::string& s)
{
if (s == "data")
@@ -1256,23 +1182,21 @@ CoreDumpTypes coreDumpTypeFromString(const std::string& s)
std::string toString(CoreDumpTypes type)
{
- switch (type)
- {
- case CoreDumpTypes::Mini:
- return "mini";
+ switch (type) {
+ case CoreDumpTypes::Mini:
+ return "mini";
- case CoreDumpTypes::Data:
- return "data";
+ case CoreDumpTypes::Data:
+ return "data";
- case CoreDumpTypes::Full:
- return "full";
+ case CoreDumpTypes::Full:
+ return "full";
- default:
- return "?";
+ default:
+ return "?";
}
}
-
bool createMiniDump(const wchar_t* dir, HANDLE process, CoreDumpTypes type)
{
const DWORD pid = GetProcessId(process);
@@ -1283,30 +1207,27 @@ bool createMiniDump(const wchar_t* dir, HANDLE process, CoreDumpTypes type)
return false;
}
- auto flags = _MINIDUMP_TYPE(
- MiniDumpNormal |
- MiniDumpWithHandleData |
- MiniDumpWithUnloadedModules |
- MiniDumpWithProcessThreadData);
+ auto flags =
+ _MINIDUMP_TYPE(MiniDumpNormal | MiniDumpWithHandleData |
+ MiniDumpWithUnloadedModules | MiniDumpWithProcessThreadData);
if (type == CoreDumpTypes::Data) {
std::wclog << L"writing minidump with data\n";
flags = _MINIDUMP_TYPE(flags | MiniDumpWithDataSegs);
- } else if (type == CoreDumpTypes::Full) {
+ } else if (type == CoreDumpTypes::Full) {
std::wclog << L"writing full minidump\n";
flags = _MINIDUMP_TYPE(flags | MiniDumpWithFullMemory);
} else {
std::wclog << L"writing mini minidump\n";
}
- const auto ret = MiniDumpWriteDump(
- process, pid, file.get(), flags, nullptr, nullptr, nullptr);
+ const auto ret =
+ MiniDumpWriteDump(process, pid, file.get(), flags, nullptr, nullptr, nullptr);
if (!ret) {
const auto e = GetLastError();
- std::wcerr
- << L"failed to write mini dump, " << formatSystemMessage(e) << L"\n";
+ std::wcerr << L"failed to write mini dump, " << formatSystemMessage(e) << L"\n";
return false;
}
@@ -1315,7 +1236,6 @@ bool createMiniDump(const wchar_t* dir, HANDLE process, CoreDumpTypes type)
return true;
}
-
bool coredump(const wchar_t* dir, CoreDumpTypes type)
{
std::wclog << L"creating minidump for the current process\n";
@@ -1334,15 +1254,14 @@ bool coredumpOther(CoreDumpTypes type)
std::wclog << L"found other process with pid " << pid << L"\n";
- HandlePtr handle(OpenProcess(
- PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid));
+ HandlePtr handle(
+ OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid));
if (!handle) {
const auto e = GetLastError();
- std::wcerr
- << L"failed to open process " << pid << L", "
- << formatSystemMessage(e) << L"\n";
+ std::wcerr << L"failed to open process " << pid << L", " << formatSystemMessage(e)
+ << L"\n";
return false;
}
@@ -1350,4 +1269,4 @@ bool coredumpOther(CoreDumpTypes type)
return createMiniDump(nullptr, handle.get(), type);
}
-} // namespace
+} // namespace env