[PATCH] setenv.c: Get rid of alloca.
Joe Simmons-Talbott
josimmon@redhat.com
Fri Jun 23 15:25:17 GMT 2023
Use a scratch_buffer rather than alloca to avoid potential stack
overflow.
---
stdlib/setenv.c | 35 ++++++++++-------------------------
1 file changed, 10 insertions(+), 25 deletions(-)
diff --git a/stdlib/setenv.c b/stdlib/setenv.c
index ba5257d3bf..90bc30b219 100644
--- a/stdlib/setenv.c
+++ b/stdlib/setenv.c
@@ -44,6 +44,8 @@ extern int errno;
# include <unistd.h>
#endif
+#include <scratch_buffer.h>
+
#if !_LIBC
# define __environ environ
# ifndef HAVE_ENVIRON_DECL
@@ -182,19 +184,14 @@ __add_to_environ (const char *name, const char *value, const char *combined,
{
const size_t varlen = namelen + 1 + vallen;
#ifdef USE_TSEARCH
- char *new_value;
- int use_alloca = __libc_use_alloca (varlen);
- if (__builtin_expect (use_alloca, 1))
- new_value = (char *) alloca (varlen);
- else
+ struct scratch_buffer buf;
+ scratch_buffer_init (&buf);
+ if (!scratch_buffer_set_array_size (&buf, 1, varlen))
{
- new_value = malloc (varlen);
- if (new_value == NULL)
- {
- UNLOCK;
- return -1;
- }
+ UNLOCK;
+ return -1;
}
+ char *new_value = buf.data;
# ifdef _LIBC
__mempcpy (__mempcpy (__mempcpy (new_value, name, namelen), "=", 1),
value, vallen);
@@ -209,18 +206,9 @@ __add_to_environ (const char *name, const char *value, const char *combined,
#endif
{
#ifdef USE_TSEARCH
- if (__glibc_unlikely (! use_alloca))
- np = new_value;
- else
+ np = new_value;
#endif
{
- np = malloc (varlen);
- if (__glibc_unlikely (np == NULL))
- {
- UNLOCK;
- return -1;
- }
-
#ifdef USE_TSEARCH
memcpy (np, new_value, varlen);
#else
@@ -234,10 +222,7 @@ __add_to_environ (const char *name, const char *value, const char *combined,
}
#ifdef USE_TSEARCH
else
- {
- if (__glibc_unlikely (! use_alloca))
- free (new_value);
- }
+ scratch_buffer_free (&buf);
#endif
}
--
2.39.2
More information about the Libc-alpha
mailing list