Re: [PATCH] tools/nolibc/stdlib: fix getenv() with empty environment

From: Willy Tarreau
Date: Wed Oct 16 2024 - 08:17:54 EST


Hi Thomas!

On Wed, Oct 16, 2024 at 01:14:51PM +0200, Thomas Weißschuh wrote:
> The environ pointer itself is never NULL, this is guaranteed by crt.h.
> However if the environment is empty, environ will point to a NULL
> pointer.

Good point, however from what I'm seeing on glibc, if the user sets
environ to NULL, getenv() safely reports NULL and doesn't crash. I
don't know what the spec says about environ being NULL, though. I
just tested on freebsd to compare and also get a NULL in this case
as well. So I'd be tempted by keeping the check.

> int idx, i;
>
> - if (environ) {
> + if (*environ) {
> for (idx = 0; environ[idx]; idx++) {
> for (i = 0; name[i] && name[i] == environ[idx][i];)
> i++;

However as a quick note, if we decide we don't care about environ being
NULL, and since this is essentially a cleanup, why not even get rid of
the whole "if" condition, since the loop takes care of it ?

FWIW I tested glibc with this:

#include <stdlib.h>


int main(int argc, char **argv)
{
extern char **environ;

environ=NULL;
return getenv("HOME") == NULL;
}

Cheers,
Willy