SDL_getenv.c 16 KB

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