-
Notifications
You must be signed in to change notification settings - Fork 9
fix: use pthread_once for thread-safe getenv initialization #609
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| . |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -45,18 +45,24 @@ static pthread_mutex_t token_mutex = PTHREAD_MUTEX_INITIALIZER; | |
| /* Pointer to the real getenv function */ | ||
| static char *(*real_getenv)(const char *name) = NULL; | ||
|
|
||
| /* Initialize the real getenv pointer */ | ||
| static void init_real_getenv(void) { | ||
| /* pthread_once control for thread-safe initialization */ | ||
| static pthread_once_t getenv_init_once = PTHREAD_ONCE_INIT; | ||
|
|
||
| /* Initialize the real getenv pointer (called exactly once via pthread_once) */ | ||
| static void init_real_getenv_once(void) { | ||
| real_getenv = dlsym(RTLD_NEXT, "getenv"); | ||
| if (real_getenv == NULL) { | ||
| real_getenv = dlsym(RTLD_NEXT, "getenv"); | ||
| if (real_getenv == NULL) { | ||
| fprintf(stderr, "[one-shot-token] ERROR: Could not find real getenv: %s\n", dlerror()); | ||
| /* Fall back to a no-op to prevent crash */ | ||
| abort(); | ||
| } | ||
| fprintf(stderr, "[one-shot-token] FATAL: Could not find real getenv: %s\n", dlerror()); | ||
| /* Cannot recover - abort to prevent undefined behavior */ | ||
| abort(); | ||
| } | ||
|
Comment on lines
+52
to
58
|
||
| } | ||
|
|
||
| /* Ensure real_getenv is initialized (thread-safe) */ | ||
| static void init_real_getenv(void) { | ||
| pthread_once(&getenv_init_once, init_real_getenv_once); | ||
| } | ||
|
|
||
| /* Check if a variable name is a sensitive token */ | ||
| static int get_token_index(const char *name) { | ||
| if (name == NULL) return -1; | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Assigning the
void *result ofdlsym()directly to a function pointer is not portable ISO C and can trigger warnings (even if it works on many POSIX platforms). Prefer assigning via an intermediatevoid *andmemcpy, or the common POSIX pattern*(void **)(&real_getenv) = dlsym(...);to avoid undefined-behavior concerns and compiler diagnostics.See below for a potential fix: