Skip to content

Commit d912cce

Browse files
committed
utilities: Implement real function iio_snprintf
Everything in libiio expects iio_snprintf() to return an error when the data to be written overflows the buffer, but it is not how snprintf() behaves; instead, it returns the number of characters that would have been written if there was enough space in the buffer. Therefore, to know that the data was truncated, it is required to compare the return value with the size of the buffer, and nothing in libiio does that. Address this issue by returning -ERANGE if an overflow is detected. Signed-off-by: Paul Cercueil <[email protected]>
1 parent ed60003 commit d912cce

File tree

2 files changed

+25
-2
lines changed

2 files changed

+25
-2
lines changed

iio-private.h

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,13 +32,19 @@
3232

3333
#ifdef _MSC_BUILD
3434
#define inline __inline
35-
#define iio_snprintf sprintf_s
3635
#define iio_sscanf sscanf_s
3736
#else
38-
#define iio_snprintf snprintf
3937
#define iio_sscanf sscanf
4038
#endif
4139

40+
#if defined(__MINGW32__)
41+
# define __iio_printf __attribute__((__format__(ms_printf, 3, 4)))
42+
#elif defined(__GNUC__)
43+
# define __iio_printf __attribute__((__format__(gnu_printf, 3, 4)))
44+
#else
45+
# define __iio_printf
46+
#endif
47+
4248
#define ARRAY_SIZE(x) (sizeof(x) ? sizeof(x) / sizeof((x)[0]) : 0)
4349
#define BIT(x) (1 << (x))
4450
#define BIT_MASK(bit) BIT((bit) % 32)
@@ -287,6 +293,8 @@ struct iio_context_pdata * iio_context_get_pdata(const struct iio_context *ctx);
287293
int add_iio_dev_attr(struct iio_dev_attrs *attrs, const char *attr,
288294
const char *type, const char *dev_id);
289295

296+
ssize_t __iio_printf iio_snprintf(char *buf, size_t len, const char *fmt, ...);
297+
290298
#undef __api
291299

292300
#endif /* __IIO_PRIVATE_H__ */

utilities.c

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515

1616
#include <errno.h>
1717
#include <locale.h>
18+
#include <stdarg.h>
1819
#include <stdio.h>
1920
#include <stdlib.h>
2021
#include <string.h>
@@ -315,3 +316,17 @@ char * iio_getenv (char * envvar)
315316
#endif
316317
return NULL;
317318
}
319+
320+
ssize_t __iio_printf iio_snprintf(char *buf, size_t len, const char *fmt, ...)
321+
{
322+
va_list ap;
323+
int ret;
324+
325+
va_start(ap, fmt);
326+
ret = vsnprintf(buf, len, fmt, ap);
327+
if (len && ret >= (ssize_t)len)
328+
ret = -ERANGE;
329+
va_end(ap);
330+
331+
return (ssize_t)ret;
332+
}

0 commit comments

Comments
 (0)