Fix an off-by-one in dt_opt_setenv().

The bug would cause incorrect behaviour when attempting to override
an already set environment variable with -x setenv, as long as the
variable is not the last one in the array.

Reported by:	Samuel Lepetit <slepetit@apple.com>
MFC after:	2 weeks
This commit is contained in:
Mark Johnston 2018-01-10 21:37:11 +00:00
parent 86bbef4379
commit ff9ebfc4b6

View File

@ -415,7 +415,7 @@ dt_opt_setenv(dtrace_hdl_t *dtp, const char *arg, uintptr_t option)
{
char **p;
char *var;
int i;
int nvars;
/*
* We can't effectively set environment variables from #pragma lines
@ -430,7 +430,7 @@ dt_opt_setenv(dtrace_hdl_t *dtp, const char *arg, uintptr_t option)
if (!option && strchr(arg, '=') != NULL)
return (dt_set_errno(dtp, EDT_BADOPTVAL));
for (i = 1, p = dtp->dt_proc_env; *p != NULL; i++, p++)
for (nvars = 0, p = dtp->dt_proc_env; *p != NULL; nvars++, p++)
continue;
for (p = dtp->dt_proc_env; *p != NULL; p++) {
@ -439,9 +439,9 @@ dt_opt_setenv(dtrace_hdl_t *dtp, const char *arg, uintptr_t option)
var = *p + strlen(*p);
if (strncmp(*p, arg, var - *p) == 0) {
dt_free(dtp, *p);
*p = dtp->dt_proc_env[i - 1];
dtp->dt_proc_env[i - 1] = NULL;
i--;
*p = dtp->dt_proc_env[nvars - 1];
dtp->dt_proc_env[nvars - 1] = NULL;
nvars--;
}
}
@ -449,17 +449,18 @@ dt_opt_setenv(dtrace_hdl_t *dtp, const char *arg, uintptr_t option)
if ((var = strdup(arg)) == NULL)
return (dt_set_errno(dtp, EDT_NOMEM));
if ((p = dt_alloc(dtp, sizeof (char *) * (i + 1))) == NULL) {
nvars++;
if ((p = dt_alloc(dtp, sizeof(char *) * (nvars + 1))) == NULL) {
dt_free(dtp, var);
return (dt_set_errno(dtp, EDT_NOMEM));
}
bcopy(dtp->dt_proc_env, p, sizeof (char *) * i);
bcopy(dtp->dt_proc_env, p, sizeof(char *) * nvars);
dt_free(dtp, dtp->dt_proc_env);
dtp->dt_proc_env = p;
dtp->dt_proc_env[i - 1] = var;
dtp->dt_proc_env[i] = NULL;
dtp->dt_proc_env[nvars - 1] = var;
dtp->dt_proc_env[nvars] = NULL;
}
return (0);