* [PATCH v2] setenv.c: Get rid of alloca.
@ 2023-06-27 14:04 Joe Simmons-Talbott
0 siblings, 0 replies; only message in thread
From: Joe Simmons-Talbott @ 2023-06-27 14:04 UTC (permalink / raw)
To: libc-alpha; +Cc: Joe Simmons-Talbott
Use malloc rather than alloca to avoid potential stack overflow.
---
Changes to v1:
* Use malloc since alloca'd memory is later malloc'd anyway.
* Fix free logic that was breaking several testcases.
stdlib/setenv.c | 42 ++++++++----------------------------------
1 file changed, 8 insertions(+), 34 deletions(-)
diff --git a/stdlib/setenv.c b/stdlib/setenv.c
index ba5257d3bf..4d9848e263 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,18 +184,11 @@ __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
+ char *new_value = malloc (varlen);
+ if (new_value == NULL)
{
- new_value = malloc (varlen);
- if (new_value == NULL)
- {
- UNLOCK;
- return -1;
- }
+ UNLOCK;
+ return -1;
}
# ifdef _LIBC
__mempcpy (__mempcpy (__mempcpy (new_value, name, namelen), "=", 1),
@@ -209,35 +204,14 @@ __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
-#endif
- {
- np = malloc (varlen);
- if (__glibc_unlikely (np == NULL))
- {
- UNLOCK;
- return -1;
- }
-
-#ifdef USE_TSEARCH
- memcpy (np, new_value, varlen);
-#else
- memcpy (np, name, namelen);
- np[namelen] = '=';
- memcpy (&np[namelen + 1], value, vallen);
+ np = new_value;
#endif
- }
/* And remember the value. */
STORE_VALUE (np);
}
#ifdef USE_TSEARCH
else
- {
- if (__glibc_unlikely (! use_alloca))
- free (new_value);
- }
+ free (new_value);
#endif
}
--
2.39.2
^ permalink raw reply [flat|nested] only message in thread
only message in thread, other threads:[~2023-06-27 14:05 UTC | newest]
Thread overview: (only message) (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2023-06-27 14:04 [PATCH v2] setenv.c: Get rid of alloca Joe Simmons-Talbott
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).