src: Don't rely on virAsprintf() returning string length

In a few places our code relies on the fact that virAsprintf()
not only prints to allocated string but also that it returns the
length of that string. Fortunately, only few such places were
identified:

  https://www.redhat.com/archives/libvir-list/2019-September/msg01382.html

In case of virNWFilterSnoopLeaseFileWrite() and virFilePrintf()
we can use strlen() right after virAsprintf() to calculate the
length. In case of virDoubleToStr() it's only caller checks for
error case only, so we can limit the set of returned values to
just [-1, 0].

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
Reviewed-by: Ján Tomko <jtomko@redhat.com>
This commit is contained in:
Michal Privoznik 2019-10-19 12:09:32 +02:00
parent 67a61a1bf6
commit 9e9d78057d
3 changed files with 12 additions and 10 deletions

View File

@ -1766,13 +1766,12 @@ virNWFilterSnoopLeaseFileWrite(int lfd, const char *ifkey,
}
/* time intf ip dhcpserver */
len = virAsprintf(&lbuf, "%u %s %s %s\n", ipl->timeout,
ifkey, ipstr, dhcpstr);
if (len < 0) {
if (virAsprintf(&lbuf, "%u %s %s %s\n", ipl->timeout,
ifkey, ipstr, dhcpstr) < 0) {
ret = -1;
goto cleanup;
}
len = strlen(lbuf);
if (safewrite(lfd, lbuf, len) != len) {
virReportSystemError(errno, "%s", _("lease file write failed"));

View File

@ -3394,12 +3394,13 @@ int virFilePrintf(FILE *fp, const char *msg, ...)
{
va_list vargs;
g_autofree char *str = NULL;
int ret;
int ret = -1;
va_start(vargs, msg);
if ((ret = virVasprintf(&str, msg, vargs)) < 0)
if (virVasprintf(&str, msg, vargs) < 0)
goto cleanup;
ret = strlen(str);
if (fwrite(str, 1, ret, fp) != ret) {
virReportSystemError(errno, "%s",

View File

@ -703,23 +703,25 @@ virStrToDouble(char const *s,
*
* converts double to string with C locale (thread-safe).
*
* Returns -1 on error, size of the string otherwise.
* Returns: 0 on success, -1 otherwise.
*/
int
virDoubleToStr(char **strp, double number)
{
virLocale oldlocale;
int ret = -1;
int rc;
if (virLocaleSetRaw(&oldlocale) < 0)
return -1;
ret = virAsprintf(strp, "%lf", number);
rc = virAsprintf(strp, "%lf", number);
virLocaleRevert(&oldlocale);
virLocaleFixupRadix(strp);
return ret;
if (rc < 0)
return -1;
return 0;
}