Fix a potential buffer overflow in strrpl

This caused an error using clang with -O3 -flto
This commit is contained in:
Rangi
2021-01-19 15:57:12 -05:00
committed by Eldred Habert
parent ca1c934629
commit f28b4abafc

View File

@@ -179,11 +179,13 @@ static void strrpl(char *dest, size_t destLen, char const *src, char const *old,
} }
for (char const *next = strstr(src, old); next && *next; next = strstr(src, old)) { for (char const *next = strstr(src, old); next && *next; next = strstr(src, old)) {
// Copy anything before the substring to replace
memcpy(dest + i, src, next - src < destLen - i ? next - src : destLen - i); memcpy(dest + i, src, next - src < destLen - i ? next - src : destLen - i);
i += next - src; i += next - src;
if (i >= destLen) if (i >= destLen)
break; break;
// Copy the replacement substring
memcpy(dest + i, new, newLen < destLen - i ? newLen : destLen - i); memcpy(dest + i, new, newLen < destLen - i ? newLen : destLen - i);
i += newLen; i += newLen;
if (i >= destLen) if (i >= destLen)
@@ -192,10 +194,13 @@ static void strrpl(char *dest, size_t destLen, char const *src, char const *old,
src = next + oldLen; src = next + oldLen;
} }
if (i < destLen) {
size_t srcLen = strlen(src); size_t srcLen = strlen(src);
// Copy anything after the last replaced substring
memcpy(dest + i, src, srcLen < destLen - i ? srcLen : destLen - i); memcpy(dest + i, src, srcLen < destLen - i ? srcLen : destLen - i);
i += srcLen; i += srcLen;
}
if (i >= destLen) { if (i >= destLen) {
warning(WARNING_LONG_STR, "STRRPL: String too long, got truncated\n"); warning(WARNING_LONG_STR, "STRRPL: String too long, got truncated\n");