SDL_getenv.c 16 KB

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