Browse Source

Allow setenv(3) and putenv(3) to operate on a NULL environ pointer.

The getenv(3) and unsetenv(3) functions already support this.
This will make it easier to emulate the glibc clearenv() function in ports.
Based on a diff from and OK jca@
OPENBSD_6_0
millert 8 years ago
parent
commit
96b30ff942
1 changed files with 15 additions and 11 deletions
  1. +15
    -11
      src/lib/libc/stdlib/setenv.c

+ 15
- 11
src/lib/libc/stdlib/setenv.c View File

@ -1,4 +1,4 @@
/* $OpenBSD: setenv.c,v 1.17 2016/03/13 18:34:21 guenther Exp $ */
/* $OpenBSD: setenv.c,v 1.18 2016/04/25 21:36:04 millert Exp $ */
/* /*
* Copyright (c) 1987 Regents of the University of California. * Copyright (c) 1987 Regents of the University of California.
* All rights reserved. * All rights reserved.
@ -43,7 +43,7 @@ int
putenv(char *str) putenv(char *str)
{ {
char **P, *cp; char **P, *cp;
size_t cnt;
size_t cnt = 0;
int offset = 0; int offset = 0;
for (cp = str; *cp && *cp != '='; ++cp) for (cp = str; *cp && *cp != '='; ++cp)
@ -65,13 +65,15 @@ putenv(char *str)
} }
/* create new slot for string */ /* create new slot for string */
for (P = environ; *P != NULL; P++)
;
cnt = P - environ;
if (environ != NULL) {
for (P = environ; *P != NULL; P++)
;
cnt = P - environ;
}
P = reallocarray(lastenv, cnt + 2, sizeof(char *)); P = reallocarray(lastenv, cnt + 2, sizeof(char *));
if (!P) if (!P)
return (-1); return (-1);
if (lastenv != environ)
if (lastenv != environ && environ != NULL)
memcpy(P, environ, cnt * sizeof(char *)); memcpy(P, environ, cnt * sizeof(char *));
lastenv = environ = P; lastenv = environ = P;
environ[cnt] = str; environ[cnt] = str;
@ -122,15 +124,17 @@ setenv(const char *name, const char *value, int rewrite)
break; break;
} }
} else { /* create new slot */ } else { /* create new slot */
size_t cnt;
size_t cnt = 0;
for (P = environ; *P != NULL; P++)
;
cnt = P - environ;
if (environ != NULL) {
for (P = environ; *P != NULL; P++)
;
cnt = P - environ;
}
P = reallocarray(lastenv, cnt + 2, sizeof(char *)); P = reallocarray(lastenv, cnt + 2, sizeof(char *));
if (!P) if (!P)
return (-1); return (-1);
if (lastenv != environ)
if (lastenv != environ && environ != NULL)
memcpy(P, environ, cnt * sizeof(char *)); memcpy(P, environ, cnt * sizeof(char *));
lastenv = environ = P; lastenv = environ = P;
offset = cnt; offset = cnt;


Loading…
Cancel
Save