git/list[1] front-page[2] threads[3] people[4] search[5] about
 

[PATCH] mem-pool: use st_add() in mem_pool_strvfmt()

From
René Scharfe <l.s.r@web.de>
Date
Mar 31, 2024, 18:53 UTC
Message-ID
<bbe00b9e-64d8-4ec8-a2b9-2c6917c72dbd@web.de>

If len is INT_MAX in mem_pool_strvfmt(), then len + 1 overflows. Casting it to size_t would prevent that. Use st_add() to go a step further and make the addition *obviously* safe. The compiler can optimize the check away on platforms where SIZE_MAX > INT_MAX, i.e. basically everywhere.

Signed-off-by: René Scharfe <l.s.r@web.de>
---
 mem-pool.c | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)
diff --git a/mem-pool.c b/mem-pool.c
index 2078c22b09..3065b12b23 100644
--- a/mem-pool.c
+++ b/mem-pool.c
@@ -115,6 +115,7 @@ static char *mem_pool_strvfmt(struct mem_pool *pool, const char *fmt,
 	size_t available = block ? block->end - block->next_free : 0;
 	va_list cp;
 	int len, len2;
+	size_t size;
 	char *ret;

 	va_copy(cp, ap);
@@ -123,13 +124,14 @@ static char *mem_pool_strvfmt(struct mem_pool *pool, const char *fmt,
 	if (len < 0)
 		BUG("your vsnprintf is broken (returned %d)", len);

-	ret = mem_pool_alloc(pool, len + 1);  /* 1 for NUL */
+	size = st_add(len, 1); /* 1 for NUL */
+	ret = mem_pool_alloc(pool, size);

 	/* Shortcut; relies on mem_pool_alloc() not touching buffer contents. */
 	if (ret == next_free)
 		return ret;

-	len2 = vsnprintf(ret, len + 1, fmt, ap);
+	len2 = vsnprintf(ret, size, fmt, ap);
 	if (len2 != len)
 		BUG("your vsnprintf is broken (returns inconsistent lengths)");
 	return ret;
--
2.44.0
Next: Jeff King
Message 1 of 9 in “mem-pool: use st_add() in mem_pool_strvfmt()”
  1. mem-pool: use st_add() in mem_pool_strvfmt()René Scharfe, Mar 31, 2024
  2. Jeff KingApr 1, 2024
  3. René ScharfeApr 2, 2024
  4. Jeff KingApr 3, 2024
  5. René ScharfeApr 3, 2024
  6. Jeff KingApr 3, 2024
  7. Jeff KingApr 3, 2024
  8. René ScharfeApr 5, 2024
  9. Jeff KingApr 5, 2024

Read the whole thread, see it on lore, or plain text.

$ cat FOOTERMessages come from the public archive at lore.kernel.org/git, fetched every hour. The front page is chosen and written each morning by an AI editor and can be wrong; the threads themselves are the record. About and API. For agents: an MCP server at https://gitlist.dev/mcp, and any thread, story or person page as Markdown by adding .md to its URL (or sending Accept: text/markdown). Details in /llms.txt.