make GetEnv more robust and not limit length of variables

This commit is contained in:
mjk 2021-03-05 23:54:35 +00:00 committed by LAGonauta
parent fb754b0d43
commit 34519e96bd

View file

@ -9,6 +9,8 @@ win32_error::win32_error() noexcept
: win32_error{::GetLastError()} : win32_error{::GetLastError()}
{} {}
constexpr auto noncharacter = L'\uFFFF';
std::wstring GetExePath() std::wstring GetExePath()
{ {
std::wstring exePath(MAX_PATH, 0); std::wstring exePath(MAX_PATH, 0);
@ -23,14 +25,18 @@ std::wstring GetExePath()
std::wstring GetEnv(const wchar_t *const variable_name) std::wstring GetEnv(const wchar_t *const variable_name)
{ {
std::wstring shortcutPath(MAX_PATH, 0); const auto bufsize = ::GetEnvironmentVariableW(variable_name, nullptr, 0);
auto charWritten = GetEnvironmentVariable(variable_name, shortcutPath.data(), shortcutPath.size()); if (not bufsize)
if (charWritten > 0) throw win32_error{};
{ std::wstring buf(bufsize, noncharacter);
shortcutPath.resize(charWritten); const auto res =
return shortcutPath; ::GetEnvironmentVariableW(variable_name, buf.data(), bufsize);
} if (const auto e = ::GetLastError())
throw win32_error{}; throw win32_error{e};
if (not res or res >= bufsize) // not entirely sure this isn't just paranoia
throw std::runtime_error{"GetEnvironmentVariableW misbehaved"};
buf.resize(res);
return buf;
} }
bool ImplSetProcessAumid(const char *const aumid) bool ImplSetProcessAumid(const char *const aumid)