Keep track of the originally allocated environ

We need to keep a pointer to the originally allocated environ because
adding more environment variables can cause it to be changed to something
else.

For example:

    100.times do |i|
      ENV["FOO#{i}"] = "1"
    end

Causes Valgrind to report:

    312 bytes in 1 blocks are definitely lost in loss record 9 of 13
      at 0x484D444: calloc (vg_replace_malloc.c:1340)
      by 0x1884F8: calloc1 (gc.c:1844)
      by 0x1884F8: objspace_xcalloc (gc.c:12202)
      by 0x1884F8: ruby_xcalloc_body (gc.c:12209)
      by 0x4204DD: ruby_init_setproctitle (setproctitle.c:119)
      by 0x27DDF4: ruby_process_options (ruby.c:3101)
      by 0x160BD1: ruby_options (eval.c:117)
      by 0x15B96E: rb_main (main.c:40)
      by 0x15B96E: main (main.c:59)
This commit is contained in:
Peter Zhu 2024-05-01 11:15:28 -04:00
parent 12cbfd8e2f
commit 4f69d318b8

View File

@ -87,6 +87,7 @@ static char **argv1_addr = NULL;
#endif
#if ALLOCATE_ENVIRON
static char **system_environ = NULL;
static char **orig_environ = NULL;
static char **alloc_environ = NULL;
#endif
@ -113,10 +114,10 @@ compat_init_setproctitle(int argc, char *argv[])
/* Fail if we can't allocate room for the new environment */
for (i = 0; envp[i] != NULL; i++);
orig_environ = environ;
system_environ = environ;
alloc_environ = xcalloc(i + 1, sizeof(*environ));
environ = xcalloc(i + 1, sizeof(*environ));
orig_environ = environ = xcalloc(i + 1, sizeof(*environ));
if (environ == NULL) {
environ = envp; /* put it back */
return;
@ -161,9 +162,9 @@ ruby_free_proctitle(void)
xfree(alloc_environ[i]);
}
xfree(alloc_environ);
xfree(environ);
xfree(orig_environ);
environ = orig_environ;
environ = system_environ;
#endif
}