Skip to content

Commit 51f018c

Browse files
Rob SandersDavid Parrish
authored andcommitted
Fix varargs usage
Coverity found a number of 'missing varargs init or cleanup' issues in the _print() method. While examing these I found another potential issue in the vasprintf() code, which is used only for WIN32 platforms. Our target is Linux, and so that change is not tested. The fix for _print() is to call vasprintf() directly without using a loop. The contents of cli->buffer (if any) will be freed before updating cli->buffer and cli->buf_size with the new string results, otherwise they are unchanged. The fix for WIN32 only vasprintf() is to wrap the first call to vsnprintf() with a va_copy()/va_end() to preserve the passed in va_list.
1 parent c223261 commit 51f018c

1 file changed

Lines changed: 12 additions & 29 deletions

File tree

libcli.c

Lines changed: 12 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -47,8 +47,12 @@ int write(int fd, const void *buf, unsigned int count) {
4747

4848
int vasprintf(char **strp, const char *fmt, va_list args) {
4949
int size;
50-
51-
size = vsnprintf(NULL, 0, fmt, args);
50+
va_list argCopy;
51+
52+
// do initial vsnprintf on a copy of the va_list
53+
va_copy(argCopy, args);
54+
size = vsnprintf(NULL, 0, fmt, argCopy);
55+
va_end(argCopy);
5256
if ((*strp = malloc(size + 1)) == NULL) {
5357
return -1;
5458
}
@@ -2006,37 +2010,16 @@ int cli_file(struct cli_def *cli, FILE *fh, int privilege, int mode)
20062010

20072011
static void _print(struct cli_def *cli, int print_mode, const char *format, va_list ap)
20082012
{
2009-
va_list aq;
20102013
int n;
2011-
char *p;
2014+
char *p = NULL;
20122015

20132016
if (!cli) return; // sanity check
20142017

2015-
while (1)
2016-
{
2017-
va_copy(aq, ap);
2018-
if ((n = vsnprintf(cli->buffer, cli->buf_size, format, ap)) == -1)
2019-
return;
2020-
2021-
if ((unsigned)n >= cli->buf_size)
2022-
{
2023-
char *newbuf;
2024-
cli->buf_size = n + 1;
2025-
newbuf = (char*)realloc(cli->buffer, cli->buf_size);
2026-
if (!newbuf)
2027-
{
2028-
free(cli->buffer);
2029-
cli->buffer = NULL;
2030-
return;
2031-
}
2032-
cli->buffer = newbuf;
2033-
va_end(ap);
2034-
va_copy(ap, aq);
2035-
continue;
2036-
}
2037-
break;
2038-
}
2039-
2018+
n = vasprintf(&p, format, ap);
2019+
if (n < 0) return;
2020+
if (cli->buffer) free(cli->buffer);
2021+
cli->buffer = p;
2022+
cli->buf_size = n;
20402023

20412024
p = cli->buffer;
20422025
do

0 commit comments

Comments
 (0)