From 34519e96bd6cc6af8634affea65c5d3fb90b926a Mon Sep 17 00:00:00 2001 From: mjk Date: Fri, 5 Mar 2021 23:54:35 +0000 Subject: [PATCH] make GetEnv more robust and not limit length of variables --- .../windows-notification/api/src/win32.cpp | 22 ++++++++++++------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/plugins/windows-notification/api/src/win32.cpp b/plugins/windows-notification/api/src/win32.cpp index 91d3ad8e..1c0f4b9a 100644 --- a/plugins/windows-notification/api/src/win32.cpp +++ b/plugins/windows-notification/api/src/win32.cpp @@ -9,6 +9,8 @@ win32_error::win32_error() noexcept : win32_error{::GetLastError()} {} +constexpr auto noncharacter = L'\uFFFF'; + std::wstring GetExePath() { std::wstring exePath(MAX_PATH, 0); @@ -23,14 +25,18 @@ std::wstring GetExePath() std::wstring GetEnv(const wchar_t *const variable_name) { - std::wstring shortcutPath(MAX_PATH, 0); - auto charWritten = GetEnvironmentVariable(variable_name, shortcutPath.data(), shortcutPath.size()); - if (charWritten > 0) - { - shortcutPath.resize(charWritten); - return shortcutPath; - } - throw win32_error{}; + const auto bufsize = ::GetEnvironmentVariableW(variable_name, nullptr, 0); + if (not bufsize) + throw win32_error{}; + std::wstring buf(bufsize, noncharacter); + const auto res = + ::GetEnvironmentVariableW(variable_name, buf.data(), bufsize); + if (const auto e = ::GetLastError()) + 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)