This is the mail archive of the
libc-alpha@sourceware.org
mailing list for the glibc project.
Re: [RFC] Make getenv O(1)
- From: OndÅej BÃlka <neleai at seznam dot cz>
- To: Rich Felker <dalias at aerifal dot cx>
- Cc: Alexander Monakov <amonakov at ispras dot ru>, Florian Weimer <fweimer at redhat dot com>, libc-alpha at sourceware dot org
- Date: Mon, 21 Oct 2013 20:59:55 +0200
- Subject: Re: [RFC] Make getenv O(1)
- Authentication-results: sourceware.org; auth=none
- References: <alpine dot LNX dot 2 dot 00 dot 1310181656380 dot 3212 at monopod dot intra dot ispras dot ru> <20131018132604 dot GA16445 at domone dot podge> <alpine dot LNX dot 2 dot 00 dot 1310181744060 dot 3212 at monopod dot intra dot ispras dot ru> <20131018140705 dot GA18542 at domone dot podge> <20131021152356 dot GQ20515 at brightrain dot aerifal dot cx> <20131021161938 dot GA26730 at domone dot podge> <alpine dot LNX dot 2 dot 00 dot 1310212054470 dot 3212 at monopod dot intra dot ispras dot ru> <20131021170934 dot GA26031 at domone dot podge> <alpine dot LNX dot 2 dot 00 dot 1310212123580 dot 3212 at monopod dot intra dot ispras dot ru> <20131021180453 dot GT20515 at brightrain dot aerifal dot cx>
On Mon, Oct 21, 2013 at 02:04:53PM -0400, Rich Felker wrote:
> On Mon, Oct 21, 2013 at 09:26:32PM +0400, Alexander Monakov wrote:
> >
> >
> > On Mon, 21 Oct 2013, OndÅej BÃlka wrote:
> >
> > > On Mon, Oct 21, 2013 at 08:55:37PM +0400, Alexander Monakov wrote:
> > > > On Mon, 21 Oct 2013, OndÅej BÃlka wrote:
> > > > > Why, following does not need synchronization.
> > > > >
> > > > > #define GETENV(x) ({ \
> > > > > static char *__ret = NULL; \
> > > > > if (__builtin_constant_p (x) && !__cached) \
> > > > > __ret = getenv (x) + 1; \
> > > > > __builtin_constant_p (x) ? __ret - 1: getenv (x);})
> > > >
> > > > This wouldn't compile as __cached is not defined (and I'll admit I don't see
> > > > what approach you're trying to convey).
> > > >
> > > s/__cached/__ret/
> >
> > Ah, my bad. While this would be ok in practice, I think incrementing a
> > pointer containing a NULL value invokes undefined behavior, doesn't it?
>
> It does. So does unsynchronized access to an object, even if you think
> it's harmless like in this case. If you only care about the null UB,
> you could however just use the address of a "static const char
> __sentinel" instead of NULL as the flag for uninitialized. But I think
> it's best to simply write this with clean, correct use of
> synchronization rather than ugly hacks.
>
If you want you could use conversion from/to uintptr_t for arithmetic
and atomic write/exchange for storing.
Or say that getenv is not required to be thread safe and problem is in
user code.