From 380895a2ca27e3ded69ec2741d723b73f1ffc7cc Mon Sep 17 00:00:00 2001 From: Andrey Nekrasov Date: Thu, 7 Sep 2023 16:33:07 +0200 Subject: [PATCH] =?UTF-8?q?[PowerRename]=20Do=20not=20crash=20with=20big?= =?UTF-8?q?=20counter=20values=20and=20bound=20max=20padd=E2=80=A6=20(#282?= =?UTF-8?q?49)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/modules/powerrename/lib/Enumerating.h | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/modules/powerrename/lib/Enumerating.h b/src/modules/powerrename/lib/Enumerating.h index 7318daa66d..166a375971 100644 --- a/src/modules/powerrename/lib/Enumerating.h +++ b/src/modules/powerrename/lib/Enumerating.h @@ -32,7 +32,7 @@ std::vector parseEnumOptions(const std::wstring& replaceWith); struct Enumerator { inline Enumerator(EnumOptions options) : - start{ options.start.value_or(0) }, increment{ options.increment.value_or(1) }, padding{ options.padding.value_or(0) }, replaceStrSpan{ options.replaceStrSpan } + start{ options.start.value_or(0) }, increment{ options.increment.value_or(1) }, padding{ options.padding.value_or(0) % MAX_PATH }, replaceStrSpan{ options.replaceStrSpan } { } @@ -43,6 +43,15 @@ struct Enumerator const int32_t enumeratedIndex = enumerate(index); wchar_t format[32]; swprintf_s(format, sizeof(format) / sizeof(wchar_t), L"%%0%ud", padding); + + //swprintf panics when the buffer is too small, so we're checking the required buffer size ahead of printing to it and falling back to 0 padding in case it cannot fit. Note that we must use swprintf with nullptr buf, because the _s version panics on it as well. + const size_t requiredBufSize = swprintf(nullptr, 0, format, enumeratedIndex) + 1ull; + const bool fitsBuf = requiredBufSize < bufSize; + if (!fitsBuf) + { + swprintf_s(format, sizeof(format) / sizeof(wchar_t), L"%%%ud", 0); + } + return swprintf_s(buf, bufSize, format, enumeratedIndex); }