mem-pool: use st_add() in mem_pool_strvfmt()

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> Signed-off-by: Junio C Hamano <gitster@pobox.com>

René Scharfe committed Mar 31, 2024 at 20:53 UTC ffeaf2f76ab422428d6190d0cfbca2f34f06602a
1 file changed +4 -2
mem-pool.c
+4 -2
@@ -115,6 +115,7 @@ static char *mem_pool_strvfmt(struct mem_pool *pool, const char *fmt,
115 size_t available = block ? block->end - block->next_free : 0;
116 va_list cp;
117 int len, len2;
118 + size_t size;
119 char *ret;
120
121 va_copy(cp, ap);
@@ -123,13 +124,14 @@ static char *mem_pool_strvfmt(struct mem_pool *pool, const char *fmt,
124 if (len < 0)
125 BUG("your vsnprintf is broken (returned %d)", len);
126
126 - ret = mem_pool_alloc(pool, len + 1); /* 1 for NUL */
127 + size = st_add(len, 1); /* 1 for NUL */
128 + ret = mem_pool_alloc(pool, size);
129
130 /* Shortcut; relies on mem_pool_alloc() not touching buffer contents. */
131 if (ret == next_free)
132 return ret;
133
132 - len2 = vsnprintf(ret, len + 1, fmt, ap);
134 + len2 = vsnprintf(ret, size, fmt, ap);
135 if (len2 != len)
136 BUG("your vsnprintf is broken (returns inconsistent lengths)");
137 return ret;