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.

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