This is the mail archive of the
libc-alpha@sourceware.org
mailing list for the glibc project.
Re: [RFC] Make getenv O(1)
- From: Rich Felker <dalias at aerifal dot cx>
- To: OndÅej BÃlka <neleai at seznam dot cz>
- 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 11:23:56 -0400
- Subject: Re: [RFC] Make getenv O(1)
- Authentication-results: sourceware.org; auth=none
- References: <20131014155229 dot GA25159 at domone dot podge> <20131014165411 dot GZ20515 at brightrain dot aerifal dot cx> <20131014172852 dot GA26005 at domone dot podge> <52611F60 dot 3080700 at redhat dot com> <20131018124013 dot GA15803 at domone dot podge> <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>
On Fri, Oct 18, 2013 at 04:07:05PM +0200, OndÅej BÃlka wrote:
> On Fri, Oct 18, 2013 at 05:46:57PM +0400, Alexander Monakov wrote:
> > On Fri, 18 Oct 2013, OndÅej BÃlka wrote:
> > > You could argue that this does not help when likely case is that
> > > variable is not defined. For that I would need posix say that changing
> > > variable name via environ pointers is illegal.
> >
> > Indeed; I would also ask if such functions are allowed to query interesting
> > environment variables once on first call and then cache the result (similar to
> > how the dynamic linker stashes initial LD_LIBRARY_PATH on the side and calls
> > to dlopen do not check the environment again).
> >
> > Alexander
>
> This could be done by following macro with global renaming of
> getenv->GETENV.
>
> Also do we support in libc setenv to change behaviour?
>
> #define GETENV(x) ({ \
> static char *__ret; \
> static int __cached; \
> if (__builtin_constant_p (x) && !__cached) \
> { \
> __ret = getenv (x); \
> __cached = 1; \
> } \
> __builtin_constant_p (x) ? __ret : getenv (x);})
I think this is the best approach, either via such a macro or simply
writing out the caching directly. However the above code performs
unsynchronized access on __cached and __ret. In particular the
compiler could store __cached before storing __ret, or due to cache
line issues, __cached might simply become visible to other cores
before __ret does.
IMO the proper fix is to put the above in a function with proper
synchronization, and make a macro which simply expands to the right
static objects and a call to the function with pointers to those
static objects.
Rich