[v4] C++ify gdb/common/environ.c

Message ID 20170614192219.12364-1-sergiodj@redhat.com
State New, archived
Headers

Commit Message

Sergio Durigan Junior June 14, 2017, 7:22 p.m. UTC
  As part of the preparation necessary for my upcoming task, I'd like to
propose that we turn gdb_environ into a class.  The approach taken
here is simple: the class gdb_environ contains everything that is
needed to manipulate the environment variables.  These variables are
stored in an std::vector<char *>, which can be converted to a 'char
**' and passed as argument to functions that need it.

The usage has not changed much.  As per Pedro's suggestion, this class
uses a static factory method initialization.  This means that when an
instance is created, it is initially empty.  When needed, it has to be
initialized using the static method 'from_host_environ'.

As mentioned before, this is a preparation for an upcoming work that I
will be posting in the next few weeks or so.  For that work, I'll
probably create another data structure that will contain all the
environment variables that were set by the user using the 'set
environment' command, because I'll need access to them.  This will be
much easier with the class-ification of gdb_environ.

As noted, this has been regression-tested with the new version of
environ.exp and no regressions were found.

gdb/ChangeLog:
yyyy-mm-dd  Sergio Durigan Junior  <sergiodj@redhat.com>

	* Makefile.in (SUBDIR_UNITTESTS_SRCS): Add
	'unittests/environ-selftests.c'.
	(SUBDIR_UNITTESTS_OBS): Add 'environ-selftests.o'.
	* charset.c (find_charset_names): Declare object 'iconv_env'.
	Update code to use 'iconv_env' object.  Remove call to
	'free_environ'.
	* common/environ.c: Include <utility>.
	(make_environ): Delete function.
	(free_environ): Delete function.
	(gdb_environ::clear): New function.
	(gdb_environ::gdb_environ): New function.
	(gdb_environ::~gdb_environ): New function.
	(gdb_environ::operator=): New function.
	(gdb_environ::get): Likewise.
	(environ_vector): Delete function.
	(set_in_environ): Delete function.
	(gdb_environ::set): New function.
	(unset_in_environ): Delete function.
	(gdb_environ::unset): New function.
	(gdb_environ::get_char_vector): Likewise.
	* common/environ.h: Include <vector>.
	(struct gdb_environ): Delete; transform into...
	(class gdb_environ): ... this class.
	(free_environ): Delete prototype.
	(init_environ, get_in_environ, set_in_environ, unset_in_environ,
	environ_vector): Likewise.
	* infcmd.c (run_command_1): Update code to call
	'get_char_vector' from 'gdb_environ' class.
	(environment_info): Update code to call methods from 'gdb_environ'
	class.
	(unset_environment_command): Likewise.
	(path_info): Likewise.
	(path_command): Likewise.
	* inferior.c (inferior::~inferior): Delete call to 'free_environ'.
	(inferior::~inferior): Initialize 'environment' using the host's
	information.
	* inferior.h: Remove forward declaration of 'struct gdb_environ'.
	Include "environ.h".
	(class inferior) <environment>: Change type from 'struct
	gdb_environ' to 'gdb_environ'.
	* mi/mi-cmd-env.c (mi_cmd_env_path): Update code to call
	methods from 'gdb_environ' class.
	(mi_cmd_inferior_tty_show): Use 'getenv' instead of 'gdb_environ'.
	(_initialize_mi_cmd_env): Update code to call methods from
	'gdb_environ' class.
	* solib.c (solib_find_1): Likewise
	* unittests/environ-selftests.c: New file.

gdb/gdbserver/ChangeLog:
yyyy-mm-dd  Sergio Durigan Junior  <sergiodj@redhat.com>

	* linux-low.c (linux_create_inferior): Adjust code to access the
	environment information via 'gdb_environ' class.
	* lynx-low.c (lynx_create_inferior): Likewise.
	* server.c (our_environ): Make it an instance of 'gdb_environ'.
	(get_environ): Return a pointer to 'our_environ'.
	(captured_main): Initialize 'our_environ'.
	* server.h (get_environ): Adjust prototype.
	* spu-low.c (spu_create_inferior): Adjust code to access the
	environment information via 'gdb_environ' class.
---
 gdb/Makefile.in                   |   6 +-
 gdb/charset.c                     |  11 +--
 gdb/common/environ.c              | 191 +++++++++++++-------------------------
 gdb/common/environ.h              |  70 ++++++++++----
 gdb/gdbserver/linux-low.c         |   2 +-
 gdb/gdbserver/lynx-low.c          |   2 +-
 gdb/gdbserver/server.c            |   9 +-
 gdb/gdbserver/server.h            |   6 +-
 gdb/gdbserver/spu-low.c           |   2 +-
 gdb/infcmd.c                      |  37 ++++----
 gdb/inferior.c                    |   4 +-
 gdb/inferior.h                    |   6 +-
 gdb/mi/mi-cmd-env.c               |  12 +--
 gdb/solib.c                       |   7 +-
 gdb/unittests/environ-selftests.c |  79 ++++++++++++++++
 15 files changed, 242 insertions(+), 202 deletions(-)
 create mode 100644 gdb/unittests/environ-selftests.c
  

Comments

Pedro Alves June 16, 2017, 3:45 p.m. UTC | #1
On 06/14/2017 08:22 PM, Sergio Durigan Junior wrote:

> diff --git a/gdb/Makefile.in b/gdb/Makefile.in
> index 5e5fcaa..133db1a 100644
> --- a/gdb/Makefile.in
> +++ b/gdb/Makefile.in
> @@ -530,14 +530,16 @@ SUBDIR_UNITTESTS_SRCS = \
>  	unittests/offset-type-selftests.c \
>  	unittests/optional-selftests.c \
>  	unittests/ptid-selftests.c \
> -	unittests/scoped_restore-selftests.c
> +	unittests/scoped_restore-selftests.c \
> +	unittests/environ-selftests.c

Please keep the list sorted.

