Fix potential freeing of an immutable static buffer

strerror_r() has two versions: GNU-specific and XSI-compliant. The XSI
version always stores the string in the provided buffer, but the GNU
version might store it in the provided buffer or it might use some
immutable static buffer instead. Since we always free the error string,
we might end up freeing the immutable static buffer.
This commit is contained in:
Maxim Biro 2022-02-01 22:20:02 -05:00
parent 28dc8c1ded
commit cda6c9b6e8
No known key found for this signature in database
GPG Key ID: AB3AD9896472BFA4
2 changed files with 26 additions and 8 deletions

View File

@ -1 +1 @@
de00572e0a22b67defb05759a4d5aac6bf0e107bfd6834a1edc20ffb0379528d /usr/local/bin/tox-bootstrapd
746158481ebd16d70aadc0bf4d2dc6da6a2f3ac4eb12d219b49fc6fd7e60d149 /usr/local/bin/tox-bootstrapd

View File

@ -1746,18 +1746,36 @@ char *net_new_strerror(int error)
error, 0, (char *)&str, 0, nullptr);
return str;
#else
char *str = (char *)malloc(256);
#ifdef _GNU_SOURCE
str = strerror_r(error, str, 256);
#else
const int fmt_error = strerror_r(error, str, 256);
char tmp[256];
if (fmt_error != 0) {
snprintf(str, 256, "error %d (strerror failed with error %d)", error, fmt_error);
errno = 0;
#ifdef _GNU_SOURCE
const char *retstr = strerror_r(error, tmp, sizeof(tmp));
if (errno != 0) {
snprintf(tmp, sizeof(tmp), "error %d (strerror_r failed with errno %d)", error, errno);
}
#else
const int fmt_error = strerror_r(error, tmp, sizeof(tmp));
if (fmt_error != 0) {
snprintf(tmp, sizeof(tmp), "error %d (strerror_r failed with error %d, errno %d)", error, fmt_error, errno);
}
const char *retstr = tmp;
#endif
const size_t retstr_len = strlen(retstr);
char *str = (char *)malloc(retstr_len + 1);
if (str == nullptr) {
return nullptr;
}
memcpy(str, retstr, retstr_len + 1);
return str;
#endif
}