1/* Copyright (C) 1992,1995-1999,2000-2002 Free Software Foundation, Inc.
2   This file is part of the GNU C Library.
3
4   This program is free software; you can redistribute it and/or modify
5   it under the terms of the GNU General Public License as published by
6   the Free Software Foundation; either version 2, or (at your option)
7   any later version.
8
9   This program is distributed in the hope that it will be useful,
10   but WITHOUT ANY WARRANTY; without even the implied warranty of
11   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12   GNU General Public License for more details.
13
14   You should have received a copy of the GNU General Public License along
15   with this program; if not, write to the Free Software Foundation,
16   Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
17#include <sys/cdefs.h>
18__RCSID("$NetBSD: unsetenv.c,v 1.2 2016/05/17 14:00:09 christos Exp $");
19
20
21#if HAVE_CONFIG_H
22# include <config.h>
23#endif
24
25#include <errno.h>
26#if !_LIBC
27# if !defined errno && !defined HAVE_ERRNO_DECL
28extern int errno;
29# endif
30# define __set_errno(ev) ((errno) = (ev))
31#endif
32
33#include <stdlib.h>
34#include <string.h>
35#if _LIBC || HAVE_UNISTD_H
36# include <unistd.h>
37#endif
38
39#if !_LIBC
40# define __environ	environ
41# ifndef HAVE_ENVIRON_DECL
42extern char **environ;
43# endif
44#endif
45
46#if _LIBC
47/* This lock protects against simultaneous modifications of `environ'.  */
48# include <bits/libc-lock.h>
49__libc_lock_define_initialized (static, envlock)
50# define LOCK	__libc_lock_lock (envlock)
51# define UNLOCK	__libc_lock_unlock (envlock)
52#else
53# define LOCK
54# define UNLOCK
55#endif
56
57/* In the GNU C library we must keep the namespace clean.  */
58#ifdef _LIBC
59# define unsetenv __unsetenv
60#endif
61
62
63int
64unsetenv (const char *name)
65{
66  size_t len;
67  char **ep;
68
69  if (name == NULL || *name == '\0' || strchr (name, '=') != NULL)
70    {
71      __set_errno (EINVAL);
72      return -1;
73    }
74
75  len = strlen (name);
76
77  LOCK;
78
79  ep = __environ;
80  while (*ep != NULL)
81    if (!strncmp (*ep, name, len) && (*ep)[len] == '=')
82      {
83	/* Found it.  Remove this pointer by moving later ones back.  */
84	char **dp = ep;
85
86	do
87	  dp[0] = dp[1];
88	while (*dp++);
89	/* Continue the loop in case NAME appears again.  */
90      }
91    else
92      ++ep;
93
94  UNLOCK;
95
96  return 0;
97}
98
99#ifdef _LIBC
100# undef unsetenv
101weak_alias (__unsetenv, unsetenv)
102#endif
103