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.

2158 lines
61 KiB

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