Skip to content
0.2.0-dev Download ZIP
634 lines ·17.1 KB Raw
1/*
2 Simple DirectMedia Layer
3 Copyright (C) 1997-2026 Sam Lantinga <slouken@libsdl.org>
4
5 This software is provided 'as-is', without any express or implied
6 warranty. In no event will the authors be held liable for any damages
7 arising from the use of this software.
8
9 Permission is granted to anyone to use this software for any purpose,
10 including commercial applications, and to alter it and redistribute it
11 freely, subject to the following restrictions:
12
13 1. The origin of this software must not be misrepresented; you must not
14 claim that you wrote the original software. If you use this software
15 in a product, an acknowledgment in the product documentation would be
16 appreciated but is not required.
17 2. Altered source versions must be plainly marked as such, and must not be
18 misrepresented as being the original software.
19 3. This notice may not be removed or altered from any source distribution.
20*/
21#include "SDL_internal.h"
22
23#include "SDL_getenv_c.h"
24
25#if defined(SDL_PLATFORM_WINDOWS)
26#include "../core/windows/SDL_windows.h"
27#endif
28
29#ifdef SDL_PLATFORM_ANDROID
30#include "../core/android/SDL_android.h"
31#endif
32
33#if defined(SDL_PLATFORM_WINDOWS)
34#define HAVE_WIN32_ENVIRONMENT
35#elif defined(HAVE_GETENV) && \
36 (defined(HAVE_SETENV) || defined(HAVE_PUTENV)) && \
37 (defined(HAVE_UNSETENV) || defined(HAVE_PUTENV))
38#define HAVE_LIBC_ENVIRONMENT
39#if defined(SDL_PLATFORM_MACOS)
40#include <crt_externs.h>
41#define environ (*_NSGetEnviron())
42#elif defined(SDL_PLATFORM_FREEBSD)
43#include <dlfcn.h>
44static char **get_environ_rtld(void)
45{
46 char ***environ_rtld = (char ***)dlsym(RTLD_DEFAULT, "environ");
47 return environ_rtld ? *environ_rtld : NULL;
48}
49#define environ (get_environ_rtld())
50#else
51extern char **environ;
52#endif
53#else
54#define HAVE_LOCAL_ENVIRONMENT
55static char **environ;
56#endif
57
58struct SDL_Environment
59{
60 SDL_Mutex *lock; // !!! FIXME: reuse SDL_HashTable's lock.
61 SDL_HashTable *strings;
62};
63static SDL_Environment *SDL_environment;
64
65SDL_Environment *SDL_GetEnvironment(void)
66{
67 if (!SDL_environment) {
68 SDL_environment = SDL_CreateEnvironment(true);
69 }
70 return SDL_environment;
71}
72
73bool SDL_InitEnvironment(void)
74{
75 return (SDL_GetEnvironment() != NULL);
76}
77
78void SDL_QuitEnvironment(void)
79{
80 SDL_Environment *env = SDL_environment;
81
82 if (env) {
83 SDL_environment = NULL;
84 SDL_DestroyEnvironment(env);
85 }
86}
87
88SDL_Environment *SDL_CreateEnvironment(bool populated)
89{
90 SDL_Environment *env = SDL_calloc(1, sizeof(*env));
91 if (!env) {
92 return NULL;
93 }
94
95 env->strings = SDL_CreateHashTable(0, false, SDL_HashString, SDL_KeyMatchString, SDL_DestroyHashKey, NULL);
96 if (!env->strings) {
97 SDL_free(env);
98 return NULL;
99 }
100
101 // Don't fail if we can't create a mutex (e.g. on a single-thread environment) // !!! FIXME: single-threaded environments should still return a non-NULL, do-nothing object here. Check for failure!
102 env->lock = SDL_CreateMutex();
103
104 if (populated) {
105#ifdef SDL_PLATFORM_WINDOWS
106 LPWCH strings = GetEnvironmentStringsW();
107 if (strings) {
108 for (LPWCH string = strings; *string; string += SDL_wcslen(string) + 1) {
109 char *variable = WIN_StringToUTF8W(string);
110 if (!variable) {
111 continue;
112 }
113
114 char *value = SDL_strchr(variable, '=');
115 if (!value || value == variable) {
116 SDL_free(variable);
117 continue;
118 }
119 *value++ = '\0';
120
121 SDL_InsertIntoHashTable(env->strings, variable, value, true);
122 }
123 FreeEnvironmentStringsW(strings);
124 }
125#else
126#ifdef SDL_PLATFORM_ANDROID
127 // Make sure variables from the application manifest are available
128 Android_JNI_GetManifestEnvironmentVariables();
129#endif
130 char **strings = environ;
131 if (strings) {
132 for (int i = 0; strings[i]; ++i) {
133 char *variable = SDL_strdup(strings[i]);
134 if (!variable) {
135 continue;
136 }
137
138 char *value = SDL_strchr(variable, '=');
139 if (!value || value == variable) {
140 SDL_free(variable);
141 continue;
142 }
143 *value++ = '\0';
144
145 SDL_InsertIntoHashTable(env->strings, variable, value, true);
146 }
147 }
148#endif // SDL_PLATFORM_WINDOWS
149 }
150
151 return env;
152}
153
154const char *SDL_GetEnvironmentVariable(SDL_Environment *env, const char *name)
155{
156#if defined(SDL_PLATFORM_LINUX) || defined(SDL_PLATFORM_MACOS) || defined(SDL_PLATFORM_FREEBSD)
157 return getenv(name);
158#else
159 const char *result = NULL;
160
161 if (!env) {
162 return NULL;
163 } else if (!name || *name == '\0') {
164 return NULL;
165 }
166
167 SDL_LockMutex(env->lock);
168 {
169 const char *value;
170
171 if (SDL_FindInHashTable(env->strings, name, (const void **)&value)) {
172 result = SDL_GetPersistentString(value);
173 }
174 }
175 SDL_UnlockMutex(env->lock);
176
177 return result;
178#endif
179}
180
181typedef struct CountEnvStringsData
182{
183 size_t count;
184 size_t length;
185} CountEnvStringsData;
186
187static bool SDLCALL CountEnvStrings(void *userdata, const SDL_HashTable *table, const void *key, const void *value)
188{
189 CountEnvStringsData *data = (CountEnvStringsData *) userdata;
190 data->length += SDL_strlen((const char *) key) + 1 + SDL_strlen((const char *) value) + 1;
191 data->count++;
192 return true; // keep iterating.
193}
194
195typedef struct CopyEnvStringsData
196{
197 char **result;
198 char *string;
199 size_t count;
200} CopyEnvStringsData;
201
202static bool SDLCALL CopyEnvStrings(void *userdata, const SDL_HashTable *table, const void *vkey, const void *vvalue)
203{
204 CopyEnvStringsData *data = (CopyEnvStringsData *) userdata;
205 const char *key = (const char *) vkey;
206 const char *value = (const char *) vvalue;
207 size_t len;
208
209 len = SDL_strlen(key);
210 data->result[data->count] = data->string;
211 SDL_memcpy(data->string, key, len);
212 data->string += len;
213 *(data->string++) = '=';
214
215 len = SDL_strlen(value);
216 SDL_memcpy(data->string, value, len);
217 data->string += len;
218 *(data->string++) = '\0';
219 data->count++;
220
221 return true; // keep iterating.
222}
223
224char **SDL_GetEnvironmentVariables(SDL_Environment *env)
225{
226 char **result = NULL;
227
228 CHECK_PARAM(!env) {
229 SDL_InvalidParamError("env");
230 return NULL;
231 }
232
233 SDL_LockMutex(env->lock);
234 {
235 // First pass, get the size we need for all the strings
236 CountEnvStringsData countdata = { 0, 0 };
237 SDL_IterateHashTable(env->strings, CountEnvStrings, &countdata);
238
239 // Allocate memory for the strings
240 result = (char **)SDL_malloc((countdata.count + 1) * sizeof(*result) + countdata.length);
241 if (result) {
242 // Second pass, copy the strings
243 char *string = (char *)(result + countdata.count + 1);
244 CopyEnvStringsData cpydata = { result, string, 0 };
245 SDL_IterateHashTable(env->strings, CopyEnvStrings, &cpydata);
246 SDL_assert(countdata.count == cpydata.count);
247 result[cpydata.count] = NULL;
248 }
249 }
250 SDL_UnlockMutex(env->lock);
251
252 return result;
253}
254
255bool SDL_SetEnvironmentVariable(SDL_Environment *env, const char *name, const char *value, bool overwrite)
256{
257#if defined(SDL_PLATFORM_LINUX) || defined(SDL_PLATFORM_MACOS) || defined(SDL_PLATFORM_FREEBSD)
258 return setenv(name, value, overwrite);
259#else
260 bool result = false;
261
262 CHECK_PARAM(!env) {
263 return SDL_InvalidParamError("env");
264 }
265 CHECK_PARAM(!name || *name == '\0' || SDL_strchr(name, '=') != NULL) {
266 return SDL_InvalidParamError("name");
267 }
268 CHECK_PARAM(!value) {
269 return SDL_InvalidParamError("value");
270 }
271
272 SDL_LockMutex(env->lock);
273 {
274 char *string = NULL;
275 if (SDL_asprintf(&string, "%s=%s", name, value) > 0) {
276 const size_t len = SDL_strlen(name);
277 string[len] = '\0';
278 const char *origname = name;
279 name = string;
280 value = string + len + 1;
281 result = SDL_InsertIntoHashTable(env->strings, name, value, overwrite);
282 if (!result) {
283 SDL_free(string);
284 if (!overwrite) {
285 const void *existing_value = NULL;
286 // !!! FIXME: InsertIntoHashTable does this lookup too, maybe we should have a means to report that, to avoid duplicate work?
287 if (SDL_FindInHashTable(env->strings, origname, &existing_value)) {
288 result = true; // it already existed, and we refused to overwrite it. Call it success.
289 }
290 }
291 }
292 }
293 }
294 SDL_UnlockMutex(env->lock);
295
296 return result;
297#endif
298}
299
300bool SDL_UnsetEnvironmentVariable(SDL_Environment *env, const char *name)
301{
302#if defined(SDL_PLATFORM_LINUX) || defined(SDL_PLATFORM_MACOS) || defined(SDL_PLATFORM_FREEBSD)
303 return unsetenv(name);
304#else
305 bool result = false;
306
307 CHECK_PARAM(!env) {
308 return SDL_InvalidParamError("env");
309 }
310 CHECK_PARAM(!name || *name == '\0' || SDL_strchr(name, '=') != NULL) {
311 return SDL_InvalidParamError("name");
312 }
313
314 SDL_LockMutex(env->lock);
315 {
316 const void *value;
317 if (SDL_FindInHashTable(env->strings, name, &value)) {
318 result = SDL_RemoveFromHashTable(env->strings, name);
319 } else {
320 result = true;
321 }
322 }
323 SDL_UnlockMutex(env->lock);
324
325 return result;
326#endif
327}
328
329void SDL_DestroyEnvironment(SDL_Environment *env)
330{
331 if (!env || env == SDL_environment) {
332 return;
333 }
334
335 SDL_DestroyMutex(env->lock);
336 SDL_DestroyHashTable(env->strings);
337 SDL_free(env);
338}
339
340// Put a variable into the environment
341// Note: Name may not contain a '=' character. (Reference: http://www.unix.com/man-page/Linux/3/setenv/)
342#ifdef HAVE_LIBC_ENVIRONMENT
343#if defined(HAVE_SETENV)
344int SDL_setenv_unsafe(const char *name, const char *value, int overwrite)
345{
346 // Input validation
347 if (!name || *name == '\0' || SDL_strchr(name, '=') != NULL || !value) {
348 return -1;
349 }
350
351 if (SDL_environment) {
352 SDL_SetEnvironmentVariable(SDL_environment, name, value, (overwrite != 0));
353 }
354
355 return setenv(name, value, overwrite);
356}
357// We have a real environment table, but no real setenv? Fake it w/ putenv.
358#else
359int SDL_setenv_unsafe(const char *name, const char *value, int overwrite)
360{
361 char *new_variable;
362
363 // Input validation
364 if (!name || *name == '\0' || SDL_strchr(name, '=') != NULL || !value) {
365 return -1;
366 }
367
368 if (SDL_environment) {
369 SDL_SetEnvironmentVariable(SDL_environment, name, value, (overwrite != 0));
370 }
371
372 if (getenv(name) != NULL) {
373 if (!overwrite) {
374 return 0; // leave the existing one there.
375 }
376 }
377
378 // This leaks. Sorry. Get a better OS so we don't have to do this.
379 SDL_asprintf(&new_variable, "%s=%s", name, value);
380 if (!new_variable) {
381 return -1;
382 }
383 return putenv(new_variable);
384}
385#endif
386#elif defined(HAVE_WIN32_ENVIRONMENT)
387int SDL_setenv_unsafe(const char *name, const char *value, int overwrite)
388{
389 // Input validation
390 if (!name || *name == '\0' || SDL_strchr(name, '=') != NULL || !value) {
391 return -1;
392 }
393
394 if (SDL_environment) {
395 SDL_SetEnvironmentVariable(SDL_environment, name, value, (overwrite != 0));
396 }
397
398 if (!overwrite) {
399 if (GetEnvironmentVariableA(name, NULL, 0) > 0) {
400 return 0; // asked not to overwrite existing value.
401 }
402 }
403 if (!SetEnvironmentVariableA(name, value)) {
404 return -1;
405 }
406 return 0;
407}
408#else // roll our own
409
410int SDL_setenv_unsafe(const char *name, const char *value, int overwrite)
411{
412 int added;
413 size_t len, i;
414 char **new_env;
415 char *new_variable;
416
417 // Input validation
418 if (!name || *name == '\0' || SDL_strchr(name, '=') != NULL || !value) {
419 return -1;
420 }
421
422 // See if it already exists
423 if (!overwrite && SDL_getenv_unsafe(name)) {
424 return 0;
425 }
426
427 if (SDL_environment) {
428 SDL_SetEnvironmentVariable(SDL_environment, name, value, (overwrite != 0));
429 }
430
431 // Allocate memory for the variable
432 len = SDL_strlen(name) + SDL_strlen(value) + 2;
433 new_variable = (char *)SDL_malloc(len);
434 if (!new_variable) {
435 return -1;
436 }
437
438 SDL_snprintf(new_variable, len, "%s=%s", name, value);
439 value = new_variable + SDL_strlen(name) + 1;
440 name = new_variable;
441
442 // Actually put it into the environment
443 added = 0;
444 i = 0;
445 if (environ) {
446 // Check to see if it's already there...
447 len = (value - name);
448 for (; environ[i]; ++i) {
449 if (SDL_strncmp(environ[i], name, len) == 0) {
450 // If we found it, just replace the entry
451 SDL_free(environ[i]);
452 environ[i] = new_variable;
453 added = 1;
454 break;
455 }
456 }
457 }
458
459 // Didn't find it in the environment, expand and add
460 if (!added) {
461 new_env = SDL_realloc(environ, (i + 2) * sizeof(char *));
462 if (new_env) {
463 environ = new_env;
464 environ[i++] = new_variable;
465 environ[i++] = (char *)0;
466 added = 1;
467 } else {
468 SDL_free(new_variable);
469 }
470 }
471 return added ? 0 : -1;
472}
473#endif // HAVE_LIBC_ENVIRONMENT
474
475#ifdef HAVE_LIBC_ENVIRONMENT
476#if defined(HAVE_UNSETENV)
477int SDL_unsetenv_unsafe(const char *name)
478{
479 // Input validation
480 if (!name || *name == '\0' || SDL_strchr(name, '=') != NULL) {
481 return -1;
482 }
483
484 if (SDL_environment) {
485 SDL_UnsetEnvironmentVariable(SDL_environment, name);
486 }
487
488 return unsetenv(name);
489}
490// We have a real environment table, but no unsetenv? Fake it w/ putenv.
491#else
492int SDL_unsetenv_unsafe(const char *name)
493{
494 // Input validation
495 if (!name || *name == '\0' || SDL_strchr(name, '=') != NULL) {
496 return -1;
497 }
498
499 if (SDL_environment) {
500 SDL_UnsetEnvironmentVariable(SDL_environment, name);
501 }
502
503 // Hope this environment uses the non-standard extension of removing the environment variable if it has no '='
504 return putenv(name);
505}
506#endif
507#elif defined(HAVE_WIN32_ENVIRONMENT)
508int SDL_unsetenv_unsafe(const char *name)
509{
510 // Input validation
511 if (!name || *name == '\0' || SDL_strchr(name, '=') != NULL) {
512 return -1;
513 }
514
515 if (SDL_environment) {
516 SDL_UnsetEnvironmentVariable(SDL_environment, name);
517 }
518
519 if (!SetEnvironmentVariableA(name, NULL)) {
520 return -1;
521 }
522 return 0;
523}
524#else
525int SDL_unsetenv_unsafe(const char *name)
526{
527 size_t len, i;
528
529 // Input validation
530 if (!name || *name == '\0' || SDL_strchr(name, '=') != NULL) {
531 return -1;
532 }
533
534 if (SDL_environment) {
535 SDL_UnsetEnvironmentVariable(SDL_environment, name);
536 }
537
538 if (environ) {
539 len = SDL_strlen(name);
540 for (i = 0; environ[i]; ++i) {
541 if ((SDL_strncmp(environ[i], name, len) == 0) &&
542 (environ[i][len] == '=')) {
543 // Just clear out this entry for now
544 *environ[i] = '\0';
545 break;
546 }
547 }
548 }
549 return 0;
550}
551#endif // HAVE_LIBC_ENVIRONMENT
552
553// Retrieve a variable named "name" from the environment
554#if defined(SDL_PLATFORM_LINUX) || defined(SDL_PLATFORM_MACOS) || defined(SDL_PLATFORM_FREEBSD)
555const char *SDL_getenv_unsafe(const char *name)
556{
557#ifdef SDL_PLATFORM_ANDROID
558 // Make sure variables from the application manifest are available
559 Android_JNI_GetManifestEnvironmentVariables();
560#endif
561
562 // Input validation
563 if (!name || *name == '\0') {
564 return NULL;
565 }
566
567 return getenv(name);
568}
569#elif defined(HAVE_WIN32_ENVIRONMENT)
570const char *SDL_getenv_unsafe(const char *name)
571{
572 DWORD length, maxlen = 0;
573 char *string = NULL;
574 const char *result = NULL;
575
576 // Input validation
577 if (!name || *name == '\0') {
578 return NULL;
579 }
580
581 for ( ; ; ) {
582 SetLastError(ERROR_SUCCESS);
583 length = GetEnvironmentVariableA(name, string, maxlen);
584
585 if (length > maxlen) {
586 char *temp = (char *)SDL_realloc(string, length);
587 if (!temp) {
588 return NULL;
589 }
590 string = temp;
591 maxlen = length;
592 } else {
593 if (GetLastError() != ERROR_SUCCESS) {
594 SDL_free(string);
595 return NULL;
596 }
597 break;
598 }
599 }
600 if (string) {
601 result = SDL_GetPersistentString(string);
602 SDL_free(string);
603 }
604 return result;
605}
606#else
607const char *SDL_getenv_unsafe(const char *name)
608{
609 size_t len, i;
610 const char *value = NULL;
611
612 // Input validation
613 if (!name || *name == '\0') {
614 return NULL;
615 }
616
617 if (environ) {
618 len = SDL_strlen(name);
619 for (i = 0; environ[i]; ++i) {
620 if ((SDL_strncmp(environ[i], name, len) == 0) &&
621 (environ[i][len] == '=')) {
622 value = &environ[i][len + 1];
623 break;
624 }
625 }
626 }
627 return value;
628}
629#endif // HAVE_LIBC_ENVIRONMENT
630
631const char *SDL_getenv(const char *name)
632{
633 return SDL_GetEnvironmentVariable(SDL_GetEnvironment(), name);
634}