Fix use-after-free of pointer after realloc(3)

We can't use a pointer that was input to realloc(3), nor any pointers
that point to reallocated memory, without making sure that the memory
wasn't moved.  If we do, the Behavior is Undefined.

Signed-off-by: Alejandro Colomar <alx@kernel.org>
This commit is contained in:
Alejandro Colomar 2023-02-05 00:01:13 +01:00 committed by Serge Hallyn
parent efbbcade43
commit 7668f77439

View File

@ -128,12 +128,14 @@ void addenv (const char *string, /*@null@*/const char *value)
*/ */
if ((newenvc & (NEWENVP_STEP - 1)) == 0) { if ((newenvc & (NEWENVP_STEP - 1)) == 0) {
bool update_environ;
char **__newenvp; char **__newenvp;
/* /*
* If the resize operation succeeds we can * If the resize operation succeeds we can
* happily go on, else print a message. * happily go on, else print a message.
*/ */
update_environ = (environ == newenvp);
__newenvp = REALLOCARRAY(newenvp, newenvc + NEWENVP_STEP, char *); __newenvp = REALLOCARRAY(newenvp, newenvc + NEWENVP_STEP, char *);
@ -143,9 +145,8 @@ void addenv (const char *string, /*@null@*/const char *value)
* environ so that it doesn't point to some * environ so that it doesn't point to some
* free memory area (realloc() could move it). * free memory area (realloc() could move it).
*/ */
if (environ == newenvp) { if (update_environ)
environ = __newenvp; environ = __newenvp;
}
newenvp = __newenvp; newenvp = __newenvp;
} else { } else {
(void) fputs (_("Environment overflow\n"), log_get_logfd()); (void) fputs (_("Environment overflow\n"), log_get_logfd());