Re: [PATCH v2 1/2] iio: test: iio-test-format: check that nothing is written past the string

From: Andy Shevchenko

Date: Tue Nov 03 2026 - 06:50:16 EST


On Mon, Nov 02, 2026 at 08:33:55AM +0000, Raffaele Tranfaglia via B4 Relay wrote:
>
> IIO_TEST_FORMAT_EXPECT_EQ() compares the buffer only up to the first NUL
> character. It does not notice if iio_format_value() writes past the end
> of the formatted string, and it cannot check output that contains a NUL.
>
> Poison the buffer before each call. Check the expected bytes, including
> the NUL terminator, with KUNIT_EXPECT_MEMEQ(), and check that the rest of
> the page still holds the poison value. Take the expected length from the
> string literal instead of calling strlen() on the buffer.

> Suggested-by: Andy Shevchenko <andriy.shevchenko@xxxxxxxxx>

...

> +#define IIO_TEST_FORMAT_POISON 0x5a
> +
> +/*
> + * Check the formatted string including its NUL terminator, and that nothing
> + * beyond it was written. _val must be a string literal. The buffer is poisoned
> + * again afterwards for the next check.
> + */
> +#define IIO_TEST_FORMAT_EXPECT_EQ(_test, _buf, _ret, _val) do { \
> + KUNIT_EXPECT_EQ(_test, _ret, (ssize_t)sizeof(_val) - 1); \
> + KUNIT_EXPECT_MEMEQ(_test, _buf, _val, sizeof(_val)); \
> + KUNIT_EXPECT_NULL(_test, memchr_inv((_buf) + sizeof(_val), \
> + IIO_TEST_FORMAT_POISON, \
> + PAGE_SIZE - sizeof(_val))); \
> + memset(_buf, IIO_TEST_FORMAT_POISON, PAGE_SIZE); \
> } while (0)


Format it as

#define IIO_TEST_FORMAT_EXPECT_EQ(_test, _buf, _ret, _val) \
do { \
KUNIT_EXPECT_EQ(_test, _ret, (ssize_t)sizeof(_val) - 1); \
KUNIT_EXPECT_MEMEQ(_test, _buf, _val, sizeof(_val)); \
KUNIT_EXPECT_NULL(_test, \
memchr_inv((_buf) + sizeof(_val), \
IIO_TEST_FORMAT_POISON, \
PAGE_SIZE - sizeof(_val))); \
memset(_buf, IIO_TEST_FORMAT_POISON, PAGE_SIZE); \
} while (0)

Alternatively

#define IIO_TEST_FORMAT_EXPECT_EQ(_test, _buf, _ret, _val) \
do { \
size_t _sz = sizeof(_val); \
\
KUNIT_EXPECT_EQ(_test, _ret, (ssize_t)sz - 1); \
KUNIT_EXPECT_MEMEQ(_test, _buf, _val, sz); \
KUNIT_EXPECT_NULL(_test, \
memchr_inv((_buf) + sz, IIO_TEST_FORMAT_POISON, PAGE_SIZE - sz)); \
memset(_buf, IIO_TEST_FORMAT_POISON, PAGE_SIZE); \
} while (0)

--
With Best Regards,
Andy Shevchenko