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.

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