You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2161 lines
61 KiB

  1. #include "Python.h"
  2. #include "osdefs.h" /* DELIM */
  3. #include "pycore_coreconfig.h"
  4. #include "pycore_fileutils.h"
  5. #include "pycore_getopt.h"
  6. #include "pycore_pylifecycle.h"
  7. #include "pycore_pymem.h"
  8. #include "pycore_pathconfig.h"
  9. #include <locale.h> /* setlocale() */
  10. #ifdef HAVE_LANGINFO_H
  11. # include <langinfo.h> /* nl_langinfo(CODESET) */
  12. #endif
  13. #if defined(MS_WINDOWS) || defined(__CYGWIN__)
  14. # include <windows.h> /* GetACP() */
  15. # ifdef HAVE_IO_H
  16. # include <io.h>
  17. # endif
  18. # ifdef HAVE_FCNTL_H
  19. # include <fcntl.h> /* O_BINARY */
  20. # endif
  21. #endif
  22. /* --- Command line options --------------------------------------- */
  23. /* Short usage message (with %s for argv0) */
  24. static const char usage_line[] =
  25. "usage: %ls [option] ... [-c cmd | -m mod | file | -] [arg] ...\n";
  26. /* Long usage message, split into parts < 512 bytes */
  27. static const char usage_1[] = "\
  28. Options and arguments (and corresponding environment variables):\n\
  29. -b : issue warnings about str(bytes_instance), str(bytearray_instance)\n\
  30. and comparing bytes/bytearray with str. (-bb: issue errors)\n\
  31. -B : don't write .pyc files on import; also PYTHONDONTWRITEBYTECODE=x\n\
  32. -c cmd : program passed in as string (terminates option list)\n\
  33. -d : debug output from parser; also PYTHONDEBUG=x\n\
  34. -E : ignore PYTHON* environment variables (such as PYTHONPATH)\n\
  35. -h : print this help message and exit (also --help)\n\
  36. ";
  37. static const char usage_2[] = "\
  38. -i : inspect interactively after running script; forces a prompt even\n\
  39. if stdin does not appear to be a terminal; also PYTHONINSPECT=x\n\
  40. -I : isolate Python from the user's environment (implies -E and -s)\n\
  41. -m mod : run library module as a script (terminates option list)\n\
  42. -O : remove assert and __debug__-dependent statements; add .opt-1 before\n\
  43. .pyc extension; also PYTHONOPTIMIZE=x\n\
  44. -OO : do -O changes and also discard docstrings; add .opt-2 before\n\
  45. .pyc extension\n\
  46. -q : don't print version and copyright messages on interactive startup\n\
  47. -s : don't add user site directory to sys.path; also PYTHONNOUSERSITE\n\
  48. -S : don't imply 'import site' on initialization\n\
  49. ";
  50. static const char usage_3[] = "\
  51. -u : force the stdout and stderr streams to be unbuffered;\n\
  52. this option has no effect on stdin; also PYTHONUNBUFFERED=x\n\
  53. -v : verbose (trace import statements); also PYTHONVERBOSE=x\n\
  54. can be supplied multiple times to increase verbosity\n\
  55. -V : print the Python version number and exit (also --version)\n\
  56. when given twice, print more information about the build\n\
  57. -W arg : warning control; arg is action:message:category:module:lineno\n\
  58. also PYTHONWARNINGS=arg\n\
  59. -x : skip first line of source, allowing use of non-Unix forms of #!cmd\n\
  60. -X opt : set implementation-specific option\n\
  61. --check-hash-based-pycs always|default|never:\n\
  62. control how Python invalidates hash-based .pyc files\n\
  63. ";
  64. static const char usage_4[] = "\
  65. file : program read from script file\n\
  66. - : program read from stdin (default; interactive mode if a tty)\n\
  67. arg ...: arguments passed to program in sys.argv[1:]\n\n\
  68. Other environment variables:\n\
  69. PYTHONSTARTUP: file executed on interactive startup (no default)\n\
  70. PYTHONPATH : '%lc'-separated list of directories prefixed to the\n\
  71. default module search path. The result is sys.path.\n\
  72. ";
  73. static const char usage_5[] =
  74. "PYTHONHOME : alternate <prefix> directory (or <prefix>%lc<exec_prefix>).\n"
  75. " The default module search path uses %s.\n"
  76. "PYTHONCASEOK : ignore case in 'import' statements (Windows).\n"
  77. "PYTHONIOENCODING: Encoding[:errors] used for stdin/stdout/stderr.\n"
  78. "PYTHONFAULTHANDLER: dump the Python traceback on fatal errors.\n";
  79. static const char usage_6[] =
  80. "PYTHONHASHSEED: if this variable is set to 'random', a random value is used\n"
  81. " to seed the hashes of str, bytes and datetime objects. It can also be\n"
  82. " set to an integer in the range [0,4294967295] to get hash values with a\n"
  83. " predictable seed.\n"
  84. "PYTHONMALLOC: set the Python memory allocators and/or install debug hooks\n"
  85. " on Python memory allocators. Use PYTHONMALLOC=debug to install debug\n"
  86. " hooks.\n"
  87. "PYTHONCOERCECLOCALE: if this variable is set to 0, it disables the locale\n"
  88. " coercion behavior. Use PYTHONCOERCECLOCALE=warn to request display of\n"
  89. " locale coercion and locale compatibility warnings on stderr.\n"
  90. "PYTHONBREAKPOINT: if this variable is set to 0, it disables the default\n"
  91. " debugger. It can be set to the callable of your debugger of choice.\n"
  92. "PYTHONDEVMODE: enable the development mode.\n"
  93. "PYTHONPYCACHEPREFIX: root directory for bytecode cache (pyc) files.\n";
  94. #if defined(MS_WINDOWS)
  95. # define PYTHONHOMEHELP "<prefix>\\python{major}{minor}"
  96. #else
  97. # define PYTHONHOMEHELP "<prefix>/lib/pythonX.X"
  98. #endif
  99. /* --- Global configuration variables ----------------------------- */
  100. /* UTF-8 mode (PEP 540): if equals to 1, use the UTF-8 encoding, and change
  101. stdin and stdout error handler to "surrogateescape". It is equal to
  102. -1 by default: unknown, will be set by Py_Main() */
  103. int Py_UTF8Mode = -1;
  104. int Py_DebugFlag = 0; /* Needed by parser.c */
  105. int Py_VerboseFlag = 0; /* Needed by import.c */
  106. int Py_QuietFlag = 0; /* Needed by sysmodule.c */
  107. int Py_InteractiveFlag = 0; /* Needed by Py_FdIsInteractive() below */
  108. int Py_InspectFlag = 0; /* Needed to determine whether to exit at SystemExit */
  109. int Py_OptimizeFlag = 0; /* Needed by compile.c */
  110. int Py_NoSiteFlag = 0; /* Suppress 'import site' */
  111. int Py_BytesWarningFlag = 0; /* Warn on str(bytes) and str(buffer) */
  112. int Py_FrozenFlag = 0; /* Needed by getpath.c */
  113. int Py_IgnoreEnvironmentFlag = 0; /* e.g. PYTHONPATH, PYTHONHOME */
  114. int Py_DontWriteBytecodeFlag = 0; /* Suppress writing bytecode files (*.pyc) */
  115. int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
  116. int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
  117. int Py_HashRandomizationFlag = 0; /* for -R and PYTHONHASHSEED */
  118. int Py_IsolatedFlag = 0; /* for -I, isolate from user's env */
  119. #ifdef MS_WINDOWS
  120. int Py_LegacyWindowsFSEncodingFlag = 0; /* Uses mbcs instead of utf-8 */
  121. int Py_LegacyWindowsStdioFlag = 0; /* Uses FileIO instead of WindowsConsoleIO */
  122. #endif
  123. PyObject *
  124. _Py_GetGlobalVariablesAsDict(void)
  125. {
  126. PyObject *dict, *obj;
  127. dict = PyDict_New();
  128. if (dict == NULL) {
  129. return NULL;
  130. }
  131. #define SET_ITEM(KEY, EXPR) \
  132. do { \
  133. obj = (EXPR); \
  134. if (obj == NULL) { \
  135. return NULL; \
  136. } \
  137. int res = PyDict_SetItemString(dict, (KEY), obj); \
  138. Py_DECREF(obj); \
  139. if (res < 0) { \
  140. goto fail; \
  141. } \
  142. } while (0)
  143. #define SET_ITEM_INT(VAR) \
  144. SET_ITEM(#VAR, PyLong_FromLong(VAR))
  145. #define FROM_STRING(STR) \
  146. ((STR != NULL) ? \
  147. PyUnicode_FromString(STR) \
  148. : (Py_INCREF(Py_None), Py_None))
  149. #define SET_ITEM_STR(VAR) \
  150. SET_ITEM(#VAR, FROM_STRING(VAR))
  151. SET_ITEM_STR(Py_FileSystemDefaultEncoding);
  152. SET_ITEM_INT(Py_HasFileSystemDefaultEncoding);
  153. SET_ITEM_STR(Py_FileSystemDefaultEncodeErrors);
  154. SET_ITEM_INT(_Py_HasFileSystemDefaultEncodeErrors);
  155. SET_ITEM_INT(Py_UTF8Mode);
  156. SET_ITEM_INT(Py_DebugFlag);
  157. SET_ITEM_INT(Py_VerboseFlag);
  158. SET_ITEM_INT(Py_QuietFlag);
  159. SET_ITEM_INT(Py_InteractiveFlag);
  160. SET_ITEM_INT(Py_InspectFlag);
  161. SET_ITEM_INT(Py_OptimizeFlag);
  162. SET_ITEM_INT(Py_NoSiteFlag);
  163. SET_ITEM_INT(Py_BytesWarningFlag);
  164. SET_ITEM_INT(Py_FrozenFlag);
  165. SET_ITEM_INT(Py_IgnoreEnvironmentFlag);
  166. SET_ITEM_INT(Py_DontWriteBytecodeFlag);
  167. SET_ITEM_INT(Py_NoUserSiteDirectory);
  168. SET_ITEM_INT(Py_UnbufferedStdioFlag);
  169. SET_ITEM_INT(Py_HashRandomizationFlag);
  170. SET_ITEM_INT(Py_IsolatedFlag);
  171. #ifdef MS_WINDOWS
  172. SET_ITEM_INT(Py_LegacyWindowsFSEncodingFlag);
  173. SET_ITEM_INT(Py_LegacyWindowsStdioFlag);
  174. #endif
  175. return dict;
  176. fail:
  177. Py_DECREF(dict);
  178. return NULL;
  179. #undef FROM_STRING
  180. #undef SET_ITEM
  181. #undef SET_ITEM_INT
  182. #undef SET_ITEM_STR
  183. }
  184. /* --- _Py_wstrlist ----------------------------------------------- */
  185. void
  186. _Py_wstrlist_clear(int len, wchar_t **list)
  187. {
  188. for (int i=0; i < len; i++) {
  189. PyMem_RawFree(list[i]);
  190. }
  191. PyMem_RawFree(list);
  192. }
  193. wchar_t**
  194. _Py_wstrlist_copy(int len, wchar_t * const *list)
  195. {
  196. assert((len > 0 && list != NULL) || len == 0);
  197. size_t size = len * sizeof(list[0]);
  198. wchar_t **list_copy = PyMem_RawMalloc(size);
  199. if (list_copy == NULL) {
  200. return NULL;
  201. }
  202. for (int i=0; i < len; i++) {
  203. wchar_t* arg = _PyMem_RawWcsdup(list[i]);
  204. if (arg == NULL) {
  205. _Py_wstrlist_clear(i, list_copy);
  206. return NULL;
  207. }
  208. list_copy[i] = arg;
  209. }
  210. return list_copy;
  211. }
  212. _PyInitError
  213. _Py_wstrlist_append(int *len, wchar_t ***list, const wchar_t *str)
  214. {
  215. if (*len == INT_MAX) {
  216. /* len+1 would overflow */
  217. return _Py_INIT_NO_MEMORY();
  218. }
  219. wchar_t *str2 = _PyMem_RawWcsdup(str);
  220. if (str2 == NULL) {
  221. return _Py_INIT_NO_MEMORY();
  222. }
  223. size_t size = (*len + 1) * sizeof(list[0]);
  224. wchar_t **list2 = (wchar_t **)PyMem_RawRealloc(*list, size);
  225. if (list2 == NULL) {
  226. PyMem_RawFree(str2);
  227. return _Py_INIT_NO_MEMORY();
  228. }
  229. list2[*len] = str2;
  230. *list = list2;
  231. (*len)++;
  232. return _Py_INIT_OK();
  233. }
  234. PyObject*
  235. _Py_wstrlist_as_pylist(int len, wchar_t **list)
  236. {
  237. assert(list != NULL || len < 1);
  238. PyObject *pylist = PyList_New(len);
  239. if (pylist == NULL) {
  240. return NULL;
  241. }
  242. for (int i = 0; i < len; i++) {
  243. PyObject *v = PyUnicode_FromWideChar(list[i], -1);
  244. if (v == NULL) {
  245. Py_DECREF(pylist);
  246. return NULL;
  247. }
  248. PyList_SET_ITEM(pylist, i, v);
  249. }
  250. return pylist;
  251. }
  252. /* --- Py_SetStandardStreamEncoding() ----------------------------- */
  253. /* Helper to allow an embedding application to override the normal
  254. * mechanism that attempts to figure out an appropriate IO encoding
  255. */
  256. static char *_Py_StandardStreamEncoding = NULL;
  257. static char *_Py_StandardStreamErrors = NULL;
  258. int
  259. Py_SetStandardStreamEncoding(const char *encoding, const char *errors)
  260. {
  261. if (Py_IsInitialized()) {
  262. /* This is too late to have any effect */
  263. return -1;
  264. }
  265. int res = 0;
  266. /* Py_SetStandardStreamEncoding() can be called before Py_Initialize(),
  267. but Py_Initialize() can change the allocator. Use a known allocator
  268. to be able to release the memory later. */
  269. PyMemAllocatorEx old_alloc;
  270. _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
  271. /* Can't call PyErr_NoMemory() on errors, as Python hasn't been
  272. * initialised yet.
  273. *
  274. * However, the raw memory allocators are initialised appropriately
  275. * as C static variables, so _PyMem_RawStrdup is OK even though
  276. * Py_Initialize hasn't been called yet.
  277. */
  278. if (encoding) {
  279. _Py_StandardStreamEncoding = _PyMem_RawStrdup(encoding);
  280. if (!_Py_StandardStreamEncoding) {
  281. res = -2;
  282. goto done;
  283. }
  284. }
  285. if (errors) {
  286. _Py_StandardStreamErrors = _PyMem_RawStrdup(errors);
  287. if (!_Py_StandardStreamErrors) {
  288. if (_Py_StandardStreamEncoding) {
  289. PyMem_RawFree(_Py_StandardStreamEncoding);
  290. }
  291. res = -3;
  292. goto done;
  293. }
  294. }
  295. #ifdef MS_WINDOWS
  296. if (_Py_StandardStreamEncoding) {
  297. /* Overriding the stream encoding implies legacy streams */
  298. Py_LegacyWindowsStdioFlag = 1;
  299. }
  300. #endif
  301. done:
  302. PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
  303. return res;
  304. }
  305. void
  306. _Py_ClearStandardStreamEncoding(void)
  307. {
  308. /* Use the same allocator than Py_SetStandardStreamEncoding() */
  309. PyMemAllocatorEx old_alloc;
  310. _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
  311. /* We won't need them anymore. */
  312. if (_Py_StandardStreamEncoding) {
  313. PyMem_RawFree(_Py_StandardStreamEncoding);
  314. _Py_StandardStreamEncoding = NULL;
  315. }
  316. if (_Py_StandardStreamErrors) {
  317. PyMem_RawFree(_Py_StandardStreamErrors);
  318. _Py_StandardStreamErrors = NULL;
  319. }
  320. PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
  321. }
  322. /* --- Py_GetArgcArgv() ------------------------------------------- */
  323. /* For Py_GetArgcArgv(); set by _Py_SetArgcArgv() */
  324. static int orig_argc = 0;
  325. static wchar_t **orig_argv = NULL;
  326. void
  327. _Py_ClearArgcArgv(void)
  328. {
  329. PyMemAllocatorEx old_alloc;
  330. _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
  331. _Py_wstrlist_clear(orig_argc, orig_argv);
  332. orig_argc = 0;
  333. orig_argv = NULL;
  334. PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
  335. }
  336. int
  337. _Py_SetArgcArgv(int argc, wchar_t * const *argv)
  338. {
  339. int res;
  340. PyMemAllocatorEx old_alloc;
  341. _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
  342. wchar_t **argv_copy = _Py_wstrlist_copy(argc, argv);
  343. if (argv_copy != NULL) {
  344. _Py_ClearArgcArgv();
  345. orig_argc = argc;
  346. orig_argv = argv_copy;
  347. res = 0;
  348. }
  349. else {
  350. res = -1;
  351. }
  352. PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
  353. return res;
  354. }
  355. /* Make the *original* argc/argv available to other modules.
  356. This is rare, but it is needed by the secureware extension. */
  357. void
  358. Py_GetArgcArgv(int *argc, wchar_t ***argv)
  359. {
  360. *argc = orig_argc;
  361. *argv = orig_argv;
  362. }
  363. /* --- _PyCoreConfig ---------------------------------------------- */
  364. #define DECODE_LOCALE_ERR(NAME, LEN) \
  365. (((LEN) == -2) \
  366. ? _Py_INIT_USER_ERR("cannot decode " NAME) \
  367. : _Py_INIT_NO_MEMORY())
  368. /* Free memory allocated in config, but don't clear all attributes */
  369. void
  370. _PyCoreConfig_Clear(_PyCoreConfig *config)
  371. {
  372. _PyPreConfig_Clear(&config->preconfig);
  373. #define CLEAR(ATTR) \
  374. do { \
  375. PyMem_RawFree(ATTR); \
  376. ATTR = NULL; \
  377. } while (0)
  378. #define CLEAR_WSTRLIST(LEN, LIST) \
  379. do { \
  380. _Py_wstrlist_clear(LEN, LIST); \
  381. LEN = 0; \
  382. LIST = NULL; \
  383. } while (0)
  384. CLEAR(config->pycache_prefix);
  385. CLEAR(config->module_search_path_env);
  386. CLEAR(config->home);
  387. CLEAR(config->program_name);
  388. CLEAR(config->program);
  389. CLEAR_WSTRLIST(config->argc, config->argv);
  390. config->argc = -1;
  391. CLEAR_WSTRLIST(config->nwarnoption, config->warnoptions);
  392. CLEAR_WSTRLIST(config->nxoption, config->xoptions);
  393. CLEAR_WSTRLIST(config->nmodule_search_path, config->module_search_paths);
  394. config->nmodule_search_path = -1;
  395. CLEAR(config->executable);
  396. CLEAR(config->prefix);
  397. CLEAR(config->base_prefix);
  398. CLEAR(config->exec_prefix);
  399. #ifdef MS_WINDOWS
  400. CLEAR(config->dll_path);
  401. #endif
  402. CLEAR(config->base_exec_prefix);
  403. CLEAR(config->filesystem_encoding);
  404. CLEAR(config->filesystem_errors);
  405. CLEAR(config->stdio_encoding);
  406. CLEAR(config->stdio_errors);
  407. #undef CLEAR
  408. #undef CLEAR_WSTRLIST
  409. }
  410. int
  411. _PyCoreConfig_Copy(_PyCoreConfig *config, const _PyCoreConfig *config2)
  412. {
  413. _PyCoreConfig_Clear(config);
  414. if (_PyPreConfig_Copy(&config->preconfig, &config2->preconfig) < 0) {
  415. return -1;
  416. }
  417. #define COPY_ATTR(ATTR) config->ATTR = config2->ATTR
  418. #define COPY_STR_ATTR(ATTR) \
  419. do { \
  420. if (config2->ATTR != NULL) { \
  421. config->ATTR = _PyMem_RawStrdup(config2->ATTR); \
  422. if (config->ATTR == NULL) { \
  423. return -1; \
  424. } \
  425. } \
  426. } while (0)
  427. #define COPY_WSTR_ATTR(ATTR) \
  428. do { \
  429. if (config2->ATTR != NULL) { \
  430. config->ATTR = _PyMem_RawWcsdup(config2->ATTR); \
  431. if (config->ATTR == NULL) { \
  432. return -1; \
  433. } \
  434. } \
  435. } while (0)
  436. #define COPY_WSTRLIST(LEN, LIST) \
  437. do { \
  438. if (config2->LIST != NULL) { \
  439. config->LIST = _Py_wstrlist_copy(config2->LEN, config2->LIST); \
  440. if (config->LIST == NULL) { \
  441. return -1; \
  442. } \
  443. } \
  444. config->LEN = config2->LEN; \
  445. } while (0)
  446. COPY_ATTR(install_signal_handlers);
  447. COPY_ATTR(use_hash_seed);
  448. COPY_ATTR(hash_seed);
  449. COPY_ATTR(_install_importlib);
  450. COPY_ATTR(allocator);
  451. COPY_ATTR(dev_mode);
  452. COPY_ATTR(faulthandler);
  453. COPY_ATTR(tracemalloc);
  454. COPY_ATTR(import_time);
  455. COPY_ATTR(show_ref_count);
  456. COPY_ATTR(show_alloc_count);
  457. COPY_ATTR(dump_refs);
  458. COPY_ATTR(malloc_stats);
  459. COPY_WSTR_ATTR(pycache_prefix);
  460. COPY_WSTR_ATTR(module_search_path_env);
  461. COPY_WSTR_ATTR(home);
  462. COPY_WSTR_ATTR(program_name);
  463. COPY_WSTR_ATTR(program);
  464. COPY_WSTRLIST(argc, argv);
  465. COPY_WSTRLIST(nwarnoption, warnoptions);
  466. COPY_WSTRLIST(nxoption, xoptions);
  467. COPY_WSTRLIST(nmodule_search_path, module_search_paths);
  468. COPY_WSTR_ATTR(executable);
  469. COPY_WSTR_ATTR(prefix);
  470. COPY_WSTR_ATTR(base_prefix);
  471. COPY_WSTR_ATTR(exec_prefix);
  472. #ifdef MS_WINDOWS
  473. COPY_WSTR_ATTR(dll_path);
  474. #endif
  475. COPY_WSTR_ATTR(base_exec_prefix);
  476. COPY_ATTR(site_import);
  477. COPY_ATTR(bytes_warning);
  478. COPY_ATTR(inspect);
  479. COPY_ATTR(interactive);
  480. COPY_ATTR(optimization_level);
  481. COPY_ATTR(parser_debug);
  482. COPY_ATTR(write_bytecode);
  483. COPY_ATTR(verbose);
  484. COPY_ATTR(quiet);
  485. COPY_ATTR(user_site_directory);
  486. COPY_ATTR(buffered_stdio);
  487. COPY_STR_ATTR(filesystem_encoding);
  488. COPY_STR_ATTR(filesystem_errors);
  489. COPY_STR_ATTR(stdio_encoding);
  490. COPY_STR_ATTR(stdio_errors);
  491. #ifdef MS_WINDOWS
  492. COPY_ATTR(legacy_windows_stdio);
  493. #endif
  494. COPY_ATTR(skip_source_first_line);
  495. COPY_WSTR_ATTR(run_command);
  496. COPY_WSTR_ATTR(run_module);
  497. COPY_WSTR_ATTR(run_filename);
  498. COPY_ATTR(_check_hash_pycs_mode);
  499. COPY_ATTR(_frozen);
  500. #undef COPY_ATTR
  501. #undef COPY_STR_ATTR
  502. #undef COPY_WSTR_ATTR
  503. #undef COPY_WSTRLIST
  504. return 0;
  505. }
  506. const char*
  507. _PyCoreConfig_GetEnv(const _PyCoreConfig *config, const char *name)
  508. {
  509. return _PyPreConfig_GetEnv(&config->preconfig, name);
  510. }
  511. int
  512. _PyCoreConfig_GetEnvDup(const _PyCoreConfig *config,
  513. wchar_t **dest,
  514. wchar_t *wname, char *name)
  515. {
  516. assert(config->preconfig.use_environment >= 0);
  517. if (!config->preconfig.use_environment) {
  518. *dest = NULL;
  519. return 0;
  520. }
  521. #ifdef MS_WINDOWS
  522. const wchar_t *var = _wgetenv(wname);
  523. if (!var || var[0] == '\0') {
  524. *dest = NULL;
  525. return 0;
  526. }
  527. wchar_t *copy = _PyMem_RawWcsdup(var);
  528. if (copy == NULL) {
  529. return -1;
  530. }
  531. *dest = copy;
  532. #else
  533. const char *var = getenv(name);
  534. if (!var || var[0] == '\0') {
  535. *dest = NULL;
  536. return 0;
  537. }
  538. size_t len;
  539. wchar_t *wvar = Py_DecodeLocale(var, &len);
  540. if (!wvar) {
  541. if (len == (size_t)-2) {
  542. return -2;
  543. }
  544. else {
  545. return -1;
  546. }
  547. }
  548. *dest = wvar;
  549. #endif
  550. return 0;
  551. }
  552. void
  553. _PyCoreConfig_GetGlobalConfig(_PyCoreConfig *config)
  554. {
  555. _PyPreConfig_GetGlobalConfig(&config->preconfig);
  556. #define COPY_FLAG(ATTR, VALUE) \
  557. if (config->ATTR == -1) { \
  558. config->ATTR = VALUE; \
  559. }
  560. #define COPY_NOT_FLAG(ATTR, VALUE) \
  561. if (config->ATTR == -1) { \
  562. config->ATTR = !(VALUE); \
  563. }
  564. COPY_FLAG(bytes_warning, Py_BytesWarningFlag);
  565. COPY_FLAG(inspect, Py_InspectFlag);
  566. COPY_FLAG(interactive, Py_InteractiveFlag);
  567. COPY_FLAG(optimization_level, Py_OptimizeFlag);
  568. COPY_FLAG(parser_debug, Py_DebugFlag);
  569. COPY_FLAG(verbose, Py_VerboseFlag);
  570. COPY_FLAG(quiet, Py_QuietFlag);
  571. #ifdef MS_WINDOWS
  572. COPY_FLAG(legacy_windows_stdio, Py_LegacyWindowsStdioFlag);
  573. #endif
  574. COPY_FLAG(_frozen, Py_FrozenFlag);
  575. COPY_NOT_FLAG(buffered_stdio, Py_UnbufferedStdioFlag);
  576. COPY_NOT_FLAG(site_import, Py_NoSiteFlag);
  577. COPY_NOT_FLAG(write_bytecode, Py_DontWriteBytecodeFlag);
  578. COPY_NOT_FLAG(user_site_directory, Py_NoUserSiteDirectory);
  579. #undef COPY_FLAG
  580. #undef COPY_NOT_FLAG
  581. }
  582. /* Set Py_xxx global configuration variables from 'config' configuration. */
  583. void
  584. _PyCoreConfig_SetGlobalConfig(const _PyCoreConfig *config)
  585. {
  586. _PyPreConfig_SetGlobalConfig(&config->preconfig);
  587. #define COPY_FLAG(ATTR, VAR) \
  588. if (config->ATTR != -1) { \
  589. VAR = config->ATTR; \
  590. }
  591. #define COPY_NOT_FLAG(ATTR, VAR) \
  592. if (config->ATTR != -1) { \
  593. VAR = !config->ATTR; \
  594. }
  595. COPY_FLAG(bytes_warning, Py_BytesWarningFlag);
  596. COPY_FLAG(inspect, Py_InspectFlag);
  597. COPY_FLAG(interactive, Py_InteractiveFlag);
  598. COPY_FLAG(optimization_level, Py_OptimizeFlag);
  599. COPY_FLAG(parser_debug, Py_DebugFlag);
  600. COPY_FLAG(verbose, Py_VerboseFlag);
  601. COPY_FLAG(quiet, Py_QuietFlag);
  602. #ifdef MS_WINDOWS
  603. COPY_FLAG(legacy_windows_stdio, Py_LegacyWindowsStdioFlag);
  604. #endif
  605. COPY_FLAG(_frozen, Py_FrozenFlag);
  606. COPY_NOT_FLAG(buffered_stdio, Py_UnbufferedStdioFlag);
  607. COPY_NOT_FLAG(site_import, Py_NoSiteFlag);
  608. COPY_NOT_FLAG(write_bytecode, Py_DontWriteBytecodeFlag);
  609. COPY_NOT_FLAG(user_site_directory, Py_NoUserSiteDirectory);
  610. /* Random or non-zero hash seed */
  611. Py_HashRandomizationFlag = (config->use_hash_seed == 0 ||
  612. config->hash_seed != 0);
  613. #undef COPY_FLAG
  614. #undef COPY_NOT_FLAG
  615. }
  616. /* Get the program name: use PYTHONEXECUTABLE and __PYVENV_LAUNCHER__
  617. environment variables on macOS if available. */
  618. static _PyInitError
  619. config_init_program_name(_PyCoreConfig *config)
  620. {
  621. assert(config->program_name == NULL);
  622. /* If Py_SetProgramName() was called, use its value */
  623. const wchar_t *program_name = _Py_path_config.program_name;
  624. if (program_name != NULL) {
  625. config->program_name = _PyMem_RawWcsdup(program_name);
  626. if (config->program_name == NULL) {
  627. return _Py_INIT_NO_MEMORY();
  628. }
  629. return _Py_INIT_OK();
  630. }
  631. #ifdef __APPLE__
  632. /* On MacOS X, when the Python interpreter is embedded in an
  633. application bundle, it gets executed by a bootstrapping script
  634. that does os.execve() with an argv[0] that's different from the
  635. actual Python executable. This is needed to keep the Finder happy,
  636. or rather, to work around Apple's overly strict requirements of
  637. the process name. However, we still need a usable sys.executable,
  638. so the actual executable path is passed in an environment variable.
  639. See Lib/plat-mac/bundlebuiler.py for details about the bootstrap
  640. script. */
  641. const char *p = _PyCoreConfig_GetEnv(config, "PYTHONEXECUTABLE");
  642. if (p != NULL) {
  643. size_t len;
  644. wchar_t* program_name = Py_DecodeLocale(p, &len);
  645. if (program_name == NULL) {
  646. return DECODE_LOCALE_ERR("PYTHONEXECUTABLE environment "
  647. "variable", (Py_ssize_t)len);
  648. }
  649. config->program_name = program_name;
  650. return _Py_INIT_OK();
  651. }
  652. #ifdef WITH_NEXT_FRAMEWORK
  653. else {
  654. const char* pyvenv_launcher = getenv("__PYVENV_LAUNCHER__");
  655. if (pyvenv_launcher && *pyvenv_launcher) {
  656. /* Used by Mac/Tools/pythonw.c to forward
  657. * the argv0 of the stub executable
  658. */
  659. size_t len;
  660. wchar_t* program_name = Py_DecodeLocale(pyvenv_launcher, &len);
  661. if (program_name == NULL) {
  662. return DECODE_LOCALE_ERR("__PYVENV_LAUNCHER__ environment "
  663. "variable", (Py_ssize_t)len);
  664. }
  665. config->program_name = program_name;
  666. return _Py_INIT_OK();
  667. }
  668. }
  669. #endif /* WITH_NEXT_FRAMEWORK */
  670. #endif /* __APPLE__ */
  671. /* Use argv[0] by default, if available */
  672. if (config->program != NULL) {
  673. config->program_name = _PyMem_RawWcsdup(config->program);
  674. if (config->program_name == NULL) {
  675. return _Py_INIT_NO_MEMORY();
  676. }
  677. return _Py_INIT_OK();
  678. }
  679. /* Last fall back: hardcoded string */
  680. #ifdef MS_WINDOWS
  681. const wchar_t *default_program_name = L"python";
  682. #else
  683. const wchar_t *default_program_name = L"python3";
  684. #endif
  685. config->program_name = _PyMem_RawWcsdup(default_program_name);
  686. if (config->program_name == NULL) {
  687. return _Py_INIT_NO_MEMORY();
  688. }
  689. return _Py_INIT_OK();
  690. }
  691. static _PyInitError
  692. config_init_executable(_PyCoreConfig *config)
  693. {
  694. assert(config->executable == NULL);
  695. /* If Py_SetProgramFullPath() was called, use its value */
  696. const wchar_t *program_full_path = _Py_path_config.program_full_path;
  697. if (program_full_path != NULL) {
  698. config->executable = _PyMem_RawWcsdup(program_full_path);
  699. if (config->executable == NULL) {
  700. return _Py_INIT_NO_MEMORY();
  701. }
  702. return _Py_INIT_OK();
  703. }
  704. return _Py_INIT_OK();
  705. }
  706. static const wchar_t*
  707. config_get_xoption(const _PyCoreConfig *config, wchar_t *name)
  708. {
  709. return _Py_get_xoption(config->nxoption, config->xoptions, name);
  710. }
  711. static _PyInitError
  712. config_init_home(_PyCoreConfig *config)
  713. {
  714. wchar_t *home;
  715. /* If Py_SetPythonHome() was called, use its value */
  716. home = _Py_path_config.home;
  717. if (home) {
  718. config->home = _PyMem_RawWcsdup(home);
  719. if (config->home == NULL) {
  720. return _Py_INIT_NO_MEMORY();
  721. }
  722. return _Py_INIT_OK();
  723. }
  724. int res = _PyCoreConfig_GetEnvDup(config, &home,
  725. L"PYTHONHOME", "PYTHONHOME");
  726. if (res < 0) {
  727. return DECODE_LOCALE_ERR("PYTHONHOME", res);
  728. }
  729. config->home = home;
  730. return _Py_INIT_OK();
  731. }
  732. static _PyInitError
  733. config_init_hash_seed(_PyCoreConfig *config)
  734. {
  735. const char *seed_text = _PyCoreConfig_GetEnv(config, "PYTHONHASHSEED");
  736. Py_BUILD_ASSERT(sizeof(_Py_HashSecret_t) == sizeof(_Py_HashSecret.uc));
  737. /* Convert a text seed to a numeric one */
  738. if (seed_text && strcmp(seed_text, "random") != 0) {
  739. const char *endptr = seed_text;
  740. unsigned long seed;
  741. errno = 0;
  742. seed = strtoul(seed_text, (char **)&endptr, 10);
  743. if (*endptr != '\0'
  744. || seed > 4294967295UL
  745. || (errno == ERANGE && seed == ULONG_MAX))
  746. {
  747. return _Py_INIT_USER_ERR("PYTHONHASHSEED must be \"random\" "
  748. "or an integer in range [0; 4294967295]");
  749. }
  750. /* Use a specific hash */
  751. config->use_hash_seed = 1;
  752. config->hash_seed = seed;
  753. }
  754. else {
  755. /* Use a random hash */
  756. config->use_hash_seed = 0;
  757. config->hash_seed = 0;
  758. }
  759. return _Py_INIT_OK();
  760. }
  761. static int
  762. config_wstr_to_int(const wchar_t *wstr, int *result)
  763. {
  764. const wchar_t *endptr = wstr;
  765. errno = 0;
  766. long value = wcstol(wstr, (wchar_t **)&endptr, 10);
  767. if (*endptr != '\0' || errno == ERANGE) {
  768. return -1;
  769. }
  770. if (value < INT_MIN || value > INT_MAX) {
  771. return -1;
  772. }
  773. *result = (int)value;
  774. return 0;
  775. }
  776. static _PyInitError
  777. config_read_env_vars(_PyCoreConfig *config)
  778. {
  779. #define get_env_flag(CONFIG, ATTR, NAME) \
  780. _Py_get_env_flag(&(CONFIG)->preconfig, (ATTR), (NAME))
  781. /* Get environment variables */
  782. get_env_flag(config, &config->parser_debug, "PYTHONDEBUG");
  783. get_env_flag(config, &config->verbose, "PYTHONVERBOSE");
  784. get_env_flag(config, &config->optimization_level, "PYTHONOPTIMIZE");
  785. get_env_flag(config, &config->inspect, "PYTHONINSPECT");
  786. int dont_write_bytecode = 0;
  787. get_env_flag(config, &dont_write_bytecode, "PYTHONDONTWRITEBYTECODE");
  788. if (dont_write_bytecode) {
  789. config->write_bytecode = 0;
  790. }
  791. int no_user_site_directory = 0;
  792. get_env_flag(config, &no_user_site_directory, "PYTHONNOUSERSITE");
  793. if (no_user_site_directory) {
  794. config->user_site_directory = 0;
  795. }
  796. int unbuffered_stdio = 0;
  797. get_env_flag(config, &unbuffered_stdio, "PYTHONUNBUFFERED");
  798. if (unbuffered_stdio) {
  799. config->buffered_stdio = 0;
  800. }
  801. #ifdef MS_WINDOWS
  802. get_env_flag(config, &config->legacy_windows_stdio,
  803. "PYTHONLEGACYWINDOWSSTDIO");
  804. #endif
  805. if (config->allocator == NULL) {
  806. config->allocator = _PyCoreConfig_GetEnv(config, "PYTHONMALLOC");
  807. }
  808. if (_PyCoreConfig_GetEnv(config, "PYTHONDUMPREFS")) {
  809. config->dump_refs = 1;
  810. }
  811. if (_PyCoreConfig_GetEnv(config, "PYTHONMALLOCSTATS")) {
  812. config->malloc_stats = 1;
  813. }
  814. wchar_t *path;
  815. int res = _PyCoreConfig_GetEnvDup(config, &path,
  816. L"PYTHONPATH", "PYTHONPATH");
  817. if (res < 0) {
  818. return DECODE_LOCALE_ERR("PYTHONPATH", res);
  819. }
  820. config->module_search_path_env = path;
  821. if (config->use_hash_seed < 0) {
  822. _PyInitError err = config_init_hash_seed(config);
  823. if (_Py_INIT_FAILED(err)) {
  824. return err;
  825. }
  826. }
  827. return _Py_INIT_OK();
  828. #undef get_env_flag
  829. }
  830. static _PyInitError
  831. config_init_tracemalloc(_PyCoreConfig *config)
  832. {
  833. int nframe;
  834. int valid;
  835. const char *env = _PyCoreConfig_GetEnv(config, "PYTHONTRACEMALLOC");
  836. if (env) {
  837. if (!_Py_str_to_int(env, &nframe)) {
  838. valid = (nframe >= 0);
  839. }
  840. else {
  841. valid = 0;
  842. }
  843. if (!valid) {
  844. return _Py_INIT_USER_ERR("PYTHONTRACEMALLOC: invalid number "
  845. "of frames");
  846. }
  847. config->tracemalloc = nframe;
  848. }
  849. const wchar_t *xoption = config_get_xoption(config, L"tracemalloc");
  850. if (xoption) {
  851. const wchar_t *sep = wcschr(xoption, L'=');
  852. if (sep) {
  853. if (!config_wstr_to_int(sep + 1, &nframe)) {
  854. valid = (nframe >= 0);
  855. }
  856. else {
  857. valid = 0;
  858. }
  859. if (!valid) {
  860. return _Py_INIT_USER_ERR("-X tracemalloc=NFRAME: "
  861. "invalid number of frames");
  862. }
  863. }
  864. else {
  865. /* -X tracemalloc behaves as -X tracemalloc=1 */
  866. nframe = 1;
  867. }
  868. config->tracemalloc = nframe;
  869. }
  870. return _Py_INIT_OK();
  871. }
  872. static _PyInitError
  873. config_init_pycache_prefix(_PyCoreConfig *config)
  874. {
  875. assert(config->pycache_prefix == NULL);
  876. const wchar_t *xoption = config_get_xoption(config, L"pycache_prefix");
  877. if (xoption) {
  878. const wchar_t *sep = wcschr(xoption, L'=');
  879. if (sep && wcslen(sep) > 1) {
  880. config->pycache_prefix = _PyMem_RawWcsdup(sep + 1);
  881. if (config->pycache_prefix == NULL) {
  882. return _Py_INIT_NO_MEMORY();
  883. }
  884. }
  885. else {
  886. // -X pycache_prefix= can cancel the env var
  887. config->pycache_prefix = NULL;
  888. }
  889. }
  890. else {
  891. wchar_t *env;
  892. int res = _PyCoreConfig_GetEnvDup(config, &env,
  893. L"PYTHONPYCACHEPREFIX",
  894. "PYTHONPYCACHEPREFIX");
  895. if (res < 0) {
  896. return DECODE_LOCALE_ERR("PYTHONPYCACHEPREFIX", res);
  897. }
  898. if (env) {
  899. config->pycache_prefix = env;
  900. }
  901. }
  902. return _Py_INIT_OK();
  903. }
  904. static _PyInitError
  905. config_read_complex_options(_PyCoreConfig *config)
  906. {
  907. /* More complex options configured by env var and -X option */
  908. if (config->faulthandler < 0) {
  909. if (_PyCoreConfig_GetEnv(config, "PYTHONFAULTHANDLER")
  910. || config_get_xoption(config, L"faulthandler")) {
  911. config->faulthandler = 1;
  912. }
  913. }
  914. if (_PyCoreConfig_GetEnv(config, "PYTHONPROFILEIMPORTTIME")
  915. || config_get_xoption(config, L"importtime")) {
  916. config->import_time = 1;
  917. }
  918. if (config_get_xoption(config, L"dev" ) ||
  919. _PyCoreConfig_GetEnv(config, "PYTHONDEVMODE"))
  920. {
  921. config->dev_mode = 1;
  922. }
  923. _PyInitError err;
  924. if (config->tracemalloc < 0) {
  925. err = config_init_tracemalloc(config);
  926. if (_Py_INIT_FAILED(err)) {
  927. return err;
  928. }
  929. }
  930. if (config->pycache_prefix == NULL) {
  931. err = config_init_pycache_prefix(config);
  932. if (_Py_INIT_FAILED(err)) {
  933. return err;
  934. }
  935. }
  936. return _Py_INIT_OK();
  937. }
  938. static const char *
  939. get_stdio_errors(const _PyCoreConfig *config)
  940. {
  941. #ifndef MS_WINDOWS
  942. const char *loc = setlocale(LC_CTYPE, NULL);
  943. if (loc != NULL) {
  944. /* surrogateescape is the default in the legacy C and POSIX locales */
  945. if (strcmp(loc, "C") == 0 || strcmp(loc, "POSIX") == 0) {
  946. return "surrogateescape";
  947. }
  948. #ifdef PY_COERCE_C_LOCALE
  949. /* surrogateescape is the default in locale coercion target locales */
  950. if (_Py_IsLocaleCoercionTarget(loc)) {
  951. return "surrogateescape";
  952. }
  953. #endif
  954. }
  955. return "strict";
  956. #else
  957. /* On Windows, always use surrogateescape by default */
  958. return "surrogateescape";
  959. #endif
  960. }
  961. static _PyInitError
  962. get_locale_encoding(char **locale_encoding)
  963. {
  964. #ifdef MS_WINDOWS
  965. char encoding[20];
  966. PyOS_snprintf(encoding, sizeof(encoding), "cp%d", GetACP());
  967. #elif defined(__ANDROID__) || defined(__VXWORKS__)
  968. const char *encoding = "UTF-8";
  969. #else
  970. const char *encoding = nl_langinfo(CODESET);
  971. if (!encoding || encoding[0] == '\0') {
  972. return _Py_INIT_USER_ERR("failed to get the locale encoding: "
  973. "nl_langinfo(CODESET) failed");
  974. }
  975. #endif
  976. *locale_encoding = _PyMem_RawStrdup(encoding);
  977. if (*locale_encoding == NULL) {
  978. return _Py_INIT_NO_MEMORY();
  979. }
  980. return _Py_INIT_OK();
  981. }
  982. static _PyInitError
  983. config_init_stdio_encoding(_PyCoreConfig *config)
  984. {
  985. /* If Py_SetStandardStreamEncoding() have been called, use these
  986. parameters. */
  987. if (config->stdio_encoding == NULL && _Py_StandardStreamEncoding != NULL) {
  988. config->stdio_encoding = _PyMem_RawStrdup(_Py_StandardStreamEncoding);
  989. if (config->stdio_encoding == NULL) {
  990. return _Py_INIT_NO_MEMORY();
  991. }
  992. }
  993. if (config->stdio_errors == NULL && _Py_StandardStreamErrors != NULL) {
  994. config->stdio_errors = _PyMem_RawStrdup(_Py_StandardStreamErrors);
  995. if (config->stdio_errors == NULL) {
  996. return _Py_INIT_NO_MEMORY();
  997. }
  998. }
  999. if (config->stdio_encoding != NULL && config->stdio_errors != NULL) {
  1000. return _Py_INIT_OK();
  1001. }
  1002. /* PYTHONIOENCODING environment variable */
  1003. const char *opt = _PyCoreConfig_GetEnv(config, "PYTHONIOENCODING");
  1004. if (opt) {
  1005. char *pythonioencoding = _PyMem_RawStrdup(opt);
  1006. if (pythonioencoding == NULL) {
  1007. return _Py_INIT_NO_MEMORY();
  1008. }
  1009. char *err = strchr(pythonioencoding, ':');
  1010. if (err) {
  1011. *err = '\0';
  1012. err++;
  1013. if (!err[0]) {
  1014. err = NULL;
  1015. }
  1016. }
  1017. /* Does PYTHONIOENCODING contain an encoding? */
  1018. if (pythonioencoding[0]) {
  1019. if (config->stdio_encoding == NULL) {
  1020. config->stdio_encoding = _PyMem_RawStrdup(pythonioencoding);
  1021. if (config->stdio_encoding == NULL) {
  1022. PyMem_RawFree(pythonioencoding);
  1023. return _Py_INIT_NO_MEMORY();
  1024. }
  1025. }
  1026. /* If the encoding is set but not the error handler,
  1027. use "strict" error handler by default.
  1028. PYTHONIOENCODING=latin1 behaves as
  1029. PYTHONIOENCODING=latin1:strict. */
  1030. if (!err) {
  1031. err = "strict";
  1032. }
  1033. }
  1034. if (config->stdio_errors == NULL && err != NULL) {
  1035. config->stdio_errors = _PyMem_RawStrdup(err);
  1036. if (config->stdio_errors == NULL) {
  1037. PyMem_RawFree(pythonioencoding);
  1038. return _Py_INIT_NO_MEMORY();
  1039. }
  1040. }
  1041. PyMem_RawFree(pythonioencoding);
  1042. }
  1043. /* UTF-8 Mode uses UTF-8/surrogateescape */
  1044. if (config->preconfig.utf8_mode) {
  1045. if (config->stdio_encoding == NULL) {
  1046. config->stdio_encoding = _PyMem_RawStrdup("utf-8");
  1047. if (config->stdio_encoding == NULL) {
  1048. return _Py_INIT_NO_MEMORY();
  1049. }
  1050. }
  1051. if (config->stdio_errors == NULL) {
  1052. config->stdio_errors = _PyMem_RawStrdup("surrogateescape");
  1053. if (config->stdio_errors == NULL) {
  1054. return _Py_INIT_NO_MEMORY();
  1055. }
  1056. }
  1057. }
  1058. /* Choose the default error handler based on the current locale. */
  1059. if (config->stdio_encoding == NULL) {
  1060. _PyInitError err = get_locale_encoding(&config->stdio_encoding);
  1061. if (_Py_INIT_FAILED(err)) {
  1062. return err;
  1063. }
  1064. }
  1065. if (config->stdio_errors == NULL) {
  1066. const char *errors = get_stdio_errors(config);
  1067. config->stdio_errors = _PyMem_RawStrdup(errors);
  1068. if (config->stdio_errors == NULL) {
  1069. return _Py_INIT_NO_MEMORY();
  1070. }
  1071. }
  1072. return _Py_INIT_OK();
  1073. }
  1074. static _PyInitError
  1075. config_init_fs_encoding(_PyCoreConfig *config)
  1076. {
  1077. #ifdef MS_WINDOWS
  1078. if (config->preconfig.legacy_windows_fs_encoding) {
  1079. /* Legacy Windows filesystem encoding: mbcs/replace */
  1080. if (config->filesystem_encoding == NULL) {
  1081. config->filesystem_encoding = _PyMem_RawStrdup("mbcs");
  1082. if (config->filesystem_encoding == NULL) {
  1083. return _Py_INIT_NO_MEMORY();
  1084. }
  1085. }
  1086. if (config->filesystem_errors == NULL) {
  1087. config->filesystem_errors = _PyMem_RawStrdup("replace");
  1088. if (config->filesystem_errors == NULL) {
  1089. return _Py_INIT_NO_MEMORY();
  1090. }
  1091. }
  1092. }
  1093. /* Windows defaults to utf-8/surrogatepass (PEP 529).
  1094. Note: UTF-8 Mode takes the same code path and the Legacy Windows FS
  1095. encoding has the priortiy over UTF-8 Mode. */
  1096. if (config->filesystem_encoding == NULL) {
  1097. config->filesystem_encoding = _PyMem_RawStrdup("utf-8");
  1098. if (config->filesystem_encoding == NULL) {
  1099. return _Py_INIT_NO_MEMORY();
  1100. }
  1101. }
  1102. if (config->filesystem_errors == NULL) {
  1103. config->filesystem_errors = _PyMem_RawStrdup("surrogatepass");
  1104. if (config->filesystem_errors == NULL) {
  1105. return _Py_INIT_NO_MEMORY();
  1106. }
  1107. }
  1108. #else
  1109. if (config->filesystem_encoding == NULL) {
  1110. if (config->preconfig.utf8_mode) {
  1111. /* UTF-8 Mode use: utf-8/surrogateescape */
  1112. config->filesystem_encoding = _PyMem_RawStrdup("utf-8");
  1113. /* errors defaults to surrogateescape above */
  1114. }
  1115. else if (_Py_GetForceASCII()) {
  1116. config->filesystem_encoding = _PyMem_RawStrdup("ascii");
  1117. }
  1118. else {
  1119. /* macOS and Android use UTF-8,
  1120. other platforms use the locale encoding. */
  1121. #if defined(__APPLE__) || defined(__ANDROID__)
  1122. config->filesystem_encoding = _PyMem_RawStrdup("utf-8");
  1123. #else
  1124. _PyInitError err = get_locale_encoding(&config->filesystem_encoding);
  1125. if (_Py_INIT_FAILED(err)) {
  1126. return err;
  1127. }
  1128. #endif
  1129. }
  1130. if (config->filesystem_encoding == NULL) {
  1131. return _Py_INIT_NO_MEMORY();
  1132. }
  1133. }
  1134. if (config->filesystem_errors == NULL) {
  1135. /* by default, use the "surrogateescape" error handler */
  1136. config->filesystem_errors = _PyMem_RawStrdup("surrogateescape");
  1137. if (config->filesystem_errors == NULL) {
  1138. return _Py_INIT_NO_MEMORY();
  1139. }
  1140. }
  1141. #endif
  1142. return _Py_INIT_OK();
  1143. }
  1144. static _PyInitError
  1145. _PyCoreConfig_ReadPreConfig(_PyCoreConfig *config)
  1146. {
  1147. _PyInitError err;
  1148. _PyPreConfig local_preconfig = _PyPreConfig_INIT;
  1149. _PyPreConfig_GetGlobalConfig(&local_preconfig);
  1150. if (_PyPreConfig_Copy(&local_preconfig, &config->preconfig) < 0) {
  1151. err = _Py_INIT_NO_MEMORY();
  1152. goto done;
  1153. }
  1154. err = _PyPreConfig_Read(&local_preconfig);
  1155. if (_Py_INIT_FAILED(err)) {
  1156. goto done;
  1157. }
  1158. if (_PyPreConfig_Copy(&config->preconfig, &local_preconfig) < 0) {
  1159. err = _Py_INIT_NO_MEMORY();
  1160. goto done;
  1161. }
  1162. err = _Py_INIT_OK();
  1163. done:
  1164. _PyPreConfig_Clear(&local_preconfig);
  1165. return err;
  1166. }
  1167. /* Read the configuration into _PyCoreConfig and initialize the LC_CTYPE
  1168. locale: enable UTF-8 mode (PEP 540) and/or coerce the C locale (PEP 538).
  1169. Read the configuration from:
  1170. * Environment variables
  1171. * Py_xxx global configuration variables
  1172. See _PyCoreConfig_ReadFromArgv() to parse also command line arguments. */
  1173. _PyInitError
  1174. _PyCoreConfig_Read(_PyCoreConfig *config, const _PyPreConfig *preconfig)
  1175. {
  1176. _PyInitError err;
  1177. _PyCoreConfig_GetGlobalConfig(config);
  1178. if (preconfig != NULL) {
  1179. if (_PyPreConfig_Copy(&config->preconfig, preconfig) < 0) {
  1180. return _Py_INIT_NO_MEMORY();
  1181. }
  1182. }
  1183. else {
  1184. err = _PyCoreConfig_ReadPreConfig(config);
  1185. if (_Py_INIT_FAILED(err)) {
  1186. return err;
  1187. }
  1188. }
  1189. assert(config->preconfig.use_environment >= 0);
  1190. if (config->preconfig.isolated > 0) {
  1191. config->user_site_directory = 0;
  1192. }
  1193. if (config->preconfig.use_environment) {
  1194. err = config_read_env_vars(config);
  1195. if (_Py_INIT_FAILED(err)) {
  1196. return err;
  1197. }
  1198. }
  1199. /* -X options */
  1200. if (config_get_xoption(config, L"showrefcount")) {
  1201. config->show_ref_count = 1;
  1202. }
  1203. if (config_get_xoption(config, L"showalloccount")) {
  1204. config->show_alloc_count = 1;
  1205. }
  1206. err = config_read_complex_options(config);
  1207. if (_Py_INIT_FAILED(err)) {
  1208. return err;
  1209. }
  1210. if (config->home == NULL) {
  1211. err = config_init_home(config);
  1212. if (_Py_INIT_FAILED(err)) {
  1213. return err;
  1214. }
  1215. }
  1216. if (config->program_name == NULL) {
  1217. err = config_init_program_name(config);
  1218. if (_Py_INIT_FAILED(err)) {
  1219. return err;
  1220. }
  1221. }
  1222. if (config->executable == NULL) {
  1223. err = config_init_executable(config);
  1224. if (_Py_INIT_FAILED(err)) {
  1225. return err;
  1226. }
  1227. }
  1228. if (config->_install_importlib) {
  1229. err = _PyCoreConfig_InitPathConfig(config);
  1230. if (_Py_INIT_FAILED(err)) {
  1231. return err;
  1232. }
  1233. }
  1234. /* default values */
  1235. if (config->dev_mode) {
  1236. if (config->faulthandler < 0) {
  1237. config->faulthandler = 1;
  1238. }
  1239. if (config->allocator == NULL) {
  1240. config->allocator = "debug";
  1241. }
  1242. }
  1243. if (config->use_hash_seed < 0) {
  1244. config->use_hash_seed = 0;
  1245. config->hash_seed = 0;
  1246. }
  1247. if (config->faulthandler < 0) {
  1248. config->faulthandler = 0;
  1249. }
  1250. if (config->tracemalloc < 0) {
  1251. config->tracemalloc = 0;
  1252. }
  1253. if (config->argc < 0) {
  1254. config->argc = 0;
  1255. }
  1256. if (config->filesystem_encoding == NULL || config->filesystem_errors == NULL) {
  1257. err = config_init_fs_encoding(config);
  1258. if (_Py_INIT_FAILED(err)) {
  1259. return err;
  1260. }
  1261. }
  1262. err = config_init_stdio_encoding(config);
  1263. if (_Py_INIT_FAILED(err)) {
  1264. return err;
  1265. }
  1266. assert(config->preconfig.use_environment >= 0);
  1267. assert(config->filesystem_encoding != NULL);
  1268. assert(config->filesystem_errors != NULL);
  1269. assert(config->stdio_encoding != NULL);
  1270. assert(config->stdio_errors != NULL);
  1271. assert(config->_check_hash_pycs_mode != NULL);
  1272. return _Py_INIT_OK();
  1273. }
  1274. static void
  1275. config_init_stdio(const _PyCoreConfig *config)
  1276. {
  1277. #if defined(MS_WINDOWS) || defined(__CYGWIN__)
  1278. /* don't translate newlines (\r\n <=> \n) */
  1279. _setmode(fileno(stdin), O_BINARY);
  1280. _setmode(fileno(stdout), O_BINARY);
  1281. _setmode(fileno(stderr), O_BINARY);
  1282. #endif
  1283. if (!config->buffered_stdio) {
  1284. #ifdef HAVE_SETVBUF
  1285. setvbuf(stdin, (char *)NULL, _IONBF, BUFSIZ);
  1286. setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ);
  1287. setvbuf(stderr, (char *)NULL, _IONBF, BUFSIZ);
  1288. #else /* !HAVE_SETVBUF */
  1289. setbuf(stdin, (char *)NULL);
  1290. setbuf(stdout, (char *)NULL);
  1291. setbuf(stderr, (char *)NULL);
  1292. #endif /* !HAVE_SETVBUF */
  1293. }
  1294. else if (config->interactive) {
  1295. #ifdef MS_WINDOWS
  1296. /* Doesn't have to have line-buffered -- use unbuffered */
  1297. /* Any set[v]buf(stdin, ...) screws up Tkinter :-( */
  1298. setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ);
  1299. #else /* !MS_WINDOWS */
  1300. #ifdef HAVE_SETVBUF
  1301. setvbuf(stdin, (char *)NULL, _IOLBF, BUFSIZ);
  1302. setvbuf(stdout, (char *)NULL, _IOLBF, BUFSIZ);
  1303. #endif /* HAVE_SETVBUF */
  1304. #endif /* !MS_WINDOWS */
  1305. /* Leave stderr alone - it should be unbuffered anyway. */
  1306. }
  1307. }
  1308. /* Write the configuration:
  1309. - coerce the LC_CTYPE locale (PEP 538)
  1310. - UTF-8 mode (PEP 540)
  1311. - set Py_xxx global configuration variables
  1312. - initialize C standard streams (stdin, stdout, stderr) */
  1313. void
  1314. _PyCoreConfig_Write(const _PyCoreConfig *config)
  1315. {
  1316. _PyCoreConfig_SetGlobalConfig(config);
  1317. config_init_stdio(config);
  1318. }
  1319. PyObject *
  1320. _PyCoreConfig_AsDict(const _PyCoreConfig *config)
  1321. {
  1322. PyObject *dict;
  1323. dict = PyDict_New();
  1324. if (dict == NULL) {
  1325. return NULL;
  1326. }
  1327. if (_PyPreConfig_AsDict(&config->preconfig, dict) < 0) {
  1328. Py_DECREF(dict);
  1329. return NULL;
  1330. }
  1331. #define SET_ITEM(KEY, EXPR) \
  1332. do { \
  1333. PyObject *obj = (EXPR); \
  1334. if (obj == NULL) { \
  1335. goto fail; \
  1336. } \
  1337. int res = PyDict_SetItemString(dict, (KEY), obj); \
  1338. Py_DECREF(obj); \
  1339. if (res < 0) { \
  1340. goto fail; \
  1341. } \
  1342. } while (0)
  1343. #define FROM_STRING(STR) \
  1344. ((STR != NULL) ? \
  1345. PyUnicode_FromString(STR) \
  1346. : (Py_INCREF(Py_None), Py_None))
  1347. #define SET_ITEM_INT(ATTR) \
  1348. SET_ITEM(#ATTR, PyLong_FromLong(config->ATTR))
  1349. #define SET_ITEM_UINT(ATTR) \
  1350. SET_ITEM(#ATTR, PyLong_FromUnsignedLong(config->ATTR))
  1351. #define SET_ITEM_STR(ATTR) \
  1352. SET_ITEM(#ATTR, FROM_STRING(config->ATTR))
  1353. #define FROM_WSTRING(STR) \
  1354. ((STR != NULL) ? \
  1355. PyUnicode_FromWideChar(STR, -1) \
  1356. : (Py_INCREF(Py_None), Py_None))
  1357. #define SET_ITEM_WSTR(ATTR) \
  1358. SET_ITEM(#ATTR, FROM_WSTRING(config->ATTR))
  1359. #define SET_ITEM_WSTRLIST(NOPTION, OPTIONS) \
  1360. SET_ITEM(#OPTIONS, _Py_wstrlist_as_pylist(config->NOPTION, config->OPTIONS))
  1361. SET_ITEM_INT(install_signal_handlers);
  1362. SET_ITEM_INT(use_hash_seed);
  1363. SET_ITEM_UINT(hash_seed);
  1364. SET_ITEM_STR(allocator);
  1365. SET_ITEM_INT(dev_mode);
  1366. SET_ITEM_INT(faulthandler);
  1367. SET_ITEM_INT(tracemalloc);
  1368. SET_ITEM_INT(import_time);
  1369. SET_ITEM_INT(show_ref_count);
  1370. SET_ITEM_INT(show_alloc_count);
  1371. SET_ITEM_INT(dump_refs);
  1372. SET_ITEM_INT(malloc_stats);
  1373. SET_ITEM_STR(filesystem_encoding);
  1374. SET_ITEM_STR(filesystem_errors);
  1375. SET_ITEM_WSTR(pycache_prefix);
  1376. SET_ITEM_WSTR(program_name);
  1377. SET_ITEM_WSTRLIST(argc, argv);
  1378. SET_ITEM_WSTR(program);
  1379. SET_ITEM_WSTRLIST(nxoption, xoptions);
  1380. SET_ITEM_WSTRLIST(nwarnoption, warnoptions);
  1381. SET_ITEM_WSTR(module_search_path_env);
  1382. SET_ITEM_WSTR(home);
  1383. SET_ITEM_WSTRLIST(nmodule_search_path, module_search_paths);
  1384. SET_ITEM_WSTR(executable);
  1385. SET_ITEM_WSTR(prefix);
  1386. SET_ITEM_WSTR(base_prefix);
  1387. SET_ITEM_WSTR(exec_prefix);
  1388. SET_ITEM_WSTR(base_exec_prefix);
  1389. #ifdef MS_WINDOWS
  1390. SET_ITEM_WSTR(dll_path);
  1391. #endif
  1392. SET_ITEM_INT(site_import);
  1393. SET_ITEM_INT(bytes_warning);
  1394. SET_ITEM_INT(inspect);
  1395. SET_ITEM_INT(interactive);
  1396. SET_ITEM_INT(optimization_level);
  1397. SET_ITEM_INT(parser_debug);
  1398. SET_ITEM_INT(write_bytecode);
  1399. SET_ITEM_INT(verbose);
  1400. SET_ITEM_INT(quiet);
  1401. SET_ITEM_INT(user_site_directory);
  1402. SET_ITEM_INT(buffered_stdio);
  1403. SET_ITEM_STR(stdio_encoding);
  1404. SET_ITEM_STR(stdio_errors);
  1405. #ifdef MS_WINDOWS
  1406. SET_ITEM_INT(legacy_windows_stdio);
  1407. #endif
  1408. SET_ITEM_INT(skip_source_first_line);
  1409. SET_ITEM_WSTR(run_command);
  1410. SET_ITEM_WSTR(run_module);
  1411. SET_ITEM_WSTR(run_filename);
  1412. SET_ITEM_INT(_install_importlib);
  1413. SET_ITEM_STR(_check_hash_pycs_mode);
  1414. SET_ITEM_INT(_frozen);
  1415. return dict;
  1416. fail:
  1417. Py_DECREF(dict);
  1418. return NULL;
  1419. #undef FROM_STRING
  1420. #undef FROM_WSTRING
  1421. #undef SET_ITEM
  1422. #undef SET_ITEM_INT
  1423. #undef SET_ITEM_UINT
  1424. #undef SET_ITEM_STR
  1425. #undef SET_ITEM_WSTR
  1426. #undef SET_ITEM_WSTRLIST
  1427. }
  1428. /* --- _PyCmdline ------------------------------------------------- */
  1429. typedef struct {
  1430. const _PyArgv *args;
  1431. int argc;
  1432. wchar_t **argv;
  1433. int nwarnoption; /* Number of -W command line options */
  1434. wchar_t **warnoptions; /* Command line -W options */
  1435. int nenv_warnoption; /* Number of PYTHONWARNINGS environment variables */
  1436. wchar_t **env_warnoptions; /* PYTHONWARNINGS environment variables */
  1437. int print_help; /* -h, -? options */
  1438. int print_version; /* -V option */
  1439. } _PyCmdline;
  1440. static void
  1441. cmdline_clear(_PyCmdline *cmdline)
  1442. {
  1443. _Py_wstrlist_clear(cmdline->nwarnoption, cmdline->warnoptions);
  1444. cmdline->nwarnoption = 0;
  1445. cmdline->warnoptions = NULL;
  1446. _Py_wstrlist_clear(cmdline->nenv_warnoption, cmdline->env_warnoptions);
  1447. cmdline->nenv_warnoption = 0;
  1448. cmdline->env_warnoptions = NULL;
  1449. if (cmdline->args->use_bytes_argv && cmdline->argv != NULL) {
  1450. _Py_wstrlist_clear(cmdline->args->argc, cmdline->argv);
  1451. }
  1452. cmdline->argv = NULL;
  1453. }
  1454. /* --- _PyCoreConfig command line parser -------------------------- */
  1455. /* Parse the command line arguments */
  1456. static _PyInitError
  1457. config_parse_cmdline(_PyCoreConfig *config, _PyCmdline *cmdline,
  1458. int *need_usage)
  1459. {
  1460. _PyInitError err;
  1461. _PyOS_ResetGetOpt();
  1462. do {
  1463. int longindex = -1;
  1464. int c = _PyOS_GetOpt(cmdline->args->argc, cmdline->argv, &longindex);
  1465. if (c == EOF) {
  1466. break;
  1467. }
  1468. if (c == 'c') {
  1469. /* -c is the last option; following arguments
  1470. that look like options are left for the
  1471. command to interpret. */
  1472. size_t len = wcslen(_PyOS_optarg) + 1 + 1;
  1473. wchar_t *command = PyMem_RawMalloc(sizeof(wchar_t) * len);
  1474. if (command == NULL) {
  1475. return _Py_INIT_NO_MEMORY();
  1476. }
  1477. memcpy(command, _PyOS_optarg, (len - 2) * sizeof(wchar_t));
  1478. command[len - 2] = '\n';
  1479. command[len - 1] = 0;
  1480. config->run_command = command;
  1481. break;
  1482. }
  1483. if (c == 'm') {
  1484. /* -m is the last option; following arguments
  1485. that look like options are left for the
  1486. module to interpret. */
  1487. config->run_module = _PyMem_RawWcsdup(_PyOS_optarg);
  1488. if (config->run_module == NULL) {
  1489. return _Py_INIT_NO_MEMORY();
  1490. }
  1491. break;
  1492. }
  1493. switch (c) {
  1494. case 0:
  1495. // Handle long option.
  1496. assert(longindex == 0); // Only one long option now.
  1497. if (!wcscmp(_PyOS_optarg, L"always")) {
  1498. config->_check_hash_pycs_mode = "always";
  1499. } else if (!wcscmp(_PyOS_optarg, L"never")) {
  1500. config->_check_hash_pycs_mode = "never";
  1501. } else if (!wcscmp(_PyOS_optarg, L"default")) {
  1502. config->_check_hash_pycs_mode = "default";
  1503. } else {
  1504. fprintf(stderr, "--check-hash-based-pycs must be one of "
  1505. "'default', 'always', or 'never'\n");
  1506. *need_usage = 1;
  1507. return _Py_INIT_OK();
  1508. }
  1509. break;
  1510. case 'b':
  1511. config->bytes_warning++;
  1512. break;
  1513. case 'd':
  1514. config->parser_debug++;
  1515. break;
  1516. case 'i':
  1517. config->inspect++;
  1518. config->interactive++;
  1519. break;
  1520. case 'E':
  1521. case 'I':
  1522. /* option handled by _PyPreConfig_ReadFromArgv() */
  1523. break;
  1524. /* case 'J': reserved for Jython */
  1525. case 'O':
  1526. config->optimization_level++;
  1527. break;
  1528. case 'B':
  1529. config->write_bytecode = 0;
  1530. break;
  1531. case 's':
  1532. config->user_site_directory = 0;
  1533. break;
  1534. case 'S':
  1535. config->site_import = 0;
  1536. break;
  1537. case 't':
  1538. /* ignored for backwards compatibility */
  1539. break;
  1540. case 'u':
  1541. config->buffered_stdio = 0;
  1542. break;
  1543. case 'v':
  1544. config->verbose++;
  1545. break;
  1546. case 'x':
  1547. config->skip_source_first_line = 1;
  1548. break;
  1549. case 'h':
  1550. case '?':
  1551. cmdline->print_help++;
  1552. break;
  1553. case 'V':
  1554. cmdline->print_version++;
  1555. break;
  1556. case 'W':
  1557. err = _Py_wstrlist_append(&cmdline->nwarnoption,
  1558. &cmdline->warnoptions,
  1559. _PyOS_optarg);
  1560. if (_Py_INIT_FAILED(err)) {
  1561. return err;
  1562. }
  1563. break;
  1564. case 'X':
  1565. err = _Py_wstrlist_append(&config->nxoption,
  1566. &config->xoptions,
  1567. _PyOS_optarg);
  1568. if (_Py_INIT_FAILED(err)) {
  1569. return err;
  1570. }
  1571. break;
  1572. case 'q':
  1573. config->quiet++;
  1574. break;
  1575. case 'R':
  1576. config->use_hash_seed = 0;
  1577. break;
  1578. /* This space reserved for other options */
  1579. default:
  1580. /* unknown argument: parsing failed */
  1581. *need_usage = 1;
  1582. return _Py_INIT_OK();
  1583. }
  1584. } while (1);
  1585. if (config->run_command == NULL && config->run_module == NULL
  1586. && _PyOS_optind < cmdline->args->argc
  1587. && wcscmp(cmdline->argv[_PyOS_optind], L"-") != 0)
  1588. {
  1589. config->run_filename = _PyMem_RawWcsdup(cmdline->argv[_PyOS_optind]);
  1590. if (config->run_filename == NULL) {
  1591. return _Py_INIT_NO_MEMORY();
  1592. }
  1593. }
  1594. if (config->run_command != NULL || config->run_module != NULL) {
  1595. /* Backup _PyOS_optind */
  1596. _PyOS_optind--;
  1597. }
  1598. /* -c and -m options are exclusive */
  1599. assert(!(config->run_command != NULL && config->run_module != NULL));
  1600. return _Py_INIT_OK();
  1601. }
  1602. #ifdef MS_WINDOWS
  1603. # define WCSTOK wcstok_s
  1604. #else
  1605. # define WCSTOK wcstok
  1606. #endif
  1607. /* Get warning options from PYTHONWARNINGS environment variable. */
  1608. static _PyInitError
  1609. cmdline_init_env_warnoptions(_PyCmdline *cmdline, const _PyCoreConfig *config)
  1610. {
  1611. wchar_t *env;
  1612. int res = _PyCoreConfig_GetEnvDup(config, &env,
  1613. L"PYTHONWARNINGS", "PYTHONWARNINGS");
  1614. if (res < 0) {
  1615. return DECODE_LOCALE_ERR("PYTHONWARNINGS", res);
  1616. }
  1617. if (env == NULL) {
  1618. return _Py_INIT_OK();
  1619. }
  1620. wchar_t *warning, *context = NULL;
  1621. for (warning = WCSTOK(env, L",", &context);
  1622. warning != NULL;
  1623. warning = WCSTOK(NULL, L",", &context))
  1624. {
  1625. _PyInitError err = _Py_wstrlist_append(&cmdline->nenv_warnoption,
  1626. &cmdline->env_warnoptions,
  1627. warning);
  1628. if (_Py_INIT_FAILED(err)) {
  1629. PyMem_RawFree(env);
  1630. return err;
  1631. }
  1632. }
  1633. PyMem_RawFree(env);
  1634. return _Py_INIT_OK();
  1635. }
  1636. static _PyInitError
  1637. config_init_program(_PyCoreConfig *config, const _PyCmdline *cmdline)
  1638. {
  1639. wchar_t *program;
  1640. if (cmdline->args->argc >= 1 && cmdline->argv != NULL) {
  1641. program = cmdline->argv[0];
  1642. }
  1643. else {
  1644. program = L"";
  1645. }
  1646. config->program = _PyMem_RawWcsdup(program);
  1647. if (config->program == NULL) {
  1648. return _Py_INIT_NO_MEMORY();
  1649. }
  1650. return _Py_INIT_OK();
  1651. }
  1652. static _PyInitError
  1653. config_add_warnings_optlist(_PyCoreConfig *config,
  1654. int len, wchar_t * const *options)
  1655. {
  1656. for (int i = 0; i < len; i++) {
  1657. _PyInitError err = _Py_wstrlist_append(&config->nwarnoption,
  1658. &config->warnoptions,
  1659. options[i]);
  1660. if (_Py_INIT_FAILED(err)) {
  1661. return err;
  1662. }
  1663. }
  1664. return _Py_INIT_OK();
  1665. }
  1666. static _PyInitError
  1667. config_init_warnoptions(_PyCoreConfig *config, const _PyCmdline *cmdline)
  1668. {
  1669. _PyInitError err;
  1670. assert(config->nwarnoption == 0);
  1671. /* The priority order for warnings configuration is (highest precedence
  1672. * first):
  1673. *
  1674. * - the BytesWarning filter, if needed ('-b', '-bb')
  1675. * - any '-W' command line options; then
  1676. * - the 'PYTHONWARNINGS' environment variable; then
  1677. * - the dev mode filter ('-X dev', 'PYTHONDEVMODE'); then
  1678. * - any implicit filters added by _warnings.c/warnings.py
  1679. *
  1680. * All settings except the last are passed to the warnings module via
  1681. * the `sys.warnoptions` list. Since the warnings module works on the basis
  1682. * of "the most recently added filter will be checked first", we add
  1683. * the lowest precedence entries first so that later entries override them.
  1684. */
  1685. if (config->dev_mode) {
  1686. err = _Py_wstrlist_append(&config->nwarnoption,
  1687. &config->warnoptions,
  1688. L"default");
  1689. if (_Py_INIT_FAILED(err)) {
  1690. return err;
  1691. }
  1692. }
  1693. err = config_add_warnings_optlist(config,
  1694. cmdline->nenv_warnoption,
  1695. cmdline->env_warnoptions);
  1696. if (_Py_INIT_FAILED(err)) {
  1697. return err;
  1698. }
  1699. err = config_add_warnings_optlist(config,
  1700. cmdline->nwarnoption,
  1701. cmdline->warnoptions);
  1702. if (_Py_INIT_FAILED(err)) {
  1703. return err;
  1704. }
  1705. /* If the bytes_warning_flag isn't set, bytesobject.c and bytearrayobject.c
  1706. * don't even try to emit a warning, so we skip setting the filter in that
  1707. * case.
  1708. */
  1709. if (config->bytes_warning) {
  1710. wchar_t *filter;
  1711. if (config->bytes_warning> 1) {
  1712. filter = L"error::BytesWarning";
  1713. }
  1714. else {
  1715. filter = L"default::BytesWarning";
  1716. }
  1717. err = _Py_wstrlist_append(&config->nwarnoption,
  1718. &config->warnoptions,
  1719. filter);
  1720. if (_Py_INIT_FAILED(err)) {
  1721. return err;
  1722. }
  1723. }
  1724. return _Py_INIT_OK();
  1725. }
  1726. static _PyInitError
  1727. config_init_argv(_PyCoreConfig *config, const _PyCmdline *cmdline)
  1728. {
  1729. /* Copy argv to be able to modify it (to force -c/-m) */
  1730. int argc = cmdline->args->argc - _PyOS_optind;
  1731. wchar_t **argv;
  1732. if (argc <= 0 || cmdline->argv == NULL) {
  1733. /* Ensure at least one (empty) argument is seen */
  1734. static wchar_t *empty_argv[1] = {L""};
  1735. argc = 1;
  1736. argv = _Py_wstrlist_copy(1, empty_argv);
  1737. }
  1738. else {
  1739. argv = _Py_wstrlist_copy(argc, &cmdline->argv[_PyOS_optind]);
  1740. }
  1741. if (argv == NULL) {
  1742. return _Py_INIT_NO_MEMORY();
  1743. }
  1744. wchar_t *arg0 = NULL;
  1745. if (config->run_command != NULL) {
  1746. /* Force sys.argv[0] = '-c' */
  1747. arg0 = L"-c";
  1748. }
  1749. else if (config->run_module != NULL) {
  1750. /* Force sys.argv[0] = '-m'*/
  1751. arg0 = L"-m";
  1752. }
  1753. if (arg0 != NULL) {
  1754. arg0 = _PyMem_RawWcsdup(arg0);
  1755. if (arg0 == NULL) {
  1756. _Py_wstrlist_clear(argc, argv);
  1757. return _Py_INIT_NO_MEMORY();
  1758. }
  1759. assert(argc >= 1);
  1760. PyMem_RawFree(argv[0]);
  1761. argv[0] = arg0;
  1762. }
  1763. config->argc = argc;
  1764. config->argv = argv;
  1765. return _Py_INIT_OK();
  1766. }
  1767. static void
  1768. config_usage(int error, const wchar_t* program)
  1769. {
  1770. FILE *f = error ? stderr : stdout;
  1771. fprintf(f, usage_line, program);
  1772. if (error)
  1773. fprintf(f, "Try `python -h' for more information.\n");
  1774. else {
  1775. fputs(usage_1, f);
  1776. fputs(usage_2, f);
  1777. fputs(usage_3, f);
  1778. fprintf(f, usage_4, (wint_t)DELIM);
  1779. fprintf(f, usage_5, (wint_t)DELIM, PYTHONHOMEHELP);
  1780. fputs(usage_6, f);
  1781. }
  1782. }
  1783. /* Parse command line options and environment variables. */
  1784. static _PyInitError
  1785. config_from_cmdline(_PyCoreConfig *config, _PyCmdline *cmdline,
  1786. const _PyPreConfig *preconfig)
  1787. {
  1788. int need_usage = 0;
  1789. _PyInitError err;
  1790. err = config_init_program(config, cmdline);
  1791. if (_Py_INIT_FAILED(err)) {
  1792. return err;
  1793. }
  1794. err = config_parse_cmdline(config, cmdline, &need_usage);
  1795. if (_Py_INIT_FAILED(err)) {
  1796. return err;
  1797. }
  1798. if (need_usage) {
  1799. config_usage(1, config->program);
  1800. return _Py_INIT_EXIT(2);
  1801. }
  1802. if (cmdline->print_help) {
  1803. config_usage(0, config->program);
  1804. return _Py_INIT_EXIT(0);
  1805. }
  1806. if (cmdline->print_version) {
  1807. printf("Python %s\n",
  1808. (cmdline->print_version >= 2) ? Py_GetVersion() : PY_VERSION);
  1809. return _Py_INIT_EXIT(0);
  1810. }
  1811. err = config_init_argv(config, cmdline);
  1812. if (_Py_INIT_FAILED(err)) {
  1813. return err;
  1814. }
  1815. err = _PyCoreConfig_Read(config, preconfig);
  1816. if (_Py_INIT_FAILED(err)) {
  1817. return err;
  1818. }
  1819. if (config->preconfig.use_environment) {
  1820. err = cmdline_init_env_warnoptions(cmdline, config);
  1821. if (_Py_INIT_FAILED(err)) {
  1822. return err;
  1823. }
  1824. }
  1825. err = config_init_warnoptions(config, cmdline);
  1826. if (_Py_INIT_FAILED(err)) {
  1827. return err;
  1828. }
  1829. if (_Py_SetArgcArgv(cmdline->args->argc, cmdline->argv) < 0) {
  1830. return _Py_INIT_NO_MEMORY();
  1831. }
  1832. return _Py_INIT_OK();
  1833. }
  1834. /* Read the configuration into _PyCoreConfig and initialize the LC_CTYPE
  1835. locale: enable UTF-8 mode (PEP 540) and/or coerce the C locale (PEP 538).
  1836. Read the configuration from:
  1837. * Command line arguments
  1838. * Environment variables
  1839. * Py_xxx global configuration variables */
  1840. _PyInitError
  1841. _PyCoreConfig_ReadFromArgv(_PyCoreConfig *config, const _PyArgv *args,
  1842. const _PyPreConfig *preconfig)
  1843. {
  1844. _PyInitError err;
  1845. _PyCmdline cmdline;
  1846. memset(&cmdline, 0, sizeof(cmdline));
  1847. cmdline.args = args;
  1848. err = _PyArgv_Decode(cmdline.args, &cmdline.argv);
  1849. if (_Py_INIT_FAILED(err)) {
  1850. goto done;
  1851. }
  1852. err = config_from_cmdline(config, &cmdline, preconfig);
  1853. if (_Py_INIT_FAILED(err)) {
  1854. goto done;
  1855. }
  1856. err = _Py_INIT_OK();
  1857. done:
  1858. cmdline_clear(&cmdline);
  1859. return err;
  1860. }