util: Add l_safe_memcpy
PATCH v2 1/2 util: Add l_safe_memcpy
Some callers use memcpy without checking whether the size 'n' is greater than zero. This is generally fine, but does cause sanitizers to complain. Add a new l_safe_memcpy function to take care of this case.
--- ell/util.h | 10 ++++++++++ 1 file changed, 10 insertions(+)
ell/util.h +10 -0
@@ -243,6 +243,16 @@ static inline void l_put_be64(uint64_t val, void *ptr)void *l_malloc (size_t size) __attribute__ ((warn_unused_result, malloc));void *l_memdup (const void *mem,size_t size) __attribute__ ((warn_unused_result, malloc)); + +static inline void * __attribute__((nonnull(1))) l_safe_memcpy(void *dest, + const void *src, size_t n) +{ +if (!n) +return dest; + +return __builtin_memcpy (dest, src, n); +} +void l_free (void *ptr);DEFINE_CLEANUP_FUNC (l_free);
Signature · 1 line
2.45.2
PATCH v2 2/2 unit: Add l_safe_memcpy test
--- unit/test-util.c | 12 ++++++++++++ 1 file changed, 12 insertions(+)
unit/test-util.c +12 -0
@@ -288,6 +288,16 @@ static void test_roundup_pow_of_two(const void *test_data) } } +static void test_safe_memcpy (const void *test_data) +{ +static const uint8_t src[] = {0x00 ,0xff ,0xff ,0xff }; +uint8_t dst[10 ]; + +assert (l_safe_memcpy (dst, src,sizeof (src)) == dst); +assert (l_safe_memcpy (dst, src,0 ) == dst); +assert (l_safe_memcpy (dst,NULL ,0 ) == dst); +} +int main (int argc,char *argv[]) {l_test_init (&argc, &argv);
@@ -313,5 +323,7 @@ int main(int argc, char *argv[])l_test_add ("roundup_pow_of_two" , test_roundup_pow_of_two,NULL ); +l_test_add ("l_safememcpy" , test_safe_memcpy,NULL ); +return l_test_run (); }
Signature · 1 line
2.45.2
Hi Denis,
Quoted 17 lines
Some callers use memcpy without checking whether the size 'n' is greater than zero. This is generally fine, but does cause sanitizers to complain. Add a new
l_safe_memcpyfunction to take care of this case.
---ell/util.h| 10 ++++++++++1 file changed, 10 insertions(+)ell/util.h +2
-0@@ -243,6 +243,16 @@ static inline void l_put_be64(uint64_t val, void *ptr)void *l_malloc (size_t size) __attribute__ ((warn_unused_result, malloc));void *l_memdup (const void *mem,size_t size) __attribute__ ((warn_unused_result, malloc)); + +static inline void * __attribute__((nonnull(1))) l_safe_memcpy(void *dest,
ell/util.h static inline void l_put_be64(uint64_t val, void *ptr) · line 257
Quoted 10 lines
ell/util.h +8
-0+ const void *src, size_t n) +{ + if (!n) + return dest; + +return __builtin_memcpy (dest, src, n); +} +void l_free (void *ptr);DEFINE_CLEANUP_FUNC (l_free);
why not just l_memcpy?
Regards
Marcel