(I'm guilty of missing that before too.)

>  
>  SUBDIR_UNITTESTS_OBS = \
>  	function-view-selftests.o \
>  	offset-type-selftests.o \
>  	optional-selftests.o \
>  	ptid-selftests.o \
> -	scoped_restore-selftests.o
> +	scoped_restore-selftests.o \
> +	environ-selftests.o

Ditto.

> diff --git a/gdb/common/environ.c b/gdb/common/environ.c
> index 3145d01..657f2e0 100644
> --- a/gdb/common/environ.c
> +++ b/gdb/common/environ.c
> @@ -18,165 +18,102 @@
>  #include "common-defs.h"
>  #include "environ.h"
>  #include <algorithm>
> -
> +#include <utility>
>  
> -/* Return a new environment object.  */
> +/* See common/environ.h.  */
>  
> -struct gdb_environ *
> -make_environ (void)
> +gdb_environ::gdb_environ ()
>  {
> -  struct gdb_environ *e;
> +}
>  
> -  e = XNEW (struct gdb_environ);
> +/* See common/environ.h.  */
>  
> -  e->allocated = 10;
> -  e->vector = (char **) xmalloc ((e->allocated + 1) * sizeof (char *));
> -  e->vector[0] = 0;
> -  return e;
> +gdb_environ::~gdb_environ ()
> +{
> +  clear ();
>  }
>  
> -/* Free an environment and all the strings in it.  */
> +/* See common/environ.h.  */
>  
> -void
> -free_environ (struct gdb_environ *e)
> +gdb_environ::gdb_environ (gdb_environ &&e)
> +  : m_environ_vector (std::move (e.m_environ_vector))
>  {
> -  char **vector = e->vector;
> +}
>  
> -  while (*vector)
> -    xfree (*vector++);
> +/* See common/environ.h.  */
>  
> -  xfree (e->vector);
> -  xfree (e);
> +gdb_environ &
> +gdb_environ::operator= (gdb_environ &&e)
> +{
> +  clear ();
> +  m_environ_vector = std::move (e.m_environ_vector);
> +  return *this;
>  }
>  
> -/* Copy the environment given to this process into E.
> -   Also copies all the strings in it, so we can be sure
> -   that all strings in these environments are safe to free.  */
> +/* See common/environ.h.  */
>  
>  void
> -init_environ (struct gdb_environ *e)
> +gdb_environ::clear ()
>  {
> -  extern char **environ;
> -  int i;
> -
> -  if (environ == NULL)
> -    return;
> -
> -  for (i = 0; environ[i]; i++) /*EMPTY */ ;
> +  for (char *v : m_environ_vector)
> +    xfree (v);
> +  m_environ_vector.clear ();
> +}
>  
> -  if (e->allocated < i)
> -    {
> -      e->allocated = std::max (i, e->allocated + 10);
> -      e->vector = (char **) xrealloc ((char *) e->vector,
> -				      (e->allocated + 1) * sizeof (char *));
> -    }
> +/* See common/environ.h.  */
>  
> -  memcpy (e->vector, environ, (i + 1) * sizeof (char *));
> +const char *
> +gdb_environ::get (const std::string &var) const
> +{

Does this need to be a std::string instead of "const char *"?
Callers always pass a string literal down, so this is going to
force a deep string dup for no good reason, AFAICS.


> +  size_t len = var.size ();
> +  const char *var_str = var.c_str ();
>  
> -  while (--i >= 0)
> -    {
> -      int len = strlen (e->vector[i]);
> -      char *newobj = (char *) xmalloc (len + 1);
> +  for (char *el : m_environ_vector)
> +    if (el != NULL && strncmp (el, var_str, len) == 0 && el[len] == '=')
> +      return &el[len + 1];
>  
> -      memcpy (newobj, e->vector[i], len + 1);
> -      e->vector[i] = newobj;
> -    }
> +  return NULL;
>  }

> -char *
> -get_in_environ (const struct gdb_environ *e, const char *var)
> +void
> +gdb_environ::set (const std::string &var, const std::string &value)

Ditto.

>  {
> -  int len = strlen (var);
> -  char **vector = e->vector;
> -  char *s;
> -
> -  for (; (s = *vector) != NULL; vector++)
> -    if (strncmp (s, var, len) == 0 && s[len] == '=')
> -      return &s[len + 1];
> +  /* We have to unset the variable in the vector if it exists.  */
> +  unset (var);
>  
> -  return 0;
> +  /* Insert the element before the last one, which is always NULL.  */
> +  m_environ_vector.insert (m_environ_vector.end () - 1,
> +			   concat (var.c_str (), "=",
> +				   value.c_str (), NULL));
>  }
>  
> -/* Store the value in E of VAR as VALUE.  */
> +/* See common/environ.h.  */
>  
>  void
> -set_in_environ (struct gdb_environ *e, const char *var, const char *value)
> +gdb_environ::unset (const std::string &var)

Ditto.


> -
> -  return;
> +  std::string match = var + '=';
> +  const char *match_str = match.c_str ();
> +
> +  /* We iterate until '.cend () - 1' because the last element is
> +     always NULL.  */
> +  for (std::vector<char *>::const_iterator el = m_environ_vector.cbegin ();
> +       el != m_environ_vector.cend () - 1;
> +       ++el)
> +    if (startswith (*el, match_str))

In gdb_environ::set you used:

    strncmp (el, var_str, len) == 0 && el[len] == '='

It'd be better if places used the same matching code.  Maybe even put
this in a separate helper function.  The gdb_environ::set version
looks better to me for avoiding temporary heap-allocated strings.


> -/* Remove the setting for variable VAR from environment E.  */
> +/* See common/environ.h.  */
>  
> -void
> -unset_in_environ (struct gdb_environ *e, const char *var)
> +char **
> +gdb_environ::get_char_vector () const

So far, getters in gdb's classes don't have a "get_" prefix.
(except "get()" or course, but that's really a getter in
the same sense.)  Can we drop it here?  Like:

 char **gdb_environ::char_vector () const

Though I'd rename it like this instead:

 char ** gdb_environ::envp () const

Because that's what the env vector is traditionally called, e.g.,
from "man 2 execve":

     int execve(const char *filename, char *const argv[],
                  char *const envp[]);

     int main(int argc, char *argv[], char *envp[])

Likewise I'd use that name for local variables where
we call gdb_environ::get_char_vector, just to follow
traditional terminology throughout.

> +/* Class that represents the environment variables as seen by the
> +   inferior.  */
> +
> +class gdb_environ
> +{
> +public:
> +  /* Regular constructor and destructor.  */
> +  gdb_environ ();
> +  ~gdb_environ ();
> +
> +  /* Move constructor.  */
> +  gdb_environ (gdb_environ &&e);
> +
> +  /* Move assignment.  */
> +  gdb_environ &operator= (gdb_environ &&e);
> +
> +  /* Create a gdb_environ object using the host's environment
> +     variables.  */
> +  static gdb_environ from_host_environ ()
>    {

Nit: I find it a bit odd that the ctors/dtors are short but 
defined out of line, while this function is defined inline.
If I was looking at controlling what the compiler could inline,
then I'd do it the other way around -- small ctor/dtor in
the header, and this larger function out of line in the .c file.

> -    /* Number of usable slots allocated in VECTOR.
> -       VECTOR always has one slot not counted here,
> -       to hold the terminating zero.  */
> -    int allocated;
> -    /* A vector of slots, ALLOCATED + 1 of them.
> -       The first few slots contain strings "VAR=VALUE"
> -       and the next one contains zero.
> -       Then come some unused slots.  */
> -    char **vector;
> -  };
> +    extern char **environ;
> +    gdb_environ e;
> +
> +    if (environ == NULL)
> +      return e;
> +
> +    for (int i = 0; environ[i] != NULL; ++i)
> +      e.m_environ_vector.push_back (xstrdup (environ[i]));
> +
> +    /* The last element of the vector is always going to be NULL.  */
> +    e.m_environ_vector.push_back (NULL);
>  
> -extern struct gdb_environ *make_environ (void);
> +    return e;
> +  }

>    run_target->to_create_inferior (run_target, exec_file,
>  				  std::string (get_inferior_args ()),
> -				  environ_vector (current_inferior ()->environment),
> +				  current_inferior ()
> +				  ->environment.get_char_vector (),
>  				  from_tty);
> @@ -270,7 +270,6 @@ mi_cmd_inferior_tty_show (const char *command, char **argv, int argc)
>  void 
>  _initialize_mi_cmd_env (void)
>  {
> -  struct gdb_environ *environment;
>    const char *env;
>  
>    /* We want original execution path to reset to, if desired later.
> @@ -278,13 +277,10 @@ _initialize_mi_cmd_env (void)
>       current_inferior ()->environment.  Also, there's no obvious
>       place where this code can be moved such that it surely run
>       before any code possibly mangles original PATH.  */
> -  environment = make_environ ();
> -  init_environ (environment);
> -  env = get_in_environ (environment, path_var_name);
> +  env = getenv (path_var_name);
>  
>    /* Can be null if path is not set.  */
>    if (!env)
>      env = "";
>    orig_path = xstrdup (env);
> -  free_environ (environment);
>  }

Please split this change to a separate patch.  Don't we need to
update the comment just above?


> diff --git a/gdb/unittests/environ-selftests.c b/gdb/unittests/environ-selftests.c
> new file mode 100644
> index 0000000..948eacf
> --- /dev/null
> +++ b/gdb/unittests/environ-selftests.c
> @@ -0,0 +1,79 @@
> +/* Self tests for gdb_environ for GDB, the GNU debugger.
> +
> +   Copyright (C) 2017 Free Software Foundation, Inc.
> +
> +   This file is part of GDB.
> +
> +   This program is free software; you can redistribute it and/or modify
> +   it under the terms of the GNU General Public License as published by
> +   the Free Software Foundation; either version 3 of the License, or
> +   (at your option) any later version.
> +
> +   This program is distributed in the hope that it will be useful,
> +   but WITHOUT ANY WARRANTY; without even the implied warranty of
> +   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
> +   GNU General Public License for more details.
> +
> +   You should have received a copy of the GNU General Public License
> +   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
> +
> +#include "defs.h"
> +#include "selftest.h"
> +#include "common/environ.h"
> +
> +namespace selftests {
> +namespace environ {

"environ" as an identifier will be problematic.  Please
pick some other name here.

On some hosts "environ" is a define.  E.g., on my Fedora's
mingw-w64 install I see:

 /usr/x86_64-w64-mingw32/sys-root/mingw/include/stdlib.h:624:#define environ _environ

and gnulib has too:

 $ srcgrep -rn environ gnulib/import/ | grep define
 gnulib/import/extra/snippet/warn-on-use.h:61:   # define environ (*rpl_environ ())
 gnulib/import/unistd.in.h:411:#   define environ (*_NSGetEnviron ())
 gnulib/import/unistd.in.h:432:#  define environ (*rpl_environ ())

I don't think "namespace (*_NSGetEnviron ())" would compile.  :-)


> +
> +static void
> +run_tests ()
> +{
> +  if (setenv ("GDB_SELFTEST_ENVIRON", "1", 1) != 0)
> +    error ("Could not set environment variable for testing.");
> +
> +  gdb_environ env;
> +

Please add a test that that checks that get_char_vector() on an
empty gdb_environ works as expected.  I.e., something like:

   gdb_environ env;
   SELF_CHECK (env.get_char_vector()[0] == NULL);

AFAICS from:

 gdb_environ::gdb_environ ()
 {
 }

 char **
 gdb_environ::get_char_vector () const
 {
   return const_cast<char **> (&m_environ_vector[0]);
 }

we end up with a bogus envp, because it points at
m_environ_vector.end(), which is not a valid pointer
to dereference.  Even ignoring that, it does not point
to NULL.  So if we pass such a pointer to execve or some syscall
that accepts an envp, then it'll try iterating the vector until
it finds a NULL entry, and of course do the wrong thing,
maybe crash if you're lucky.

Note we can get this situation from here too:

  static gdb_environ from_host_environ ()
  {
    extern char **environ;
    gdb_environ e;

    if (environ == NULL)
      return e;


The old code did not suffer from this because it always
allocated gdb_environ::vector:

 struct gdb_environ *
 make_environ (void)
 {
   struct gdb_environ *e;

   e = XNEW (struct gdb_environ);

   e->allocated = 10;
   e->vector = (char **) xmalloc ((e->allocated + 1) * sizeof (char *));
   e->vector[0] = 0;
   return e;
 }

So we either always add a NULL to the vector, or we
change gdb_environ::get_char_vector instead, like:

 char **
 gdb_environ::get_char_vector () const
 {
   if (m_environ_vector.empty ())
     {
       static const char *const empty_envp[1] = { NULL };
       return const_cast<char **> (empty_envp);
     }
   return const_cast<char **> (&m_environ_vector[0]);
 }

This is OK because execve etc. are garanteed to never change
the envp they're passed.

> +  SELF_CHECK (env.get ("PWD") == NULL);
> +
> +  env = gdb_environ::from_host_environ ();
> +
> +  SELF_CHECK (strcmp (env.get ("GDB_SELFTEST_ENVIRON"), "1") == 0);
> +
> +  env.set ("GDB_SELFTEST_ENVIRON", "test");
> +  SELF_CHECK (strcmp (env.get ("GDB_SELFTEST_ENVIRON"), "test") == 0);
> +
> +  env.unset ("GDB_SELFTEST_ENVIRON");
> +  SELF_CHECK (env.get ("GDB_SELFTEST_ENVIRON") == NULL);
> +
> +  env.set ("GDB_SELFTEST_ENVIRON", "1");
> +  SELF_CHECK (strcmp (env.get ("GDB_SELFTEST_ENVIRON"), "1") == 0);
> +
> +  env.clear ();
> +  SELF_CHECK (env.get ("GDB_SELFTEST_ENVIRON") == NULL);

Like above, after env.clear() check that this works:

   SELF_CHECK (env.get_char_vector()[0] == NULL);

> +
> +  if (setenv ("GDB_SELFTEST_ENVIRON", "1", 1) != 0)
> +    error ("Could not set environment variable for testing.");

This setenv looks like a stale copy from the one at the top?
I'm not seeing why it's necessary here.

> +
> +  env = gdb_environ::from_host_environ ();
> +  char **penv = env.get_char_vector ();
> +  bool found_var = false, found_twice = false;
> +
> +  for (size_t i = 0; penv[i] != NULL; ++i)
> +    if (strcmp (penv[i], "GDB_SELFTEST_ENVIRON=1") == 0)
> +      {
> +	if (found_var)
> +	  found_twice = true;
> +	found_var = true;
> +      }
> +  SELF_CHECK (found_var == true);
> +  SELF_CHECK (found_twice == false);

Why not simply a count:

  int found_count = 0;
  for (size_t i = 0; penv[i] != NULL; ++i)
    if (strcmp (penv[i], "GDB_SELFTEST_ENVIRON=1") == 0)
      found_count++;
  SELF_CHECK (found_count == 1);


I think that no test actually explicitly sets more than one
var in the vector.  I think you should exercise that.
Also check that removing some other var doesn't remove the
first.  Etc.  E.g., set var 1, set var 2, unset var 1,
check that  var 2 is still there.

Thanks,
Pedro Alves
  
Sergio Durigan Junior June 16, 2017, 6:01 p.m. UTC | #2
On Friday, June 16 2017, Pedro Alves wrote:

> On 06/14/2017 08:22 PM, Sergio Durigan Junior wrote:
>
>> diff --git a/gdb/Makefile.in b/gdb/Makefile.in
>> index 5e5fcaa..133db1a 100644
>> --- a/gdb/Makefile.in
>> +++ b/gdb/Makefile.in
>> @@ -530,14 +530,16 @@ SUBDIR_UNITTESTS_SRCS = \
>>  	unittests/offset-type-selftests.c \
>>  	unittests/optional-selftests.c \
>>  	unittests/ptid-selftests.c \
>> -	unittests/scoped_restore-selftests.c
>> +	unittests/scoped_restore-selftests.c \
>> +	unittests/environ-selftests.c
>
> Please keep the list sorted.
>
> (I'm guilty of missing that before too.)

Done.

>>  
>>  SUBDIR_UNITTESTS_OBS = \
>>  	function-view-selftests.o \
>>  	offset-type-selftests.o \
>>  	optional-selftests.o \
>>  	ptid-selftests.o \
>> -	scoped_restore-selftests.o
>> +	scoped_restore-selftests.o \
>> +	environ-selftests.o
>
> Ditto.

Done.

>> diff --git a/gdb/common/environ.c b/gdb/common/environ.c
>> index 3145d01..657f2e0 100644
>> --- a/gdb/common/environ.c
>> +++ b/gdb/common/environ.c
>> @@ -18,165 +18,102 @@
>>  #include "common-defs.h"
>>  #include "environ.h"
>>  #include <algorithm>
>> -
>> +#include <utility>
>>  
>> -/* Return a new environment object.  */
>> +/* See common/environ.h.  */
>>  
>> -struct gdb_environ *
>> -make_environ (void)
>> +gdb_environ::gdb_environ ()
>>  {
>> -  struct gdb_environ *e;
>> +}
>>  
>> -  e = XNEW (struct gdb_environ);
>> +/* See common/environ.h.  */
>>  
>> -  e->allocated = 10;
>> -  e->vector = (char **) xmalloc ((e->allocated + 1) * sizeof (char *));
>> -  e->vector[0] = 0;
>> -  return e;
>> +gdb_environ::~gdb_environ ()
>> +{
>> +  clear ();
>>  }
>>  
>> -/* Free an environment and all the strings in it.  */
>> +/* See common/environ.h.  */
>>  
>> -void
>> -free_environ (struct gdb_environ *e)
>> +gdb_environ::gdb_environ (gdb_environ &&e)
>> +  : m_environ_vector (std::move (e.m_environ_vector))
>>  {
>> -  char **vector = e->vector;
>> +}
>>  
>> -  while (*vector)
>> -    xfree (*vector++);
>> +/* See common/environ.h.  */
>>  
>> -  xfree (e->vector);
>> -  xfree (e);
>> +gdb_environ &
>> +gdb_environ::operator= (gdb_environ &&e)
>> +{
>> +  clear ();
>> +  m_environ_vector = std::move (e.m_environ_vector);
>> +  return *this;
>>  }
>>  
>> -/* Copy the environment given to this process into E.
>> -   Also copies all the strings in it, so we can be sure
>> -   that all strings in these environments are safe to free.  */
>> +/* See common/environ.h.  */
>>  
>>  void
>> -init_environ (struct gdb_environ *e)
>> +gdb_environ::clear ()
>>  {
>> -  extern char **environ;
>> -  int i;
>> -
>> -  if (environ == NULL)
>> -    return;
>> -
>> -  for (i = 0; environ[i]; i++) /*EMPTY */ ;
>> +  for (char *v : m_environ_vector)
>> +    xfree (v);
>> +  m_environ_vector.clear ();
>> +}
>>  
>> -  if (e->allocated < i)
>> -    {
>> -      e->allocated = std::max (i, e->allocated + 10);
>> -      e->vector = (char **) xrealloc ((char *) e->vector,
>> -				      (e->allocated + 1) * sizeof (char *));
>> -    }
>> +/* See common/environ.h.  */
>>  
>> -  memcpy (e->vector, environ, (i + 1) * sizeof (char *));
>> +const char *
>> +gdb_environ::get (const std::string &var) const
>> +{
>
> Does this need to be a std::string instead of "const char *"?
> Callers always pass a string literal down, so this is going to
> force a deep string dup for no good reason, AFAICS.

It doesn't.  Changed to const char *.

>
>> +  size_t len = var.size ();
>> +  const char *var_str = var.c_str ();
>>  
>> -  while (--i >= 0)
>> -    {
>> -      int len = strlen (e->vector[i]);
>> -      char *newobj = (char *) xmalloc (len + 1);
>> +  for (char *el : m_environ_vector)
>> +    if (el != NULL && strncmp (el, var_str, len) == 0 && el[len] == '=')
>> +      return &el[len + 1];
>>  
>> -      memcpy (newobj, e->vector[i], len + 1);
>> -      e->vector[i] = newobj;
>> -    }
>> +  return NULL;
>>  }
>
>> -char *
>> -get_in_environ (const struct gdb_environ *e, const char *var)
>> +void
>> +gdb_environ::set (const std::string &var, const std::string &value)
>
> Ditto.

Likewise.

>>  {
>> -  int len = strlen (var);
>> -  char **vector = e->vector;
>> -  char *s;
>> -
>> -  for (; (s = *vector) != NULL; vector++)
>> -    if (strncmp (s, var, len) == 0 && s[len] == '=')
>> -      return &s[len + 1];
>> +  /* We have to unset the variable in the vector if it exists.  */
>> +  unset (var);
>>  
>> -  return 0;
>> +  /* Insert the element before the last one, which is always NULL.  */
>> +  m_environ_vector.insert (m_environ_vector.end () - 1,
>> +			   concat (var.c_str (), "=",
>> +				   value.c_str (), NULL));
>>  }
>>  
>> -/* Store the value in E of VAR as VALUE.  */
>> +/* See common/environ.h.  */
>>  
>>  void
>> -set_in_environ (struct gdb_environ *e, const char *var, const char *value)
>> +gdb_environ::unset (const std::string &var)
>
> Ditto.

Likewise.

>
>> -
>> -  return;
>> +  std::string match = var + '=';
>> +  const char *match_str = match.c_str ();
>> +
>> +  /* We iterate until '.cend () - 1' because the last element is
>> +     always NULL.  */
>> +  for (std::vector<char *>::const_iterator el = m_environ_vector.cbegin ();
>> +       el != m_environ_vector.cend () - 1;
>> +       ++el)
>> +    if (startswith (*el, match_str))
>
> In gdb_environ::set you used:

I assume you meant gdb_environ::get, right?

>
>     strncmp (el, var_str, len) == 0 && el[len] == '='
>
> It'd be better if places used the same matching code.  Maybe even put
> this in a separate helper function.  The gdb_environ::set version
> looks better to me for avoiding temporary heap-allocated strings.

Right, done.

>
>> -/* Remove the setting for variable VAR from environment E.  */
>> +/* See common/environ.h.  */
>>  
>> -void
>> -unset_in_environ (struct gdb_environ *e, const char *var)
>> +char **
>> +gdb_environ::get_char_vector () const
>
> So far, getters in gdb's classes don't have a "get_" prefix.
> (except "get()" or course, but that's really a getter in
> the same sense.)  Can we drop it here?  Like:

Yeah, sure.  Simon made this observation in a previous review about the
other methods, but I thought it'd make sense to keep the "get_" prefix
for this specific one.

>
>  char **gdb_environ::char_vector () const
>
> Though I'd rename it like this instead:
>
>  char ** gdb_environ::envp () const
>
> Because that's what the env vector is traditionally called, e.g.,
> from "man 2 execve":
>
>      int execve(const char *filename, char *const argv[],
>                   char *const envp[]);
>
>      int main(int argc, char *argv[], char *envp[])
>
> Likewise I'd use that name for local variables where
> we call gdb_environ::get_char_vector, just to follow
> traditional terminology throughout.

OK, fair enough.  I'll rename it to envp then.  There's just one place
where we assign the return of gdb_environ::get_char_vector to a local
variable (in infcmd.c), so I renamed it accordingly.

>> +/* Class that represents the environment variables as seen by the
>> +   inferior.  */
>> +
>> +class gdb_environ
>> +{
>> +public:
>> +  /* Regular constructor and destructor.  */
>> +  gdb_environ ();
>> +  ~gdb_environ ();
>> +
>> +  /* Move constructor.  */
>> +  gdb_environ (gdb_environ &&e);
>> +
>> +  /* Move assignment.  */
>> +  gdb_environ &operator= (gdb_environ &&e);
>> +
>> +  /* Create a gdb_environ object using the host's environment
>> +     variables.  */
>> +  static gdb_environ from_host_environ ()
>>    {
>
> Nit: I find it a bit odd that the ctors/dtors are short but 
> defined out of line, while this function is defined inline.
> If I was looking at controlling what the compiler could inline,
> then I'd do it the other way around -- small ctor/dtor in
> the header, and this larger function out of line in the .c file.

Question: if I define a method inside the class, does this implicitly
tell the compiler that I want to inline it, as oppose to defining the
method outside?

I'll follow your advice and define the short ctors inside the class, and
move the definition of from_host_environ to the C file.

>> -    /* Number of usable slots allocated in VECTOR.
>> -       VECTOR always has one slot not counted here,
>> -       to hold the terminating zero.  */
>> -    int allocated;
>> -    /* A vector of slots, ALLOCATED + 1 of them.
>> -       The first few slots contain strings "VAR=VALUE"
>> -       and the next one contains zero.
>> -       Then come some unused slots.  */
>> -    char **vector;
>> -  };
>> +    extern char **environ;
>> +    gdb_environ e;
>> +
>> +    if (environ == NULL)
>> +      return e;
>> +
>> +    for (int i = 0; environ[i] != NULL; ++i)
>> +      e.m_environ_vector.push_back (xstrdup (environ[i]));
>> +
>> +    /* The last element of the vector is always going to be NULL.  */
>> +    e.m_environ_vector.push_back (NULL);
>>  
>> -extern struct gdb_environ *make_environ (void);
>> +    return e;
>> +  }
>
>>    run_target->to_create_inferior (run_target, exec_file,
>>  				  std::string (get_inferior_args ()),
>> -				  environ_vector (current_inferior ()->environment),
>> +				  current_inferior ()
>> +				  ->environment.get_char_vector (),
>>  				  from_tty);
>> @@ -270,7 +270,6 @@ mi_cmd_inferior_tty_show (const char *command, char **argv, int argc)
>>  void 
>>  _initialize_mi_cmd_env (void)
>>  {
>> -  struct gdb_environ *environment;
>>    const char *env;
>>  
>>    /* We want original execution path to reset to, if desired later.
>> @@ -278,13 +277,10 @@ _initialize_mi_cmd_env (void)
>>       current_inferior ()->environment.  Also, there's no obvious
>>       place where this code can be moved such that it surely run
>>       before any code possibly mangles original PATH.  */
>> -  environment = make_environ ();
>> -  init_environ (environment);
>> -  env = get_in_environ (environment, path_var_name);
>> +  env = getenv (path_var_name);
>>  
>>    /* Can be null if path is not set.  */
>>    if (!env)
>>      env = "";
>>    orig_path = xstrdup (env);
>> -  free_environ (environment);
>>  }
>
> Please split this change to a separate patch.  Don't we need to
> update the comment just above?

Sure, I'll split and send a separate patch.  And yeah, the comment needs
updating, thanks for noticing that.

>
>> diff --git a/gdb/unittests/environ-selftests.c b/gdb/unittests/environ-selftests.c
>> new file mode 100644
>> index 0000000..948eacf
>> --- /dev/null
>> +++ b/gdb/unittests/environ-selftests.c
>> @@ -0,0 +1,79 @@
>> +/* Self tests for gdb_environ for GDB, the GNU debugger.
>> +
>> +   Copyright (C) 2017 Free Software Foundation, Inc.
>> +
>> +   This file is part of GDB.
>> +
>> +   This program is free software; you can redistribute it and/or modify
>> +   it under the terms of the GNU General Public License as published by
>> +   the Free Software Foundation; either version 3 of the License, or
>> +   (at your option) any later version.
>> +
>> +   This program is distributed in the hope that it will be useful,
>> +   but WITHOUT ANY WARRANTY; without even the implied warranty of
>> +   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
>> +   GNU General Public License for more details.
>> +
>> +   You should have received a copy of the GNU General Public License
>> +   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
>> +
>> +#include "defs.h"
>> +#include "selftest.h"
>> +#include "common/environ.h"
>> +
>> +namespace selftests {
>> +namespace environ {
>
> "environ" as an identifier will be problematic.  Please
> pick some other name here.
>
> On some hosts "environ" is a define.  E.g., on my Fedora's
> mingw-w64 install I see:
>
>  /usr/x86_64-w64-mingw32/sys-root/mingw/include/stdlib.h:624:#define environ _environ
>
> and gnulib has too:
>
>  $ srcgrep -rn environ gnulib/import/ | grep define
>  gnulib/import/extra/snippet/warn-on-use.h:61:   # define environ (*rpl_environ ())
>  gnulib/import/unistd.in.h:411:#   define environ (*_NSGetEnviron ())
>  gnulib/import/unistd.in.h:432:#  define environ (*rpl_environ ())
>
> I don't think "namespace (*_NSGetEnviron ())" would compile.  :-)

Hah, right :-).  I'll pick "namespace gdb_environ" then.

>
>> +
>> +static void
>> +run_tests ()
>> +{
>> +  if (setenv ("GDB_SELFTEST_ENVIRON", "1", 1) != 0)
>> +    error ("Could not set environment variable for testing.");
>> +
>> +  gdb_environ env;
>> +
>
> Please add a test that that checks that get_char_vector() on an
> empty gdb_environ works as expected.  I.e., something like:
>
>    gdb_environ env;
>    SELF_CHECK (env.get_char_vector()[0] == NULL);

Hm, right, makes sense.  I'll add that.

> AFAICS from:
>
>  gdb_environ::gdb_environ ()
>  {
>  }
>
>  char **
>  gdb_environ::get_char_vector () const
>  {
>    return const_cast<char **> (&m_environ_vector[0]);
>  }
>
> we end up with a bogus envp, because it points at
> m_environ_vector.end(), which is not a valid pointer
> to dereference.  Even ignoring that, it does not point
> to NULL.  So if we pass such a pointer to execve or some syscall
> that accepts an envp, then it'll try iterating the vector until
> it finds a NULL entry, and of course do the wrong thing,
> maybe crash if you're lucky.
>
> Note we can get this situation from here too:
>
>   static gdb_environ from_host_environ ()
>   {
>     extern char **environ;
>     gdb_environ e;
>
>     if (environ == NULL)
>       return e;
>
>
> The old code did not suffer from this because it always
> allocated gdb_environ::vector:
>
>  struct gdb_environ *
>  make_environ (void)
>  {
>    struct gdb_environ *e;
>
>    e = XNEW (struct gdb_environ);
>
>    e->allocated = 10;
>    e->vector = (char **) xmalloc ((e->allocated + 1) * sizeof (char *));
>    e->vector[0] = 0;
>    return e;
>  }
>
> So we either always add a NULL to the vector, or we
> change gdb_environ::get_char_vector instead, like:
>
>  char **
>  gdb_environ::get_char_vector () const
>  {
>    if (m_environ_vector.empty ())
>      {
>        static const char *const empty_envp[1] = { NULL };
>        return const_cast<char **> (empty_envp);
>      }
>    return const_cast<char **> (&m_environ_vector[0]);
>  }
>
> This is OK because execve etc. are garanteed to never change
> the envp they're passed.

Oh, good catch.  I prefer to just initialize the vector with a NULL
value in the ctor; will do that now.

>> +  SELF_CHECK (env.get ("PWD") == NULL);
>> +
>> +  env = gdb_environ::from_host_environ ();
>> +
>> +  SELF_CHECK (strcmp (env.get ("GDB_SELFTEST_ENVIRON"), "1") == 0);
>> +
>> +  env.set ("GDB_SELFTEST_ENVIRON", "test");
>> +  SELF_CHECK (strcmp (env.get ("GDB_SELFTEST_ENVIRON"), "test") == 0);
>> +
>> +  env.unset ("GDB_SELFTEST_ENVIRON");
>> +  SELF_CHECK (env.get ("GDB_SELFTEST_ENVIRON") == NULL);
>> +
>> +  env.set ("GDB_SELFTEST_ENVIRON", "1");
>> +  SELF_CHECK (strcmp (env.get ("GDB_SELFTEST_ENVIRON"), "1") == 0);
>> +
>> +  env.clear ();
>> +  SELF_CHECK (env.get ("GDB_SELFTEST_ENVIRON") == NULL);
>
> Like above, after env.clear() check that this works:
>
>    SELF_CHECK (env.get_char_vector()[0] == NULL);

Will do.

>> +
>> +  if (setenv ("GDB_SELFTEST_ENVIRON", "1", 1) != 0)
>> +    error ("Could not set environment variable for testing.");
>
> This setenv looks like a stale copy from the one at the top?
> I'm not seeing why it's necessary here.

It is indeed, thanks.  Removed.

>> +
>> +  env = gdb_environ::from_host_environ ();
>> +  char **penv = env.get_char_vector ();
>> +  bool found_var = false, found_twice = false;
>> +
>> +  for (size_t i = 0; penv[i] != NULL; ++i)
>> +    if (strcmp (penv[i], "GDB_SELFTEST_ENVIRON=1") == 0)
>> +      {
>> +	if (found_var)
>> +	  found_twice = true;
>> +	found_var = true;
>> +      }
>> +  SELF_CHECK (found_var == true);
>> +  SELF_CHECK (found_twice == false);
>
> Why not simply a count:
>
>   int found_count = 0;
>   for (size_t i = 0; penv[i] != NULL; ++i)
>     if (strcmp (penv[i], "GDB_SELFTEST_ENVIRON=1") == 0)
>       found_count++;
>   SELF_CHECK (found_count == 1);

Good idea, thanks.

> I think that no test actually explicitly sets more than one
> var in the vector.  I think you should exercise that.
> Also check that removing some other var doesn't remove the
> first.  Etc.  E.g., set var 1, set var 2, unset var 1,
> check that  var 2 is still there.

Will do.

Thanks for the review.  I'll send v5 soon.
  
Pedro Alves June 16, 2017, 6:23 p.m. UTC | #3
On 06/16/2017 07:01 PM, Sergio Durigan Junior wrote:
> On Friday, June 16 2017, Pedro Alves wrote:
> 
>> On 06/14/2017 08:22 PM, Sergio Durigan Junior wrote:
>>
>>> diff --git a/gdb/Makefile.in b/gdb/Makefile.in
>>> index 5e5fcaa..133db1a 100644
>>> --- a/gdb/Makefile.in
>>> +++ b/gdb/Makefile.in
>>> @@ -530,14 +530,16 @@ SUBDIR_UNITTESTS_SRCS = \
>>>  	unittests/offset-type-selftests.c \
>>>  	unittests/optional-selftests.c \
>>>  	unittests/ptid-selftests.c \
>>> -	unittests/scoped_restore-selftests.c
>>> +	unittests/scoped_restore-selftests.c \
>>> +	unittests/environ-selftests.c
>>
>> Please keep the list sorted.
>>
>> (I'm guilty of missing that before too.)
> 
> Done.
> 
>>>  
>>>  SUBDIR_UNITTESTS_OBS = \
>>>  	function-view-selftests.o \
>>>  	offset-type-selftests.o \
>>>  	optional-selftests.o \
>>>  	ptid-selftests.o \
>>> -	scoped_restore-selftests.o
>>> +	scoped_restore-selftests.o \
>>> +	environ-selftests.o
>>
>> Ditto.
> 
> Done.
> 
>>> diff --git a/gdb/common/environ.c b/gdb/common/environ.c
>>> index 3145d01..657f2e0 100644
>>> --- a/gdb/common/environ.c
>>> +++ b/gdb/common/environ.c
>>> @@ -18,165 +18,102 @@
>>>  #include "common-defs.h"
>>>  #include "environ.h"
>>>  #include <algorithm>
>>> -
>>> +#include <utility>
>>>  
>>> -/* Return a new environment object.  */
>>> +/* See common/environ.h.  */
>>>  
>>> -struct gdb_environ *
>>> -make_environ (void)
>>> +gdb_environ::gdb_environ ()
>>>  {
>>> -  struct gdb_environ *e;
>>> +}
>>>  
>>> -  e = XNEW (struct gdb_environ);
>>> +/* See common/environ.h.  */
>>>  
>>> -  e->allocated = 10;
>>> -  e->vector = (char **) xmalloc ((e->allocated + 1) * sizeof (char *));
>>> -  e->vector[0] = 0;
>>> -  return e;
>>> +gdb_environ::~gdb_environ ()
>>> +{
>>> +  clear ();
>>>  }
>>>  
>>> -/* Free an environment and all the strings in it.  */
>>> +/* See common/environ.h.  */
>>>  
>>> -void
>>> -free_environ (struct gdb_environ *e)
>>> +gdb_environ::gdb_environ (gdb_environ &&e)
>>> +  : m_environ_vector (std::move (e.m_environ_vector))
>>>  {
>>> -  char **vector = e->vector;
>>> +}
>>>  
>>> -  while (*vector)
>>> -    xfree (*vector++);
>>> +/* See common/environ.h.  */
>>>  
>>> -  xfree (e->vector);
>>> -  xfree (e);
>>> +gdb_environ &
>>> +gdb_environ::operator= (gdb_environ &&e)
>>> +{
>>> +  clear ();
>>> +  m_environ_vector = std::move (e.m_environ_vector);
>>> +  return *this;
>>>  }
>>>  
>>> -/* Copy the environment given to this process into E.
>>> -   Also copies all the strings in it, so we can be sure
>>> -   that all strings in these environments are safe to free.  */
>>> +/* See common/environ.h.  */
>>>  
>>>  void
>>> -init_environ (struct gdb_environ *e)
>>> +gdb_environ::clear ()
>>>  {
>>> -  extern char **environ;
>>> -  int i;
>>> -
>>> -  if (environ == NULL)
>>> -    return;
>>> -
>>> -  for (i = 0; environ[i]; i++) /*EMPTY */ ;
>>> +  for (char *v : m_environ_vector)
>>> +    xfree (v);
>>> +  m_environ_vector.clear ();
>>> +}
>>>  
>>> -  if (e->allocated < i)
>>> -    {
>>> -      e->allocated = std::max (i, e->allocated + 10);
>>> -      e->vector = (char **) xrealloc ((char *) e->vector,
>>> -				      (e->allocated + 1) * sizeof (char *));
>>> -    }
>>> +/* See common/environ.h.  */
>>>  
>>> -  memcpy (e->vector, environ, (i + 1) * sizeof (char *));
>>> +const char *
>>> +gdb_environ::get (const std::string &var) const
>>> +{
>>
>> Does this need to be a std::string instead of "const char *"?
>> Callers always pass a string literal down, so this is going to
>> force a deep string dup for no good reason, AFAICS.
> 
> It doesn't.  Changed to const char *.
> 
>>
>>> +  size_t len = var.size ();
>>> +  const char *var_str = var.c_str ();
>>>  
>>> -  while (--i >= 0)
>>> -    {
>>> -      int len = strlen (e->vector[i]);
>>> -      char *newobj = (char *) xmalloc (len + 1);
>>> +  for (char *el : m_environ_vector)
>>> +    if (el != NULL && strncmp (el, var_str, len) == 0 && el[len] == '=')
>>> +      return &el[len + 1];
>>>  
>>> -      memcpy (newobj, e->vector[i], len + 1);
>>> -      e->vector[i] = newobj;
>>> -    }
>>> +  return NULL;
>>>  }
>>
>>> -char *
>>> -get_in_environ (const struct gdb_environ *e, const char *var)
>>> +void
>>> +gdb_environ::set (const std::string &var, const std::string &value)
>>
>> Ditto.
> 
> Likewise.
> 
>>>  {
>>> -  int len = strlen (var);
>>> -  char **vector = e->vector;
>>> -  char *s;
>>> -
>>> -  for (; (s = *vector) != NULL; vector++)
>>> -    if (strncmp (s, var, len) == 0 && s[len] == '=')
>>> -      return &s[len + 1];
>>> +  /* We have to unset the variable in the vector if it exists.  */
>>> +  unset (var);
>>>  
>>> -  return 0;
>>> +  /* Insert the element before the last one, which is always NULL.  */
>>> +  m_environ_vector.insert (m_environ_vector.end () - 1,
>>> +			   concat (var.c_str (), "=",
>>> +				   value.c_str (), NULL));
>>>  }
>>>  
>>> -/* Store the value in E of VAR as VALUE.  */
>>> +/* See common/environ.h.  */
>>>  
>>>  void
>>> -set_in_environ (struct gdb_environ *e, const char *var, const char *value)
>>> +gdb_environ::unset (const std::string &var)
>>
>> Ditto.
> 
> Likewise.
> 
>>
>>> -
>>> -  return;
>>> +  std::string match = var + '=';
>>> +  const char *match_str = match.c_str ();
>>> +
>>> +  /* We iterate until '.cend () - 1' because the last element is
>>> +     always NULL.  */
>>> +  for (std::vector<char *>::const_iterator el = m_environ_vector.cbegin ();
>>> +       el != m_environ_vector.cend () - 1;
>>> +       ++el)
>>> +    if (startswith (*el, match_str))
>>
>> In gdb_environ::set you used:
> 
> I assume you meant gdb_environ::get, right?

Maybe, (I don't have the patch handy anymore.)  Whatever the
other code that looped over all vars.

>> Nit: I find it a bit odd that the ctors/dtors are short but 
>> defined out of line, while this function is defined inline.
>> If I was looking at controlling what the compiler could inline,
>> then I'd do it the other way around -- small ctor/dtor in
>> the header, and this larger function out of line in the .c file.
> 
> Question: if I define a method inside the class, does this implicitly
> tell the compiler that I want to inline it, as oppose to defining the
> method outside?

It's not about inside vs outside.  It's about the compiler seeing the
body when compiling a foo.c file that includes the gdb_environ.h header.
The compiler is invoked on a per-compilation-unit base.  If you put the
method's definition outside the class but still in the gdb_environ.h header,
then the compiler would still be able to inline the method's body in the
foo.c compilation unit if it so chooses.  Of course, then you'd run into
multiple definition problems at link time.  So you can then mark
the definition as inline explicitly.  But that's no different from putting a
free function's definition in a header.

If you put the method instead in gdb_environ.c instead, then when the compiler
is compiling compilation unit foo.c, it has no idea what the body of
the method is, so it can't inline it.  Unless you build with -flto,
of course.

>> So we either always add a NULL to the vector, or we
>> change gdb_environ::get_char_vector instead, like:
>>
>>  char **
>>  gdb_environ::get_char_vector () const
>>  {
>>    if (m_environ_vector.empty ())
>>      {
>>        static const char *const empty_envp[1] = { NULL };
>>        return const_cast<char **> (empty_envp);
>>      }
>>    return const_cast<char **> (&m_environ_vector[0]);
>>  }
>>
>> This is OK because execve etc. are garanteed to never change
>> the envp they're passed.
> 
> Oh, good catch.  I prefer to just initialize the vector with a NULL
> value in the ctor; will do that now.

I'd prefer the other option.  Because then constructing gdb_environ
is dirt cheap and doesn't require heap memory.  We're constructing one
environ per inferior, even if we end up not setting any variable
[now thinking ahead to when we make this work with remote].

Thanks,
Pedro Alves
  
Sergio Durigan Junior June 16, 2017, 9:59 p.m. UTC | #4
On Friday, June 16 2017, Pedro Alves wrote:

>>> Nit: I find it a bit odd that the ctors/dtors are short but 
>>> defined out of line, while this function is defined inline.
>>> If I was looking at controlling what the compiler could inline,
>>> then I'd do it the other way around -- small ctor/dtor in
>>> the header, and this larger function out of line in the .c file.
>> 
>> Question: if I define a method inside the class, does this implicitly
>> tell the compiler that I want to inline it, as oppose to defining the
>> method outside?
>
> It's not about inside vs outside.  It's about the compiler seeing the
> body when compiling a foo.c file that includes the gdb_environ.h header.
> The compiler is invoked on a per-compilation-unit base.  If you put the
> method's definition outside the class but still in the gdb_environ.h header,
> then the compiler would still be able to inline the method's body in the
> foo.c compilation unit if it so chooses.  Of course, then you'd run into
> multiple definition problems at link time.  So you can then mark
> the definition as inline explicitly.  But that's no different from putting a
> free function's definition in a header.
>
> If you put the method instead in gdb_environ.c instead, then when the compiler
> is compiling compilation unit foo.c, it has no idea what the body of
> the method is, so it can't inline it.  Unless you build with -flto,
> of course.

Ah, of course, thanks for the explanation, it makes sense obviously.

>>> So we either always add a NULL to the vector, or we
>>> change gdb_environ::get_char_vector instead, like:
>>>
>>>  char **
>>>  gdb_environ::get_char_vector () const
>>>  {
>>>    if (m_environ_vector.empty ())
>>>      {
>>>        static const char *const empty_envp[1] = { NULL };
>>>        return const_cast<char **> (empty_envp);
>>>      }
>>>    return const_cast<char **> (&m_environ_vector[0]);
>>>  }
>>>
>>> This is OK because execve etc. are garanteed to never change
>>> the envp they're passed.
>> 
>> Oh, good catch.  I prefer to just initialize the vector with a NULL
>> value in the ctor; will do that now.
>
> I'd prefer the other option.  Because then constructing gdb_environ
> is dirt cheap and doesn't require heap memory.  We're constructing one
> environ per inferior, even if we end up not setting any variable
> [now thinking ahead to when we make this work with remote].

I guess I should always implement the option that I *don't* prefer...

Anyway, v5 is ready, should be arriving at your INBOX soon.
  

Patch

diff --git a/gdb/Makefile.in b/gdb/Makefile.in
index 5e5fcaa..133db1a 100644
--- a/gdb/Makefile.in
+++ b/gdb/Makefile.in
@@ -530,14 +530,16 @@  SUBDIR_UNITTESTS_SRCS = \
 	unittests/offset-type-selftests.c \
 	unittests/optional-selftests.c \
 	unittests/ptid-selftests.c \
-	unittests/scoped_restore-selftests.c
+	unittests/scoped_restore-selftests.c \
+	unittests/environ-selftests.c
 
 SUBDIR_UNITTESTS_OBS = \
 	function-view-selftests.o \
 	offset-type-selftests.o \
 	optional-selftests.o \
 	ptid-selftests.o \
-	scoped_restore-selftests.o
+	scoped_restore-selftests.o \
+	environ-selftests.o
 
 # Opcodes currently live in one of two places.  Either they are in the
 # opcode library, typically ../opcodes, or they are in a header file
diff --git a/gdb/charset.c b/gdb/charset.c
index dbe46a4..51ebeaa 100644
--- a/gdb/charset.c
+++ b/gdb/charset.c
@@ -794,16 +794,14 @@  find_charset_names (void)
   int err, status;
   int fail = 1;
   int flags;
-  struct gdb_environ *iconv_env;
+  gdb_environ iconv_env = gdb_environ::from_host_environ ();
   char *iconv_program;
 
   /* Older iconvs, e.g. 2.2.2, don't omit the intro text if stdout is
      not a tty.  We need to recognize it and ignore it.  This text is
      subject to translation, so force LANGUAGE=C.  */
-  iconv_env = make_environ ();
-  init_environ (iconv_env);
-  set_in_environ (iconv_env, "LANGUAGE", "C");
-  set_in_environ (iconv_env, "LC_ALL", "C");
+  iconv_env.set ("LANGUAGE", "C");
+  iconv_env.set ("LC_ALL", "C");
 
   child = pex_init (PEX_USE_PIPES, "iconv", NULL);
 
@@ -827,7 +825,7 @@  find_charset_names (void)
   /* Note that we simply ignore errors here.  */
   if (!pex_run_in_environment (child, flags,
 			       args[0], const_cast<char **> (args),
-			       environ_vector (iconv_env),
+			       iconv_env.get_char_vector (),
 			       NULL, NULL, &err))
     {
       FILE *in = pex_read_output (child, 0);
@@ -901,7 +899,6 @@  find_charset_names (void)
 
   xfree (iconv_program);
   pex_free (child);
-  free_environ (iconv_env);
 
   if (fail)
     {
diff --git a/gdb/common/environ.c b/gdb/common/environ.c
index 3145d01..657f2e0 100644
--- a/gdb/common/environ.c
+++ b/gdb/common/environ.c
@@ -18,165 +18,102 @@ 
 #include "common-defs.h"
 #include "environ.h"
 #include <algorithm>
-
+#include <utility>
 
-/* Return a new environment object.  */
+/* See common/environ.h.  */
 
-struct gdb_environ *
-make_environ (void)
+gdb_environ::gdb_environ ()
 {
-  struct gdb_environ *e;
+}
 
-  e = XNEW (struct gdb_environ);
+/* See common/environ.h.  */
 
-  e->allocated = 10;
-  e->vector = (char **) xmalloc ((e->allocated + 1) * sizeof (char *));
-  e->vector[0] = 0;
-  return e;
+gdb_environ::~gdb_environ ()
+{
+  clear ();
 }
 
-/* Free an environment and all the strings in it.  */
+/* See common/environ.h.  */
 
-void
-free_environ (struct gdb_environ *e)
+gdb_environ::gdb_environ (gdb_environ &&e)
+  : m_environ_vector (std::move (e.m_environ_vector))
 {
-  char **vector = e->vector;
+}
 
-  while (*vector)
-    xfree (*vector++);
+/* See common/environ.h.  */
 
-  xfree (e->vector);
-  xfree (e);
+gdb_environ &
+gdb_environ::operator= (gdb_environ &&e)
+{
+  clear ();
+  m_environ_vector = std::move (e.m_environ_vector);
+  return *this;
 }
 
-/* Copy the environment given to this process into E.
-   Also copies all the strings in it, so we can be sure
-   that all strings in these environments are safe to free.  */
+/* See common/environ.h.  */
 
 void
-init_environ (struct gdb_environ *e)
+gdb_environ::clear ()
 {
-  extern char **environ;
-  int i;
-
-  if (environ == NULL)
-    return;
-
-  for (i = 0; environ[i]; i++) /*EMPTY */ ;
+  for (char *v : m_environ_vector)
+    xfree (v);
+  m_environ_vector.clear ();
+}
 
-  if (e->allocated < i)
-    {
-      e->allocated = std::max (i, e->allocated + 10);
-      e->vector = (char **) xrealloc ((char *) e->vector,
-				      (e->allocated + 1) * sizeof (char *));
-    }
+/* See common/environ.h.  */
 
-  memcpy (e->vector, environ, (i + 1) * sizeof (char *));
+const char *
+gdb_environ::get (const std::string &var) const
+{
+  size_t len = var.size ();
+  const char *var_str = var.c_str ();
 
-  while (--i >= 0)
-    {
-      int len = strlen (e->vector[i]);
-      char *newobj = (char *) xmalloc (len + 1);
+  for (char *el : m_environ_vector)
+    if (el != NULL && strncmp (el, var_str, len) == 0 && el[len] == '=')
+      return &el[len + 1];
 
-      memcpy (newobj, e->vector[i], len + 1);
-      e->vector[i] = newobj;
-    }
+  return NULL;
 }
 
-/* Return the vector of environment E.
-   This is used to get something to pass to execve.  */
+/* See common/environ.h.  */
 
-char **
-environ_vector (struct gdb_environ *e)
-{
-  return e->vector;
-}
-
-/* Return the value in environment E of variable VAR.  */
-
-char *
-get_in_environ (const struct gdb_environ *e, const char *var)
+void
+gdb_environ::set (const std::string &var, const std::string &value)
 {
-  int len = strlen (var);
-  char **vector = e->vector;
-  char *s;
-
-  for (; (s = *vector) != NULL; vector++)
-    if (strncmp (s, var, len) == 0 && s[len] == '=')
-      return &s[len + 1];
+  /* We have to unset the variable in the vector if it exists.  */
+  unset (var);
 
-  return 0;
+  /* Insert the element before the last one, which is always NULL.  */
+  m_environ_vector.insert (m_environ_vector.end () - 1,
+			   concat (var.c_str (), "=",
+				   value.c_str (), NULL));
 }
 
-/* Store the value in E of VAR as VALUE.  */
+/* See common/environ.h.  */
 
 void
-set_in_environ (struct gdb_environ *e, const char *var, const char *value)
+gdb_environ::unset (const std::string &var)
 {
-  int i;
-  int len = strlen (var);
-  char **vector = e->vector;
-  char *s;
-
-  for (i = 0; (s = vector[i]) != NULL; i++)
-    if (strncmp (s, var, len) == 0 && s[len] == '=')
-      break;
-
-  if (s == 0)
-    {
-      if (i == e->allocated)
-	{
-	  e->allocated += 10;
-	  vector = (char **) xrealloc ((char *) vector,
-				       (e->allocated + 1) * sizeof (char *));
-	  e->vector = vector;
-	}
-      vector[i + 1] = 0;
-    }
-  else
-    xfree (s);
-
-  s = (char *) xmalloc (len + strlen (value) + 2);
-  strcpy (s, var);
-  strcat (s, "=");
-  strcat (s, value);
-  vector[i] = s;
-
-  /* This used to handle setting the PATH and GNUTARGET variables
-     specially.  The latter has been replaced by "set gnutarget"
-     (which has worked since GDB 4.11).  The former affects searching
-     the PATH to find SHELL, and searching the PATH to find the
-     argument of "symbol-file" or "exec-file".  Maybe we should have
-     some kind of "set exec-path" for that.  But in any event, having
-     "set env" affect anything besides the inferior is a bad idea.
-     What if we want to change the environment we pass to the program
-     without afecting GDB's behavior?  */
-
-  return;
+  std::string match = var + '=';
+  const char *match_str = match.c_str ();
+
+  /* We iterate until '.cend () - 1' because the last element is
+     always NULL.  */
+  for (std::vector<char *>::const_iterator el = m_environ_vector.cbegin ();
+       el != m_environ_vector.cend () - 1;
+       ++el)
+    if (startswith (*el, match_str))
+      {
+	xfree (*el);
+	m_environ_vector.erase (el);
+	break;
+      }
 }
 
-/* Remove the setting for variable VAR from environment E.  */
+/* See common/environ.h.  */
 
-void
-unset_in_environ (struct gdb_environ *e, const char *var)
+char **
+gdb_environ::get_char_vector () const
 {
-  int len = strlen (var);
-  char **vector = e->vector;
-  char *s;
-
-  for (; (s = *vector) != NULL; vector++)
-    {
-      if (strncmp (s, var, len) == 0 && s[len] == '=')
-	{
-	  xfree (s);
-	  /* Walk through the vector, shuffling args down by one, including
-	     the NULL terminator.  Can't use memcpy() here since the regions
-	     overlap, and memmove() might not be available.  */
-	  while ((vector[0] = vector[1]) != NULL)
-	    {
-	      vector++;
-	    }
-	  break;
-	}
-    }
+  return const_cast<char **> (&m_environ_vector[0]);
 }
diff --git a/gdb/common/environ.h b/gdb/common/environ.h
index 3ace69e..c3503e1 100644
--- a/gdb/common/environ.h
+++ b/gdb/common/environ.h
@@ -17,33 +17,65 @@ 
 #if !defined (ENVIRON_H)
 #define ENVIRON_H 1
 
-/* We manipulate environments represented as these structures.  */
+#include <vector>
 
-struct gdb_environ
+/* Class that represents the environment variables as seen by the
+   inferior.  */
+
+class gdb_environ
+{
+public:
+  /* Regular constructor and destructor.  */
+  gdb_environ ();
+  ~gdb_environ ();
+
+  /* Move constructor.  */
+  gdb_environ (gdb_environ &&e);
+
+  /* Move assignment.  */
+  gdb_environ &operator= (gdb_environ &&e);
+
+  /* Create a gdb_environ object using the host's environment
+     variables.  */
+  static gdb_environ from_host_environ ()
   {
-    /* Number of usable slots allocated in VECTOR.
-       VECTOR always has one slot not counted here,
-       to hold the terminating zero.  */
-    int allocated;
-    /* A vector of slots, ALLOCATED + 1 of them.
-       The first few slots contain strings "VAR=VALUE"
-       and the next one contains zero.
-       Then come some unused slots.  */
-    char **vector;
-  };
+    extern char **environ;
+    gdb_environ e;
+
+    if (environ == NULL)
+      return e;
+
+    for (int i = 0; environ[i] != NULL; ++i)
+      e.m_environ_vector.push_back (xstrdup (environ[i]));
+
+    /* The last element of the vector is always going to be NULL.  */
+    e.m_environ_vector.push_back (NULL);
 
-extern struct gdb_environ *make_environ (void);
+    return e;
+  }
 
-extern void free_environ (struct gdb_environ *);
+  /* Clear the environment variables stored in the object.  */
+  void clear ();
 
-extern void init_environ (struct gdb_environ *);
+  /* Return the value in the environment for the variable VAR.  The
+     return pointer is only valid as long as VAR is not
+     removed/replaced from the environment.  */
+  const char *get (const std::string &var) const;
 
-extern char *get_in_environ (const struct gdb_environ *, const char *);
+  /* Store VAR=VALUE in the environment.  */
+  void set (const std::string &var, const std::string &value);
 
-extern void set_in_environ (struct gdb_environ *, const char *, const char *);
+  /* Unset VAR in environment.  */
+  void unset (const std::string &var);
 
-extern void unset_in_environ (struct gdb_environ *, const char *);
+  /* Return the environment vector represented as a 'char **'.  */
+  char **get_char_vector () const;
 
-extern char **environ_vector (struct gdb_environ *);
+private:
+  /* A vector containing the environment variables.  This is useful
+     for when we need to obtain a 'char **' with all the existing
+     variables.  */
+  std::vector<char *> m_environ_vector;
+};
 
 #endif /* defined (ENVIRON_H) */
diff --git a/gdb/gdbserver/linux-low.c b/gdb/gdbserver/linux-low.c
index 7fbf744..33272f0 100644
--- a/gdb/gdbserver/linux-low.c
+++ b/gdb/gdbserver/linux-low.c
@@ -998,7 +998,7 @@  linux_create_inferior (const char *program,
 
   pid = fork_inferior (program,
 		       str_program_args.c_str (),
-		       environ_vector (get_environ ()), linux_ptrace_fun,
+		       get_environ ()->get_char_vector (), linux_ptrace_fun,
 		       NULL, NULL, NULL, NULL);
 
   do_cleanups (restore_personality);
diff --git a/gdb/gdbserver/lynx-low.c b/gdb/gdbserver/lynx-low.c
index 35160d6..ddca54b 100644
--- a/gdb/gdbserver/lynx-low.c
+++ b/gdb/gdbserver/lynx-low.c
@@ -259,7 +259,7 @@  lynx_create_inferior (const char *program,
 
   pid = fork_inferior (program,
 		       str_program_args.c_str (),
-		       environ_vector (get_environ ()), lynx_ptrace_fun,
+		       get_environ ()->get_char_vector (), lynx_ptrace_fun,
 		       NULL, NULL, NULL, NULL);
 
   post_fork_inferior (pid, program);
diff --git a/gdb/gdbserver/server.c b/gdb/gdbserver/server.c
index 1d7a8b0..3838351 100644
--- a/gdb/gdbserver/server.c
+++ b/gdb/gdbserver/server.c
@@ -42,7 +42,7 @@ 
 
 /* The environment to pass to the inferior when creating it.  */
 
-struct gdb_environ *our_environ = NULL;
+static gdb_environ our_environ;
 
 /* Start the inferior using a shell.  */
 
@@ -257,10 +257,10 @@  get_exec_file (int err)
 
 /* See server.h.  */
 
-struct gdb_environ *
+gdb_environ *
 get_environ ()
 {
-  return our_environ;
+  return &our_environ;
 }
 
 static int
@@ -3698,8 +3698,7 @@  captured_main (int argc, char *argv[])
     }
 
   /* Gather information about the environment.  */
-  our_environ = make_environ ();
-  init_environ (our_environ);
+  our_environ = gdb_environ::from_host_environ ();
 
   initialize_async_io ();
   initialize_low ();
diff --git a/gdb/gdbserver/server.h b/gdb/gdbserver/server.h
index 4de4244..46b614c 100644
--- a/gdb/gdbserver/server.h
+++ b/gdb/gdbserver/server.h
@@ -62,6 +62,7 @@  int vsnprintf(char *str, size_t size, const char *format, va_list ap);
 #include "mem-break.h"
 #include "gdbthread.h"
 #include "inferiors.h"
+#include "environ.h"
 
 /* Target-specific functions */
 
@@ -154,9 +155,8 @@  extern int in_queued_stop_replies (ptid_t ptid);
    inferior and PROGRAM is its name.  */
 extern void post_fork_inferior (int pid, const char *program);
 
-/* Get the 'struct gdb_environ *' being used in the current
-   session.  */
-extern struct gdb_environ *get_environ ();
+/* Get the gdb_environ being used in the current session.  */
+extern gdb_environ *get_environ ();
 
 extern target_waitstatus last_status;
 extern ptid_t last_ptid;
diff --git a/gdb/gdbserver/spu-low.c b/gdb/gdbserver/spu-low.c
index 0f770a0..d54b121 100644
--- a/gdb/gdbserver/spu-low.c
+++ b/gdb/gdbserver/spu-low.c
@@ -289,7 +289,7 @@  spu_create_inferior (const char *program,
 
   pid = fork_inferior (program,
 		       str_program_args.c_str (),
-		       environ_vector (get_environ ()), spu_ptrace_fun,
+		       get_environ ()->get_char_vector (), spu_ptrace_fun,
 		       NULL, NULL, NULL, NULL);
 
   post_fork_inferior (pid, program);
diff --git a/gdb/infcmd.c b/gdb/infcmd.c
index db09f19..ab46c1a 100644
--- a/gdb/infcmd.c
+++ b/gdb/infcmd.c
@@ -610,7 +610,8 @@  run_command_1 (char *args, int from_tty, int tbreak_at_main)
      the value now.  */
   run_target->to_create_inferior (run_target, exec_file,
 				  std::string (get_inferior_args ()),
-				  environ_vector (current_inferior ()->environment),
+				  current_inferior ()
+				  ->environment.get_char_vector (),
 				  from_tty);
   /* to_create_inferior should push the target, so after this point we
      shouldn't refer to run_target again.  */
@@ -2131,7 +2132,7 @@  environment_info (char *var, int from_tty)
 {
   if (var)
     {
-      char *val = get_in_environ (current_inferior ()->environment, var);
+      const char *val = current_inferior ()->environment.get (var);
 
       if (val)
 	{
@@ -2149,13 +2150,15 @@  environment_info (char *var, int from_tty)
     }
   else
     {
-      char **vector = environ_vector (current_inferior ()->environment);
+      char **env_vec
+	= current_inferior ()->environment.get_char_vector ();
 
-      while (*vector)
-	{
-	  puts_filtered (*vector++);
-	  puts_filtered ("\n");
-	}
+      if (env_vec != NULL)
+	for (int idx = 0; env_vec[idx] != NULL; ++idx)
+	  {
+	    puts_filtered (env_vec[idx]);
+	    puts_filtered ("\n");
+	  }
     }
 }
 
@@ -2215,10 +2218,10 @@  set_environment_command (char *arg, int from_tty)
       printf_filtered (_("Setting environment variable "
 			 "\"%s\" to null value.\n"),
 		       var);
-      set_in_environ (current_inferior ()->environment, var, "");
+      current_inferior ()->environment.set (var, "");
     }
   else
-    set_in_environ (current_inferior ()->environment, var, val);
+    current_inferior ()->environment.set (var, val);
   xfree (var);
 }
 
@@ -2230,13 +2233,10 @@  unset_environment_command (char *var, int from_tty)
       /* If there is no argument, delete all environment variables.
          Ask for confirmation if reading from the terminal.  */
       if (!from_tty || query (_("Delete all environment variables? ")))
-	{
-	  free_environ (current_inferior ()->environment);
-	  current_inferior ()->environment = make_environ ();
-	}
+	current_inferior ()->environment = gdb_environ::from_host_environ ();
     }
   else
-    unset_in_environ (current_inferior ()->environment, var);
+    current_inferior ()->environment.unset (var);
 }
 
 /* Handle the execution path (PATH variable).  */
@@ -2247,8 +2247,7 @@  static void
 path_info (char *args, int from_tty)
 {
   puts_filtered ("Executable and object file path: ");
-  puts_filtered (get_in_environ (current_inferior ()->environment,
-				 path_var_name));
+  puts_filtered (current_inferior ()->environment.get (path_var_name));
   puts_filtered ("\n");
 }
 
@@ -2261,13 +2260,13 @@  path_command (char *dirname, int from_tty)
   const char *env;
 
   dont_repeat ();
-  env = get_in_environ (current_inferior ()->environment, path_var_name);
+  env = current_inferior ()->environment.get (path_var_name);
   /* Can be null if path is not set.  */
   if (!env)
     env = "";
   exec_path = xstrdup (env);
   mod_path (dirname, &exec_path);
-  set_in_environ (current_inferior ()->environment, path_var_name, exec_path);
+  current_inferior ()->environment.set (path_var_name, exec_path);
   xfree (exec_path);
   if (from_tty)
     path_info ((char *) NULL, from_tty);
diff --git a/gdb/inferior.c b/gdb/inferior.c
index 0b655f4..9fa2dad 100644
--- a/gdb/inferior.c
+++ b/gdb/inferior.c
@@ -81,7 +81,6 @@  inferior::~inferior ()
   inferior_free_data (inf);
   xfree (inf->args);
   xfree (inf->terminal);
-  free_environ (inf->environment);
   target_desc_info_free (inf->tdesc_info);
   xfree (inf->priv);
 }
@@ -89,10 +88,9 @@  inferior::~inferior ()
 inferior::inferior (int pid_)
   : num (++highest_inferior_num),
     pid (pid_),
-    environment (make_environ ()),
+    environment (gdb_environ::from_host_environ ()),
     registry_data ()
 {
-  init_environ (this->environment);
   inferior_alloc_data (this);
 }
 
diff --git a/gdb/inferior.h b/gdb/inferior.h
index 1c541b7..8ada4f8 100644
--- a/gdb/inferior.h
+++ b/gdb/inferior.h
@@ -30,7 +30,6 @@  struct regcache;
 struct ui_out;
 struct terminal_info;
 struct target_desc_info;
-struct gdb_environ;
 struct continuation;
 struct inferior;
 
@@ -43,6 +42,9 @@  struct inferior;
 /* For struct frame_id.  */
 #include "frame.h"
 
+/* For gdb_environ.  */
+#include "environ.h"
+
 #include "progspace.h"
 #include "registry.h"
 
@@ -363,7 +365,7 @@  public:
 
   /* Environment to use for running inferior,
      in format described in environ.h.  */
-  gdb_environ *environment = NULL;
+  gdb_environ environment;
 
   /* True if this child process was attached rather than forked.  */
   bool attach_flag = false;
diff --git a/gdb/mi/mi-cmd-env.c b/gdb/mi/mi-cmd-env.c
index 4093178..a185096 100644
--- a/gdb/mi/mi-cmd-env.c
+++ b/gdb/mi/mi-cmd-env.c
@@ -167,7 +167,7 @@  mi_cmd_env_path (const char *command, char **argv, int argc)
   else
     {
       /* Otherwise, get current path to modify.  */
-      env = get_in_environ (current_inferior ()->environment, path_var_name);
+      env = current_inferior ()->environment.get (path_var_name);
 
       /* Can be null if path is not set.  */
       if (!env)
@@ -178,9 +178,9 @@  mi_cmd_env_path (const char *command, char **argv, int argc)
   for (i = argc - 1; i >= 0; --i)
     env_mod_path (argv[i], &exec_path);
 
-  set_in_environ (current_inferior ()->environment, path_var_name, exec_path);
+  current_inferior ()->environment.set (path_var_name, exec_path);
   xfree (exec_path);
-  env = get_in_environ (current_inferior ()->environment, path_var_name);
+  env = current_inferior ()->environment.get (path_var_name);
   uiout->field_string ("path", env);
 }
 
@@ -270,7 +270,6 @@  mi_cmd_inferior_tty_show (const char *command, char **argv, int argc)
 void 
 _initialize_mi_cmd_env (void)
 {
-  struct gdb_environ *environment;
   const char *env;
 
   /* We want original execution path to reset to, if desired later.
@@ -278,13 +277,10 @@  _initialize_mi_cmd_env (void)
      current_inferior ()->environment.  Also, there's no obvious
      place where this code can be moved such that it surely run
      before any code possibly mangles original PATH.  */
-  environment = make_environ ();
-  init_environ (environment);
-  env = get_in_environ (environment, path_var_name);
+  env = getenv (path_var_name);
 
   /* Can be null if path is not set.  */
   if (!env)
     env = "";
   orig_path = xstrdup (env);
-  free_environ (environment);
 }
diff --git a/gdb/solib.c b/gdb/solib.c
index 491c18a..788cf15 100644
--- a/gdb/solib.c
+++ b/gdb/solib.c
@@ -350,16 +350,15 @@  solib_find_1 (const char *in_pathname, int *fd, int is_solib)
 
   /* If not found, next search the inferior's $PATH environment variable.  */
   if (found_file < 0 && sysroot == NULL)
-    found_file = openp (get_in_environ (current_inferior ()->environment,
-					"PATH"),
+    found_file = openp (current_inferior ()->environment.get ("PATH"),
 			OPF_TRY_CWD_FIRST | OPF_RETURN_REALPATH, in_pathname,
 			O_RDONLY | O_BINARY, &temp_pathname);
 
   /* If not found, and we're looking for a solib, next search the
      inferior's $LD_LIBRARY_PATH environment variable.  */
   if (is_solib && found_file < 0 && sysroot == NULL)
-    found_file = openp (get_in_environ (current_inferior ()->environment,
-					"LD_LIBRARY_PATH"),
+    found_file = openp (current_inferior ()->environment.get
+			("LD_LIBRARY_PATH"),
 			OPF_TRY_CWD_FIRST | OPF_RETURN_REALPATH, in_pathname,
 			O_RDONLY | O_BINARY, &temp_pathname);
 
diff --git a/gdb/unittests/environ-selftests.c b/gdb/unittests/environ-selftests.c
new file mode 100644
index 0000000..948eacf
--- /dev/null
+++ b/gdb/unittests/environ-selftests.c
@@ -0,0 +1,79 @@ 
+/* Self tests for gdb_environ for GDB, the GNU debugger.
+
+   Copyright (C) 2017 Free Software Foundation, Inc.
+
+   This file is part of GDB.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+#include "defs.h"
+#include "selftest.h"
+#include "common/environ.h"
+
+namespace selftests {
+namespace environ {
+
+static void
+run_tests ()
+{
+  if (setenv ("GDB_SELFTEST_ENVIRON", "1", 1) != 0)
+    error ("Could not set environment variable for testing.");
+
+  gdb_environ env;
+
+  SELF_CHECK (env.get ("PWD") == NULL);
+
+  env = gdb_environ::from_host_environ ();
+
+  SELF_CHECK (strcmp (env.get ("GDB_SELFTEST_ENVIRON"), "1") == 0);
+
+  env.set ("GDB_SELFTEST_ENVIRON", "test");
+  SELF_CHECK (strcmp (env.get ("GDB_SELFTEST_ENVIRON"), "test") == 0);
+
+  env.unset ("GDB_SELFTEST_ENVIRON");
+  SELF_CHECK (env.get ("GDB_SELFTEST_ENVIRON") == NULL);
+
+  env.set ("GDB_SELFTEST_ENVIRON", "1");
+  SELF_CHECK (strcmp (env.get ("GDB_SELFTEST_ENVIRON"), "1") == 0);
+
+  env.clear ();
+  SELF_CHECK (env.get ("GDB_SELFTEST_ENVIRON") == NULL);
+
+  if (setenv ("GDB_SELFTEST_ENVIRON", "1", 1) != 0)
+    error ("Could not set environment variable for testing.");
+
+  env = gdb_environ::from_host_environ ();
+  char **penv = env.get_char_vector ();
+  bool found_var = false, found_twice = false;
+
+  for (size_t i = 0; penv[i] != NULL; ++i)
+    if (strcmp (penv[i], "GDB_SELFTEST_ENVIRON=1") == 0)
+      {
+	if (found_var)
+	  found_twice = true;
+	found_var = true;
+      }
+  SELF_CHECK (found_var == true);
+  SELF_CHECK (found_twice == false);
+
+  unsetenv ("GDB_SELFTEST_ENVIRON");
+}
+} /* namespace environ */
+} /* namespace selftests */
+
+void
+_initialize_environ_selftests ()
+{
+  register_self_test (selftests::environ::run_tests);
+}