public inbox for linux-i2c@vger.kernel.org
 help / color / mirror / Atom feed
* [PATCH 1/3] i2ctransfer: Don't free memory which was never allocated
@ 2025-05-13 15:21 Jean Delvare
  2025-05-13 15:23 ` [PATCH 2/3] i2ctransfer: Prevent msgs[] overflow with many parameters Jean Delvare
                   ` (2 more replies)
  0 siblings, 3 replies; 6+ messages in thread
From: Jean Delvare @ 2025-05-13 15:21 UTC (permalink / raw)
  To: Linux I2C; +Cc: Wolfram Sang

If an error occurs while msgs[] is been prepared for the transfer,
we jump to the clean-up path. How many buffers need to be freed
depends on the state. If we were parsing data, we should free up to
nmsgs. However, if we were parsing descriptors, we should free
up to nmsgs - 1 only. The code was unconditionally freeing up to
nmsgs, potentially freeing a non-allocated buffer.

In most cases, it was not a problem, we would simply call free() on a
NULL pointer and that's a no-op. However, if msgs[] was full then we
would access memory beyond its end and call free() on a random
pointer.

Fixes: 9fc53a7fc669 ("i2c-tools: add new tool 'i2ctransfer'")
Signed-off-by: Jean Delvare <jdelvare@suse.de>
---
 tools/i2ctransfer.c |    8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)

--- i2c-tools.orig/tools/i2ctransfer.c
+++ i2c-tools/tools/i2ctransfer.c
@@ -364,7 +364,13 @@ int main(int argc, char *argv[])
  err_out:
 	close(file);
 
-	for (i = 0; i <= nmsgs; i++)
+	/*
+	 * If we were parsing data, the buffer for the last message was
+	 * already allocated and nmsgs still points to it.
+	 */
+	if (state == PARSE_GET_DATA)
+		free(msgs[nmsgs].buf);
+	for (i = 0; i < nmsgs; i++)
 		free(msgs[i].buf);
 
 	exit(1);


-- 
Jean Delvare
SUSE L3 Support

^ permalink raw reply	[flat|nested] 6+ messages in thread

end of thread, other threads:[~2025-05-19 15:36 UTC | newest]

Thread overview: 6+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2025-05-13 15:21 [PATCH 1/3] i2ctransfer: Don't free memory which was never allocated Jean Delvare
2025-05-13 15:23 ` [PATCH 2/3] i2ctransfer: Prevent msgs[] overflow with many parameters Jean Delvare
2025-05-19 15:35   ` Wolfram Sang
2025-05-13 15:35 ` [PATCH 3/3] i2ctransfer: Zero out memory passed to ioctl() Jean Delvare
2025-05-19 15:36   ` Wolfram Sang
2025-05-19 15:31 ` [PATCH 1/3] i2ctransfer: Don't free memory which was never allocated Wolfram Sang

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox