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.

2111 lines
59 KiB

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