trace2: remove use of xstrdup()

In the previous change, we removed a use of xsprintf() that caused a
recursive die() loop when failing to allocate memory. The trace2 library is
too low-level to be calling die(), especially because of these recursive
loops that can occur during the die handler.

For full defense in depth, we remove the xstrdup() calls from
trace2/tr2_sysenv.c.

First, in tr2_sysenv_cb(), we need to handle a failed assignment of the
value with a zero-valued return to halt the config parsing loop. Note
that we don't want to use a negative return here or we would imply to
the config system that the config key or value was somehow invalid; such
an output would mask the real issue that the process failed to allocate
memory.

Second, in tr2_sysenv_get(), the method will return NULL when strdup()
returns NULL. This return is indistinguishable from the environment variable
having no value. That means that all callers know how to handle a NULL
response, but no behavior change will occur between the case of no
environment being set and detecting an environment variable exists but we
fail to duplicate it. This seems an appropriate trade-off, as an allocation
failure at this level will likely lead to failure in another system, but at
least the trace2 API will not cause the process to fail early.

Helped-by: Elijah Newren <newren@gmail.com>
Signed-off-by: Derrick Stolee <stolee@gmail.com>
Signed-off-by: Junio C Hamano <gitster@pobox.com>
seen
Derrick Stolee 2026-08-31 17:25:39 +00:00 committed by Junio C Hamano
parent 4ea9448a9c
commit c331d73b3e
2 changed files with 7 additions and 2 deletions

View File

@ -14,4 +14,7 @@
#undef xsnprintf #undef xsnprintf
#define xsnprintf(...) BANNED(xsnprintf) #define xsnprintf(...) BANNED(xsnprintf)


#undef xstrdup
#define xstrdup(str) BANNED(xstrdup)

#endif /* BANNED_DIE_H */ #endif /* BANNED_DIE_H */

View File

@ -75,7 +75,9 @@ static int tr2_sysenv_cb(const char *key, const char *value,
if (!value) if (!value)
return config_error_nonbool(key); return config_error_nonbool(key);
free(tr2_sysenv_settings[k].value); free(tr2_sysenv_settings[k].value);
tr2_sysenv_settings[k].value = xstrdup(value); tr2_sysenv_settings[k].value = strdup(value);
if (!tr2_sysenv_settings[k].value)
return 0;
return 0; return 0;
} }
} }
@ -111,7 +113,7 @@ const char *tr2_sysenv_get(enum tr2_sysenv_variable var)
const char *v = getenv(tr2_sysenv_settings[var].env_var_name); const char *v = getenv(tr2_sysenv_settings[var].env_var_name);
if (v && *v) { if (v && *v) {
free(tr2_sysenv_settings[var].value); free(tr2_sysenv_settings[var].value);
tr2_sysenv_settings[var].value = xstrdup(v); tr2_sysenv_settings[var].value = strdup(v);
} }
tr2_sysenv_settings[var].getenv_called = 1; tr2_sysenv_settings[var].getenv_called = 1;
} }