From 67ce07178f1ebae63a319e3d19ab1084d64fe6e2 Mon Sep 17 00:00:00 2001 From: Michael Duda Date: Sun, 29 Jan 2023 11:49:11 -0700 Subject: [PATCH] Switch from memcpy to memmove when copying within buffers In the usb_write_bytes and uart_write_bytes routines, a memcpy was previously used to copy untransmitted bytes to the beginning of the buffer (ud->uart_buffer and ud->usb_buffer, respectively). Since the source and destination regions of memory may potentially overlap, the use of memcpy may lead to undefined results. From the draft C89 standard: 4.11.2.1 The memcpy function Synopsis #include void *memcpy(void *s1, const void *s2, size_t n); Description The memcpy function copies n characters from the object pointed to by s2 into the object pointed to by s1 . If copying takes place between objects that overlap, the behavior is undefined. Returns The memcpy function returns the value of s1 . By using memmove rather than memcpy in the usb_write_bytes and uart_write_bytes routines, the potential for undefined behavior can be avoided. --- uart-bridge.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/uart-bridge.c b/uart-bridge.c index e2aa518..9791df6 100644 --- a/uart-bridge.c +++ b/uart-bridge.c @@ -157,7 +157,7 @@ void usb_write_bytes(uint8_t itf) count = tud_cdc_n_write(itf, ud->uart_buffer, ud->uart_pos); if (count < ud->uart_pos) - memcpy(ud->uart_buffer, &ud->uart_buffer[count], + memmove(ud->uart_buffer, &ud->uart_buffer[count], ud->uart_pos - count); ud->uart_pos -= count; @@ -245,7 +245,7 @@ void uart_write_bytes(uint8_t itf) } if (count < ud->usb_pos) - memcpy(ud->usb_buffer, &ud->usb_buffer[count], + memmove(ud->usb_buffer, &ud->usb_buffer[count], ud->usb_pos - count); ud->usb_pos -= count;