1 /* environ.c -- library for manipulating environments for GNU.
3 Copyright (C) 1986-2017 Free Software Foundation, Inc.
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 3 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. */
18 #include "common-defs.h"
23 /* See common/environ.h. */
26 gdb_environ::operator= (gdb_environ &&e)
28 /* Are we self-moving? */
32 m_environ_vector = std::move (e.m_environ_vector);
33 e.m_environ_vector.clear ();
34 e.m_environ_vector.push_back (NULL);
38 /* See common/environ.h. */
40 gdb_environ gdb_environ::from_host_environ ()
42 extern char **environ;
48 for (int i = 0; environ[i] != NULL; ++i)
50 /* Make sure we add the element before the last (NULL). */
51 e.m_environ_vector.insert (e.m_environ_vector.end () - 1,
52 xstrdup (environ[i]));
58 /* See common/environ.h. */
63 for (char *v : m_environ_vector)
65 m_environ_vector.clear ();
66 /* Always add the NULL element. */
67 m_environ_vector.push_back (NULL);
70 /* Helper function to check if STRING contains an environment variable
71 assignment of VAR, i.e., if STRING starts with 'VAR='. Return true
72 if it contains, false otherwise. */
75 match_var_in_string (char *string, const char *var, size_t var_len)
77 if (strncmp (string, var, var_len) == 0 && string[var_len] == '=')
83 /* See common/environ.h. */
86 gdb_environ::get (const char *var) const
88 size_t len = strlen (var);
90 for (char *el : m_environ_vector)
91 if (el != NULL && match_var_in_string (el, var, len))
97 /* See common/environ.h. */
100 gdb_environ::set (const char *var, const char *value)
102 /* We have to unset the variable in the vector if it exists. */
105 /* Insert the element before the last one, which is always NULL. */
106 m_environ_vector.insert (m_environ_vector.end () - 1,
107 concat (var, "=", value, NULL));
110 /* See common/environ.h. */
113 gdb_environ::unset (const char *var)
115 size_t len = strlen (var);
117 /* We iterate until '.end () - 1' because the last element is
119 for (std::vector<char *>::iterator el = m_environ_vector.begin ();
120 el != m_environ_vector.end () - 1;
122 if (match_var_in_string (*el, var, len))
125 m_environ_vector.erase (el);
130 /* See common/environ.h. */
133 gdb_environ::envp () const
135 return const_cast<char **> (&m_environ_vector[0]);