kmp_environment.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. /*
  2. * kmp_environment.cpp -- Handle environment variables OS-independently.
  3. */
  4. //===----------------------------------------------------------------------===//
  5. //
  6. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  7. // See https://llvm.org/LICENSE.txt for license information.
  8. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  9. //
  10. //===----------------------------------------------------------------------===//
  11. /* We use GetEnvironmentVariable for Windows* OS instead of getenv because the
  12. act of loading a DLL on Windows* OS makes any user-set environment variables
  13. (i.e. with putenv()) unavailable. getenv() apparently gets a clean copy of
  14. the env variables as they existed at the start of the run. JH 12/23/2002
  15. On Windows* OS, there are two environments (at least, see below):
  16. 1. Environment maintained by Windows* OS on IA-32 architecture. Accessible
  17. through GetEnvironmentVariable(), SetEnvironmentVariable(), and
  18. GetEnvironmentStrings().
  19. 2. Environment maintained by C RTL. Accessible through getenv(), putenv().
  20. putenv() function updates both C and Windows* OS on IA-32 architecture.
  21. getenv() function search for variables in C RTL environment only.
  22. Windows* OS on IA-32 architecture functions work *only* with Windows* OS on
  23. IA-32 architecture.
  24. Windows* OS on IA-32 architecture maintained by OS, so there is always only
  25. one Windows* OS on IA-32 architecture per process. Changes in Windows* OS on
  26. IA-32 architecture are process-visible.
  27. C environment maintained by C RTL. Multiple copies of C RTL may be present
  28. in the process, and each C RTL maintains its own environment. :-(
  29. Thus, proper way to work with environment on Windows* OS is:
  30. 1. Set variables with putenv() function -- both C and Windows* OS on IA-32
  31. architecture are being updated. Windows* OS on IA-32 architecture may be
  32. considered primary target, while updating C RTL environment is free bonus.
  33. 2. Get variables with GetEnvironmentVariable() -- getenv() does not
  34. search Windows* OS on IA-32 architecture, and can not see variables
  35. set with SetEnvironmentVariable().
  36. 2007-04-05 -- lev
  37. */
  38. #include "kmp_environment.h"
  39. #include "kmp.h" //
  40. #include "kmp_i18n.h"
  41. #include "kmp_os.h" // KMP_OS_*.
  42. #include "kmp_str.h" // __kmp_str_*().
  43. #if KMP_OS_UNIX
  44. #include <stdlib.h> // getenv, setenv, unsetenv.
  45. #include <string.h> // strlen, strcpy.
  46. #if KMP_OS_DARWIN
  47. #include <crt_externs.h>
  48. #define environ (*_NSGetEnviron())
  49. #else
  50. extern char **environ;
  51. #endif
  52. #elif KMP_OS_WINDOWS
  53. #include <windows.h> // GetEnvironmentVariable, SetEnvironmentVariable,
  54. // GetLastError.
  55. #else
  56. #error Unknown or unsupported OS.
  57. #endif
  58. // TODO: Eliminate direct memory allocations, use string operations instead.
  59. static inline void *allocate(size_t size) {
  60. void *ptr = KMP_INTERNAL_MALLOC(size);
  61. if (ptr == NULL) {
  62. KMP_FATAL(MemoryAllocFailed);
  63. }
  64. return ptr;
  65. } // allocate
  66. char *__kmp_env_get(char const *name) {
  67. char *result = NULL;
  68. #if KMP_OS_UNIX
  69. char const *value = getenv(name);
  70. if (value != NULL) {
  71. size_t len = KMP_STRLEN(value) + 1;
  72. result = (char *)KMP_INTERNAL_MALLOC(len);
  73. if (result == NULL) {
  74. KMP_FATAL(MemoryAllocFailed);
  75. }
  76. KMP_STRNCPY_S(result, len, value, len);
  77. }
  78. #elif KMP_OS_WINDOWS
  79. /* We use GetEnvironmentVariable for Windows* OS instead of getenv because the
  80. act of loading a DLL on Windows* OS makes any user-set environment
  81. variables (i.e. with putenv()) unavailable. getenv() apparently gets a
  82. clean copy of the env variables as they existed at the start of the run.
  83. JH 12/23/2002 */
  84. DWORD rc;
  85. rc = GetEnvironmentVariable(name, NULL, 0);
  86. if (!rc) {
  87. DWORD error = GetLastError();
  88. if (error != ERROR_ENVVAR_NOT_FOUND) {
  89. __kmp_fatal(KMP_MSG(CantGetEnvVar, name), KMP_ERR(error), __kmp_msg_null);
  90. }
  91. // Variable is not found, it's ok, just continue.
  92. } else {
  93. DWORD len = rc;
  94. result = (char *)KMP_INTERNAL_MALLOC(len);
  95. if (result == NULL) {
  96. KMP_FATAL(MemoryAllocFailed);
  97. }
  98. rc = GetEnvironmentVariable(name, result, len);
  99. if (!rc) {
  100. // GetEnvironmentVariable() may return 0 if variable is empty.
  101. // In such a case GetLastError() returns ERROR_SUCCESS.
  102. DWORD error = GetLastError();
  103. if (error != ERROR_SUCCESS) {
  104. // Unexpected error. The variable should be in the environment,
  105. // and buffer should be large enough.
  106. __kmp_fatal(KMP_MSG(CantGetEnvVar, name), KMP_ERR(error),
  107. __kmp_msg_null);
  108. KMP_INTERNAL_FREE((void *)result);
  109. result = NULL;
  110. }
  111. }
  112. }
  113. #else
  114. #error Unknown or unsupported OS.
  115. #endif
  116. return result;
  117. } // func __kmp_env_get
  118. // TODO: Find and replace all regular free() with __kmp_env_free().
  119. void __kmp_env_free(char const **value) {
  120. KMP_DEBUG_ASSERT(value != NULL);
  121. KMP_INTERNAL_FREE(CCAST(char *, *value));
  122. *value = NULL;
  123. } // func __kmp_env_free
  124. int __kmp_env_exists(char const *name) {
  125. #if KMP_OS_UNIX
  126. char const *value = getenv(name);
  127. return ((value == NULL) ? (0) : (1));
  128. #elif KMP_OS_WINDOWS
  129. DWORD rc;
  130. rc = GetEnvironmentVariable(name, NULL, 0);
  131. if (rc == 0) {
  132. DWORD error = GetLastError();
  133. if (error != ERROR_ENVVAR_NOT_FOUND) {
  134. __kmp_fatal(KMP_MSG(CantGetEnvVar, name), KMP_ERR(error), __kmp_msg_null);
  135. }
  136. return 0;
  137. }
  138. return 1;
  139. #else
  140. #error Unknown or unsupported OS.
  141. #endif
  142. } // func __kmp_env_exists
  143. void __kmp_env_set(char const *name, char const *value, int overwrite) {
  144. #if KMP_OS_UNIX
  145. int rc = setenv(name, value, overwrite);
  146. if (rc != 0) {
  147. // Dead code. I tried to put too many variables into Linux* OS
  148. // environment on IA-32 architecture. When application consumes
  149. // more than ~2.5 GB of memory, entire system feels bad. Sometimes
  150. // application is killed (by OS?), sometimes system stops
  151. // responding... But this error message never appears. --ln
  152. __kmp_fatal(KMP_MSG(CantSetEnvVar, name), KMP_HNT(NotEnoughMemory),
  153. __kmp_msg_null);
  154. }
  155. #elif KMP_OS_WINDOWS
  156. BOOL rc;
  157. if (!overwrite) {
  158. rc = GetEnvironmentVariable(name, NULL, 0);
  159. if (rc) {
  160. // Variable exists, do not overwrite.
  161. return;
  162. }
  163. DWORD error = GetLastError();
  164. if (error != ERROR_ENVVAR_NOT_FOUND) {
  165. __kmp_fatal(KMP_MSG(CantGetEnvVar, name), KMP_ERR(error), __kmp_msg_null);
  166. }
  167. }
  168. rc = SetEnvironmentVariable(name, value);
  169. if (!rc) {
  170. DWORD error = GetLastError();
  171. __kmp_fatal(KMP_MSG(CantSetEnvVar, name), KMP_ERR(error), __kmp_msg_null);
  172. }
  173. #else
  174. #error Unknown or unsupported OS.
  175. #endif
  176. } // func __kmp_env_set
  177. void __kmp_env_unset(char const *name) {
  178. #if KMP_OS_UNIX
  179. unsetenv(name);
  180. #elif KMP_OS_WINDOWS
  181. BOOL rc = SetEnvironmentVariable(name, NULL);
  182. if (!rc) {
  183. DWORD error = GetLastError();
  184. __kmp_fatal(KMP_MSG(CantSetEnvVar, name), KMP_ERR(error), __kmp_msg_null);
  185. }
  186. #else
  187. #error Unknown or unsupported OS.
  188. #endif
  189. } // func __kmp_env_unset
  190. /* Intel OpenMP RTL string representation of environment: just a string of
  191. characters, variables are separated with vertical bars, e. g.:
  192. "KMP_WARNINGS=0|KMP_AFFINITY=compact|"
  193. Empty variables are allowed and ignored:
  194. "||KMP_WARNINGS=1||"
  195. */
  196. static void
  197. ___kmp_env_blk_parse_string(kmp_env_blk_t *block, // M: Env block to fill.
  198. char const *env // I: String to parse.
  199. ) {
  200. char const chr_delimiter = '|';
  201. char const str_delimiter[] = {chr_delimiter, 0};
  202. char *bulk = NULL;
  203. kmp_env_var_t *vars = NULL;
  204. int count = 0; // Number of used elements in vars array.
  205. int delimiters = 0; // Number of delimiters in input string.
  206. // Copy original string, we will modify the copy.
  207. bulk = __kmp_str_format("%s", env);
  208. // Loop thru all the vars in environment block. Count delimiters (maximum
  209. // number of variables is number of delimiters plus one).
  210. {
  211. char const *ptr = bulk;
  212. for (;;) {
  213. ptr = strchr(ptr, chr_delimiter);
  214. if (ptr == NULL) {
  215. break;
  216. }
  217. ++delimiters;
  218. ptr += 1;
  219. }
  220. }
  221. // Allocate vars array.
  222. vars = (kmp_env_var_t *)allocate((delimiters + 1) * sizeof(kmp_env_var_t));
  223. // Loop thru all the variables.
  224. {
  225. char *var; // Pointer to variable (both name and value).
  226. char *name; // Pointer to name of variable.
  227. char *value; // Pointer to value.
  228. char *buf; // Buffer for __kmp_str_token() function.
  229. var = __kmp_str_token(bulk, str_delimiter, &buf); // Get the first var.
  230. while (var != NULL) {
  231. // Save found variable in vars array.
  232. __kmp_str_split(var, '=', &name, &value);
  233. KMP_DEBUG_ASSERT(count < delimiters + 1);
  234. vars[count].name = name;
  235. vars[count].value = value;
  236. ++count;
  237. // Get the next var.
  238. var = __kmp_str_token(NULL, str_delimiter, &buf);
  239. }
  240. }
  241. // Fill out result.
  242. block->bulk = bulk;
  243. block->vars = vars;
  244. block->count = count;
  245. }
  246. /* Windows* OS (actually, DOS) environment block is a piece of memory with
  247. environment variables. Each variable is terminated with zero byte, entire
  248. block is terminated with one extra zero byte, so we have two zero bytes at
  249. the end of environment block, e. g.:
  250. "HOME=C:\\users\\lev\x00OS=Windows_NT\x00\x00"
  251. It is not clear how empty environment is represented. "\x00\x00"?
  252. */
  253. #if KMP_OS_WINDOWS
  254. static void ___kmp_env_blk_parse_windows(
  255. kmp_env_blk_t *block, // M: Env block to fill.
  256. char const *env // I: Pointer to Windows* OS (DOS) environment block.
  257. ) {
  258. char *bulk = NULL;
  259. kmp_env_var_t *vars = NULL;
  260. int count = 0; // Number of used elements in vars array.
  261. int size = 0; // Size of bulk.
  262. char *name; // Pointer to name of variable.
  263. char *value; // Pointer to value.
  264. if (env != NULL) {
  265. // Loop thru all the vars in environment block. Count variables, find size
  266. // of block.
  267. {
  268. char const *var; // Pointer to beginning of var.
  269. int len; // Length of variable.
  270. count = 0;
  271. var =
  272. env; // The first variable starts and beginning of environment block.
  273. len = KMP_STRLEN(var);
  274. while (len != 0) {
  275. ++count;
  276. size = size + len + 1;
  277. var = var + len +
  278. 1; // Move pointer to the beginning of the next variable.
  279. len = KMP_STRLEN(var);
  280. }
  281. size =
  282. size + 1; // Total size of env block, including terminating zero byte.
  283. }
  284. // Copy original block to bulk, we will modify bulk, not original block.
  285. bulk = (char *)allocate(size);
  286. KMP_MEMCPY_S(bulk, size, env, size);
  287. // Allocate vars array.
  288. vars = (kmp_env_var_t *)allocate(count * sizeof(kmp_env_var_t));
  289. // Loop thru all the vars, now in bulk.
  290. {
  291. char *var; // Pointer to beginning of var.
  292. int len; // Length of variable.
  293. count = 0;
  294. var = bulk;
  295. len = KMP_STRLEN(var);
  296. while (len != 0) {
  297. // Save variable in vars array.
  298. __kmp_str_split(var, '=', &name, &value);
  299. vars[count].name = name;
  300. vars[count].value = value;
  301. ++count;
  302. // Get the next var.
  303. var = var + len + 1;
  304. len = KMP_STRLEN(var);
  305. }
  306. }
  307. }
  308. // Fill out result.
  309. block->bulk = bulk;
  310. block->vars = vars;
  311. block->count = count;
  312. }
  313. #endif
  314. /* Unix environment block is a array of pointers to variables, last pointer in
  315. array is NULL:
  316. { "HOME=/home/lev", "TERM=xterm", NULL }
  317. */
  318. #if KMP_OS_UNIX
  319. static void
  320. ___kmp_env_blk_parse_unix(kmp_env_blk_t *block, // M: Env block to fill.
  321. char **env // I: Unix environment to parse.
  322. ) {
  323. char *bulk = NULL;
  324. kmp_env_var_t *vars = NULL;
  325. int count = 0;
  326. size_t size = 0; // Size of bulk.
  327. // Count number of variables and length of required bulk.
  328. {
  329. while (env[count] != NULL) {
  330. size += KMP_STRLEN(env[count]) + 1;
  331. ++count;
  332. }
  333. }
  334. // Allocate memory.
  335. bulk = (char *)allocate(size);
  336. vars = (kmp_env_var_t *)allocate(count * sizeof(kmp_env_var_t));
  337. // Loop thru all the vars.
  338. {
  339. char *var; // Pointer to beginning of var.
  340. char *name; // Pointer to name of variable.
  341. char *value; // Pointer to value.
  342. size_t len; // Length of variable.
  343. int i;
  344. var = bulk;
  345. for (i = 0; i < count; ++i) {
  346. // Copy variable to bulk.
  347. len = KMP_STRLEN(env[i]);
  348. KMP_MEMCPY_S(var, size, env[i], len + 1);
  349. // Save found variable in vars array.
  350. __kmp_str_split(var, '=', &name, &value);
  351. vars[i].name = name;
  352. vars[i].value = value;
  353. // Move pointer.
  354. var += len + 1;
  355. }
  356. }
  357. // Fill out result.
  358. block->bulk = bulk;
  359. block->vars = vars;
  360. block->count = count;
  361. }
  362. #endif
  363. void __kmp_env_blk_init(kmp_env_blk_t *block, // M: Block to initialize.
  364. char const *bulk // I: Initialization string, or NULL.
  365. ) {
  366. if (bulk != NULL) {
  367. ___kmp_env_blk_parse_string(block, bulk);
  368. } else {
  369. #if KMP_OS_UNIX
  370. ___kmp_env_blk_parse_unix(block, environ);
  371. #elif KMP_OS_WINDOWS
  372. {
  373. char *mem = GetEnvironmentStrings();
  374. if (mem == NULL) {
  375. DWORD error = GetLastError();
  376. __kmp_fatal(KMP_MSG(CantGetEnvironment), KMP_ERR(error),
  377. __kmp_msg_null);
  378. }
  379. ___kmp_env_blk_parse_windows(block, mem);
  380. FreeEnvironmentStrings(mem);
  381. }
  382. #else
  383. #error Unknown or unsupported OS.
  384. #endif
  385. }
  386. } // __kmp_env_blk_init
  387. static int ___kmp_env_var_cmp( // Comparison function for qsort().
  388. kmp_env_var_t const *lhs, kmp_env_var_t const *rhs) {
  389. return strcmp(lhs->name, rhs->name);
  390. }
  391. void __kmp_env_blk_sort(
  392. kmp_env_blk_t *block // M: Block of environment variables to sort.
  393. ) {
  394. qsort(CCAST(kmp_env_var_t *, block->vars), block->count,
  395. sizeof(kmp_env_var_t),
  396. (int (*)(void const *, void const *)) & ___kmp_env_var_cmp);
  397. } // __kmp_env_block_sort
  398. void __kmp_env_blk_free(
  399. kmp_env_blk_t *block // M: Block of environment variables to free.
  400. ) {
  401. KMP_INTERNAL_FREE(CCAST(kmp_env_var_t *, block->vars));
  402. __kmp_str_free(&(block->bulk));
  403. block->count = 0;
  404. block->vars = NULL;
  405. } // __kmp_env_blk_free
  406. char const * // R: Value of variable or NULL if variable does not exist.
  407. __kmp_env_blk_var(kmp_env_blk_t *block, // I: Block of environment variables.
  408. char const *name // I: Name of variable to find.
  409. ) {
  410. int i;
  411. for (i = 0; i < block->count; ++i) {
  412. if (strcmp(block->vars[i].name, name) == 0) {
  413. return block->vars[i].value;
  414. }
  415. }
  416. return NULL;
  417. } // __kmp_env_block_var
  418. // end of file //