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.

2136 lines
60 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. static 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. CLEAR(config->run_command);
  408. CLEAR(config->run_module);
  409. CLEAR(config->run_filename);
  410. #undef CLEAR
  411. #undef CLEAR_WSTRLIST
  412. }
  413. int
  414. _PyCoreConfig_Copy(_PyCoreConfig *config, const _PyCoreConfig *config2)
  415. {
  416. _PyCoreConfig_Clear(config);
  417. if (_PyPreConfig_Copy(&config->preconfig, &config2->preconfig) < 0) {
  418. return -1;
  419. }
  420. #define COPY_ATTR(ATTR) config->ATTR = config2->ATTR
  421. #define COPY_STR_ATTR(ATTR) \
  422. do { \
  423. if (config2->ATTR != NULL) { \
  424. config->ATTR = _PyMem_RawStrdup(config2->ATTR); \
  425. if (config->ATTR == NULL) { \
  426. return -1; \
  427. } \
  428. } \
  429. } while (0)
  430. #define COPY_WSTR_ATTR(ATTR) \
  431. do { \
  432. if (config2->ATTR != NULL) { \
  433. config->ATTR = _PyMem_RawWcsdup(config2->ATTR); \
  434. if (config->ATTR == NULL) { \
  435. return -1; \
  436. } \
  437. } \
  438. } while (0)
  439. #define COPY_WSTRLIST(LEN, LIST) \
  440. do { \
  441. if (config2->LIST != NULL) { \
  442. config->LIST = _Py_wstrlist_copy(config2->LEN, config2->LIST); \
  443. if (config->LIST == NULL) { \
  444. return -1; \
  445. } \
  446. } \
  447. config->LEN = config2->LEN; \
  448. } while (0)
  449. COPY_ATTR(install_signal_handlers);
  450. COPY_ATTR(use_hash_seed);
  451. COPY_ATTR(hash_seed);
  452. COPY_ATTR(_install_importlib);
  453. COPY_ATTR(faulthandler);
  454. COPY_ATTR(tracemalloc);
  455. COPY_ATTR(import_time);
  456. COPY_ATTR(show_ref_count);
  457. COPY_ATTR(show_alloc_count);
  458. COPY_ATTR(dump_refs);
  459. COPY_ATTR(malloc_stats);
  460. COPY_WSTR_ATTR(pycache_prefix);
  461. COPY_WSTR_ATTR(module_search_path_env);
  462. COPY_WSTR_ATTR(home);
  463. COPY_WSTR_ATTR(program_name);
  464. COPY_WSTR_ATTR(program);
  465. COPY_WSTRLIST(argc, argv);
  466. COPY_WSTRLIST(nwarnoption, warnoptions);
  467. COPY_WSTRLIST(nxoption, xoptions);
  468. COPY_WSTRLIST(nmodule_search_path, module_search_paths);
  469. COPY_WSTR_ATTR(executable);
  470. COPY_WSTR_ATTR(prefix);
  471. COPY_WSTR_ATTR(base_prefix);
  472. COPY_WSTR_ATTR(exec_prefix);
  473. #ifdef MS_WINDOWS
  474. COPY_WSTR_ATTR(dll_path);
  475. #endif
  476. COPY_WSTR_ATTR(base_exec_prefix);
  477. COPY_ATTR(site_import);
  478. COPY_ATTR(bytes_warning);
  479. COPY_ATTR(inspect);
  480. COPY_ATTR(interactive);
  481. COPY_ATTR(optimization_level);
  482. COPY_ATTR(parser_debug);
  483. COPY_ATTR(write_bytecode);
  484. COPY_ATTR(verbose);
  485. COPY_ATTR(quiet);
  486. COPY_ATTR(user_site_directory);
  487. COPY_ATTR(buffered_stdio);
  488. COPY_STR_ATTR(filesystem_encoding);
  489. COPY_STR_ATTR(filesystem_errors);
  490. COPY_STR_ATTR(stdio_encoding);
  491. COPY_STR_ATTR(stdio_errors);
  492. #ifdef MS_WINDOWS
  493. COPY_ATTR(legacy_windows_stdio);
  494. #endif
  495. COPY_ATTR(skip_source_first_line);
  496. COPY_WSTR_ATTR(run_command);
  497. COPY_WSTR_ATTR(run_module);
  498. COPY_WSTR_ATTR(run_filename);
  499. COPY_ATTR(_check_hash_pycs_mode);
  500. COPY_ATTR(_frozen);
  501. #undef COPY_ATTR
  502. #undef COPY_STR_ATTR
  503. #undef COPY_WSTR_ATTR
  504. #undef COPY_WSTRLIST
  505. return 0;
  506. }
  507. const char*
  508. _PyCoreConfig_GetEnv(const _PyCoreConfig *config, const char *name)
  509. {
  510. return _PyPreConfig_GetEnv(&config->preconfig, name);
  511. }
  512. int
  513. _PyCoreConfig_GetEnvDup(const _PyCoreConfig *config,
  514. wchar_t **dest,
  515. wchar_t *wname, char *name)
  516. {
  517. assert(config->preconfig.use_environment >= 0);
  518. if (!config->preconfig.use_environment) {
  519. *dest = NULL;
  520. return 0;
  521. }
  522. #ifdef MS_WINDOWS
  523. const wchar_t *var = _wgetenv(wname);
  524. if (!var || var[0] == '\0') {
  525. *dest = NULL;
  526. return 0;
  527. }
  528. wchar_t *copy = _PyMem_RawWcsdup(var);
  529. if (copy == NULL) {
  530. return -1;
  531. }
  532. *dest = copy;
  533. #else
  534. const char *var = getenv(name);
  535. if (!var || var[0] == '\0') {
  536. *dest = NULL;
  537. return 0;
  538. }
  539. size_t len;
  540. wchar_t *wvar = Py_DecodeLocale(var, &len);
  541. if (!wvar) {
  542. if (len == (size_t)-2) {
  543. return -2;
  544. }
  545. else {
  546. return -1;
  547. }
  548. }
  549. *dest = wvar;
  550. #endif
  551. return 0;
  552. }
  553. void
  554. _PyCoreConfig_GetGlobalConfig(_PyCoreConfig *config)
  555. {
  556. _PyPreConfig_GetGlobalConfig(&config->preconfig);
  557. #define COPY_FLAG(ATTR, VALUE) \
  558. if (config->ATTR == -1) { \
  559. config->ATTR = VALUE; \
  560. }
  561. #define COPY_NOT_FLAG(ATTR, VALUE) \
  562. if (config->ATTR == -1) { \
  563. config->ATTR = !(VALUE); \
  564. }
  565. COPY_FLAG(bytes_warning, Py_BytesWarningFlag);
  566. COPY_FLAG(inspect, Py_InspectFlag);
  567. COPY_FLAG(interactive, Py_InteractiveFlag);
  568. COPY_FLAG(optimization_level, Py_OptimizeFlag);
  569. COPY_FLAG(parser_debug, Py_DebugFlag);
  570. COPY_FLAG(verbose, Py_VerboseFlag);
  571. COPY_FLAG(quiet, Py_QuietFlag);
  572. #ifdef MS_WINDOWS
  573. COPY_FLAG(legacy_windows_stdio, Py_LegacyWindowsStdioFlag);
  574. #endif
  575. COPY_FLAG(_frozen, Py_FrozenFlag);
  576. COPY_NOT_FLAG(buffered_stdio, Py_UnbufferedStdioFlag);
  577. COPY_NOT_FLAG(site_import, Py_NoSiteFlag);
  578. COPY_NOT_FLAG(write_bytecode, Py_DontWriteBytecodeFlag);
  579. COPY_NOT_FLAG(user_site_directory, Py_NoUserSiteDirectory);
  580. #undef COPY_FLAG
  581. #undef COPY_NOT_FLAG
  582. }
  583. /* Set Py_xxx global configuration variables from 'config' configuration. */
  584. void
  585. _PyCoreConfig_SetGlobalConfig(const _PyCoreConfig *config)
  586. {
  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. _PyPreConfig *preconfig = &config->preconfig;
  780. /* Get environment variables */
  781. _Py_get_env_flag(preconfig, &config->parser_debug, "PYTHONDEBUG");
  782. _Py_get_env_flag(preconfig, &config->verbose, "PYTHONVERBOSE");
  783. _Py_get_env_flag(preconfig, &config->optimization_level, "PYTHONOPTIMIZE");
  784. _Py_get_env_flag(preconfig, &config->inspect, "PYTHONINSPECT");
  785. int dont_write_bytecode = 0;
  786. _Py_get_env_flag(preconfig, &dont_write_bytecode, "PYTHONDONTWRITEBYTECODE");
  787. if (dont_write_bytecode) {
  788. config->write_bytecode = 0;
  789. }
  790. int no_user_site_directory = 0;
  791. _Py_get_env_flag(preconfig, &no_user_site_directory, "PYTHONNOUSERSITE");
  792. if (no_user_site_directory) {
  793. config->user_site_directory = 0;
  794. }
  795. int unbuffered_stdio = 0;
  796. _Py_get_env_flag(preconfig, &unbuffered_stdio, "PYTHONUNBUFFERED");
  797. if (unbuffered_stdio) {
  798. config->buffered_stdio = 0;
  799. }
  800. #ifdef MS_WINDOWS
  801. _Py_get_env_flag(preconfig, &config->legacy_windows_stdio,
  802. "PYTHONLEGACYWINDOWSSTDIO");
  803. #endif
  804. if (_PyCoreConfig_GetEnv(config, "PYTHONDUMPREFS")) {
  805. config->dump_refs = 1;
  806. }
  807. if (_PyCoreConfig_GetEnv(config, "PYTHONMALLOCSTATS")) {
  808. config->malloc_stats = 1;
  809. }
  810. wchar_t *path;
  811. int res = _PyCoreConfig_GetEnvDup(config, &path,
  812. L"PYTHONPATH", "PYTHONPATH");
  813. if (res < 0) {
  814. return DECODE_LOCALE_ERR("PYTHONPATH", res);
  815. }
  816. config->module_search_path_env = path;
  817. if (config->use_hash_seed < 0) {
  818. _PyInitError err = config_init_hash_seed(config);
  819. if (_Py_INIT_FAILED(err)) {
  820. return err;
  821. }
  822. }
  823. return _Py_INIT_OK();
  824. }
  825. static _PyInitError
  826. config_init_tracemalloc(_PyCoreConfig *config)
  827. {
  828. int nframe;
  829. int valid;
  830. const char *env = _PyCoreConfig_GetEnv(config, "PYTHONTRACEMALLOC");
  831. if (env) {
  832. if (!_Py_str_to_int(env, &nframe)) {
  833. valid = (nframe >= 0);
  834. }
  835. else {
  836. valid = 0;
  837. }
  838. if (!valid) {
  839. return _Py_INIT_USER_ERR("PYTHONTRACEMALLOC: invalid number "
  840. "of frames");
  841. }
  842. config->tracemalloc = nframe;
  843. }
  844. const wchar_t *xoption = config_get_xoption(config, L"tracemalloc");
  845. if (xoption) {
  846. const wchar_t *sep = wcschr(xoption, L'=');
  847. if (sep) {
  848. if (!config_wstr_to_int(sep + 1, &nframe)) {
  849. valid = (nframe >= 0);
  850. }
  851. else {
  852. valid = 0;
  853. }
  854. if (!valid) {
  855. return _Py_INIT_USER_ERR("-X tracemalloc=NFRAME: "
  856. "invalid number of frames");
  857. }
  858. }
  859. else {
  860. /* -X tracemalloc behaves as -X tracemalloc=1 */
  861. nframe = 1;
  862. }
  863. config->tracemalloc = nframe;
  864. }
  865. return _Py_INIT_OK();
  866. }
  867. static _PyInitError
  868. config_init_pycache_prefix(_PyCoreConfig *config)
  869. {
  870. assert(config->pycache_prefix == NULL);
  871. const wchar_t *xoption = config_get_xoption(config, L"pycache_prefix");
  872. if (xoption) {
  873. const wchar_t *sep = wcschr(xoption, L'=');
  874. if (sep && wcslen(sep) > 1) {
  875. config->pycache_prefix = _PyMem_RawWcsdup(sep + 1);
  876. if (config->pycache_prefix == NULL) {
  877. return _Py_INIT_NO_MEMORY();
  878. }
  879. }
  880. else {
  881. // -X pycache_prefix= can cancel the env var
  882. config->pycache_prefix = NULL;
  883. }
  884. }
  885. else {
  886. wchar_t *env;
  887. int res = _PyCoreConfig_GetEnvDup(config, &env,
  888. L"PYTHONPYCACHEPREFIX",
  889. "PYTHONPYCACHEPREFIX");
  890. if (res < 0) {
  891. return DECODE_LOCALE_ERR("PYTHONPYCACHEPREFIX", res);
  892. }
  893. if (env) {
  894. config->pycache_prefix = env;
  895. }
  896. }
  897. return _Py_INIT_OK();
  898. }
  899. static _PyInitError
  900. config_read_complex_options(_PyCoreConfig *config)
  901. {
  902. /* More complex options configured by env var and -X option */
  903. if (config->faulthandler < 0) {
  904. if (_PyCoreConfig_GetEnv(config, "PYTHONFAULTHANDLER")
  905. || config_get_xoption(config, L"faulthandler")) {
  906. config->faulthandler = 1;
  907. }
  908. }
  909. if (_PyCoreConfig_GetEnv(config, "PYTHONPROFILEIMPORTTIME")
  910. || config_get_xoption(config, L"importtime")) {
  911. config->import_time = 1;
  912. }
  913. _PyInitError err;
  914. if (config->tracemalloc < 0) {
  915. err = config_init_tracemalloc(config);
  916. if (_Py_INIT_FAILED(err)) {
  917. return err;
  918. }
  919. }
  920. if (config->pycache_prefix == NULL) {
  921. err = config_init_pycache_prefix(config);
  922. if (_Py_INIT_FAILED(err)) {
  923. return err;
  924. }
  925. }
  926. return _Py_INIT_OK();
  927. }
  928. static const char *
  929. get_stdio_errors(const _PyCoreConfig *config)
  930. {
  931. #ifndef MS_WINDOWS
  932. const char *loc = setlocale(LC_CTYPE, NULL);
  933. if (loc != NULL) {
  934. /* surrogateescape is the default in the legacy C and POSIX locales */
  935. if (strcmp(loc, "C") == 0 || strcmp(loc, "POSIX") == 0) {
  936. return "surrogateescape";
  937. }
  938. #ifdef PY_COERCE_C_LOCALE
  939. /* surrogateescape is the default in locale coercion target locales */
  940. if (_Py_IsLocaleCoercionTarget(loc)) {
  941. return "surrogateescape";
  942. }
  943. #endif
  944. }
  945. return "strict";
  946. #else
  947. /* On Windows, always use surrogateescape by default */
  948. return "surrogateescape";
  949. #endif
  950. }
  951. static _PyInitError
  952. get_locale_encoding(char **locale_encoding)
  953. {
  954. #ifdef MS_WINDOWS
  955. char encoding[20];
  956. PyOS_snprintf(encoding, sizeof(encoding), "cp%u", GetACP());
  957. #elif defined(__ANDROID__) || defined(__VXWORKS__)
  958. const char *encoding = "UTF-8";
  959. #else
  960. const char *encoding = nl_langinfo(CODESET);
  961. if (!encoding || encoding[0] == '\0') {
  962. return _Py_INIT_USER_ERR("failed to get the locale encoding: "
  963. "nl_langinfo(CODESET) failed");
  964. }
  965. #endif
  966. *locale_encoding = _PyMem_RawStrdup(encoding);
  967. if (*locale_encoding == NULL) {
  968. return _Py_INIT_NO_MEMORY();
  969. }
  970. return _Py_INIT_OK();
  971. }
  972. static _PyInitError
  973. config_init_stdio_encoding(_PyCoreConfig *config)
  974. {
  975. /* If Py_SetStandardStreamEncoding() have been called, use these
  976. parameters. */
  977. if (config->stdio_encoding == NULL && _Py_StandardStreamEncoding != NULL) {
  978. config->stdio_encoding = _PyMem_RawStrdup(_Py_StandardStreamEncoding);
  979. if (config->stdio_encoding == NULL) {
  980. return _Py_INIT_NO_MEMORY();
  981. }
  982. }
  983. if (config->stdio_errors == NULL && _Py_StandardStreamErrors != NULL) {
  984. config->stdio_errors = _PyMem_RawStrdup(_Py_StandardStreamErrors);
  985. if (config->stdio_errors == NULL) {
  986. return _Py_INIT_NO_MEMORY();
  987. }
  988. }
  989. if (config->stdio_encoding != NULL && config->stdio_errors != NULL) {
  990. return _Py_INIT_OK();
  991. }
  992. /* PYTHONIOENCODING environment variable */
  993. const char *opt = _PyCoreConfig_GetEnv(config, "PYTHONIOENCODING");
  994. if (opt) {
  995. char *pythonioencoding = _PyMem_RawStrdup(opt);
  996. if (pythonioencoding == NULL) {
  997. return _Py_INIT_NO_MEMORY();
  998. }
  999. char *err = strchr(pythonioencoding, ':');
  1000. if (err) {
  1001. *err = '\0';
  1002. err++;
  1003. if (!err[0]) {
  1004. err = NULL;
  1005. }
  1006. }
  1007. /* Does PYTHONIOENCODING contain an encoding? */
  1008. if (pythonioencoding[0]) {
  1009. if (config->stdio_encoding == NULL) {
  1010. config->stdio_encoding = _PyMem_RawStrdup(pythonioencoding);
  1011. if (config->stdio_encoding == NULL) {
  1012. PyMem_RawFree(pythonioencoding);
  1013. return _Py_INIT_NO_MEMORY();
  1014. }
  1015. }
  1016. /* If the encoding is set but not the error handler,
  1017. use "strict" error handler by default.
  1018. PYTHONIOENCODING=latin1 behaves as
  1019. PYTHONIOENCODING=latin1:strict. */
  1020. if (!err) {
  1021. err = "strict";
  1022. }
  1023. }
  1024. if (config->stdio_errors == NULL && err != NULL) {
  1025. config->stdio_errors = _PyMem_RawStrdup(err);
  1026. if (config->stdio_errors == NULL) {
  1027. PyMem_RawFree(pythonioencoding);
  1028. return _Py_INIT_NO_MEMORY();
  1029. }
  1030. }
  1031. PyMem_RawFree(pythonioencoding);
  1032. }
  1033. /* UTF-8 Mode uses UTF-8/surrogateescape */
  1034. if (config->preconfig.utf8_mode) {
  1035. if (config->stdio_encoding == NULL) {
  1036. config->stdio_encoding = _PyMem_RawStrdup("utf-8");
  1037. if (config->stdio_encoding == NULL) {
  1038. return _Py_INIT_NO_MEMORY();
  1039. }
  1040. }
  1041. if (config->stdio_errors == NULL) {
  1042. config->stdio_errors = _PyMem_RawStrdup("surrogateescape");
  1043. if (config->stdio_errors == NULL) {
  1044. return _Py_INIT_NO_MEMORY();
  1045. }
  1046. }
  1047. }
  1048. /* Choose the default error handler based on the current locale. */
  1049. if (config->stdio_encoding == NULL) {
  1050. _PyInitError err = get_locale_encoding(&config->stdio_encoding);
  1051. if (_Py_INIT_FAILED(err)) {
  1052. return err;
  1053. }
  1054. }
  1055. if (config->stdio_errors == NULL) {
  1056. const char *errors = get_stdio_errors(config);
  1057. config->stdio_errors = _PyMem_RawStrdup(errors);
  1058. if (config->stdio_errors == NULL) {
  1059. return _Py_INIT_NO_MEMORY();
  1060. }
  1061. }
  1062. return _Py_INIT_OK();
  1063. }
  1064. static _PyInitError
  1065. config_init_fs_encoding(_PyCoreConfig *config)
  1066. {
  1067. #ifdef MS_WINDOWS
  1068. if (config->preconfig.legacy_windows_fs_encoding) {
  1069. /* Legacy Windows filesystem encoding: mbcs/replace */
  1070. if (config->filesystem_encoding == NULL) {
  1071. config->filesystem_encoding = _PyMem_RawStrdup("mbcs");
  1072. if (config->filesystem_encoding == NULL) {
  1073. return _Py_INIT_NO_MEMORY();
  1074. }
  1075. }
  1076. if (config->filesystem_errors == NULL) {
  1077. config->filesystem_errors = _PyMem_RawStrdup("replace");
  1078. if (config->filesystem_errors == NULL) {
  1079. return _Py_INIT_NO_MEMORY();
  1080. }
  1081. }
  1082. }
  1083. /* Windows defaults to utf-8/surrogatepass (PEP 529).
  1084. Note: UTF-8 Mode takes the same code path and the Legacy Windows FS
  1085. encoding has the priortiy over UTF-8 Mode. */
  1086. if (config->filesystem_encoding == NULL) {
  1087. config->filesystem_encoding = _PyMem_RawStrdup("utf-8");
  1088. if (config->filesystem_encoding == NULL) {
  1089. return _Py_INIT_NO_MEMORY();
  1090. }
  1091. }
  1092. if (config->filesystem_errors == NULL) {
  1093. config->filesystem_errors = _PyMem_RawStrdup("surrogatepass");
  1094. if (config->filesystem_errors == NULL) {
  1095. return _Py_INIT_NO_MEMORY();
  1096. }
  1097. }
  1098. #else
  1099. if (config->filesystem_encoding == NULL) {
  1100. if (config->preconfig.utf8_mode) {
  1101. /* UTF-8 Mode use: utf-8/surrogateescape */
  1102. config->filesystem_encoding = _PyMem_RawStrdup("utf-8");
  1103. /* errors defaults to surrogateescape above */
  1104. }
  1105. else if (_Py_GetForceASCII()) {
  1106. config->filesystem_encoding = _PyMem_RawStrdup("ascii");
  1107. }
  1108. else {
  1109. /* macOS and Android use UTF-8,
  1110. other platforms use the locale encoding. */
  1111. #if defined(__APPLE__) || defined(__ANDROID__)
  1112. config->filesystem_encoding = _PyMem_RawStrdup("utf-8");
  1113. #else
  1114. _PyInitError err = get_locale_encoding(&config->filesystem_encoding);
  1115. if (_Py_INIT_FAILED(err)) {
  1116. return err;
  1117. }
  1118. #endif
  1119. }
  1120. if (config->filesystem_encoding == NULL) {
  1121. return _Py_INIT_NO_MEMORY();
  1122. }
  1123. }
  1124. if (config->filesystem_errors == NULL) {
  1125. /* by default, use the "surrogateescape" error handler */
  1126. config->filesystem_errors = _PyMem_RawStrdup("surrogateescape");
  1127. if (config->filesystem_errors == NULL) {
  1128. return _Py_INIT_NO_MEMORY();
  1129. }
  1130. }
  1131. #endif
  1132. return _Py_INIT_OK();
  1133. }
  1134. static _PyInitError
  1135. _PyCoreConfig_ReadPreConfig(_PyCoreConfig *config)
  1136. {
  1137. _PyInitError err;
  1138. _PyPreConfig local_preconfig = _PyPreConfig_INIT;
  1139. _PyPreConfig_GetGlobalConfig(&local_preconfig);
  1140. if (_PyPreConfig_Copy(&local_preconfig, &config->preconfig) < 0) {
  1141. err = _Py_INIT_NO_MEMORY();
  1142. goto done;
  1143. }
  1144. err = _PyPreConfig_Read(&local_preconfig);
  1145. if (_Py_INIT_FAILED(err)) {
  1146. goto done;
  1147. }
  1148. if (_PyPreConfig_Copy(&config->preconfig, &local_preconfig) < 0) {
  1149. err = _Py_INIT_NO_MEMORY();
  1150. goto done;
  1151. }
  1152. err = _Py_INIT_OK();
  1153. done:
  1154. _PyPreConfig_Clear(&local_preconfig);
  1155. return err;
  1156. }
  1157. /* Read the configuration into _PyCoreConfig from:
  1158. * Environment variables
  1159. * Py_xxx global configuration variables
  1160. See _PyCoreConfig_ReadFromArgv() to parse also command line arguments. */
  1161. _PyInitError
  1162. _PyCoreConfig_Read(_PyCoreConfig *config, const _PyPreConfig *preconfig)
  1163. {
  1164. _PyInitError err;
  1165. _PyCoreConfig_GetGlobalConfig(config);
  1166. if (preconfig != NULL) {
  1167. if (_PyPreConfig_Copy(&config->preconfig, preconfig) < 0) {
  1168. return _Py_INIT_NO_MEMORY();
  1169. }
  1170. }
  1171. else {
  1172. err = _PyCoreConfig_ReadPreConfig(config);
  1173. if (_Py_INIT_FAILED(err)) {
  1174. return err;
  1175. }
  1176. }
  1177. assert(config->preconfig.use_environment >= 0);
  1178. if (config->preconfig.isolated > 0) {
  1179. config->user_site_directory = 0;
  1180. }
  1181. if (config->preconfig.use_environment) {
  1182. err = config_read_env_vars(config);
  1183. if (_Py_INIT_FAILED(err)) {
  1184. return err;
  1185. }
  1186. }
  1187. /* -X options */
  1188. if (config_get_xoption(config, L"showrefcount")) {
  1189. config->show_ref_count = 1;
  1190. }
  1191. if (config_get_xoption(config, L"showalloccount")) {
  1192. config->show_alloc_count = 1;
  1193. }
  1194. err = config_read_complex_options(config);
  1195. if (_Py_INIT_FAILED(err)) {
  1196. return err;
  1197. }
  1198. if (config->home == NULL) {
  1199. err = config_init_home(config);
  1200. if (_Py_INIT_FAILED(err)) {
  1201. return err;
  1202. }
  1203. }
  1204. if (config->program_name == NULL) {
  1205. err = config_init_program_name(config);
  1206. if (_Py_INIT_FAILED(err)) {
  1207. return err;
  1208. }
  1209. }
  1210. if (config->executable == NULL) {
  1211. err = config_init_executable(config);
  1212. if (_Py_INIT_FAILED(err)) {
  1213. return err;
  1214. }
  1215. }
  1216. if (config->_install_importlib) {
  1217. err = _PyCoreConfig_InitPathConfig(config);
  1218. if (_Py_INIT_FAILED(err)) {
  1219. return err;
  1220. }
  1221. }
  1222. /* default values */
  1223. if (config->preconfig.dev_mode) {
  1224. if (config->faulthandler < 0) {
  1225. config->faulthandler = 1;
  1226. }
  1227. }
  1228. if (config->use_hash_seed < 0) {
  1229. config->use_hash_seed = 0;
  1230. config->hash_seed = 0;
  1231. }
  1232. if (config->faulthandler < 0) {
  1233. config->faulthandler = 0;
  1234. }
  1235. if (config->tracemalloc < 0) {
  1236. config->tracemalloc = 0;
  1237. }
  1238. if (config->argc < 0) {
  1239. config->argc = 0;
  1240. }
  1241. if (config->filesystem_encoding == NULL || config->filesystem_errors == NULL) {
  1242. err = config_init_fs_encoding(config);
  1243. if (_Py_INIT_FAILED(err)) {
  1244. return err;
  1245. }
  1246. }
  1247. err = config_init_stdio_encoding(config);
  1248. if (_Py_INIT_FAILED(err)) {
  1249. return err;
  1250. }
  1251. assert(config->preconfig.use_environment >= 0);
  1252. assert(config->filesystem_encoding != NULL);
  1253. assert(config->filesystem_errors != NULL);
  1254. assert(config->stdio_encoding != NULL);
  1255. assert(config->stdio_errors != NULL);
  1256. assert(config->_check_hash_pycs_mode != NULL);
  1257. return _Py_INIT_OK();
  1258. }
  1259. static void
  1260. config_init_stdio(const _PyCoreConfig *config)
  1261. {
  1262. #if defined(MS_WINDOWS) || defined(__CYGWIN__)
  1263. /* don't translate newlines (\r\n <=> \n) */
  1264. _setmode(fileno(stdin), O_BINARY);
  1265. _setmode(fileno(stdout), O_BINARY);
  1266. _setmode(fileno(stderr), O_BINARY);
  1267. #endif
  1268. if (!config->buffered_stdio) {
  1269. #ifdef HAVE_SETVBUF
  1270. setvbuf(stdin, (char *)NULL, _IONBF, BUFSIZ);
  1271. setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ);
  1272. setvbuf(stderr, (char *)NULL, _IONBF, BUFSIZ);
  1273. #else /* !HAVE_SETVBUF */
  1274. setbuf(stdin, (char *)NULL);
  1275. setbuf(stdout, (char *)NULL);
  1276. setbuf(stderr, (char *)NULL);
  1277. #endif /* !HAVE_SETVBUF */
  1278. }
  1279. else if (config->interactive) {
  1280. #ifdef MS_WINDOWS
  1281. /* Doesn't have to have line-buffered -- use unbuffered */
  1282. /* Any set[v]buf(stdin, ...) screws up Tkinter :-( */
  1283. setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ);
  1284. #else /* !MS_WINDOWS */
  1285. #ifdef HAVE_SETVBUF
  1286. setvbuf(stdin, (char *)NULL, _IOLBF, BUFSIZ);
  1287. setvbuf(stdout, (char *)NULL, _IOLBF, BUFSIZ);
  1288. #endif /* HAVE_SETVBUF */
  1289. #endif /* !MS_WINDOWS */
  1290. /* Leave stderr alone - it should be unbuffered anyway. */
  1291. }
  1292. }
  1293. /* Write the configuration:
  1294. - set Py_xxx global configuration variables
  1295. - initialize C standard streams (stdin, stdout, stderr) */
  1296. void
  1297. _PyCoreConfig_Write(const _PyCoreConfig *config)
  1298. {
  1299. _PyCoreConfig_SetGlobalConfig(config);
  1300. config_init_stdio(config);
  1301. }
  1302. PyObject *
  1303. _PyCoreConfig_AsDict(const _PyCoreConfig *config)
  1304. {
  1305. PyObject *dict;
  1306. dict = PyDict_New();
  1307. if (dict == NULL) {
  1308. return NULL;
  1309. }
  1310. if (_PyPreConfig_AsDict(&config->preconfig, dict) < 0) {
  1311. Py_DECREF(dict);
  1312. return NULL;
  1313. }
  1314. #define SET_ITEM(KEY, EXPR) \
  1315. do { \
  1316. PyObject *obj = (EXPR); \
  1317. if (obj == NULL) { \
  1318. goto fail; \
  1319. } \
  1320. int res = PyDict_SetItemString(dict, (KEY), obj); \
  1321. Py_DECREF(obj); \
  1322. if (res < 0) { \
  1323. goto fail; \
  1324. } \
  1325. } while (0)
  1326. #define FROM_STRING(STR) \
  1327. ((STR != NULL) ? \
  1328. PyUnicode_FromString(STR) \
  1329. : (Py_INCREF(Py_None), Py_None))
  1330. #define SET_ITEM_INT(ATTR) \
  1331. SET_ITEM(#ATTR, PyLong_FromLong(config->ATTR))
  1332. #define SET_ITEM_UINT(ATTR) \
  1333. SET_ITEM(#ATTR, PyLong_FromUnsignedLong(config->ATTR))
  1334. #define SET_ITEM_STR(ATTR) \
  1335. SET_ITEM(#ATTR, FROM_STRING(config->ATTR))
  1336. #define FROM_WSTRING(STR) \
  1337. ((STR != NULL) ? \
  1338. PyUnicode_FromWideChar(STR, -1) \
  1339. : (Py_INCREF(Py_None), Py_None))
  1340. #define SET_ITEM_WSTR(ATTR) \
  1341. SET_ITEM(#ATTR, FROM_WSTRING(config->ATTR))
  1342. #define SET_ITEM_WSTRLIST(NOPTION, OPTIONS) \
  1343. SET_ITEM(#OPTIONS, _Py_wstrlist_as_pylist(config->NOPTION, config->OPTIONS))
  1344. SET_ITEM_INT(install_signal_handlers);
  1345. SET_ITEM_INT(use_hash_seed);
  1346. SET_ITEM_UINT(hash_seed);
  1347. SET_ITEM_INT(faulthandler);
  1348. SET_ITEM_INT(tracemalloc);
  1349. SET_ITEM_INT(import_time);
  1350. SET_ITEM_INT(show_ref_count);
  1351. SET_ITEM_INT(show_alloc_count);
  1352. SET_ITEM_INT(dump_refs);
  1353. SET_ITEM_INT(malloc_stats);
  1354. SET_ITEM_STR(filesystem_encoding);
  1355. SET_ITEM_STR(filesystem_errors);
  1356. SET_ITEM_WSTR(pycache_prefix);
  1357. SET_ITEM_WSTR(program_name);
  1358. SET_ITEM_WSTRLIST(argc, argv);
  1359. SET_ITEM_WSTR(program);
  1360. SET_ITEM_WSTRLIST(nxoption, xoptions);
  1361. SET_ITEM_WSTRLIST(nwarnoption, warnoptions);
  1362. SET_ITEM_WSTR(module_search_path_env);
  1363. SET_ITEM_WSTR(home);
  1364. SET_ITEM_WSTRLIST(nmodule_search_path, module_search_paths);
  1365. SET_ITEM_WSTR(executable);
  1366. SET_ITEM_WSTR(prefix);
  1367. SET_ITEM_WSTR(base_prefix);
  1368. SET_ITEM_WSTR(exec_prefix);
  1369. SET_ITEM_WSTR(base_exec_prefix);
  1370. #ifdef MS_WINDOWS
  1371. SET_ITEM_WSTR(dll_path);
  1372. #endif
  1373. SET_ITEM_INT(site_import);
  1374. SET_ITEM_INT(bytes_warning);
  1375. SET_ITEM_INT(inspect);
  1376. SET_ITEM_INT(interactive);
  1377. SET_ITEM_INT(optimization_level);
  1378. SET_ITEM_INT(parser_debug);
  1379. SET_ITEM_INT(write_bytecode);
  1380. SET_ITEM_INT(verbose);
  1381. SET_ITEM_INT(quiet);
  1382. SET_ITEM_INT(user_site_directory);
  1383. SET_ITEM_INT(buffered_stdio);
  1384. SET_ITEM_STR(stdio_encoding);
  1385. SET_ITEM_STR(stdio_errors);
  1386. #ifdef MS_WINDOWS
  1387. SET_ITEM_INT(legacy_windows_stdio);
  1388. #endif
  1389. SET_ITEM_INT(skip_source_first_line);
  1390. SET_ITEM_WSTR(run_command);
  1391. SET_ITEM_WSTR(run_module);
  1392. SET_ITEM_WSTR(run_filename);
  1393. SET_ITEM_INT(_install_importlib);
  1394. SET_ITEM_STR(_check_hash_pycs_mode);
  1395. SET_ITEM_INT(_frozen);
  1396. return dict;
  1397. fail:
  1398. Py_DECREF(dict);
  1399. return NULL;
  1400. #undef FROM_STRING
  1401. #undef FROM_WSTRING
  1402. #undef SET_ITEM
  1403. #undef SET_ITEM_INT
  1404. #undef SET_ITEM_UINT
  1405. #undef SET_ITEM_STR
  1406. #undef SET_ITEM_WSTR
  1407. #undef SET_ITEM_WSTRLIST
  1408. }
  1409. /* --- _PyCmdline ------------------------------------------------- */
  1410. typedef struct {
  1411. const _PyArgv *args;
  1412. int argc;
  1413. wchar_t **argv;
  1414. int nwarnoption; /* Number of -W command line options */
  1415. wchar_t **warnoptions; /* Command line -W options */
  1416. int nenv_warnoption; /* Number of PYTHONWARNINGS environment variables */
  1417. wchar_t **env_warnoptions; /* PYTHONWARNINGS environment variables */
  1418. int print_help; /* -h, -? options */
  1419. int print_version; /* -V option */
  1420. } _PyCmdline;
  1421. static void
  1422. cmdline_clear(_PyCmdline *cmdline)
  1423. {
  1424. _Py_wstrlist_clear(cmdline->nwarnoption, cmdline->warnoptions);
  1425. cmdline->nwarnoption = 0;
  1426. cmdline->warnoptions = NULL;
  1427. _Py_wstrlist_clear(cmdline->nenv_warnoption, cmdline->env_warnoptions);
  1428. cmdline->nenv_warnoption = 0;
  1429. cmdline->env_warnoptions = NULL;
  1430. if (cmdline->args->use_bytes_argv && cmdline->argv != NULL) {
  1431. _Py_wstrlist_clear(cmdline->args->argc, cmdline->argv);
  1432. }
  1433. cmdline->argv = NULL;
  1434. }
  1435. /* --- _PyCoreConfig command line parser -------------------------- */
  1436. /* Parse the command line arguments */
  1437. static _PyInitError
  1438. config_parse_cmdline(_PyCoreConfig *config, _PyCmdline *cmdline,
  1439. int *need_usage)
  1440. {
  1441. _PyInitError err;
  1442. _PyOS_ResetGetOpt();
  1443. do {
  1444. int longindex = -1;
  1445. int c = _PyOS_GetOpt(cmdline->args->argc, cmdline->argv, &longindex);
  1446. if (c == EOF) {
  1447. break;
  1448. }
  1449. if (c == 'c') {
  1450. /* -c is the last option; following arguments
  1451. that look like options are left for the
  1452. command to interpret. */
  1453. size_t len = wcslen(_PyOS_optarg) + 1 + 1;
  1454. wchar_t *command = PyMem_RawMalloc(sizeof(wchar_t) * len);
  1455. if (command == NULL) {
  1456. return _Py_INIT_NO_MEMORY();
  1457. }
  1458. memcpy(command, _PyOS_optarg, (len - 2) * sizeof(wchar_t));
  1459. command[len - 2] = '\n';
  1460. command[len - 1] = 0;
  1461. config->run_command = command;
  1462. break;
  1463. }
  1464. if (c == 'm') {
  1465. /* -m is the last option; following arguments
  1466. that look like options are left for the
  1467. module to interpret. */
  1468. config->run_module = _PyMem_RawWcsdup(_PyOS_optarg);
  1469. if (config->run_module == NULL) {
  1470. return _Py_INIT_NO_MEMORY();
  1471. }
  1472. break;
  1473. }
  1474. switch (c) {
  1475. case 0:
  1476. // Handle long option.
  1477. assert(longindex == 0); // Only one long option now.
  1478. if (!wcscmp(_PyOS_optarg, L"always")) {
  1479. config->_check_hash_pycs_mode = "always";
  1480. } else if (!wcscmp(_PyOS_optarg, L"never")) {
  1481. config->_check_hash_pycs_mode = "never";
  1482. } else if (!wcscmp(_PyOS_optarg, L"default")) {
  1483. config->_check_hash_pycs_mode = "default";
  1484. } else {
  1485. fprintf(stderr, "--check-hash-based-pycs must be one of "
  1486. "'default', 'always', or 'never'\n");
  1487. *need_usage = 1;
  1488. return _Py_INIT_OK();
  1489. }
  1490. break;
  1491. case 'b':
  1492. config->bytes_warning++;
  1493. break;
  1494. case 'd':
  1495. config->parser_debug++;
  1496. break;
  1497. case 'i':
  1498. config->inspect++;
  1499. config->interactive++;
  1500. break;
  1501. case 'E':
  1502. case 'I':
  1503. /* option handled by _PyPreConfig_ReadFromArgv() */
  1504. break;
  1505. /* case 'J': reserved for Jython */
  1506. case 'O':
  1507. config->optimization_level++;
  1508. break;
  1509. case 'B':
  1510. config->write_bytecode = 0;
  1511. break;
  1512. case 's':
  1513. config->user_site_directory = 0;
  1514. break;
  1515. case 'S':
  1516. config->site_import = 0;
  1517. break;
  1518. case 't':
  1519. /* ignored for backwards compatibility */
  1520. break;
  1521. case 'u':
  1522. config->buffered_stdio = 0;
  1523. break;
  1524. case 'v':
  1525. config->verbose++;
  1526. break;
  1527. case 'x':
  1528. config->skip_source_first_line = 1;
  1529. break;
  1530. case 'h':
  1531. case '?':
  1532. cmdline->print_help++;
  1533. break;
  1534. case 'V':
  1535. cmdline->print_version++;
  1536. break;
  1537. case 'W':
  1538. err = _Py_wstrlist_append(&cmdline->nwarnoption,
  1539. &cmdline->warnoptions,
  1540. _PyOS_optarg);
  1541. if (_Py_INIT_FAILED(err)) {
  1542. return err;
  1543. }
  1544. break;
  1545. case 'X':
  1546. err = _Py_wstrlist_append(&config->nxoption,
  1547. &config->xoptions,
  1548. _PyOS_optarg);
  1549. if (_Py_INIT_FAILED(err)) {
  1550. return err;
  1551. }
  1552. break;
  1553. case 'q':
  1554. config->quiet++;
  1555. break;
  1556. case 'R':
  1557. config->use_hash_seed = 0;
  1558. break;
  1559. /* This space reserved for other options */
  1560. default:
  1561. /* unknown argument: parsing failed */
  1562. *need_usage = 1;
  1563. return _Py_INIT_OK();
  1564. }
  1565. } while (1);
  1566. if (config->run_command == NULL && config->run_module == NULL
  1567. && _PyOS_optind < cmdline->args->argc
  1568. && wcscmp(cmdline->argv[_PyOS_optind], L"-") != 0)
  1569. {
  1570. config->run_filename = _PyMem_RawWcsdup(cmdline->argv[_PyOS_optind]);
  1571. if (config->run_filename == NULL) {
  1572. return _Py_INIT_NO_MEMORY();
  1573. }
  1574. }
  1575. if (config->run_command != NULL || config->run_module != NULL) {
  1576. /* Backup _PyOS_optind */
  1577. _PyOS_optind--;
  1578. }
  1579. /* -c and -m options are exclusive */
  1580. assert(!(config->run_command != NULL && config->run_module != NULL));
  1581. return _Py_INIT_OK();
  1582. }
  1583. #ifdef MS_WINDOWS
  1584. # define WCSTOK wcstok_s
  1585. #else
  1586. # define WCSTOK wcstok
  1587. #endif
  1588. /* Get warning options from PYTHONWARNINGS environment variable. */
  1589. static _PyInitError
  1590. cmdline_init_env_warnoptions(_PyCmdline *cmdline, const _PyCoreConfig *config)
  1591. {
  1592. wchar_t *env;
  1593. int res = _PyCoreConfig_GetEnvDup(config, &env,
  1594. L"PYTHONWARNINGS", "PYTHONWARNINGS");
  1595. if (res < 0) {
  1596. return DECODE_LOCALE_ERR("PYTHONWARNINGS", res);
  1597. }
  1598. if (env == NULL) {
  1599. return _Py_INIT_OK();
  1600. }
  1601. wchar_t *warning, *context = NULL;
  1602. for (warning = WCSTOK(env, L",", &context);
  1603. warning != NULL;
  1604. warning = WCSTOK(NULL, L",", &context))
  1605. {
  1606. _PyInitError err = _Py_wstrlist_append(&cmdline->nenv_warnoption,
  1607. &cmdline->env_warnoptions,
  1608. warning);
  1609. if (_Py_INIT_FAILED(err)) {
  1610. PyMem_RawFree(env);
  1611. return err;
  1612. }
  1613. }
  1614. PyMem_RawFree(env);
  1615. return _Py_INIT_OK();
  1616. }
  1617. static _PyInitError
  1618. config_init_program(_PyCoreConfig *config, const _PyCmdline *cmdline)
  1619. {
  1620. wchar_t *program;
  1621. if (cmdline->args->argc >= 1 && cmdline->argv != NULL) {
  1622. program = cmdline->argv[0];
  1623. }
  1624. else {
  1625. program = L"";
  1626. }
  1627. config->program = _PyMem_RawWcsdup(program);
  1628. if (config->program == NULL) {
  1629. return _Py_INIT_NO_MEMORY();
  1630. }
  1631. return _Py_INIT_OK();
  1632. }
  1633. static _PyInitError
  1634. config_add_warnings_optlist(_PyCoreConfig *config,
  1635. int len, wchar_t * const *options)
  1636. {
  1637. for (int i = 0; i < len; i++) {
  1638. _PyInitError err = _Py_wstrlist_append(&config->nwarnoption,
  1639. &config->warnoptions,
  1640. options[i]);
  1641. if (_Py_INIT_FAILED(err)) {
  1642. return err;
  1643. }
  1644. }
  1645. return _Py_INIT_OK();
  1646. }
  1647. static _PyInitError
  1648. config_init_warnoptions(_PyCoreConfig *config, const _PyCmdline *cmdline)
  1649. {
  1650. _PyInitError err;
  1651. assert(config->nwarnoption == 0);
  1652. /* The priority order for warnings configuration is (highest precedence
  1653. * first):
  1654. *
  1655. * - the BytesWarning filter, if needed ('-b', '-bb')
  1656. * - any '-W' command line options; then
  1657. * - the 'PYTHONWARNINGS' environment variable; then
  1658. * - the dev mode filter ('-X dev', 'PYTHONDEVMODE'); then
  1659. * - any implicit filters added by _warnings.c/warnings.py
  1660. *
  1661. * All settings except the last are passed to the warnings module via
  1662. * the `sys.warnoptions` list. Since the warnings module works on the basis
  1663. * of "the most recently added filter will be checked first", we add
  1664. * the lowest precedence entries first so that later entries override them.
  1665. */
  1666. if (config->preconfig.dev_mode) {
  1667. err = _Py_wstrlist_append(&config->nwarnoption,
  1668. &config->warnoptions,
  1669. L"default");
  1670. if (_Py_INIT_FAILED(err)) {
  1671. return err;
  1672. }
  1673. }
  1674. err = config_add_warnings_optlist(config,
  1675. cmdline->nenv_warnoption,
  1676. cmdline->env_warnoptions);
  1677. if (_Py_INIT_FAILED(err)) {
  1678. return err;
  1679. }
  1680. err = config_add_warnings_optlist(config,
  1681. cmdline->nwarnoption,
  1682. cmdline->warnoptions);
  1683. if (_Py_INIT_FAILED(err)) {
  1684. return err;
  1685. }
  1686. /* If the bytes_warning_flag isn't set, bytesobject.c and bytearrayobject.c
  1687. * don't even try to emit a warning, so we skip setting the filter in that
  1688. * case.
  1689. */
  1690. if (config->bytes_warning) {
  1691. wchar_t *filter;
  1692. if (config->bytes_warning> 1) {
  1693. filter = L"error::BytesWarning";
  1694. }
  1695. else {
  1696. filter = L"default::BytesWarning";
  1697. }
  1698. err = _Py_wstrlist_append(&config->nwarnoption,
  1699. &config->warnoptions,
  1700. filter);
  1701. if (_Py_INIT_FAILED(err)) {
  1702. return err;
  1703. }
  1704. }
  1705. return _Py_INIT_OK();
  1706. }
  1707. static _PyInitError
  1708. config_init_argv(_PyCoreConfig *config, const _PyCmdline *cmdline)
  1709. {
  1710. /* Copy argv to be able to modify it (to force -c/-m) */
  1711. int argc = cmdline->args->argc - _PyOS_optind;
  1712. wchar_t **argv;
  1713. if (argc <= 0 || cmdline->argv == NULL) {
  1714. /* Ensure at least one (empty) argument is seen */
  1715. static wchar_t *empty_argv[1] = {L""};
  1716. argc = 1;
  1717. argv = _Py_wstrlist_copy(1, empty_argv);
  1718. }
  1719. else {
  1720. argv = _Py_wstrlist_copy(argc, &cmdline->argv[_PyOS_optind]);
  1721. }
  1722. if (argv == NULL) {
  1723. return _Py_INIT_NO_MEMORY();
  1724. }
  1725. wchar_t *arg0 = NULL;
  1726. if (config->run_command != NULL) {
  1727. /* Force sys.argv[0] = '-c' */
  1728. arg0 = L"-c";
  1729. }
  1730. else if (config->run_module != NULL) {
  1731. /* Force sys.argv[0] = '-m'*/
  1732. arg0 = L"-m";
  1733. }
  1734. if (arg0 != NULL) {
  1735. arg0 = _PyMem_RawWcsdup(arg0);
  1736. if (arg0 == NULL) {
  1737. _Py_wstrlist_clear(argc, argv);
  1738. return _Py_INIT_NO_MEMORY();
  1739. }
  1740. assert(argc >= 1);
  1741. PyMem_RawFree(argv[0]);
  1742. argv[0] = arg0;
  1743. }
  1744. config->argc = argc;
  1745. config->argv = argv;
  1746. return _Py_INIT_OK();
  1747. }
  1748. static void
  1749. config_usage(int error, const wchar_t* program)
  1750. {
  1751. FILE *f = error ? stderr : stdout;
  1752. fprintf(f, usage_line, program);
  1753. if (error)
  1754. fprintf(f, "Try `python -h' for more information.\n");
  1755. else {
  1756. fputs(usage_1, f);
  1757. fputs(usage_2, f);
  1758. fputs(usage_3, f);
  1759. fprintf(f, usage_4, (wint_t)DELIM);
  1760. fprintf(f, usage_5, (wint_t)DELIM, PYTHONHOMEHELP);
  1761. fputs(usage_6, f);
  1762. }
  1763. }
  1764. /* Parse command line options and environment variables. */
  1765. static _PyInitError
  1766. config_from_cmdline(_PyCoreConfig *config, _PyCmdline *cmdline,
  1767. const _PyPreConfig *preconfig)
  1768. {
  1769. int need_usage = 0;
  1770. _PyInitError err;
  1771. err = config_init_program(config, cmdline);
  1772. if (_Py_INIT_FAILED(err)) {
  1773. return err;
  1774. }
  1775. err = config_parse_cmdline(config, cmdline, &need_usage);
  1776. if (_Py_INIT_FAILED(err)) {
  1777. return err;
  1778. }
  1779. if (need_usage) {
  1780. config_usage(1, config->program);
  1781. return _Py_INIT_EXIT(2);
  1782. }
  1783. if (cmdline->print_help) {
  1784. config_usage(0, config->program);
  1785. return _Py_INIT_EXIT(0);
  1786. }
  1787. if (cmdline->print_version) {
  1788. printf("Python %s\n",
  1789. (cmdline->print_version >= 2) ? Py_GetVersion() : PY_VERSION);
  1790. return _Py_INIT_EXIT(0);
  1791. }
  1792. err = config_init_argv(config, cmdline);
  1793. if (_Py_INIT_FAILED(err)) {
  1794. return err;
  1795. }
  1796. err = _PyCoreConfig_Read(config, preconfig);
  1797. if (_Py_INIT_FAILED(err)) {
  1798. return err;
  1799. }
  1800. if (config->preconfig.use_environment) {
  1801. err = cmdline_init_env_warnoptions(cmdline, config);
  1802. if (_Py_INIT_FAILED(err)) {
  1803. return err;
  1804. }
  1805. }
  1806. err = config_init_warnoptions(config, cmdline);
  1807. if (_Py_INIT_FAILED(err)) {
  1808. return err;
  1809. }
  1810. if (_Py_SetArgcArgv(cmdline->args->argc, cmdline->argv) < 0) {
  1811. return _Py_INIT_NO_MEMORY();
  1812. }
  1813. return _Py_INIT_OK();
  1814. }
  1815. /* Read the configuration into _PyCoreConfig from:
  1816. * Command line arguments
  1817. * Environment variables
  1818. * Py_xxx global configuration variables */
  1819. _PyInitError
  1820. _PyCoreConfig_ReadFromArgv(_PyCoreConfig *config, const _PyArgv *args,
  1821. const _PyPreConfig *preconfig)
  1822. {
  1823. _PyInitError err;
  1824. _PyCmdline cmdline;
  1825. memset(&cmdline, 0, sizeof(cmdline));
  1826. cmdline.args = args;
  1827. err = _PyArgv_Decode(cmdline.args, &cmdline.argv);
  1828. if (_Py_INIT_FAILED(err)) {
  1829. goto done;
  1830. }
  1831. err = config_from_cmdline(config, &cmdline, preconfig);
  1832. if (_Py_INIT_FAILED(err)) {
  1833. goto done;
  1834. }
  1835. err = _Py_INIT_OK();
  1836. done:
  1837. cmdline_clear(&cmdline);
  1838. return err;
  1839. }