Coverage Report

Created: 2026-02-26 06:53

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Python/initconfig.c
Line
Count
Source
1
#include "Python.h"
2
#include "pycore_fileutils.h"     // _Py_HasFileSystemDefaultEncodeErrors
3
#include "pycore_getopt.h"        // _PyOS_GetOpt()
4
#include "pycore_initconfig.h"    // _PyStatus_OK()
5
#include "pycore_interp.h"        // _PyInterpreterState.runtime
6
#include "pycore_long.h"          // _PY_LONG_MAX_STR_DIGITS_THRESHOLD
7
#include "pycore_pathconfig.h"    // _Py_path_config
8
#include "pycore_pyerrors.h"      // _PyErr_GetRaisedException()
9
#include "pycore_pylifecycle.h"   // _Py_PreInitializeFromConfig()
10
#include "pycore_pymem.h"         // _PyMem_DefaultRawMalloc()
11
#include "pycore_pyhash.h"        // _Py_HashSecret
12
#include "pycore_pystate.h"       // _PyThreadState_GET()
13
#include "pycore_pystats.h"       // _Py_StatsOn()
14
#include "pycore_sysmodule.h"     // _PySys_SetIntMaxStrDigits()
15
16
#include "osdefs.h"               // DELIM
17
18
#include <locale.h>               // setlocale()
19
#include <stdlib.h>               // getenv()
20
#if defined(MS_WINDOWS) || defined(__CYGWIN__)
21
#  ifdef HAVE_IO_H
22
#    include <io.h>
23
#  endif
24
#  ifdef HAVE_FCNTL_H
25
#    include <fcntl.h>            // O_BINARY
26
#  endif
27
#endif
28
29
#ifdef __APPLE__
30
/* Enable system log by default on non-macOS Apple platforms */
31
#  if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
32
#define USE_SYSTEM_LOGGER_DEFAULT 1;
33
#  else
34
#define USE_SYSTEM_LOGGER_DEFAULT 0;
35
#  endif
36
#endif
37
38
#include "config_common.h"
39
40
/* --- PyConfig setters ------------------------------------------- */
41
42
typedef PyObject* (*config_sys_flag_setter) (int value);
43
44
static PyObject*
45
config_sys_flag_long(int value)
46
0
{
47
0
    return PyLong_FromLong(value);
48
0
}
49
50
static PyObject*
51
config_sys_flag_not(int value)
52
0
{
53
0
    value = (!value);
54
0
    return config_sys_flag_long(value);
55
0
}
56
57
/* --- PyConfig spec ---------------------------------------------- */
58
59
typedef enum {
60
    PyConfig_MEMBER_INT = 0,
61
    PyConfig_MEMBER_UINT = 1,
62
    PyConfig_MEMBER_ULONG = 2,
63
    PyConfig_MEMBER_BOOL = 3,
64
65
    PyConfig_MEMBER_WSTR = 10,
66
    PyConfig_MEMBER_WSTR_OPT = 11,
67
    PyConfig_MEMBER_WSTR_LIST = 12,
68
} PyConfigMemberType;
69
70
typedef enum {
71
    // Option which cannot be get or set by PyConfig_Get() and PyConfig_Set()
72
    PyConfig_MEMBER_INIT_ONLY = 0,
73
74
    // Option which cannot be set by PyConfig_Set()
75
    PyConfig_MEMBER_READ_ONLY = 1,
76
77
    // Public option: can be get and set by PyConfig_Get() and PyConfig_Set()
78
    PyConfig_MEMBER_PUBLIC = 2,
79
} PyConfigMemberVisibility;
80
81
typedef struct {
82
    const char *attr;
83
    int flag_index;
84
    config_sys_flag_setter flag_setter;
85
} PyConfigSysSpec;
86
87
typedef struct {
88
    const char *name;
89
    size_t offset;
90
    PyConfigMemberType type;
91
    PyConfigMemberVisibility visibility;
92
    PyConfigSysSpec sys;
93
} PyConfigSpec;
94
95
#define SPEC(MEMBER, TYPE, VISIBILITY, sys) \
96
    {#MEMBER, offsetof(PyConfig, MEMBER), \
97
     PyConfig_MEMBER_##TYPE, PyConfig_MEMBER_##VISIBILITY, sys}
98
99
#define SYS_ATTR(name) {name, -1, NULL}
100
#define SYS_FLAG_SETTER(index, setter) {NULL, index, setter}
101
#define SYS_FLAG(index) SYS_FLAG_SETTER(index, NULL)
102
#define NO_SYS SYS_ATTR(NULL)
103
104
// Update _test_embed_set_config when adding new members
105
static const PyConfigSpec PYCONFIG_SPEC[] = {
106
    // --- Public options -----------
107
108
    SPEC(argv, WSTR_LIST, PUBLIC, SYS_ATTR("argv")),
109
    SPEC(base_exec_prefix, WSTR_OPT, PUBLIC, SYS_ATTR("base_exec_prefix")),
110
    SPEC(base_executable, WSTR_OPT, PUBLIC, SYS_ATTR("_base_executable")),
111
    SPEC(base_prefix, WSTR_OPT, PUBLIC, SYS_ATTR("base_prefix")),
112
    SPEC(bytes_warning, UINT, PUBLIC, SYS_FLAG(9)),
113
    SPEC(cpu_count, INT, PUBLIC, NO_SYS),
114
    SPEC(lazy_imports, INT, PUBLIC, NO_SYS),
115
    SPEC(exec_prefix, WSTR_OPT, PUBLIC, SYS_ATTR("exec_prefix")),
116
    SPEC(executable, WSTR_OPT, PUBLIC, SYS_ATTR("executable")),
117
    SPEC(inspect, BOOL, PUBLIC, SYS_FLAG(1)),
118
    SPEC(int_max_str_digits, UINT, PUBLIC, NO_SYS),
119
    SPEC(interactive, BOOL, PUBLIC, SYS_FLAG(2)),
120
    SPEC(module_search_paths, WSTR_LIST, PUBLIC, SYS_ATTR("path")),
121
    SPEC(optimization_level, UINT, PUBLIC, SYS_FLAG(3)),
122
    SPEC(parser_debug, BOOL, PUBLIC, SYS_FLAG(0)),
123
    SPEC(platlibdir, WSTR, PUBLIC, SYS_ATTR("platlibdir")),
124
    SPEC(prefix, WSTR_OPT, PUBLIC, SYS_ATTR("prefix")),
125
    SPEC(pycache_prefix, WSTR_OPT, PUBLIC, SYS_ATTR("pycache_prefix")),
126
    SPEC(quiet, BOOL, PUBLIC, SYS_FLAG(10)),
127
    SPEC(stdlib_dir, WSTR_OPT, PUBLIC, SYS_ATTR("_stdlib_dir")),
128
    SPEC(use_environment, BOOL, PUBLIC, SYS_FLAG_SETTER(7, config_sys_flag_not)),
129
    SPEC(verbose, UINT, PUBLIC, SYS_FLAG(8)),
130
    SPEC(warnoptions, WSTR_LIST, PUBLIC, SYS_ATTR("warnoptions")),
131
    SPEC(write_bytecode, BOOL, PUBLIC, SYS_FLAG_SETTER(4, config_sys_flag_not)),
132
    SPEC(xoptions, WSTR_LIST, PUBLIC, SYS_ATTR("_xoptions")),
133
134
    // --- Read-only options -----------
135
136
#ifdef Py_STATS
137
    SPEC(_pystats, BOOL, READ_ONLY, NO_SYS),
138
#endif
139
    SPEC(buffered_stdio, BOOL, READ_ONLY, NO_SYS),
140
    SPEC(check_hash_pycs_mode, WSTR, READ_ONLY, NO_SYS),
141
    SPEC(code_debug_ranges, BOOL, READ_ONLY, NO_SYS),
142
    SPEC(configure_c_stdio, BOOL, READ_ONLY, NO_SYS),
143
    SPEC(dev_mode, BOOL, READ_ONLY, NO_SYS),  // sys.flags.dev_mode
144
    SPEC(dump_refs, BOOL, READ_ONLY, NO_SYS),
145
    SPEC(dump_refs_file, WSTR_OPT, READ_ONLY, NO_SYS),
146
#ifdef Py_GIL_DISABLED
147
    SPEC(enable_gil, INT, READ_ONLY, NO_SYS),
148
    SPEC(tlbc_enabled, INT, READ_ONLY, NO_SYS),
149
#endif
150
    SPEC(faulthandler, BOOL, READ_ONLY, NO_SYS),
151
    SPEC(filesystem_encoding, WSTR, READ_ONLY, NO_SYS),
152
    SPEC(filesystem_errors, WSTR, READ_ONLY, NO_SYS),
153
    SPEC(hash_seed, ULONG, READ_ONLY, NO_SYS),
154
    SPEC(home, WSTR_OPT, READ_ONLY, NO_SYS),
155
    SPEC(thread_inherit_context, INT, READ_ONLY, NO_SYS),
156
    SPEC(context_aware_warnings, INT, READ_ONLY, NO_SYS),
157
    SPEC(import_time, UINT, READ_ONLY, NO_SYS),
158
    SPEC(install_signal_handlers, BOOL, READ_ONLY, NO_SYS),
159
    SPEC(isolated, BOOL, READ_ONLY, NO_SYS),  // sys.flags.isolated
160
#ifdef MS_WINDOWS
161
    SPEC(legacy_windows_stdio, BOOL, READ_ONLY, NO_SYS),
162
#endif
163
    SPEC(malloc_stats, BOOL, READ_ONLY, NO_SYS),
164
    SPEC(pymalloc_hugepages, BOOL, READ_ONLY, NO_SYS),
165
    SPEC(orig_argv, WSTR_LIST, READ_ONLY, SYS_ATTR("orig_argv")),
166
    SPEC(parse_argv, BOOL, READ_ONLY, NO_SYS),
167
    SPEC(pathconfig_warnings, BOOL, READ_ONLY, NO_SYS),
168
    SPEC(perf_profiling, UINT, READ_ONLY, NO_SYS),
169
    SPEC(remote_debug, BOOL, READ_ONLY, NO_SYS),
170
    SPEC(program_name, WSTR, READ_ONLY, NO_SYS),
171
    SPEC(run_command, WSTR_OPT, READ_ONLY, NO_SYS),
172
    SPEC(run_filename, WSTR_OPT, READ_ONLY, NO_SYS),
173
    SPEC(run_module, WSTR_OPT, READ_ONLY, NO_SYS),
174
#ifdef Py_DEBUG
175
    SPEC(run_presite, WSTR_OPT, READ_ONLY, NO_SYS),
176
#endif
177
    SPEC(safe_path, BOOL, READ_ONLY, NO_SYS),
178
    SPEC(show_ref_count, BOOL, READ_ONLY, NO_SYS),
179
    SPEC(site_import, BOOL, READ_ONLY, NO_SYS),  // sys.flags.no_site
180
    SPEC(skip_source_first_line, BOOL, READ_ONLY, NO_SYS),
181
    SPEC(stdio_encoding, WSTR, READ_ONLY, NO_SYS),
182
    SPEC(stdio_errors, WSTR, READ_ONLY, NO_SYS),
183
    SPEC(tracemalloc, UINT, READ_ONLY, NO_SYS),
184
    SPEC(use_frozen_modules, BOOL, READ_ONLY, NO_SYS),
185
    SPEC(use_hash_seed, BOOL, READ_ONLY, NO_SYS),
186
#ifdef __APPLE__
187
    SPEC(use_system_logger, BOOL, READ_ONLY, NO_SYS),
188
#endif
189
    SPEC(user_site_directory, BOOL, READ_ONLY, NO_SYS),  // sys.flags.no_user_site
190
    SPEC(warn_default_encoding, BOOL, READ_ONLY, NO_SYS),
191
192
    // --- Init-only options -----------
193
194
    SPEC(_config_init, UINT, INIT_ONLY, NO_SYS),
195
    SPEC(_init_main, BOOL, INIT_ONLY, NO_SYS),
196
    SPEC(_install_importlib, BOOL, INIT_ONLY, NO_SYS),
197
    SPEC(_is_python_build, BOOL, INIT_ONLY, NO_SYS),
198
    SPEC(module_search_paths_set, BOOL, INIT_ONLY, NO_SYS),
199
    SPEC(pythonpath_env, WSTR_OPT, INIT_ONLY, NO_SYS),
200
    SPEC(sys_path_0, WSTR_OPT, INIT_ONLY, NO_SYS),
201
202
    // Array terminator
203
    {NULL, 0, 0, 0, NO_SYS},
204
};
205
206
#undef SPEC
207
#define SPEC(MEMBER, TYPE, VISIBILITY) \
208
    {#MEMBER, offsetof(PyPreConfig, MEMBER), PyConfig_MEMBER_##TYPE, \
209
     PyConfig_MEMBER_##VISIBILITY, NO_SYS}
210
211
static const PyConfigSpec PYPRECONFIG_SPEC[] = {
212
    // --- Read-only options -----------
213
214
    SPEC(allocator, INT, READ_ONLY),
215
    SPEC(coerce_c_locale, BOOL, READ_ONLY),
216
    SPEC(coerce_c_locale_warn, BOOL, READ_ONLY),
217
    SPEC(configure_locale, BOOL, READ_ONLY),
218
#ifdef MS_WINDOWS
219
    SPEC(legacy_windows_fs_encoding, BOOL, READ_ONLY),
220
#endif
221
    SPEC(utf8_mode, BOOL, READ_ONLY),
222
223
    // --- Init-only options -----------
224
    // Members already present in PYCONFIG_SPEC
225
226
    SPEC(_config_init, INT, INIT_ONLY),
227
    SPEC(dev_mode, BOOL, INIT_ONLY),
228
    SPEC(isolated, BOOL, INIT_ONLY),
229
    SPEC(parse_argv, BOOL, INIT_ONLY),
230
    SPEC(use_environment, BOOL, INIT_ONLY),
231
232
    // Array terminator
233
    {NULL, 0, 0, 0, NO_SYS},
234
};
235
236
#undef SPEC
237
#undef SYS_ATTR
238
#undef SYS_FLAG_SETTER
239
#undef SYS_FLAG
240
#undef NO_SYS
241
242
243
// Forward declarations
244
static PyObject* config_get(const PyConfig *config, const PyConfigSpec *spec,
245
                            int use_sys);
246
static void initconfig_free_wstr(wchar_t *member);
247
static void initconfig_free_wstr_list(PyWideStringList *list);
248
static void initconfig_free_config(const PyConfig *config);
249
250
251
/* --- Command line options --------------------------------------- */
252
253
/* Short usage message (with %s for argv0) */
254
static const char usage_line[] =
255
"usage: %ls [option] ... [-c cmd | -m mod | file | -] [arg] ...\n";
256
257
/* Long help message */
258
/* Lines sorted by option name; keep in sync with usage_envvars* below */
259
static const char usage_help[] = "\
260
Options (and corresponding environment variables):\n\
261
-b     : issue warnings about converting bytes/bytearray to str and comparing\n\
262
         bytes/bytearray with str or bytes with int. (-bb: issue errors)\n\
263
         deprecated since 3.15 and will become no-op in 3.17.\n\
264
-B     : don't write .pyc files on import; also PYTHONDONTWRITEBYTECODE=x\n\
265
-c cmd : program passed in as string (terminates option list)\n\
266
-d     : turn on parser debugging output (for experts only, only works on\n\
267
         debug builds); also PYTHONDEBUG=x\n\
268
-E     : ignore PYTHON* environment variables (such as PYTHONPATH)\n\
269
-h     : print this help message and exit (also -? or --help)\n\
270
-i     : inspect interactively after running script; forces a prompt even\n\
271
         if stdin does not appear to be a terminal; also PYTHONINSPECT=x\n\
272
-I     : isolate Python from the user's environment (implies -E, -P and -s)\n\
273
-m mod : run library module as a script (terminates option list)\n\
274
-O     : remove assert and __debug__-dependent statements; add .opt-1 before\n\
275
         .pyc extension; also PYTHONOPTIMIZE=x\n\
276
-OO    : do -O changes and also discard docstrings; add .opt-2 before\n\
277
         .pyc extension\n\
278
-P     : don't prepend a potentially unsafe path to sys.path; also\n\
279
         PYTHONSAFEPATH\n\
280
-q     : don't print version and copyright messages on interactive startup\n\
281
-s     : don't add user site directory to sys.path; also PYTHONNOUSERSITE=x\n\
282
-S     : don't imply 'import site' on initialization\n\
283
-u     : force the stdout and stderr streams to be unbuffered;\n\
284
         this option has no effect on stdin; also PYTHONUNBUFFERED=x\n\
285
-v     : verbose (trace import statements); also PYTHONVERBOSE=x\n\
286
         can be supplied multiple times to increase verbosity\n\
287
-V     : print the Python version number and exit (also --version)\n\
288
         when given twice, print more information about the build\n\
289
-W arg : warning control; arg is action:message:category:module:lineno\n\
290
         also PYTHONWARNINGS=arg\n\
291
-x     : skip first line of source, allowing use of non-Unix forms of #!cmd\n\
292
-X opt : set implementation-specific option\n\
293
--check-hash-based-pycs always|default|never:\n\
294
         control how Python invalidates hash-based .pyc files\n\
295
--help-env: print help about Python environment variables and exit\n\
296
--help-xoptions: print help about implementation-specific -X options and exit\n\
297
--help-all: print complete help information and exit\n\
298
\n\
299
Arguments:\n\
300
file   : program read from script file\n\
301
-      : program read from stdin (default; interactive mode if a tty)\n\
302
arg ...: arguments passed to program in sys.argv[1:]\n\
303
";
304
305
static const char usage_xoptions[] = "\
306
The following implementation-specific options are available:\n\
307
-X cpu_count=N: override the return value of os.cpu_count();\n\
308
         -X cpu_count=default cancels overriding; also PYTHON_CPU_COUNT\n\
309
-X dev : enable Python Development Mode; also PYTHONDEVMODE\n\
310
-X faulthandler: dump the Python traceback on fatal errors;\n\
311
         also PYTHONFAULTHANDLER\n\
312
-X frozen_modules=[on|off]: whether to use frozen modules; the default is \"on\"\n\
313
         for installed Python and \"off\" for a local build;\n\
314
         also PYTHON_FROZEN_MODULES\n\
315
"
316
#ifdef Py_GIL_DISABLED
317
"-X gil=[0|1]: enable (1) or disable (0) the GIL; also PYTHON_GIL\n"
318
#endif
319
"\
320
-X importtime[=2]: show how long each import takes; use -X importtime=2 to\n\
321
         log imports of already-loaded modules; also PYTHONPROFILEIMPORTTIME\n\
322
-X lazy_imports=[all|none|normal]: control global lazy imports;\n\
323
         default is normal; also PYTHON_LAZY_IMPORTS\n\
324
-X int_max_str_digits=N: limit the size of int<->str conversions;\n\
325
         0 disables the limit; also PYTHONINTMAXSTRDIGITS\n\
326
-X no_debug_ranges: don't include extra location information in code objects;\n\
327
         also PYTHONNODEBUGRANGES\n\
328
-X perf: support the Linux \"perf\" profiler; also PYTHONPERFSUPPORT=1\n\
329
-X perf_jit: support the Linux \"perf\" profiler with DWARF support;\n\
330
         also PYTHON_PERF_JIT_SUPPORT=1\n\
331
-X disable-remote-debug: disable remote debugging; also PYTHON_DISABLE_REMOTE_DEBUG\n\
332
"
333
#ifdef Py_DEBUG
334
"-X presite=MOD: import this module before site; also PYTHON_PRESITE\n"
335
#endif
336
"\
337
-X pycache_prefix=PATH: write .pyc files to a parallel tree instead of to the\n\
338
         code tree; also PYTHONPYCACHEPREFIX\n\
339
"
340
#ifdef Py_STATS
341
"-X pystats: enable pystats collection at startup; also PYTHONSTATS\n"
342
#endif
343
"\
344
-X showrefcount: output the total reference count and number of used\n\
345
         memory blocks when the program finishes or after each statement in\n\
346
         the interactive interpreter; only works on debug builds\n"
347
#ifdef Py_GIL_DISABLED
348
"-X tlbc=[0|1]: enable (1) or disable (0) thread-local bytecode. Also\n\
349
         PYTHON_TLBC\n"
350
#endif
351
"\
352
-X thread_inherit_context=[0|1]: enable (1) or disable (0) threads inheriting\n\
353
         context vars by default; enabled by default in the free-threaded\n\
354
         build and disabled otherwise; also PYTHON_THREAD_INHERIT_CONTEXT\n\
355
-X context_aware_warnings=[0|1]: if true (1) then the warnings module will\n\
356
         use a context variables; if false (0) then the warnings module will\n\
357
         use module globals, which is not concurrent-safe; set to true for\n\
358
         free-threaded builds and false otherwise; also\n\
359
         PYTHON_CONTEXT_AWARE_WARNINGS\n\
360
-X tracemalloc[=N]: trace Python memory allocations; N sets a traceback limit\n \
361
         of N frames (default: 1); also PYTHONTRACEMALLOC=N\n\
362
-X utf8[=0|1]: enable (1) or disable (0) UTF-8 mode; also PYTHONUTF8\n\
363
-X warn_default_encoding: enable opt-in EncodingWarning for 'encoding=None';\n\
364
         also PYTHONWARNDEFAULTENCODING\
365
";
366
367
/* Envvars that don't have equivalent command-line options are listed first */
368
static const char usage_envvars[] =
369
"Environment variables that change behavior:\n"
370
"PYTHONSTARTUP   : file executed on interactive startup (no default)\n"
371
"PYTHONPATH      : '%lc'-separated list of directories prefixed to the\n"
372
"                  default module search path.  The result is sys.path.\n"
373
"PYTHONHOME      : alternate <prefix> directory (or <prefix>%lc<exec_prefix>).\n"
374
"                  The default module search path uses %s.\n"
375
"PYTHONPLATLIBDIR: override sys.platlibdir\n"
376
"PYTHONCASEOK    : ignore case in 'import' statements (Windows)\n"
377
"PYTHONIOENCODING: encoding[:errors] used for stdin/stdout/stderr\n"
378
"PYTHONHASHSEED  : if this variable is set to 'random', a random value is used\n"
379
"                  to seed the hashes of str and bytes objects.  It can also be\n"
380
"                  set to an integer in the range [0,4294967295] to get hash\n"
381
"                  values with a predictable seed.\n"
382
"PYTHONMALLOC    : set the Python memory allocators and/or install debug hooks\n"
383
"                  on Python memory allocators.  Use PYTHONMALLOC=debug to\n"
384
"                  install debug hooks.\n"
385
"PYTHONMALLOCSTATS: print memory allocator statistics\n"
386
"PYTHONCOERCECLOCALE: if this variable is set to 0, it disables the locale\n"
387
"                  coercion behavior.  Use PYTHONCOERCECLOCALE=warn to request\n"
388
"                  display of locale coercion and locale compatibility warnings\n"
389
"                  on stderr.\n"
390
"PYTHONBREAKPOINT: if this variable is set to 0, it disables the default\n"
391
"                  debugger.  It can be set to the callable of your debugger of\n"
392
"                  choice.\n"
393
"PYTHON_COLORS   : if this variable is set to 1, the interpreter will colorize\n"
394
"                  various kinds of output.  Setting it to 0 deactivates\n"
395
"                  this behavior.\n"
396
"PYTHON_HISTORY  : the location of a .python_history file.\n"
397
"PYTHONASYNCIODEBUG: enable asyncio debug mode\n"
398
#ifdef Py_TRACE_REFS
399
"PYTHONDUMPREFS  : dump objects and reference counts still alive after shutdown\n"
400
"PYTHONDUMPREFSFILE: dump objects and reference counts to the specified file\n"
401
#endif
402
#ifdef __APPLE__
403
"PYTHONEXECUTABLE: set sys.argv[0] to this value (macOS only)\n"
404
#endif
405
#ifdef MS_WINDOWS
406
"PYTHONLEGACYWINDOWSFSENCODING: use legacy \"mbcs\" encoding for file system\n"
407
"PYTHONLEGACYWINDOWSSTDIO: use legacy Windows stdio\n"
408
#endif
409
"PYTHONUSERBASE  : defines the user base directory (site.USER_BASE)\n"
410
"PYTHON_BASIC_REPL: use the traditional parser-based REPL\n"
411
"\n"
412
"These variables have equivalent command-line options (see --help for details):\n"
413
"PYTHON_CPU_COUNT: override the return value of os.cpu_count() (-X cpu_count)\n"
414
"PYTHONDEBUG     : enable parser debug mode (-d)\n"
415
"PYTHONDEVMODE   : enable Python Development Mode (-X dev)\n"
416
"PYTHONDONTWRITEBYTECODE: don't write .pyc files (-B)\n"
417
"PYTHONFAULTHANDLER: dump the Python traceback on fatal errors (-X faulthandler)\n"
418
"PYTHON_FROZEN_MODULES: whether to use frozen modules; the default is \"on\"\n"
419
"                  for installed Python and \"off\" for a local build\n"
420
"                  (-X frozen_modules)\n"
421
#ifdef Py_GIL_DISABLED
422
"PYTHON_GIL      : when set to 0, disables the GIL (-X gil)\n"
423
#endif
424
"PYTHONINSPECT   : inspect interactively after running script (-i)\n"
425
"PYTHONINTMAXSTRDIGITS: limit the size of int<->str conversions;\n"
426
"                  0 disables the limit (-X int_max_str_digits=N)\n"
427
"PYTHONNODEBUGRANGES: don't include extra location information in code objects\n"
428
"                  (-X no_debug_ranges)\n"
429
"PYTHONNOUSERSITE: disable user site directory (-s)\n"
430
"PYTHONOPTIMIZE  : enable level 1 optimizations (-O)\n"
431
"PYTHONPERFSUPPORT: support the Linux \"perf\" profiler (-X perf)\n"
432
"PYTHON_PERF_JIT_SUPPORT: enable Linux \"perf\" profiler support with JIT\n"
433
"                  (-X perf_jit)\n"
434
#ifdef Py_DEBUG
435
"PYTHON_PRESITE: import this module before site (-X presite)\n"
436
#endif
437
"PYTHONPROFILEIMPORTTIME: show how long each import takes (-X importtime)\n"
438
"PYTHON_LAZY_IMPORTS: control global lazy imports (-X lazy_imports)\n"
439
"PYTHONPYCACHEPREFIX: root directory for bytecode cache (pyc) files\n"
440
"                  (-X pycache_prefix)\n"
441
"PYTHONSAFEPATH  : don't prepend a potentially unsafe path to sys.path.\n"
442
#ifdef Py_STATS
443
"PYTHONSTATS     : turns on statistics gathering (-X pystats)\n"
444
#endif
445
#ifdef Py_GIL_DISABLED
446
"PYTHON_TLBC     : when set to 0, disables thread-local bytecode (-X tlbc)\n"
447
#endif
448
"PYTHON_THREAD_INHERIT_CONTEXT: if true (1), threads inherit context vars\n"
449
"                   (-X thread_inherit_context)\n"
450
"PYTHON_CONTEXT_AWARE_WARNINGS: if true (1), enable thread-safe warnings module\n"
451
"                   behaviour (-X context_aware_warnings)\n"
452
"PYTHONTRACEMALLOC: trace Python memory allocations (-X tracemalloc)\n"
453
"PYTHONUNBUFFERED: disable stdout/stderr buffering (-u)\n"
454
"PYTHONUTF8      : control the UTF-8 mode (-X utf8)\n"
455
"PYTHONVERBOSE   : trace import statements (-v)\n"
456
"PYTHONWARNDEFAULTENCODING: enable opt-in EncodingWarning for 'encoding=None'\n"
457
"                  (-X warn_default_encoding)\n"
458
"PYTHONWARNINGS  : warning control (-W)\n"
459
;
460
461
#if defined(MS_WINDOWS)
462
#  define PYTHONHOMEHELP "<prefix>\\python{major}{minor}"
463
#else
464
0
#  define PYTHONHOMEHELP "<prefix>/lib/pythonX.X"
465
#endif
466
467
468
/* --- Global configuration variables ----------------------------- */
469
470
/* UTF-8 mode (PEP 540): if equal to 1, use the UTF-8 encoding, and change
471
   stdin and stdout error handler to "surrogateescape". */
472
int Py_UTF8Mode = 0;
473
int Py_DebugFlag = 0; /* Needed by parser.c */
474
int Py_VerboseFlag = 0; /* Needed by import.c */
475
int Py_QuietFlag = 0; /* Needed by sysmodule.c */
476
int Py_InteractiveFlag = 0; /* Previously, was used by Py_FdIsInteractive() */
477
int Py_InspectFlag = 0; /* Needed to determine whether to exit at SystemExit */
478
int Py_OptimizeFlag = 0; /* Needed by compile.c */
479
int Py_NoSiteFlag = 0; /* Suppress 'import site' */
480
int Py_BytesWarningFlag = 0; /* Warn on str(bytes) and str(buffer) */
481
int Py_FrozenFlag = 0; /* Needed by getpath.c */
482
int Py_IgnoreEnvironmentFlag = 0; /* e.g. PYTHONPATH, PYTHONHOME */
483
int Py_DontWriteBytecodeFlag = 0; /* Suppress writing bytecode files (*.pyc) */
484
int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
485
int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
486
int Py_HashRandomizationFlag = 0; /* for -R and PYTHONHASHSEED */
487
int Py_IsolatedFlag = 0; /* for -I, isolate from user's env */
488
#ifdef MS_WINDOWS
489
int Py_LegacyWindowsFSEncodingFlag = 0; /* Uses mbcs instead of utf-8 */
490
int Py_LegacyWindowsStdioFlag = 0; /* Uses FileIO instead of WindowsConsoleIO */
491
#endif
492
493
494
static PyObject *
495
_Py_GetGlobalVariablesAsDict(void)
496
0
{
497
0
_Py_COMP_DIAG_PUSH
498
0
_Py_COMP_DIAG_IGNORE_DEPR_DECLS
499
0
    PyObject *dict, *obj;
500
501
0
    dict = PyDict_New();
502
0
    if (dict == NULL) {
503
0
        return NULL;
504
0
    }
505
506
0
#define SET_ITEM(KEY, EXPR) \
507
0
        do { \
508
0
            obj = (EXPR); \
509
0
            if (obj == NULL) { \
510
0
                return NULL; \
511
0
            } \
512
0
            int res = PyDict_SetItemString(dict, (KEY), obj); \
513
0
            Py_DECREF(obj); \
514
0
            if (res < 0) { \
515
0
                goto fail; \
516
0
            } \
517
0
        } while (0)
518
0
#define SET_ITEM_INT(VAR) \
519
0
    SET_ITEM(#VAR, PyLong_FromLong(VAR))
520
0
#define FROM_STRING(STR) \
521
0
    ((STR != NULL) ? \
522
0
        PyUnicode_FromString(STR) \
523
0
        : Py_NewRef(Py_None))
524
0
#define SET_ITEM_STR(VAR) \
525
0
    SET_ITEM(#VAR, FROM_STRING(VAR))
526
527
0
    SET_ITEM_STR(Py_FileSystemDefaultEncoding);
528
0
    SET_ITEM_INT(Py_HasFileSystemDefaultEncoding);
529
0
    SET_ITEM_STR(Py_FileSystemDefaultEncodeErrors);
530
0
    SET_ITEM_INT(_Py_HasFileSystemDefaultEncodeErrors);
531
532
0
    SET_ITEM_INT(Py_UTF8Mode);
533
0
    SET_ITEM_INT(Py_DebugFlag);
534
0
    SET_ITEM_INT(Py_VerboseFlag);
535
0
    SET_ITEM_INT(Py_QuietFlag);
536
0
    SET_ITEM_INT(Py_InteractiveFlag);
537
0
    SET_ITEM_INT(Py_InspectFlag);
538
539
0
    SET_ITEM_INT(Py_OptimizeFlag);
540
0
    SET_ITEM_INT(Py_NoSiteFlag);
541
0
    SET_ITEM_INT(Py_BytesWarningFlag);
542
0
    SET_ITEM_INT(Py_FrozenFlag);
543
0
    SET_ITEM_INT(Py_IgnoreEnvironmentFlag);
544
0
    SET_ITEM_INT(Py_DontWriteBytecodeFlag);
545
0
    SET_ITEM_INT(Py_NoUserSiteDirectory);
546
0
    SET_ITEM_INT(Py_UnbufferedStdioFlag);
547
0
    SET_ITEM_INT(Py_HashRandomizationFlag);
548
0
    SET_ITEM_INT(Py_IsolatedFlag);
549
550
#ifdef MS_WINDOWS
551
    SET_ITEM_INT(Py_LegacyWindowsFSEncodingFlag);
552
    SET_ITEM_INT(Py_LegacyWindowsStdioFlag);
553
#endif
554
555
0
    return dict;
556
557
0
fail:
558
0
    Py_DECREF(dict);
559
0
    return NULL;
560
561
0
#undef FROM_STRING
562
0
#undef SET_ITEM
563
0
#undef SET_ITEM_INT
564
0
#undef SET_ITEM_STR
565
0
_Py_COMP_DIAG_POP
566
0
}
567
568
char*
569
Py_GETENV(const char *name)
570
288
{
571
288
_Py_COMP_DIAG_PUSH
572
288
_Py_COMP_DIAG_IGNORE_DEPR_DECLS
573
288
    if (Py_IgnoreEnvironmentFlag) {
574
0
        return NULL;
575
0
    }
576
288
    return getenv(name);
577
288
_Py_COMP_DIAG_POP
578
288
}
579
580
/* --- PyStatus ----------------------------------------------- */
581
582
PyStatus PyStatus_Ok(void)
583
96
{ return _PyStatus_OK(); }
584
585
PyStatus PyStatus_Error(const char *err_msg)
586
0
{
587
0
    assert(err_msg != NULL);
588
0
    return (PyStatus){._type = _PyStatus_TYPE_ERROR,
589
0
                      .err_msg = err_msg};
590
0
}
591
592
PyStatus PyStatus_NoMemory(void)
593
0
{ return PyStatus_Error("memory allocation failed"); }
594
595
PyStatus PyStatus_Exit(int exitcode)
596
0
{ return _PyStatus_EXIT(exitcode); }
597
598
599
int PyStatus_IsError(PyStatus status)
600
0
{ return _PyStatus_IS_ERROR(status); }
601
602
int PyStatus_IsExit(PyStatus status)
603
0
{ return _PyStatus_IS_EXIT(status); }
604
605
int PyStatus_Exception(PyStatus status)
606
0
{ return _PyStatus_EXCEPTION(status); }
607
608
void
609
_PyErr_SetFromPyStatus(PyStatus status)
610
0
{
611
0
    if (!_PyStatus_IS_ERROR(status)) {
612
0
        PyErr_Format(PyExc_SystemError,
613
0
                     "_PyErr_SetFromPyStatus() status is not an error");
614
0
        return;
615
0
    }
616
617
0
    const char *err_msg = status.err_msg;
618
0
    if (err_msg == NULL || strlen(err_msg) == 0) {
619
0
        PyErr_Format(PyExc_SystemError,
620
0
                     "_PyErr_SetFromPyStatus() status has no error message");
621
0
        return;
622
0
    }
623
624
0
    if (strcmp(err_msg, _PyStatus_NO_MEMORY_ERRMSG) == 0) {
625
0
        PyErr_NoMemory();
626
0
        return;
627
0
    }
628
629
0
    const char *func = status.func;
630
0
    if (func) {
631
0
        PyErr_Format(PyExc_RuntimeError, "%s: %s", func, err_msg);
632
0
    }
633
0
    else {
634
0
        PyErr_Format(PyExc_RuntimeError, "%s", err_msg);
635
0
    }
636
0
}
637
638
639
/* --- PyWideStringList ------------------------------------------------ */
640
641
#ifndef NDEBUG
642
int
643
_PyWideStringList_CheckConsistency(const PyWideStringList *list)
644
{
645
    assert(list->length >= 0);
646
    if (list->length != 0) {
647
        assert(list->items != NULL);
648
    }
649
    for (Py_ssize_t i = 0; i < list->length; i++) {
650
        assert(list->items[i] != NULL);
651
    }
652
    return 1;
653
}
654
#endif   /* Py_DEBUG */
655
656
657
static void
658
_PyWideStringList_ClearEx(PyWideStringList *list,
659
                          bool use_default_allocator)
660
1.60k
{
661
1.60k
    assert(_PyWideStringList_CheckConsistency(list));
662
1.79k
    for (Py_ssize_t i=0; i < list->length; i++) {
663
192
        if (use_default_allocator) {
664
0
            _PyMem_DefaultRawFree(list->items[i]);
665
0
        }
666
192
        else {
667
192
            PyMem_RawFree(list->items[i]);
668
192
        }
669
192
    }
670
1.60k
    if (use_default_allocator) {
671
32
        _PyMem_DefaultRawFree(list->items);
672
32
    }
673
1.56k
    else {
674
1.56k
        PyMem_RawFree(list->items);
675
1.56k
    }
676
1.60k
    list->length = 0;
677
1.60k
    list->items = NULL;
678
1.60k
}
679
680
void
681
_PyWideStringList_Clear(PyWideStringList *list)
682
1.05k
{
683
1.05k
    _PyWideStringList_ClearEx(list, false);
684
1.05k
}
685
686
static int
687
_PyWideStringList_CopyEx(PyWideStringList *list,
688
                         const PyWideStringList *list2,
689
                         bool use_default_allocator)
690
544
{
691
544
    assert(_PyWideStringList_CheckConsistency(list));
692
544
    assert(_PyWideStringList_CheckConsistency(list2));
693
694
544
    if (list2->length == 0) {
695
448
        _PyWideStringList_ClearEx(list, use_default_allocator);
696
448
        return 0;
697
448
    }
698
699
96
    PyWideStringList copy = _PyWideStringList_INIT;
700
701
96
    size_t size = list2->length * sizeof(list2->items[0]);
702
96
    if (use_default_allocator) {
703
0
        copy.items = _PyMem_DefaultRawMalloc(size);
704
0
    }
705
96
    else {
706
96
        copy.items = PyMem_RawMalloc(size);
707
96
    }
708
96
    if (copy.items == NULL) {
709
0
        return -1;
710
0
    }
711
712
256
    for (Py_ssize_t i=0; i < list2->length; i++) {
713
160
        wchar_t *item;
714
160
        if (use_default_allocator) {
715
0
            item = _PyMem_DefaultRawWcsdup(list2->items[i]);
716
0
        }
717
160
        else {
718
160
            item = _PyMem_RawWcsdup(list2->items[i]);
719
160
        }
720
160
        if (item == NULL) {
721
0
            _PyWideStringList_ClearEx(&copy, use_default_allocator);
722
0
            return -1;
723
0
        }
724
160
        copy.items[i] = item;
725
160
        copy.length = i + 1;
726
160
    }
727
728
96
    _PyWideStringList_ClearEx(list, use_default_allocator);
729
96
    *list = copy;
730
96
    return 0;
731
96
}
732
733
int
734
_PyWideStringList_Copy(PyWideStringList *list, const PyWideStringList *list2)
735
512
{
736
512
    return _PyWideStringList_CopyEx(list, list2, false);
737
512
}
738
739
PyStatus
740
PyWideStringList_Insert(PyWideStringList *list,
741
                        Py_ssize_t index, const wchar_t *item)
742
160
{
743
160
    Py_ssize_t len = list->length;
744
160
    if (len == PY_SSIZE_T_MAX) {
745
        /* length+1 would overflow */
746
0
        return _PyStatus_NO_MEMORY();
747
0
    }
748
160
    if (index < 0) {
749
0
        return _PyStatus_ERR("PyWideStringList_Insert index must be >= 0");
750
0
    }
751
160
    if (index > len) {
752
0
        index = len;
753
0
    }
754
755
160
    wchar_t *item2 = _PyMem_RawWcsdup(item);
756
160
    if (item2 == NULL) {
757
0
        return _PyStatus_NO_MEMORY();
758
0
    }
759
760
160
    size_t size = (len + 1) * sizeof(list->items[0]);
761
160
    wchar_t **items2 = (wchar_t **)PyMem_RawRealloc(list->items, size);
762
160
    if (items2 == NULL) {
763
0
        PyMem_RawFree(item2);
764
0
        return _PyStatus_NO_MEMORY();
765
0
    }
766
767
160
    if (index < len) {
768
0
        memmove(&items2[index + 1],
769
0
                &items2[index],
770
0
                (len - index) * sizeof(items2[0]));
771
0
    }
772
773
160
    items2[index] = item2;
774
160
    list->items = items2;
775
160
    list->length++;
776
160
    return _PyStatus_OK();
777
160
}
778
779
780
PyStatus
781
PyWideStringList_Append(PyWideStringList *list, const wchar_t *item)
782
160
{
783
160
    return PyWideStringList_Insert(list, list->length, item);
784
160
}
785
786
787
PyStatus
788
_PyWideStringList_Extend(PyWideStringList *list, const PyWideStringList *list2)
789
64
{
790
64
    for (Py_ssize_t i = 0; i < list2->length; i++) {
791
0
        PyStatus status = PyWideStringList_Append(list, list2->items[i]);
792
0
        if (_PyStatus_EXCEPTION(status)) {
793
0
            return status;
794
0
        }
795
0
    }
796
64
    return _PyStatus_OK();
797
64
}
798
799
800
static int
801
_PyWideStringList_Find(PyWideStringList *list, const wchar_t *item)
802
0
{
803
0
    for (Py_ssize_t i = 0; i < list->length; i++) {
804
0
        if (wcscmp(list->items[i], item) == 0) {
805
0
            return 1;
806
0
        }
807
0
    }
808
0
    return 0;
809
0
}
810
811
812
PyObject*
813
_PyWideStringList_AsList(const PyWideStringList *list)
814
128
{
815
128
    assert(_PyWideStringList_CheckConsistency(list));
816
817
128
    PyObject *pylist = PyList_New(list->length);
818
128
    if (pylist == NULL) {
819
0
        return NULL;
820
0
    }
821
822
256
    for (Py_ssize_t i = 0; i < list->length; i++) {
823
128
        PyObject *item = PyUnicode_FromWideChar(list->items[i], -1);
824
128
        if (item == NULL) {
825
0
            Py_DECREF(pylist);
826
0
            return NULL;
827
0
        }
828
128
        PyList_SET_ITEM(pylist, i, item);
829
128
    }
830
128
    return pylist;
831
128
}
832
833
834
static PyObject*
835
_PyWideStringList_AsTuple(const PyWideStringList *list)
836
128
{
837
128
    assert(_PyWideStringList_CheckConsistency(list));
838
839
128
    PyObject *tuple = PyTuple_New(list->length);
840
128
    if (tuple == NULL) {
841
0
        return NULL;
842
0
    }
843
844
160
    for (Py_ssize_t i = 0; i < list->length; i++) {
845
32
        PyObject *item = PyUnicode_FromWideChar(list->items[i], -1);
846
32
        if (item == NULL) {
847
0
            Py_DECREF(tuple);
848
0
            return NULL;
849
0
        }
850
32
        PyTuple_SET_ITEM(tuple, i, item);
851
32
    }
852
128
    return tuple;
853
128
}
854
855
856
/* --- Py_GetArgcArgv() ------------------------------------------- */
857
858
void
859
_Py_ClearArgcArgv(void)
860
0
{
861
0
    _PyWideStringList_ClearEx(&_PyRuntime.orig_argv, true);
862
0
}
863
864
865
static int
866
_Py_SetArgcArgv(Py_ssize_t argc, wchar_t * const *argv)
867
32
{
868
32
    const PyWideStringList argv_list = {.length = argc, .items = (wchar_t **)argv};
869
870
    // XXX _PyRuntime.orig_argv only gets cleared by Py_Main(),
871
    // so it currently leaks for embedders.
872
32
    return _PyWideStringList_CopyEx(&_PyRuntime.orig_argv, &argv_list, true);
873
32
}
874
875
876
// _PyConfig_Write() calls _Py_SetArgcArgv() with PyConfig.orig_argv.
877
void
878
Py_GetArgcArgv(int *argc, wchar_t ***argv)
879
0
{
880
0
    *argc = (int)_PyRuntime.orig_argv.length;
881
0
    *argv = _PyRuntime.orig_argv.items;
882
0
}
883
884
885
/* --- PyConfig ---------------------------------------------- */
886
887
32
#define MAX_HASH_SEED 4294967295UL
888
889
890
#ifndef NDEBUG
891
static int
892
config_check_consistency(const PyConfig *config)
893
{
894
    /* Check config consistency */
895
    assert(config->isolated >= 0);
896
    assert(config->use_environment >= 0);
897
    assert(config->dev_mode >= 0);
898
    assert(config->install_signal_handlers >= 0);
899
    assert(config->use_hash_seed >= 0);
900
    assert(config->hash_seed <= MAX_HASH_SEED);
901
    assert(config->faulthandler >= 0);
902
    assert(config->tracemalloc >= 0);
903
    assert(config->import_time >= 0);
904
    assert(config->code_debug_ranges >= 0);
905
    assert(config->show_ref_count >= 0);
906
    assert(config->dump_refs >= 0);
907
    assert(config->malloc_stats >= 0);
908
    assert(config->pymalloc_hugepages >= 0);
909
    assert(config->site_import >= 0);
910
    assert(config->bytes_warning >= 0);
911
    assert(config->warn_default_encoding >= 0);
912
    assert(config->inspect >= 0);
913
    assert(config->interactive >= 0);
914
    assert(config->optimization_level >= 0);
915
    assert(config->parser_debug >= 0);
916
    assert(config->write_bytecode >= 0);
917
    assert(config->verbose >= 0);
918
    assert(config->quiet >= 0);
919
    assert(config->user_site_directory >= 0);
920
    assert(config->parse_argv >= 0);
921
    assert(config->configure_c_stdio >= 0);
922
    assert(config->buffered_stdio >= 0);
923
    assert(_PyWideStringList_CheckConsistency(&config->orig_argv));
924
    assert(_PyWideStringList_CheckConsistency(&config->argv));
925
    /* sys.argv must be non-empty: empty argv is replaced with [''] */
926
    assert(config->argv.length >= 1);
927
    assert(_PyWideStringList_CheckConsistency(&config->xoptions));
928
    assert(_PyWideStringList_CheckConsistency(&config->warnoptions));
929
    assert(_PyWideStringList_CheckConsistency(&config->module_search_paths));
930
    assert(config->module_search_paths_set >= 0);
931
    assert(config->filesystem_encoding != NULL);
932
    assert(config->filesystem_errors != NULL);
933
    assert(config->stdio_encoding != NULL);
934
    assert(config->stdio_errors != NULL);
935
#ifdef MS_WINDOWS
936
    assert(config->legacy_windows_stdio >= 0);
937
#endif
938
    /* -c and -m options are exclusive */
939
    assert(!(config->run_command != NULL && config->run_module != NULL));
940
    assert(config->check_hash_pycs_mode != NULL);
941
    assert(config->_install_importlib >= 0);
942
    assert(config->pathconfig_warnings >= 0);
943
    assert(config->_is_python_build >= 0);
944
    assert(config->safe_path >= 0);
945
    assert(config->int_max_str_digits >= 0);
946
    // cpu_count can be -1 if the user doesn't override it.
947
    assert(config->cpu_count != 0);
948
    // lazy_imports can be -1 (default), 0 (off), or 1 (on).
949
    assert(config->lazy_imports >= -1 && config->lazy_imports <= 1);
950
    // config->use_frozen_modules is initialized later
951
    // by _PyConfig_InitImportConfig().
952
    assert(config->thread_inherit_context >= 0);
953
    assert(config->context_aware_warnings >= 0);
954
#ifdef __APPLE__
955
    assert(config->use_system_logger >= 0);
956
#endif
957
#ifdef Py_STATS
958
    assert(config->_pystats >= 0);
959
#endif
960
    return 1;
961
}
962
#endif
963
964
965
/* Free memory allocated in config, but don't clear all attributes */
966
void
967
PyConfig_Clear(PyConfig *config)
968
128
{
969
128
#define CLEAR(ATTR) \
970
2.68k
    do { \
971
2.68k
        PyMem_RawFree(ATTR); \
972
2.68k
        ATTR = NULL; \
973
2.68k
    } while (0)
974
975
128
    CLEAR(config->pycache_prefix);
976
128
    CLEAR(config->pythonpath_env);
977
128
    CLEAR(config->home);
978
128
    CLEAR(config->program_name);
979
980
128
    _PyWideStringList_Clear(&config->argv);
981
128
    _PyWideStringList_Clear(&config->warnoptions);
982
128
    _PyWideStringList_Clear(&config->xoptions);
983
128
    _PyWideStringList_Clear(&config->module_search_paths);
984
128
    config->module_search_paths_set = 0;
985
128
    CLEAR(config->stdlib_dir);
986
987
128
    CLEAR(config->executable);
988
128
    CLEAR(config->base_executable);
989
128
    CLEAR(config->prefix);
990
128
    CLEAR(config->base_prefix);
991
128
    CLEAR(config->exec_prefix);
992
128
    CLEAR(config->base_exec_prefix);
993
128
    CLEAR(config->platlibdir);
994
128
    CLEAR(config->sys_path_0);
995
996
128
    CLEAR(config->filesystem_encoding);
997
128
    CLEAR(config->filesystem_errors);
998
128
    CLEAR(config->stdio_encoding);
999
128
    CLEAR(config->stdio_errors);
1000
128
    CLEAR(config->run_command);
1001
128
    CLEAR(config->run_module);
1002
128
    CLEAR(config->run_filename);
1003
128
    CLEAR(config->check_hash_pycs_mode);
1004
#ifdef Py_DEBUG
1005
    CLEAR(config->run_presite);
1006
#endif
1007
1008
128
    _PyWideStringList_Clear(&config->orig_argv);
1009
128
#undef CLEAR
1010
128
}
1011
1012
1013
void
1014
_PyConfig_InitCompatConfig(PyConfig *config)
1015
96
{
1016
96
    memset(config, 0, sizeof(*config));
1017
1018
96
    config->_config_init = (int)_PyConfig_INIT_COMPAT;
1019
96
    config->import_time = -1;
1020
96
    config->isolated = -1;
1021
96
    config->use_environment = -1;
1022
96
    config->dev_mode = -1;
1023
96
    config->install_signal_handlers = 1;
1024
96
    config->use_hash_seed = -1;
1025
96
    config->faulthandler = -1;
1026
96
    config->tracemalloc = -1;
1027
96
    config->perf_profiling = -1;
1028
96
    config->remote_debug = -1;
1029
96
    config->module_search_paths_set = 0;
1030
96
    config->parse_argv = 0;
1031
96
    config->site_import = -1;
1032
96
    config->bytes_warning = -1;
1033
96
    config->warn_default_encoding = 0;
1034
96
    config->inspect = -1;
1035
96
    config->interactive = -1;
1036
96
    config->optimization_level = -1;
1037
96
    config->parser_debug= -1;
1038
96
    config->write_bytecode = -1;
1039
96
    config->verbose = -1;
1040
96
    config->quiet = -1;
1041
96
    config->user_site_directory = -1;
1042
96
    config->configure_c_stdio = 0;
1043
96
    config->buffered_stdio = -1;
1044
96
    config->_install_importlib = 1;
1045
96
    config->check_hash_pycs_mode = NULL;
1046
96
    config->pathconfig_warnings = -1;
1047
96
    config->_init_main = 1;
1048
#ifdef MS_WINDOWS
1049
    config->legacy_windows_stdio = -1;
1050
#endif
1051
#ifdef Py_DEBUG
1052
    config->use_frozen_modules = 0;
1053
#else
1054
96
    config->use_frozen_modules = 1;
1055
96
#endif
1056
96
    config->safe_path = 0;
1057
96
    config->int_max_str_digits = -1;
1058
96
    config->_is_python_build = 0;
1059
96
    config->code_debug_ranges = 1;
1060
96
    config->cpu_count = -1;
1061
96
    config->lazy_imports = -1;
1062
#ifdef Py_GIL_DISABLED
1063
    config->thread_inherit_context = 1;
1064
    config->context_aware_warnings = 1;
1065
#else
1066
96
    config->thread_inherit_context = 0;
1067
96
    config->context_aware_warnings = 0;
1068
96
#endif
1069
#ifdef __APPLE__
1070
    config->use_system_logger = USE_SYSTEM_LOGGER_DEFAULT;
1071
#endif
1072
#ifdef Py_GIL_DISABLED
1073
    config->enable_gil = _PyConfig_GIL_DEFAULT;
1074
    config->tlbc_enabled = 1;
1075
#endif
1076
96
}
1077
1078
1079
static void
1080
config_init_defaults(PyConfig *config)
1081
64
{
1082
64
    _PyConfig_InitCompatConfig(config);
1083
1084
64
    config->isolated = 0;
1085
64
    config->use_environment = 1;
1086
64
    config->site_import = 1;
1087
64
    config->bytes_warning = 0;
1088
64
    config->inspect = 0;
1089
64
    config->interactive = 0;
1090
64
    config->optimization_level = 0;
1091
64
    config->parser_debug= 0;
1092
64
    config->write_bytecode = 1;
1093
64
    config->verbose = 0;
1094
64
    config->quiet = 0;
1095
64
    config->user_site_directory = 1;
1096
64
    config->buffered_stdio = 1;
1097
64
    config->pathconfig_warnings = 1;
1098
#ifdef MS_WINDOWS
1099
    config->legacy_windows_stdio = 0;
1100
#endif
1101
#ifdef Py_GIL_DISABLED
1102
    config->thread_inherit_context = 1;
1103
    config->context_aware_warnings = 1;
1104
#else
1105
64
    config->thread_inherit_context = 0;
1106
64
    config->context_aware_warnings = 0;
1107
64
#endif
1108
#ifdef __APPLE__
1109
    config->use_system_logger = USE_SYSTEM_LOGGER_DEFAULT;
1110
#endif
1111
64
}
1112
1113
1114
void
1115
PyConfig_InitPythonConfig(PyConfig *config)
1116
64
{
1117
64
    config_init_defaults(config);
1118
1119
64
    config->_config_init = (int)_PyConfig_INIT_PYTHON;
1120
64
    config->configure_c_stdio = 1;
1121
64
    config->parse_argv = 1;
1122
64
}
1123
1124
1125
void
1126
PyConfig_InitIsolatedConfig(PyConfig *config)
1127
0
{
1128
0
    config_init_defaults(config);
1129
1130
0
    config->_config_init = (int)_PyConfig_INIT_ISOLATED;
1131
0
    config->isolated = 1;
1132
0
    config->use_environment = 0;
1133
0
    config->user_site_directory = 0;
1134
0
    config->dev_mode = 0;
1135
0
    config->install_signal_handlers = 0;
1136
0
    config->use_hash_seed = 0;
1137
0
    config->tracemalloc = 0;
1138
0
    config->perf_profiling = 0;
1139
0
    config->int_max_str_digits = _PY_LONG_DEFAULT_MAX_STR_DIGITS;
1140
0
    config->safe_path = 1;
1141
0
    config->pathconfig_warnings = 0;
1142
#ifdef Py_GIL_DISABLED
1143
    config->thread_inherit_context = 1;
1144
#else
1145
0
    config->thread_inherit_context = 0;
1146
0
#endif
1147
#ifdef MS_WINDOWS
1148
    config->legacy_windows_stdio = 0;
1149
#endif
1150
#ifdef __APPLE__
1151
    config->use_system_logger = USE_SYSTEM_LOGGER_DEFAULT;
1152
#endif
1153
0
}
1154
1155
1156
/* Copy str into *config_str (duplicate the string) */
1157
PyStatus
1158
PyConfig_SetString(PyConfig *config, wchar_t **config_str, const wchar_t *str)
1159
2.27k
{
1160
2.27k
    PyStatus status = _Py_PreInitializeFromConfig(config, NULL);
1161
2.27k
    if (_PyStatus_EXCEPTION(status)) {
1162
0
        return status;
1163
0
    }
1164
1165
2.27k
    wchar_t *str2;
1166
2.27k
    if (str != NULL) {
1167
800
        str2 = _PyMem_RawWcsdup(str);
1168
800
        if (str2 == NULL) {
1169
0
            return _PyStatus_NO_MEMORY();
1170
0
        }
1171
800
    }
1172
1.47k
    else {
1173
1.47k
        str2 = NULL;
1174
1.47k
    }
1175
2.27k
    PyMem_RawFree(*config_str);
1176
2.27k
    *config_str = str2;
1177
2.27k
    return _PyStatus_OK();
1178
2.27k
}
1179
1180
1181
static PyStatus
1182
config_set_bytes_string(PyConfig *config, wchar_t **config_str,
1183
                        const char *str, const char *decode_err_msg)
1184
0
{
1185
0
    PyStatus status = _Py_PreInitializeFromConfig(config, NULL);
1186
0
    if (_PyStatus_EXCEPTION(status)) {
1187
0
        return status;
1188
0
    }
1189
1190
0
    wchar_t *str2;
1191
0
    if (str != NULL) {
1192
0
        size_t len;
1193
0
        str2 = Py_DecodeLocale(str, &len);
1194
0
        if (str2 == NULL) {
1195
0
            if (len == (size_t)-2) {
1196
0
                return _PyStatus_ERR(decode_err_msg);
1197
0
            }
1198
0
            else {
1199
0
                return  _PyStatus_NO_MEMORY();
1200
0
            }
1201
0
        }
1202
0
    }
1203
0
    else {
1204
0
        str2 = NULL;
1205
0
    }
1206
0
    PyMem_RawFree(*config_str);
1207
0
    *config_str = str2;
1208
0
    return _PyStatus_OK();
1209
0
}
1210
1211
1212
#define CONFIG_SET_BYTES_STR(config, config_str, str, NAME) \
1213
0
    config_set_bytes_string(config, config_str, str, "cannot decode " NAME)
1214
1215
1216
/* Decode str using Py_DecodeLocale() and set the result into *config_str.
1217
   Pre-initialize Python if needed to ensure that encodings are properly
1218
   configured. */
1219
PyStatus
1220
PyConfig_SetBytesString(PyConfig *config, wchar_t **config_str,
1221
                        const char *str)
1222
0
{
1223
0
    return CONFIG_SET_BYTES_STR(config, config_str, str, "string");
1224
0
}
1225
1226
1227
static inline void*
1228
config_get_spec_member(const PyConfig *config, const PyConfigSpec *spec)
1229
11.3k
{
1230
11.3k
    return (char *)config + spec->offset;
1231
11.3k
}
1232
1233
1234
static inline void*
1235
preconfig_get_spec_member(const PyPreConfig *preconfig, const PyConfigSpec *spec)
1236
0
{
1237
0
    return (char *)preconfig + spec->offset;
1238
0
}
1239
1240
1241
PyStatus
1242
_PyConfig_Copy(PyConfig *config, const PyConfig *config2)
1243
64
{
1244
64
    PyConfig_Clear(config);
1245
1246
64
    PyStatus status;
1247
64
    const PyConfigSpec *spec = PYCONFIG_SPEC;
1248
4.60k
    for (; spec->name != NULL; spec++) {
1249
4.54k
        void *member = config_get_spec_member(config, spec);
1250
4.54k
        const void *member2 = config_get_spec_member((PyConfig*)config2, spec);
1251
4.54k
        switch (spec->type) {
1252
256
        case PyConfig_MEMBER_INT:
1253
768
        case PyConfig_MEMBER_UINT:
1254
2.75k
        case PyConfig_MEMBER_BOOL:
1255
2.75k
        {
1256
2.75k
            *(int*)member = *(int*)member2;
1257
2.75k
            break;
1258
768
        }
1259
64
        case PyConfig_MEMBER_ULONG:
1260
64
        {
1261
64
            *(unsigned long*)member = *(unsigned long*)member2;
1262
64
            break;
1263
768
        }
1264
448
        case PyConfig_MEMBER_WSTR:
1265
1.40k
        case PyConfig_MEMBER_WSTR_OPT:
1266
1.40k
        {
1267
1.40k
            const wchar_t *str = *(const wchar_t**)member2;
1268
1.40k
            status = PyConfig_SetString(config, (wchar_t**)member, str);
1269
1.40k
            if (_PyStatus_EXCEPTION(status)) {
1270
0
                return status;
1271
0
            }
1272
1.40k
            break;
1273
1.40k
        }
1274
1.40k
        case PyConfig_MEMBER_WSTR_LIST:
1275
320
        {
1276
320
            if (_PyWideStringList_Copy((PyWideStringList*)member,
1277
320
                                       (const PyWideStringList*)member2) < 0) {
1278
0
                return _PyStatus_NO_MEMORY();
1279
0
            }
1280
320
            break;
1281
320
        }
1282
320
        default:
1283
0
            Py_UNREACHABLE();
1284
4.54k
        }
1285
4.54k
    }
1286
64
    return _PyStatus_OK();
1287
64
}
1288
1289
1290
PyObject *
1291
_PyConfig_AsDict(const PyConfig *config)
1292
32
{
1293
32
    PyObject *dict = PyDict_New();
1294
32
    if (dict == NULL) {
1295
0
        return NULL;
1296
0
    }
1297
1298
32
    const PyConfigSpec *spec = PYCONFIG_SPEC;
1299
2.30k
    for (; spec->name != NULL; spec++) {
1300
2.27k
        PyObject *obj = config_get(config, spec, 0);
1301
2.27k
        if (obj == NULL) {
1302
0
            Py_DECREF(dict);
1303
0
            return NULL;
1304
0
        }
1305
1306
2.27k
        int res = PyDict_SetItemString(dict, spec->name, obj);
1307
2.27k
        Py_DECREF(obj);
1308
2.27k
        if (res < 0) {
1309
0
            Py_DECREF(dict);
1310
0
            return NULL;
1311
0
        }
1312
2.27k
    }
1313
32
    return dict;
1314
32
}
1315
1316
1317
static void
1318
config_dict_invalid_value(const char *name)
1319
0
{
1320
0
    PyErr_Format(PyExc_ValueError, "invalid config value: %s", name);
1321
0
}
1322
1323
1324
static int
1325
config_dict_get_int(PyObject *dict, const char *name, int *result)
1326
1.37k
{
1327
1.37k
    PyObject *item = config_dict_get(dict, name);
1328
1.37k
    if (item == NULL) {
1329
0
        return -1;
1330
0
    }
1331
1.37k
    int value = PyLong_AsInt(item);
1332
1.37k
    Py_DECREF(item);
1333
1.37k
    if (value == -1 && PyErr_Occurred()) {
1334
0
        if (PyErr_ExceptionMatches(PyExc_TypeError)) {
1335
0
            config_dict_invalid_type(name);
1336
0
        }
1337
0
        else if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
1338
0
            config_dict_invalid_value(name);
1339
0
        }
1340
0
        return -1;
1341
0
    }
1342
1.37k
    *result = value;
1343
1.37k
    return 0;
1344
1.37k
}
1345
1346
1347
static int
1348
config_dict_get_ulong(PyObject *dict, const char *name, unsigned long *result)
1349
32
{
1350
32
    PyObject *item = config_dict_get(dict, name);
1351
32
    if (item == NULL) {
1352
0
        return -1;
1353
0
    }
1354
32
    unsigned long value = PyLong_AsUnsignedLong(item);
1355
32
    Py_DECREF(item);
1356
32
    if (value == (unsigned long)-1 && PyErr_Occurred()) {
1357
0
        if (PyErr_ExceptionMatches(PyExc_TypeError)) {
1358
0
            config_dict_invalid_type(name);
1359
0
        }
1360
0
        else if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
1361
0
            config_dict_invalid_value(name);
1362
0
        }
1363
0
        return -1;
1364
0
    }
1365
32
    *result = value;
1366
32
    return 0;
1367
32
}
1368
1369
1370
static int
1371
config_dict_get_wstr(PyObject *dict, const char *name, PyConfig *config,
1372
                     wchar_t **result)
1373
704
{
1374
704
    PyObject *item = config_dict_get(dict, name);
1375
704
    if (item == NULL) {
1376
0
        return -1;
1377
0
    }
1378
1379
704
    PyStatus status;
1380
704
    if (item == Py_None) {
1381
224
        status = PyConfig_SetString(config, result, NULL);
1382
224
    }
1383
480
    else if (!PyUnicode_Check(item)) {
1384
0
        config_dict_invalid_type(name);
1385
0
        goto error;
1386
0
    }
1387
480
    else {
1388
480
        wchar_t *wstr = PyUnicode_AsWideCharString(item, NULL);
1389
480
        if (wstr == NULL) {
1390
0
            goto error;
1391
0
        }
1392
480
        status = PyConfig_SetString(config, result, wstr);
1393
480
        PyMem_Free(wstr);
1394
480
    }
1395
704
    if (_PyStatus_EXCEPTION(status)) {
1396
0
        PyErr_NoMemory();
1397
0
        goto error;
1398
0
    }
1399
704
    Py_DECREF(item);
1400
704
    return 0;
1401
1402
0
error:
1403
0
    Py_DECREF(item);
1404
0
    return -1;
1405
704
}
1406
1407
1408
static int
1409
config_dict_get_wstrlist(PyObject *dict, const char *name, PyConfig *config,
1410
                         PyWideStringList *result)
1411
128
{
1412
128
    PyObject *list = config_dict_get(dict, name);
1413
128
    if (list == NULL) {
1414
0
        return -1;
1415
0
    }
1416
1417
128
    int is_list = PyList_CheckExact(list);
1418
128
    if (!is_list && !PyTuple_CheckExact(list)) {
1419
0
        Py_DECREF(list);
1420
0
        config_dict_invalid_type(name);
1421
0
        return -1;
1422
0
    }
1423
1424
128
    PyWideStringList wstrlist = _PyWideStringList_INIT;
1425
128
    Py_ssize_t len = is_list ? PyList_GET_SIZE(list) : PyTuple_GET_SIZE(list);
1426
256
    for (Py_ssize_t i=0; i < len; i++) {
1427
128
        PyObject *item = is_list ? PyList_GET_ITEM(list, i) : PyTuple_GET_ITEM(list, i);
1428
1429
128
        if (item == Py_None) {
1430
0
            config_dict_invalid_value(name);
1431
0
            goto error;
1432
0
        }
1433
128
        else if (!PyUnicode_Check(item)) {
1434
0
            config_dict_invalid_type(name);
1435
0
            goto error;
1436
0
        }
1437
128
        wchar_t *wstr = PyUnicode_AsWideCharString(item, NULL);
1438
128
        if (wstr == NULL) {
1439
0
            goto error;
1440
0
        }
1441
128
        PyStatus status = PyWideStringList_Append(&wstrlist, wstr);
1442
128
        PyMem_Free(wstr);
1443
128
        if (_PyStatus_EXCEPTION(status)) {
1444
0
            PyErr_NoMemory();
1445
0
            goto error;
1446
0
        }
1447
128
    }
1448
1449
128
    if (_PyWideStringList_Copy(result, &wstrlist) < 0) {
1450
0
        PyErr_NoMemory();
1451
0
        goto error;
1452
0
    }
1453
128
    _PyWideStringList_Clear(&wstrlist);
1454
128
    Py_DECREF(list);
1455
128
    return 0;
1456
1457
0
error:
1458
0
    _PyWideStringList_Clear(&wstrlist);
1459
0
    Py_DECREF(list);
1460
0
    return -1;
1461
128
}
1462
1463
1464
static int
1465
config_dict_get_xoptions(PyObject *dict, const char *name, PyConfig *config,
1466
                         PyWideStringList *result)
1467
32
{
1468
32
    PyObject *xoptions = config_dict_get(dict, name);
1469
32
    if (xoptions == NULL) {
1470
0
        return -1;
1471
0
    }
1472
1473
32
    if (!PyDict_CheckExact(xoptions)) {
1474
0
        Py_DECREF(xoptions);
1475
0
        config_dict_invalid_type(name);
1476
0
        return -1;
1477
0
    }
1478
1479
32
    Py_ssize_t pos = 0;
1480
32
    PyObject *key, *value;
1481
32
    PyWideStringList wstrlist = _PyWideStringList_INIT;
1482
32
    while (PyDict_Next(xoptions, &pos, &key, &value)) {
1483
0
        PyObject *item;
1484
1485
0
        if (value != Py_True) {
1486
0
            item = PyUnicode_FromFormat("%S=%S", key, value);
1487
0
            if (item == NULL) {
1488
0
                goto error;
1489
0
            }
1490
0
        }
1491
0
        else {
1492
0
            item = Py_NewRef(key);
1493
0
        }
1494
1495
0
        wchar_t *wstr = PyUnicode_AsWideCharString(item, NULL);
1496
0
        Py_DECREF(item);
1497
0
        if (wstr == NULL) {
1498
0
            goto error;
1499
0
        }
1500
1501
0
        PyStatus status = PyWideStringList_Append(&wstrlist, wstr);
1502
0
        PyMem_Free(wstr);
1503
0
        if (_PyStatus_EXCEPTION(status)) {
1504
0
            PyErr_NoMemory();
1505
0
            goto error;
1506
0
        }
1507
0
    }
1508
1509
32
    if (_PyWideStringList_Copy(result, &wstrlist) < 0) {
1510
0
        PyErr_NoMemory();
1511
0
        goto error;
1512
0
    }
1513
32
    _PyWideStringList_Clear(&wstrlist);
1514
32
    Py_DECREF(xoptions);
1515
32
    return 0;
1516
1517
0
error:
1518
0
    _PyWideStringList_Clear(&wstrlist);
1519
0
    Py_DECREF(xoptions);
1520
0
    return -1;
1521
32
}
1522
1523
1524
int
1525
_PyConfig_FromDict(PyConfig *config, PyObject *dict)
1526
32
{
1527
32
    if (!PyDict_Check(dict)) {
1528
0
        PyErr_SetString(PyExc_TypeError, "dict expected");
1529
0
        return -1;
1530
0
    }
1531
1532
32
    const PyConfigSpec *spec = PYCONFIG_SPEC;
1533
2.30k
    for (; spec->name != NULL; spec++) {
1534
2.27k
        char *member = (char *)config + spec->offset;
1535
2.27k
        switch (spec->type) {
1536
128
        case PyConfig_MEMBER_INT:
1537
384
        case PyConfig_MEMBER_UINT:
1538
1.37k
        case PyConfig_MEMBER_BOOL:
1539
1.37k
        {
1540
1.37k
            int value;
1541
1.37k
            if (config_dict_get_int(dict, spec->name, &value) < 0) {
1542
0
                return -1;
1543
0
            }
1544
1.37k
            if (spec->type == PyConfig_MEMBER_BOOL
1545
384
                || spec->type == PyConfig_MEMBER_UINT)
1546
1.24k
            {
1547
1.24k
                if (value < 0) {
1548
0
                    config_dict_invalid_value(spec->name);
1549
0
                    return -1;
1550
0
                }
1551
1.24k
            }
1552
1.37k
            *(int*)member = value;
1553
1.37k
            break;
1554
1.37k
        }
1555
32
        case PyConfig_MEMBER_ULONG:
1556
32
        {
1557
32
            if (config_dict_get_ulong(dict, spec->name,
1558
32
                                      (unsigned long*)member) < 0) {
1559
0
                return -1;
1560
0
            }
1561
32
            break;
1562
32
        }
1563
224
        case PyConfig_MEMBER_WSTR:
1564
224
        {
1565
224
            wchar_t **wstr = (wchar_t**)member;
1566
224
            if (config_dict_get_wstr(dict, spec->name, config, wstr) < 0) {
1567
0
                return -1;
1568
0
            }
1569
224
            if (*wstr == NULL) {
1570
0
                config_dict_invalid_value(spec->name);
1571
0
                return -1;
1572
0
            }
1573
224
            break;
1574
224
        }
1575
480
        case PyConfig_MEMBER_WSTR_OPT:
1576
480
        {
1577
480
            wchar_t **wstr = (wchar_t**)member;
1578
480
            if (config_dict_get_wstr(dict, spec->name, config, wstr) < 0) {
1579
0
                return -1;
1580
0
            }
1581
480
            break;
1582
480
        }
1583
480
        case PyConfig_MEMBER_WSTR_LIST:
1584
160
        {
1585
160
            if (strcmp(spec->name, "xoptions") == 0) {
1586
32
                if (config_dict_get_xoptions(dict, spec->name, config,
1587
32
                                             (PyWideStringList*)member) < 0) {
1588
0
                    return -1;
1589
0
                }
1590
32
            }
1591
128
            else {
1592
128
                if (config_dict_get_wstrlist(dict, spec->name, config,
1593
128
                                             (PyWideStringList*)member) < 0) {
1594
0
                    return -1;
1595
0
                }
1596
128
            }
1597
160
            break;
1598
160
        }
1599
160
        default:
1600
0
            Py_UNREACHABLE();
1601
2.27k
        }
1602
2.27k
    }
1603
1604
32
    if (!(config->_config_init == _PyConfig_INIT_COMPAT
1605
0
          || config->_config_init == _PyConfig_INIT_PYTHON
1606
0
          || config->_config_init == _PyConfig_INIT_ISOLATED))
1607
0
    {
1608
0
        config_dict_invalid_value("_config_init");
1609
0
        return -1;
1610
0
    }
1611
1612
32
    if (config->hash_seed > MAX_HASH_SEED) {
1613
0
        config_dict_invalid_value("hash_seed");
1614
0
        return -1;
1615
0
    }
1616
32
    return 0;
1617
32
}
1618
1619
1620
static const char*
1621
config_get_env(const PyConfig *config, const char *name)
1622
608
{
1623
608
    return _Py_GetEnv(config->use_environment, name);
1624
608
}
1625
1626
1627
/* Get a copy of the environment variable as wchar_t*.
1628
   Return 0 on success, but *dest can be NULL.
1629
   Return -1 on memory allocation failure. Return -2 on decoding error. */
1630
static PyStatus
1631
config_get_env_dup(PyConfig *config,
1632
                   wchar_t **dest,
1633
                   wchar_t *wname, char *name,
1634
                   const char *decode_err_msg)
1635
160
{
1636
160
    assert(*dest == NULL);
1637
160
    assert(config->use_environment >= 0);
1638
1639
160
    if (!config->use_environment) {
1640
0
        *dest = NULL;
1641
0
        return _PyStatus_OK();
1642
0
    }
1643
1644
#ifdef MS_WINDOWS
1645
    const wchar_t *var = _wgetenv(wname);
1646
    if (!var || var[0] == '\0') {
1647
        *dest = NULL;
1648
        return _PyStatus_OK();
1649
    }
1650
1651
    return PyConfig_SetString(config, dest, var);
1652
#else
1653
160
    const char *var = getenv(name);
1654
160
    if (!var || var[0] == '\0') {
1655
160
        *dest = NULL;
1656
160
        return _PyStatus_OK();
1657
160
    }
1658
1659
0
    return config_set_bytes_string(config, dest, var, decode_err_msg);
1660
160
#endif
1661
160
}
1662
1663
1664
#define CONFIG_GET_ENV_DUP(CONFIG, DEST, WNAME, NAME) \
1665
160
    config_get_env_dup(CONFIG, DEST, WNAME, NAME, "cannot decode " NAME)
1666
1667
1668
static void
1669
config_get_global_vars(PyConfig *config)
1670
32
{
1671
32
_Py_COMP_DIAG_PUSH
1672
32
_Py_COMP_DIAG_IGNORE_DEPR_DECLS
1673
32
    if (config->_config_init != _PyConfig_INIT_COMPAT) {
1674
        /* Python and Isolated configuration ignore global variables */
1675
0
        return;
1676
0
    }
1677
1678
32
#define COPY_FLAG(ATTR, VALUE) \
1679
256
        if (config->ATTR == -1) { \
1680
256
            config->ATTR = VALUE; \
1681
256
        }
1682
32
#define COPY_NOT_FLAG(ATTR, VALUE) \
1683
192
        if (config->ATTR == -1) { \
1684
192
            config->ATTR = !(VALUE); \
1685
192
        }
1686
1687
32
    COPY_FLAG(isolated, Py_IsolatedFlag);
1688
32
    COPY_NOT_FLAG(use_environment, Py_IgnoreEnvironmentFlag);
1689
32
    COPY_FLAG(bytes_warning, Py_BytesWarningFlag);
1690
32
    COPY_FLAG(inspect, Py_InspectFlag);
1691
32
    COPY_FLAG(interactive, Py_InteractiveFlag);
1692
32
    COPY_FLAG(optimization_level, Py_OptimizeFlag);
1693
32
    COPY_FLAG(parser_debug, Py_DebugFlag);
1694
32
    COPY_FLAG(verbose, Py_VerboseFlag);
1695
32
    COPY_FLAG(quiet, Py_QuietFlag);
1696
#ifdef MS_WINDOWS
1697
    COPY_FLAG(legacy_windows_stdio, Py_LegacyWindowsStdioFlag);
1698
#endif
1699
32
    COPY_NOT_FLAG(pathconfig_warnings, Py_FrozenFlag);
1700
1701
32
    COPY_NOT_FLAG(buffered_stdio, Py_UnbufferedStdioFlag);
1702
32
    COPY_NOT_FLAG(site_import, Py_NoSiteFlag);
1703
32
    COPY_NOT_FLAG(write_bytecode, Py_DontWriteBytecodeFlag);
1704
32
    COPY_NOT_FLAG(user_site_directory, Py_NoUserSiteDirectory);
1705
1706
32
#undef COPY_FLAG
1707
32
#undef COPY_NOT_FLAG
1708
32
_Py_COMP_DIAG_POP
1709
32
}
1710
1711
1712
/* Set Py_xxx global configuration variables from 'config' configuration. */
1713
static void
1714
config_set_global_vars(const PyConfig *config)
1715
32
{
1716
32
_Py_COMP_DIAG_PUSH
1717
32
_Py_COMP_DIAG_IGNORE_DEPR_DECLS
1718
32
#define COPY_FLAG(ATTR, VAR) \
1719
256
        if (config->ATTR != -1) { \
1720
256
            VAR = config->ATTR; \
1721
256
        }
1722
32
#define COPY_NOT_FLAG(ATTR, VAR) \
1723
192
        if (config->ATTR != -1) { \
1724
192
            VAR = !config->ATTR; \
1725
192
        }
1726
1727
32
    COPY_FLAG(isolated, Py_IsolatedFlag);
1728
32
    COPY_NOT_FLAG(use_environment, Py_IgnoreEnvironmentFlag);
1729
32
    COPY_FLAG(bytes_warning, Py_BytesWarningFlag);
1730
32
    COPY_FLAG(inspect, Py_InspectFlag);
1731
32
    COPY_FLAG(interactive, Py_InteractiveFlag);
1732
32
    COPY_FLAG(optimization_level, Py_OptimizeFlag);
1733
32
    COPY_FLAG(parser_debug, Py_DebugFlag);
1734
32
    COPY_FLAG(verbose, Py_VerboseFlag);
1735
32
    COPY_FLAG(quiet, Py_QuietFlag);
1736
#ifdef MS_WINDOWS
1737
    COPY_FLAG(legacy_windows_stdio, Py_LegacyWindowsStdioFlag);
1738
#endif
1739
32
    COPY_NOT_FLAG(pathconfig_warnings, Py_FrozenFlag);
1740
1741
32
    COPY_NOT_FLAG(buffered_stdio, Py_UnbufferedStdioFlag);
1742
32
    COPY_NOT_FLAG(site_import, Py_NoSiteFlag);
1743
32
    COPY_NOT_FLAG(write_bytecode, Py_DontWriteBytecodeFlag);
1744
32
    COPY_NOT_FLAG(user_site_directory, Py_NoUserSiteDirectory);
1745
1746
    /* Random or non-zero hash seed */
1747
32
    Py_HashRandomizationFlag = (config->use_hash_seed == 0 ||
1748
0
                                config->hash_seed != 0);
1749
1750
32
#undef COPY_FLAG
1751
32
#undef COPY_NOT_FLAG
1752
32
_Py_COMP_DIAG_POP
1753
32
}
1754
1755
1756
static const wchar_t*
1757
config_get_xoption(const PyConfig *config, wchar_t *name)
1758
544
{
1759
544
    return _Py_get_xoption(&config->xoptions, name);
1760
544
}
1761
1762
static const wchar_t*
1763
config_get_xoption_value(const PyConfig *config, wchar_t *name)
1764
160
{
1765
160
    const wchar_t *xoption = config_get_xoption(config, name);
1766
160
    if (xoption == NULL) {
1767
160
        return NULL;
1768
160
    }
1769
0
    const wchar_t *sep = wcschr(xoption, L'=');
1770
0
    return sep ? sep + 1 : L"";
1771
160
}
1772
1773
1774
static PyStatus
1775
config_init_hash_seed(PyConfig *config)
1776
32
{
1777
32
    static_assert(sizeof(_Py_HashSecret_t) == sizeof(_Py_HashSecret.uc),
1778
32
                  "_Py_HashSecret_t has wrong size");
1779
1780
32
    const char *seed_text = config_get_env(config, "PYTHONHASHSEED");
1781
1782
    /* Convert a text seed to a numeric one */
1783
32
    if (seed_text && strcmp(seed_text, "random") != 0) {
1784
0
        const char *endptr = seed_text;
1785
0
        unsigned long seed;
1786
0
        errno = 0;
1787
0
        seed = strtoul(seed_text, (char **)&endptr, 10);
1788
0
        if (*endptr != '\0'
1789
0
            || seed > MAX_HASH_SEED
1790
0
            || (errno == ERANGE && seed == ULONG_MAX))
1791
0
        {
1792
0
            return _PyStatus_ERR("PYTHONHASHSEED must be \"random\" "
1793
0
                                "or an integer in range [0; 4294967295]");
1794
0
        }
1795
        /* Use a specific hash */
1796
0
        config->use_hash_seed = 1;
1797
0
        config->hash_seed = seed;
1798
0
    }
1799
32
    else {
1800
        /* Use a random hash */
1801
32
        config->use_hash_seed = 0;
1802
32
        config->hash_seed = 0;
1803
32
    }
1804
32
    return _PyStatus_OK();
1805
32
}
1806
1807
1808
static int
1809
config_wstr_to_int(const wchar_t *wstr, int *result)
1810
0
{
1811
0
    const wchar_t *endptr = wstr;
1812
0
    errno = 0;
1813
0
    long value = wcstol(wstr, (wchar_t **)&endptr, 10);
1814
0
    if (*endptr != '\0' || errno == ERANGE) {
1815
0
        return -1;
1816
0
    }
1817
0
    if (value < INT_MIN || value > INT_MAX) {
1818
0
        return -1;
1819
0
    }
1820
1821
0
    *result = (int)value;
1822
0
    return 0;
1823
0
}
1824
1825
static PyStatus
1826
config_read_gil(PyConfig *config, size_t len, wchar_t first_char)
1827
0
{
1828
0
    if (len == 1 && first_char == L'0') {
1829
#ifdef Py_GIL_DISABLED
1830
        config->enable_gil = _PyConfig_GIL_DISABLE;
1831
#else
1832
0
        return _PyStatus_ERR("Disabling the GIL is not supported by this build");
1833
0
#endif
1834
0
    }
1835
0
    else if (len == 1 && first_char == L'1') {
1836
#ifdef Py_GIL_DISABLED
1837
        config->enable_gil = _PyConfig_GIL_ENABLE;
1838
#else
1839
0
        return _PyStatus_OK();
1840
0
#endif
1841
0
    }
1842
0
    else {
1843
0
        return _PyStatus_ERR("PYTHON_GIL / -X gil must be \"0\" or \"1\"");
1844
0
    }
1845
0
    return _PyStatus_OK();
1846
0
}
1847
1848
static PyStatus
1849
config_read_env_vars(PyConfig *config)
1850
32
{
1851
32
    PyStatus status;
1852
32
    int use_env = config->use_environment;
1853
1854
    /* Get environment variables */
1855
32
    _Py_get_env_flag(use_env, &config->parser_debug, "PYTHONDEBUG");
1856
32
    _Py_get_env_flag(use_env, &config->verbose, "PYTHONVERBOSE");
1857
32
    _Py_get_env_flag(use_env, &config->optimization_level, "PYTHONOPTIMIZE");
1858
32
    if (!config->inspect && _Py_GetEnv(use_env, "PYTHONINSPECT")) {
1859
0
        config->inspect = 1;
1860
0
    }
1861
1862
32
    int dont_write_bytecode = 0;
1863
32
    _Py_get_env_flag(use_env, &dont_write_bytecode, "PYTHONDONTWRITEBYTECODE");
1864
32
    if (dont_write_bytecode) {
1865
0
        config->write_bytecode = 0;
1866
0
    }
1867
1868
32
    int no_user_site_directory = 0;
1869
32
    _Py_get_env_flag(use_env, &no_user_site_directory, "PYTHONNOUSERSITE");
1870
32
    if (no_user_site_directory) {
1871
0
        config->user_site_directory = 0;
1872
0
    }
1873
1874
32
    int unbuffered_stdio = 0;
1875
32
    _Py_get_env_flag(use_env, &unbuffered_stdio, "PYTHONUNBUFFERED");
1876
32
    if (unbuffered_stdio) {
1877
0
        config->buffered_stdio = 0;
1878
0
    }
1879
1880
#ifdef MS_WINDOWS
1881
    _Py_get_env_flag(use_env, &config->legacy_windows_stdio,
1882
                     "PYTHONLEGACYWINDOWSSTDIO");
1883
#endif
1884
1885
32
    if (config_get_env(config, "PYTHONDUMPREFS")) {
1886
0
        config->dump_refs = 1;
1887
0
    }
1888
32
    if (config_get_env(config, "PYTHONMALLOCSTATS")) {
1889
0
        config->malloc_stats = 1;
1890
0
    }
1891
32
    {
1892
32
        const char *env = _Py_GetEnv(use_env, "PYTHON_PYMALLOC_HUGEPAGES");
1893
32
        if (env) {
1894
0
            int value;
1895
0
            if (_Py_str_to_int(env, &value) < 0 || value < 0) {
1896
                /* PYTHON_PYMALLOC_HUGEPAGES=text or negative
1897
                   behaves as PYTHON_PYMALLOC_HUGEPAGES=1 */
1898
0
                value = 1;
1899
0
            }
1900
0
            config->pymalloc_hugepages = (value > 0);
1901
0
        }
1902
32
    }
1903
1904
32
    if (config->dump_refs_file == NULL) {
1905
32
        status = CONFIG_GET_ENV_DUP(config, &config->dump_refs_file,
1906
32
                                    L"PYTHONDUMPREFSFILE", "PYTHONDUMPREFSFILE");
1907
32
        if (_PyStatus_EXCEPTION(status)) {
1908
0
            return status;
1909
0
        }
1910
32
    }
1911
1912
32
    if (config->pythonpath_env == NULL) {
1913
32
        status = CONFIG_GET_ENV_DUP(config, &config->pythonpath_env,
1914
32
                                    L"PYTHONPATH", "PYTHONPATH");
1915
32
        if (_PyStatus_EXCEPTION(status)) {
1916
0
            return status;
1917
0
        }
1918
32
    }
1919
1920
32
    if(config->platlibdir == NULL) {
1921
32
        status = CONFIG_GET_ENV_DUP(config, &config->platlibdir,
1922
32
                                    L"PYTHONPLATLIBDIR", "PYTHONPLATLIBDIR");
1923
32
        if (_PyStatus_EXCEPTION(status)) {
1924
0
            return status;
1925
0
        }
1926
32
    }
1927
1928
32
    if (config->use_hash_seed < 0) {
1929
32
        status = config_init_hash_seed(config);
1930
32
        if (_PyStatus_EXCEPTION(status)) {
1931
0
            return status;
1932
0
        }
1933
32
    }
1934
1935
32
    if (config_get_env(config, "PYTHONSAFEPATH")) {
1936
0
        config->safe_path = 1;
1937
0
    }
1938
1939
32
    const char *gil = config_get_env(config, "PYTHON_GIL");
1940
32
    if (gil != NULL) {
1941
0
        size_t len = strlen(gil);
1942
0
        status = config_read_gil(config, len, gil[0]);
1943
0
        if (_PyStatus_EXCEPTION(status)) {
1944
0
            return status;
1945
0
        }
1946
0
    }
1947
1948
32
    return _PyStatus_OK();
1949
32
}
1950
1951
static PyStatus
1952
config_init_cpu_count(PyConfig *config)
1953
32
{
1954
32
    const char *env = config_get_env(config, "PYTHON_CPU_COUNT");
1955
32
    if (env) {
1956
0
        int cpu_count = -1;
1957
0
        if (strcmp(env, "default") == 0) {
1958
0
            cpu_count = -1;
1959
0
        }
1960
0
        else if (_Py_str_to_int(env, &cpu_count) < 0 || cpu_count < 1) {
1961
0
            goto error;
1962
0
        }
1963
0
        config->cpu_count = cpu_count;
1964
0
    }
1965
1966
32
    const wchar_t *xoption = config_get_xoption(config, L"cpu_count");
1967
32
    if (xoption) {
1968
0
        int cpu_count = -1;
1969
0
        const wchar_t *sep = wcschr(xoption, L'=');
1970
0
        if (sep) {
1971
0
            if (wcscmp(sep + 1, L"default") == 0) {
1972
0
                cpu_count = -1;
1973
0
            }
1974
0
            else if (config_wstr_to_int(sep + 1, &cpu_count) < 0 || cpu_count < 1) {
1975
0
                goto error;
1976
0
            }
1977
0
        }
1978
0
        else {
1979
0
            goto error;
1980
0
        }
1981
0
        config->cpu_count = cpu_count;
1982
0
    }
1983
32
    return _PyStatus_OK();
1984
1985
0
error:
1986
0
    return _PyStatus_ERR("-X cpu_count=n option: n is missing or an invalid number, "
1987
32
                         "n must be greater than 0");
1988
32
}
1989
1990
static PyStatus
1991
config_init_thread_inherit_context(PyConfig *config)
1992
32
{
1993
32
    const char *env = config_get_env(config, "PYTHON_THREAD_INHERIT_CONTEXT");
1994
32
    if (env) {
1995
0
        int enabled;
1996
0
        if (_Py_str_to_int(env, &enabled) < 0 || (enabled < 0) || (enabled > 1)) {
1997
0
            return _PyStatus_ERR(
1998
0
                "PYTHON_THREAD_INHERIT_CONTEXT=N: N is missing or invalid");
1999
0
        }
2000
0
        config->thread_inherit_context = enabled;
2001
0
    }
2002
2003
32
    const wchar_t *xoption = config_get_xoption(config, L"thread_inherit_context");
2004
32
    if (xoption) {
2005
0
        int enabled;
2006
0
        const wchar_t *sep = wcschr(xoption, L'=');
2007
0
        if (!sep || (config_wstr_to_int(sep + 1, &enabled) < 0) || (enabled < 0) || (enabled > 1)) {
2008
0
            return _PyStatus_ERR(
2009
0
                "-X thread_inherit_context=n: n is missing or invalid");
2010
0
        }
2011
0
        config->thread_inherit_context = enabled;
2012
0
    }
2013
32
    return _PyStatus_OK();
2014
32
}
2015
2016
static PyStatus
2017
config_init_context_aware_warnings(PyConfig *config)
2018
32
{
2019
32
    const char *env = config_get_env(config, "PYTHON_CONTEXT_AWARE_WARNINGS");
2020
32
    if (env) {
2021
0
        int enabled;
2022
0
        if (_Py_str_to_int(env, &enabled) < 0 || (enabled < 0) || (enabled > 1)) {
2023
0
            return _PyStatus_ERR(
2024
0
                "PYTHON_CONTEXT_AWARE_WARNINGS=N: N is missing or invalid");
2025
0
        }
2026
0
        config->context_aware_warnings = enabled;
2027
0
    }
2028
2029
32
    const wchar_t *xoption = config_get_xoption(config, L"context_aware_warnings");
2030
32
    if (xoption) {
2031
0
        int enabled;
2032
0
        const wchar_t *sep = wcschr(xoption, L'=');
2033
0
        if (!sep || (config_wstr_to_int(sep + 1, &enabled) < 0) || (enabled < 0) || (enabled > 1)) {
2034
0
            return _PyStatus_ERR(
2035
0
                "-X context_aware_warnings=n: n is missing or invalid");
2036
0
        }
2037
0
        config->context_aware_warnings = enabled;
2038
0
    }
2039
32
    return _PyStatus_OK();
2040
32
}
2041
2042
static PyStatus
2043
config_init_tlbc(PyConfig *config)
2044
32
{
2045
#ifdef Py_GIL_DISABLED
2046
    const char *env = config_get_env(config, "PYTHON_TLBC");
2047
    if (env) {
2048
        int enabled;
2049
        if (_Py_str_to_int(env, &enabled) < 0 || (enabled < 0) || (enabled > 1)) {
2050
            return _PyStatus_ERR(
2051
                "PYTHON_TLBC=N: N is missing or invalid");
2052
        }
2053
        config->tlbc_enabled = enabled;
2054
    }
2055
2056
    const wchar_t *xoption = config_get_xoption(config, L"tlbc");
2057
    if (xoption) {
2058
        int enabled;
2059
        const wchar_t *sep = wcschr(xoption, L'=');
2060
        if (!sep || (config_wstr_to_int(sep + 1, &enabled) < 0) || (enabled < 0) || (enabled > 1)) {
2061
            return _PyStatus_ERR(
2062
                "-X tlbc=n: n is missing or invalid");
2063
        }
2064
        config->tlbc_enabled = enabled;
2065
    }
2066
    return _PyStatus_OK();
2067
#else
2068
32
    return _PyStatus_OK();
2069
32
#endif
2070
32
}
2071
2072
static PyStatus
2073
config_init_perf_profiling(PyConfig *config)
2074
32
{
2075
32
    int active = 0;
2076
32
    const char *env = config_get_env(config, "PYTHONPERFSUPPORT");
2077
32
    if (env) {
2078
0
        if (_Py_str_to_int(env, &active) != 0) {
2079
0
            active = 0;
2080
0
        }
2081
0
        if (active) {
2082
0
            config->perf_profiling = 1;
2083
0
        }
2084
0
    }
2085
32
    const wchar_t *xoption = config_get_xoption(config, L"perf");
2086
32
    if (xoption) {
2087
0
        config->perf_profiling = 1;
2088
0
    }
2089
32
    env = config_get_env(config, "PYTHON_PERF_JIT_SUPPORT");
2090
32
    if (env) {
2091
0
        if (_Py_str_to_int(env, &active) != 0) {
2092
0
            active = 0;
2093
0
        }
2094
0
        if (active) {
2095
0
            config->perf_profiling = 2;
2096
0
        }
2097
0
    }
2098
32
    xoption = config_get_xoption(config, L"perf_jit");
2099
32
    if (xoption) {
2100
0
        config->perf_profiling = 2;
2101
0
    }
2102
2103
32
    return _PyStatus_OK();
2104
2105
32
}
2106
2107
static PyStatus
2108
config_init_remote_debug(PyConfig *config)
2109
32
{
2110
#ifndef Py_REMOTE_DEBUG
2111
    config->remote_debug = 0;
2112
#else
2113
32
    int active = 1;
2114
32
    const char *env = Py_GETENV("PYTHON_DISABLE_REMOTE_DEBUG");
2115
32
    if (env) {
2116
0
        active = 0;
2117
0
    }
2118
32
    const wchar_t *xoption = config_get_xoption(config, L"disable-remote-debug");
2119
32
    if (xoption) {
2120
0
        active = 0;
2121
0
    }
2122
2123
32
    config->remote_debug = active;
2124
32
#endif
2125
32
    return _PyStatus_OK();
2126
2127
32
}
2128
2129
static PyStatus
2130
config_init_tracemalloc(PyConfig *config)
2131
32
{
2132
32
    int nframe;
2133
32
    int valid;
2134
2135
32
    const char *env = config_get_env(config, "PYTHONTRACEMALLOC");
2136
32
    if (env) {
2137
0
        if (!_Py_str_to_int(env, &nframe)) {
2138
0
            valid = (nframe >= 0);
2139
0
        }
2140
0
        else {
2141
0
            valid = 0;
2142
0
        }
2143
0
        if (!valid) {
2144
0
            return _PyStatus_ERR("PYTHONTRACEMALLOC: invalid number of frames");
2145
0
        }
2146
0
        config->tracemalloc = nframe;
2147
0
    }
2148
2149
32
    const wchar_t *xoption = config_get_xoption(config, L"tracemalloc");
2150
32
    if (xoption) {
2151
0
        const wchar_t *sep = wcschr(xoption, L'=');
2152
0
        if (sep) {
2153
0
            if (!config_wstr_to_int(sep + 1, &nframe)) {
2154
0
                valid = (nframe >= 0);
2155
0
            }
2156
0
            else {
2157
0
                valid = 0;
2158
0
            }
2159
0
            if (!valid) {
2160
0
                return _PyStatus_ERR("-X tracemalloc=NFRAME: "
2161
0
                                     "invalid number of frames");
2162
0
            }
2163
0
        }
2164
0
        else {
2165
            /* -X tracemalloc behaves as -X tracemalloc=1 */
2166
0
            nframe = 1;
2167
0
        }
2168
0
        config->tracemalloc = nframe;
2169
0
    }
2170
32
    return _PyStatus_OK();
2171
32
}
2172
2173
static PyStatus
2174
config_init_int_max_str_digits(PyConfig *config)
2175
32
{
2176
32
    int maxdigits;
2177
2178
32
    const char *env = config_get_env(config, "PYTHONINTMAXSTRDIGITS");
2179
32
    if (env) {
2180
0
        bool valid = 0;
2181
0
        if (!_Py_str_to_int(env, &maxdigits)) {
2182
0
            valid = ((maxdigits == 0) || (maxdigits >= _PY_LONG_MAX_STR_DIGITS_THRESHOLD));
2183
0
        }
2184
0
        if (!valid) {
2185
0
#define STRINGIFY(VAL) _STRINGIFY(VAL)
2186
0
#define _STRINGIFY(VAL) #VAL
2187
0
            return _PyStatus_ERR(
2188
0
                    "PYTHONINTMAXSTRDIGITS: invalid limit; must be >= "
2189
0
                    STRINGIFY(_PY_LONG_MAX_STR_DIGITS_THRESHOLD)
2190
0
                    " or 0 for unlimited.");
2191
0
        }
2192
0
        config->int_max_str_digits = maxdigits;
2193
0
    }
2194
2195
32
    const wchar_t *xoption = config_get_xoption(config, L"int_max_str_digits");
2196
32
    if (xoption) {
2197
0
        const wchar_t *sep = wcschr(xoption, L'=');
2198
0
        bool valid = 0;
2199
0
        if (sep) {
2200
0
            if (!config_wstr_to_int(sep + 1, &maxdigits)) {
2201
0
                valid = ((maxdigits == 0) || (maxdigits >= _PY_LONG_MAX_STR_DIGITS_THRESHOLD));
2202
0
            }
2203
0
        }
2204
0
        if (!valid) {
2205
0
            return _PyStatus_ERR(
2206
0
                    "-X int_max_str_digits: invalid limit; must be >= "
2207
0
                    STRINGIFY(_PY_LONG_MAX_STR_DIGITS_THRESHOLD)
2208
0
                    " or 0 for unlimited.");
2209
0
#undef _STRINGIFY
2210
0
#undef STRINGIFY
2211
0
        }
2212
0
        config->int_max_str_digits = maxdigits;
2213
0
    }
2214
32
    if (config->int_max_str_digits < 0) {
2215
32
        config->int_max_str_digits = _PY_LONG_DEFAULT_MAX_STR_DIGITS;
2216
32
    }
2217
32
    return _PyStatus_OK();
2218
32
}
2219
2220
static PyStatus
2221
config_init_pycache_prefix(PyConfig *config)
2222
32
{
2223
32
    assert(config->pycache_prefix == NULL);
2224
2225
32
    const wchar_t *xoption = config_get_xoption(config, L"pycache_prefix");
2226
32
    if (xoption) {
2227
0
        const wchar_t *sep = wcschr(xoption, L'=');
2228
0
        if (sep && wcslen(sep) > 1) {
2229
0
            config->pycache_prefix = _PyMem_RawWcsdup(sep + 1);
2230
0
            if (config->pycache_prefix == NULL) {
2231
0
                return _PyStatus_NO_MEMORY();
2232
0
            }
2233
0
        }
2234
0
        else {
2235
            // PYTHONPYCACHEPREFIX env var ignored
2236
            // if "-X pycache_prefix=" option is used
2237
0
            config->pycache_prefix = NULL;
2238
0
        }
2239
0
        return _PyStatus_OK();
2240
0
    }
2241
2242
32
    return CONFIG_GET_ENV_DUP(config, &config->pycache_prefix,
2243
32
                              L"PYTHONPYCACHEPREFIX",
2244
32
                              "PYTHONPYCACHEPREFIX");
2245
32
}
2246
2247
2248
#ifdef Py_DEBUG
2249
static PyStatus
2250
config_init_run_presite(PyConfig *config)
2251
{
2252
    assert(config->run_presite == NULL);
2253
2254
    const wchar_t *xoption = config_get_xoption(config, L"presite");
2255
    if (xoption) {
2256
        const wchar_t *sep = wcschr(xoption, L'=');
2257
        if (sep && wcslen(sep) > 1) {
2258
            config->run_presite = _PyMem_RawWcsdup(sep + 1);
2259
            if (config->run_presite == NULL) {
2260
                return _PyStatus_NO_MEMORY();
2261
            }
2262
        }
2263
        else {
2264
            // PYTHON_PRESITE env var ignored
2265
            // if "-X presite=" option is used
2266
            config->run_presite = NULL;
2267
        }
2268
        return _PyStatus_OK();
2269
    }
2270
2271
    return CONFIG_GET_ENV_DUP(config, &config->run_presite,
2272
                              L"PYTHON_PRESITE",
2273
                              "PYTHON_PRESITE");
2274
}
2275
#endif
2276
2277
static PyStatus
2278
config_init_import_time(PyConfig *config)
2279
32
{
2280
32
    int importtime = 0;
2281
2282
32
    const char *env = config_get_env(config, "PYTHONPROFILEIMPORTTIME");
2283
32
    if (env) {
2284
0
        if (_Py_str_to_int(env, &importtime) != 0) {
2285
0
            importtime = 1;
2286
0
        }
2287
0
        if (importtime < 0 || importtime > 2) {
2288
0
            return _PyStatus_ERR(
2289
0
                "PYTHONPROFILEIMPORTTIME: numeric values other than 1 and 2 "
2290
0
                "are reserved for future use.");
2291
0
        }
2292
0
    }
2293
2294
32
    const wchar_t *x_value = config_get_xoption_value(config, L"importtime");
2295
32
    if (x_value) {
2296
0
        if (*x_value == 0 || config_wstr_to_int(x_value, &importtime) != 0) {
2297
0
            importtime = 1;
2298
0
        }
2299
0
        if (importtime < 0 || importtime > 2) {
2300
0
            return _PyStatus_ERR(
2301
0
                "-X importtime: values other than 1 and 2 "
2302
0
                "are reserved for future use.");
2303
0
        }
2304
0
    }
2305
2306
32
    config->import_time = importtime;
2307
32
    return _PyStatus_OK();
2308
32
}
2309
2310
static PyStatus
2311
config_init_lazy_imports(PyConfig *config)
2312
32
{
2313
32
    int lazy_imports = -1;
2314
2315
32
    const char *env = config_get_env(config, "PYTHON_LAZY_IMPORTS");
2316
32
    if (env) {
2317
0
        if (strcmp(env, "all") == 0) {
2318
0
            lazy_imports = 1;
2319
0
        }
2320
0
        else if (strcmp(env, "none") == 0) {
2321
0
            lazy_imports = 0;
2322
0
        }
2323
0
        else if (strcmp(env, "normal") == 0) {
2324
0
            lazy_imports = -1;
2325
0
        }
2326
0
        else {
2327
0
            return _PyStatus_ERR("PYTHON_LAZY_IMPORTS: invalid value; "
2328
0
                                 "expected 'all', 'none', or 'normal'");
2329
0
        }
2330
0
        config->lazy_imports = lazy_imports;
2331
0
    }
2332
2333
32
    const wchar_t *x_value = config_get_xoption_value(config, L"lazy_imports");
2334
32
    if (x_value) {
2335
0
        if (wcscmp(x_value, L"all") == 0) {
2336
0
            lazy_imports = 1;
2337
0
        }
2338
0
        else if (wcscmp(x_value, L"none") == 0) {
2339
0
            lazy_imports = 0;
2340
0
        }
2341
0
        else if (wcscmp(x_value, L"normal") == 0) {
2342
0
            lazy_imports = -1;
2343
0
        }
2344
0
        else {
2345
0
            return _PyStatus_ERR("-X lazy_imports: invalid value; "
2346
0
                                 "expected 'all', 'none', or 'normal'");
2347
0
        }
2348
0
        config->lazy_imports = lazy_imports;
2349
0
    }
2350
32
    return _PyStatus_OK();
2351
32
}
2352
2353
static PyStatus
2354
config_read_complex_options(PyConfig *config)
2355
32
{
2356
    /* More complex options configured by env var and -X option */
2357
32
    if (config->faulthandler < 0) {
2358
32
        if (config_get_env(config, "PYTHONFAULTHANDLER")
2359
32
           || config_get_xoption(config, L"faulthandler")) {
2360
0
            config->faulthandler = 1;
2361
0
        }
2362
32
    }
2363
32
    if (config_get_env(config, "PYTHONNODEBUGRANGES")
2364
32
       || config_get_xoption(config, L"no_debug_ranges")) {
2365
0
        config->code_debug_ranges = 0;
2366
0
    }
2367
2368
32
    PyStatus status;
2369
32
    if (config->import_time < 0) {
2370
32
        status = config_init_import_time(config);
2371
32
        if (_PyStatus_EXCEPTION(status)) {
2372
0
            return status;
2373
0
        }
2374
32
    }
2375
2376
32
    if (config->lazy_imports < 0) {
2377
32
        status = config_init_lazy_imports(config);
2378
32
        if (_PyStatus_EXCEPTION(status)) {
2379
0
            return status;
2380
0
        }
2381
32
    }
2382
2383
32
    if (config->tracemalloc < 0) {
2384
32
        status = config_init_tracemalloc(config);
2385
32
        if (_PyStatus_EXCEPTION(status)) {
2386
0
            return status;
2387
0
        }
2388
32
    }
2389
2390
32
    if (config->perf_profiling < 0) {
2391
32
        status = config_init_perf_profiling(config);
2392
32
        if (_PyStatus_EXCEPTION(status)) {
2393
0
            return status;
2394
0
        }
2395
32
    }
2396
2397
32
    if (config->remote_debug < 0) {
2398
32
        status = config_init_remote_debug(config);
2399
32
        if (_PyStatus_EXCEPTION(status)) {
2400
0
            return status;
2401
0
        }
2402
32
    }
2403
2404
32
    if (config->int_max_str_digits < 0) {
2405
32
        status = config_init_int_max_str_digits(config);
2406
32
        if (_PyStatus_EXCEPTION(status)) {
2407
0
            return status;
2408
0
        }
2409
32
    }
2410
2411
32
    if (config->cpu_count < 0) {
2412
32
        status = config_init_cpu_count(config);
2413
32
        if (_PyStatus_EXCEPTION(status)) {
2414
0
            return status;
2415
0
        }
2416
32
    }
2417
2418
32
    if (config->pycache_prefix == NULL) {
2419
32
        status = config_init_pycache_prefix(config);
2420
32
        if (_PyStatus_EXCEPTION(status)) {
2421
0
            return status;
2422
0
        }
2423
32
    }
2424
2425
#ifdef Py_DEBUG
2426
    if (config->run_presite == NULL) {
2427
        status = config_init_run_presite(config);
2428
        if (_PyStatus_EXCEPTION(status)) {
2429
            return status;
2430
        }
2431
    }
2432
#endif
2433
2434
32
    status = config_init_thread_inherit_context(config);
2435
32
    if (_PyStatus_EXCEPTION(status)) {
2436
0
        return status;
2437
0
    }
2438
2439
32
    status = config_init_context_aware_warnings(config);
2440
32
    if (_PyStatus_EXCEPTION(status)) {
2441
0
        return status;
2442
0
    }
2443
2444
32
    status = config_init_tlbc(config);
2445
32
    if (_PyStatus_EXCEPTION(status)) {
2446
0
        return status;
2447
0
    }
2448
2449
32
    return _PyStatus_OK();
2450
32
}
2451
2452
2453
static const wchar_t *
2454
config_get_stdio_errors(const PyPreConfig *preconfig)
2455
32
{
2456
32
    if (preconfig->utf8_mode) {
2457
        /* UTF-8 Mode uses UTF-8/surrogateescape */
2458
32
        return L"surrogateescape";
2459
32
    }
2460
2461
0
#ifndef MS_WINDOWS
2462
0
    const char *loc = setlocale(LC_CTYPE, NULL);
2463
0
    if (loc != NULL) {
2464
        /* surrogateescape is the default in the legacy C and POSIX locales */
2465
0
        if (strcmp(loc, "C") == 0 || strcmp(loc, "POSIX") == 0) {
2466
0
            return L"surrogateescape";
2467
0
        }
2468
2469
0
#ifdef PY_COERCE_C_LOCALE
2470
        /* surrogateescape is the default in locale coercion target locales */
2471
0
        if (_Py_IsLocaleCoercionTarget(loc)) {
2472
0
            return L"surrogateescape";
2473
0
        }
2474
0
#endif
2475
0
    }
2476
2477
0
    return L"strict";
2478
#else
2479
    /* On Windows, always use surrogateescape by default */
2480
    return L"surrogateescape";
2481
#endif
2482
0
}
2483
2484
2485
// See also config_get_fs_encoding()
2486
static PyStatus
2487
config_get_locale_encoding(PyConfig *config, const PyPreConfig *preconfig,
2488
                           wchar_t **locale_encoding)
2489
32
{
2490
32
    wchar_t *encoding;
2491
32
    if (preconfig->utf8_mode) {
2492
32
        encoding = _PyMem_RawWcsdup(L"utf-8");
2493
32
    }
2494
0
    else {
2495
0
        encoding = _Py_GetLocaleEncoding();
2496
0
    }
2497
32
    if (encoding == NULL) {
2498
0
        return _PyStatus_NO_MEMORY();
2499
0
    }
2500
32
    PyStatus status = PyConfig_SetString(config, locale_encoding, encoding);
2501
32
    PyMem_RawFree(encoding);
2502
32
    return status;
2503
32
}
2504
2505
2506
static PyStatus
2507
config_init_stdio_encoding(PyConfig *config,
2508
                           const PyPreConfig *preconfig)
2509
32
{
2510
32
    PyStatus status;
2511
2512
    // Exit if encoding and errors are defined
2513
32
    if (config->stdio_encoding != NULL && config->stdio_errors != NULL) {
2514
0
        return _PyStatus_OK();
2515
0
    }
2516
2517
    /* PYTHONIOENCODING environment variable */
2518
32
    const char *opt = config_get_env(config, "PYTHONIOENCODING");
2519
32
    if (opt) {
2520
0
        char *pythonioencoding = _PyMem_RawStrdup(opt);
2521
0
        if (pythonioencoding == NULL) {
2522
0
            return _PyStatus_NO_MEMORY();
2523
0
        }
2524
2525
0
        char *errors = strchr(pythonioencoding, ':');
2526
0
        if (errors) {
2527
0
            *errors = '\0';
2528
0
            errors++;
2529
0
            if (!errors[0]) {
2530
0
                errors = NULL;
2531
0
            }
2532
0
        }
2533
2534
        /* Does PYTHONIOENCODING contain an encoding? */
2535
0
        if (pythonioencoding[0]) {
2536
0
            if (config->stdio_encoding == NULL) {
2537
0
                status = CONFIG_SET_BYTES_STR(config, &config->stdio_encoding,
2538
0
                                              pythonioencoding,
2539
0
                                              "PYTHONIOENCODING environment variable");
2540
0
                if (_PyStatus_EXCEPTION(status)) {
2541
0
                    PyMem_RawFree(pythonioencoding);
2542
0
                    return status;
2543
0
                }
2544
0
            }
2545
2546
            /* If the encoding is set but not the error handler,
2547
               use "strict" error handler by default.
2548
               PYTHONIOENCODING=latin1 behaves as
2549
               PYTHONIOENCODING=latin1:strict. */
2550
0
            if (!errors) {
2551
0
                errors = "strict";
2552
0
            }
2553
0
        }
2554
2555
0
        if (config->stdio_errors == NULL && errors != NULL) {
2556
0
            status = CONFIG_SET_BYTES_STR(config, &config->stdio_errors,
2557
0
                                          errors,
2558
0
                                          "PYTHONIOENCODING environment variable");
2559
0
            if (_PyStatus_EXCEPTION(status)) {
2560
0
                PyMem_RawFree(pythonioencoding);
2561
0
                return status;
2562
0
            }
2563
0
        }
2564
2565
0
        PyMem_RawFree(pythonioencoding);
2566
0
    }
2567
2568
    /* Choose the default error handler based on the current locale. */
2569
32
    if (config->stdio_encoding == NULL) {
2570
32
        status = config_get_locale_encoding(config, preconfig,
2571
32
                                            &config->stdio_encoding);
2572
32
        if (_PyStatus_EXCEPTION(status)) {
2573
0
            return status;
2574
0
        }
2575
32
    }
2576
32
    if (config->stdio_errors == NULL) {
2577
32
        const wchar_t *errors = config_get_stdio_errors(preconfig);
2578
32
        assert(errors != NULL);
2579
2580
32
        status = PyConfig_SetString(config, &config->stdio_errors, errors);
2581
32
        if (_PyStatus_EXCEPTION(status)) {
2582
0
            return status;
2583
0
        }
2584
32
    }
2585
2586
32
    return _PyStatus_OK();
2587
32
}
2588
2589
2590
// See also config_get_locale_encoding()
2591
static PyStatus
2592
config_get_fs_encoding(PyConfig *config, const PyPreConfig *preconfig,
2593
                       wchar_t **fs_encoding)
2594
32
{
2595
#ifdef _Py_FORCE_UTF8_FS_ENCODING
2596
    return PyConfig_SetString(config, fs_encoding, L"utf-8");
2597
#elif defined(MS_WINDOWS)
2598
    const wchar_t *encoding;
2599
    if (preconfig->legacy_windows_fs_encoding) {
2600
        // Legacy Windows filesystem encoding: mbcs/replace
2601
        encoding = L"mbcs";
2602
    }
2603
    else {
2604
        // Windows defaults to utf-8/surrogatepass (PEP 529)
2605
        encoding = L"utf-8";
2606
    }
2607
     return PyConfig_SetString(config, fs_encoding, encoding);
2608
#else  // !MS_WINDOWS
2609
32
    if (preconfig->utf8_mode) {
2610
32
        return PyConfig_SetString(config, fs_encoding, L"utf-8");
2611
32
    }
2612
2613
0
    if (_Py_GetForceASCII()) {
2614
0
        return PyConfig_SetString(config, fs_encoding, L"ascii");
2615
0
    }
2616
2617
0
    return config_get_locale_encoding(config, preconfig, fs_encoding);
2618
0
#endif  // !MS_WINDOWS
2619
0
}
2620
2621
2622
static PyStatus
2623
config_init_fs_encoding(PyConfig *config, const PyPreConfig *preconfig)
2624
32
{
2625
32
    PyStatus status;
2626
2627
32
    if (config->filesystem_encoding == NULL) {
2628
32
        status = config_get_fs_encoding(config, preconfig,
2629
32
                                        &config->filesystem_encoding);
2630
32
        if (_PyStatus_EXCEPTION(status)) {
2631
0
            return status;
2632
0
        }
2633
32
    }
2634
2635
32
    if (config->filesystem_errors == NULL) {
2636
32
        const wchar_t *errors;
2637
#ifdef MS_WINDOWS
2638
        if (preconfig->legacy_windows_fs_encoding) {
2639
            errors = L"replace";
2640
        }
2641
        else {
2642
            errors = L"surrogatepass";
2643
        }
2644
#else
2645
32
        errors = L"surrogateescape";
2646
32
#endif
2647
32
        status = PyConfig_SetString(config, &config->filesystem_errors, errors);
2648
32
        if (_PyStatus_EXCEPTION(status)) {
2649
0
            return status;
2650
0
        }
2651
32
    }
2652
32
    return _PyStatus_OK();
2653
32
}
2654
2655
2656
static PyStatus
2657
config_init_import(PyConfig *config, int compute_path_config)
2658
64
{
2659
64
    PyStatus status;
2660
2661
64
    status = _PyConfig_InitPathConfig(config, compute_path_config);
2662
64
    if (_PyStatus_EXCEPTION(status)) {
2663
0
        return status;
2664
0
    }
2665
2666
64
    const char *env = config_get_env(config, "PYTHON_FROZEN_MODULES");
2667
64
    if (env == NULL) {
2668
64
    }
2669
0
    else if (strcmp(env, "on") == 0) {
2670
0
        config->use_frozen_modules = 1;
2671
0
    }
2672
0
    else if (strcmp(env, "off") == 0) {
2673
0
        config->use_frozen_modules = 0;
2674
0
    } else {
2675
0
        return PyStatus_Error("bad value for PYTHON_FROZEN_MODULES "
2676
0
                              "(expected \"on\" or \"off\")");
2677
0
    }
2678
2679
    /* -X frozen_modules=[on|off] */
2680
64
    const wchar_t *value = config_get_xoption_value(config, L"frozen_modules");
2681
64
    if (value == NULL) {
2682
64
    }
2683
0
    else if (wcscmp(value, L"on") == 0) {
2684
0
        config->use_frozen_modules = 1;
2685
0
    }
2686
0
    else if (wcscmp(value, L"off") == 0) {
2687
0
        config->use_frozen_modules = 0;
2688
0
    }
2689
0
    else if (wcslen(value) == 0) {
2690
        // "-X frozen_modules" and "-X frozen_modules=" both imply "on".
2691
0
        config->use_frozen_modules = 1;
2692
0
    }
2693
0
    else {
2694
0
        return PyStatus_Error("bad value for option -X frozen_modules "
2695
0
                              "(expected \"on\" or \"off\")");
2696
0
    }
2697
2698
64
    assert(config->use_frozen_modules >= 0);
2699
64
    return _PyStatus_OK();
2700
64
}
2701
2702
PyStatus
2703
_PyConfig_InitImportConfig(PyConfig *config)
2704
32
{
2705
32
    return config_init_import(config, 1);
2706
32
}
2707
2708
2709
static PyStatus
2710
config_read(PyConfig *config, int compute_path_config)
2711
32
{
2712
32
    PyStatus status;
2713
32
    const PyPreConfig *preconfig = &_PyRuntime.preconfig;
2714
2715
32
    if (config->use_environment) {
2716
32
        status = config_read_env_vars(config);
2717
32
        if (_PyStatus_EXCEPTION(status)) {
2718
0
            return status;
2719
0
        }
2720
32
    }
2721
2722
    /* -X options */
2723
32
    if (config_get_xoption(config, L"showrefcount")) {
2724
0
        config->show_ref_count = 1;
2725
0
    }
2726
2727
32
    const wchar_t *x_gil = config_get_xoption_value(config, L"gil");
2728
32
    if (x_gil != NULL) {
2729
0
        size_t len = wcslen(x_gil);
2730
0
        status = config_read_gil(config, len, x_gil[0]);
2731
0
        if (_PyStatus_EXCEPTION(status)) {
2732
0
            return status;
2733
0
        }
2734
0
    }
2735
2736
#ifdef Py_STATS
2737
    if (config_get_xoption(config, L"pystats")) {
2738
        config->_pystats = 1;
2739
    }
2740
    else if (config_get_env(config, "PYTHONSTATS")) {
2741
        config->_pystats = 1;
2742
    }
2743
    if (config->_pystats < 0) {
2744
        config->_pystats = 0;
2745
    }
2746
#endif
2747
2748
32
    status = config_read_complex_options(config);
2749
32
    if (_PyStatus_EXCEPTION(status)) {
2750
0
        return status;
2751
0
    }
2752
2753
32
    if (config->_install_importlib) {
2754
32
        status = config_init_import(config, compute_path_config);
2755
32
        if (_PyStatus_EXCEPTION(status)) {
2756
0
            return status;
2757
0
        }
2758
32
    }
2759
2760
    /* default values */
2761
32
    if (config->dev_mode) {
2762
0
        if (config->faulthandler < 0) {
2763
0
            config->faulthandler = 1;
2764
0
        }
2765
0
    }
2766
32
    if (config->faulthandler < 0) {
2767
32
        config->faulthandler = 0;
2768
32
    }
2769
32
    if (config->tracemalloc < 0) {
2770
32
        config->tracemalloc = 0;
2771
32
    }
2772
32
    if (config->lazy_imports < 0) {
2773
32
        config->lazy_imports = -1;  // Default is auto/unset
2774
32
    }
2775
32
    if (config->perf_profiling < 0) {
2776
32
        config->perf_profiling = 0;
2777
32
    }
2778
32
    if (config->remote_debug < 0) {
2779
0
        config->remote_debug = -1;
2780
0
    }
2781
32
    if (config->use_hash_seed < 0) {
2782
0
        config->use_hash_seed = 0;
2783
0
        config->hash_seed = 0;
2784
0
    }
2785
2786
32
    if (config->filesystem_encoding == NULL || config->filesystem_errors == NULL) {
2787
32
        status = config_init_fs_encoding(config, preconfig);
2788
32
        if (_PyStatus_EXCEPTION(status)) {
2789
0
            return status;
2790
0
        }
2791
32
    }
2792
2793
32
    status = config_init_stdio_encoding(config, preconfig);
2794
32
    if (_PyStatus_EXCEPTION(status)) {
2795
0
        return status;
2796
0
    }
2797
2798
32
    if (config->argv.length < 1) {
2799
        /* Ensure at least one (empty) argument is seen */
2800
32
        status = PyWideStringList_Append(&config->argv, L"");
2801
32
        if (_PyStatus_EXCEPTION(status)) {
2802
0
            return status;
2803
0
        }
2804
32
    }
2805
2806
32
    if (config->check_hash_pycs_mode == NULL) {
2807
32
        status = PyConfig_SetString(config, &config->check_hash_pycs_mode,
2808
32
                                    L"default");
2809
32
        if (_PyStatus_EXCEPTION(status)) {
2810
0
            return status;
2811
0
        }
2812
32
    }
2813
2814
32
    if (config->configure_c_stdio < 0) {
2815
0
        config->configure_c_stdio = 1;
2816
0
    }
2817
2818
    // Only parse arguments once.
2819
32
    if (config->parse_argv == 1) {
2820
0
        config->parse_argv = 2;
2821
0
    }
2822
2823
32
    return _PyStatus_OK();
2824
32
}
2825
2826
2827
static void
2828
config_init_stdio(const PyConfig *config)
2829
0
{
2830
#if defined(MS_WINDOWS) || defined(__CYGWIN__)
2831
    /* don't translate newlines (\r\n <=> \n) */
2832
    _setmode(fileno(stdin), O_BINARY);
2833
    _setmode(fileno(stdout), O_BINARY);
2834
    _setmode(fileno(stderr), O_BINARY);
2835
#endif
2836
2837
0
    if (!config->buffered_stdio) {
2838
0
#ifdef HAVE_SETVBUF
2839
0
        setvbuf(stdin,  (char *)NULL, _IONBF, BUFSIZ);
2840
0
        setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ);
2841
0
        setvbuf(stderr, (char *)NULL, _IONBF, BUFSIZ);
2842
#else /* !HAVE_SETVBUF */
2843
        setbuf(stdin,  (char *)NULL);
2844
        setbuf(stdout, (char *)NULL);
2845
        setbuf(stderr, (char *)NULL);
2846
#endif /* !HAVE_SETVBUF */
2847
0
    }
2848
0
    else if (config->interactive) {
2849
#ifdef MS_WINDOWS
2850
        /* Doesn't have to have line-buffered -- use unbuffered */
2851
        /* Any set[v]buf(stdin, ...) screws up Tkinter :-( */
2852
        setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ);
2853
#else /* !MS_WINDOWS */
2854
0
#ifdef HAVE_SETVBUF
2855
0
        setvbuf(stdin,  (char *)NULL, _IOLBF, BUFSIZ);
2856
0
        setvbuf(stdout, (char *)NULL, _IOLBF, BUFSIZ);
2857
0
#endif /* HAVE_SETVBUF */
2858
0
#endif /* !MS_WINDOWS */
2859
        /* Leave stderr alone - it should be unbuffered anyway. */
2860
0
    }
2861
0
}
2862
2863
2864
/* Write the configuration:
2865
2866
   - set Py_xxx global configuration variables
2867
   - initialize C standard streams (stdin, stdout, stderr) */
2868
PyStatus
2869
_PyConfig_Write(const PyConfig *config, _PyRuntimeState *runtime)
2870
32
{
2871
32
    config_set_global_vars(config);
2872
2873
32
    if (config->configure_c_stdio) {
2874
0
        config_init_stdio(config);
2875
0
    }
2876
2877
    /* Write the new pre-configuration into _PyRuntime */
2878
32
    PyPreConfig *preconfig = &runtime->preconfig;
2879
32
    preconfig->isolated = config->isolated;
2880
32
    preconfig->use_environment = config->use_environment;
2881
32
    preconfig->dev_mode = config->dev_mode;
2882
2883
32
    if (_Py_SetArgcArgv(config->orig_argv.length,
2884
32
                        config->orig_argv.items) < 0)
2885
0
    {
2886
0
        return _PyStatus_NO_MEMORY();
2887
0
    }
2888
2889
#ifdef PYMALLOC_USE_HUGEPAGES
2890
    runtime->allocators.use_hugepages = config->pymalloc_hugepages;
2891
#endif
2892
2893
32
    return _PyStatus_OK();
2894
32
}
2895
2896
2897
/* --- PyConfig command line parser -------------------------- */
2898
2899
static void
2900
config_usage(int error, const wchar_t* program)
2901
0
{
2902
0
    FILE *f = error ? stderr : stdout;
2903
2904
0
    fprintf(f, usage_line, program);
2905
0
    if (error)
2906
0
        fprintf(f, "Try `python -h' for more information.\n");
2907
0
    else {
2908
0
        fputs(usage_help, f);
2909
0
    }
2910
0
}
2911
2912
static void
2913
config_envvars_usage(void)
2914
0
{
2915
0
    printf(usage_envvars, (wint_t)DELIM, (wint_t)DELIM, PYTHONHOMEHELP);
2916
0
}
2917
2918
static void
2919
config_xoptions_usage(void)
2920
0
{
2921
0
    puts(usage_xoptions);
2922
0
}
2923
2924
static void
2925
config_complete_usage(const wchar_t* program)
2926
0
{
2927
0
   config_usage(0, program);
2928
0
   putchar('\n');
2929
0
   config_envvars_usage();
2930
0
   putchar('\n');
2931
0
   config_xoptions_usage();
2932
0
}
2933
2934
2935
/* Parse the command line arguments */
2936
static PyStatus
2937
config_parse_cmdline(PyConfig *config, PyWideStringList *warnoptions,
2938
                     Py_ssize_t *opt_index)
2939
0
{
2940
0
    PyStatus status;
2941
0
    const PyWideStringList *argv = &config->argv;
2942
0
    int print_version = 0;
2943
0
    const wchar_t* program = config->program_name;
2944
0
    if (!program && argv->length >= 1) {
2945
0
        program = argv->items[0];
2946
0
    }
2947
2948
0
    _PyOS_ResetGetOpt();
2949
0
    do {
2950
0
        int longindex = -1;
2951
0
        int c = _PyOS_GetOpt(argv->length, argv->items, &longindex);
2952
0
        if (c == EOF) {
2953
0
            break;
2954
0
        }
2955
2956
0
        if (c == 'c') {
2957
0
            if (config->run_command == NULL) {
2958
                /* -c is the last option; following arguments
2959
                   that look like options are left for the
2960
                   command to interpret. */
2961
0
                size_t len = wcslen(_PyOS_optarg) + 1 + 1;
2962
0
                wchar_t *command = PyMem_RawMalloc(sizeof(wchar_t) * len);
2963
0
                if (command == NULL) {
2964
0
                    return _PyStatus_NO_MEMORY();
2965
0
                }
2966
0
                memcpy(command, _PyOS_optarg, (len - 2) * sizeof(wchar_t));
2967
0
                command[len - 2] = '\n';
2968
0
                command[len - 1] = 0;
2969
0
                config->run_command = command;
2970
0
            }
2971
0
            break;
2972
0
        }
2973
2974
0
        if (c == 'm') {
2975
            /* -m is the last option; following arguments
2976
               that look like options are left for the
2977
               module to interpret. */
2978
0
            if (config->run_module == NULL) {
2979
0
                config->run_module = _PyMem_RawWcsdup(_PyOS_optarg);
2980
0
                if (config->run_module == NULL) {
2981
0
                    return _PyStatus_NO_MEMORY();
2982
0
                }
2983
0
            }
2984
0
            break;
2985
0
        }
2986
2987
0
        switch (c) {
2988
        // Integers represent long options, see Python/getopt.c
2989
0
        case 0:
2990
            // check-hash-based-pycs
2991
0
            if (wcscmp(_PyOS_optarg, L"always") == 0
2992
0
                || wcscmp(_PyOS_optarg, L"never") == 0
2993
0
                || wcscmp(_PyOS_optarg, L"default") == 0)
2994
0
            {
2995
0
                status = PyConfig_SetString(config, &config->check_hash_pycs_mode,
2996
0
                                            _PyOS_optarg);
2997
0
                if (_PyStatus_EXCEPTION(status)) {
2998
0
                    return status;
2999
0
                }
3000
0
            } else {
3001
0
                fprintf(stderr, "--check-hash-based-pycs must be one of "
3002
0
                        "'default', 'always', or 'never'\n");
3003
0
                config_usage(1, program);
3004
0
                return _PyStatus_EXIT(2);
3005
0
            }
3006
0
            break;
3007
3008
0
        case 1:
3009
            // help-all
3010
0
            config_complete_usage(program);
3011
0
            return _PyStatus_EXIT(0);
3012
3013
0
        case 2:
3014
            // help-env
3015
0
            config_envvars_usage();
3016
0
            return _PyStatus_EXIT(0);
3017
3018
0
        case 3:
3019
            // help-xoptions
3020
0
            config_xoptions_usage();
3021
0
            return _PyStatus_EXIT(0);
3022
3023
0
        case 'b':
3024
0
            config->bytes_warning++;
3025
0
            break;
3026
3027
0
        case 'd':
3028
0
            config->parser_debug++;
3029
0
            break;
3030
3031
0
        case 'i':
3032
0
            config->inspect++;
3033
0
            config->interactive++;
3034
0
            break;
3035
3036
0
        case 'E':
3037
0
        case 'I':
3038
0
        case 'X':
3039
            /* option handled by _PyPreCmdline_Read() */
3040
0
            break;
3041
3042
0
        case 'O':
3043
0
            config->optimization_level++;
3044
0
            break;
3045
3046
0
        case 'P':
3047
0
            config->safe_path = 1;
3048
0
            break;
3049
3050
0
        case 'B':
3051
0
            config->write_bytecode = 0;
3052
0
            break;
3053
3054
0
        case 's':
3055
0
            config->user_site_directory = 0;
3056
0
            break;
3057
3058
0
        case 'S':
3059
0
            config->site_import = 0;
3060
0
            break;
3061
3062
0
        case 't':
3063
            /* ignored for backwards compatibility */
3064
0
            break;
3065
3066
0
        case 'u':
3067
0
            config->buffered_stdio = 0;
3068
0
            break;
3069
3070
0
        case 'v':
3071
0
            config->verbose++;
3072
0
            break;
3073
3074
0
        case 'x':
3075
0
            config->skip_source_first_line = 1;
3076
0
            break;
3077
3078
0
        case 'h':
3079
0
        case '?':
3080
0
            config_usage(0, program);
3081
0
            return _PyStatus_EXIT(0);
3082
3083
0
        case 'V':
3084
0
            print_version++;
3085
0
            break;
3086
3087
0
        case 'W':
3088
0
            status = PyWideStringList_Append(warnoptions, _PyOS_optarg);
3089
0
            if (_PyStatus_EXCEPTION(status)) {
3090
0
                return status;
3091
0
            }
3092
0
            break;
3093
3094
0
        case 'q':
3095
0
            config->quiet++;
3096
0
            break;
3097
3098
0
        case 'R':
3099
0
            config->use_hash_seed = 0;
3100
0
            break;
3101
3102
        /* This space reserved for other options */
3103
3104
0
        default:
3105
            /* unknown argument: parsing failed */
3106
0
            config_usage(1, program);
3107
0
            return _PyStatus_EXIT(2);
3108
0
        }
3109
0
    } while (1);
3110
3111
0
    if (print_version) {
3112
0
        printf("Python %s\n",
3113
0
                (print_version >= 2) ? Py_GetVersion() : PY_VERSION);
3114
0
        return _PyStatus_EXIT(0);
3115
0
    }
3116
3117
0
    if (config->run_command == NULL && config->run_module == NULL
3118
0
        && _PyOS_optind < argv->length
3119
0
        && wcscmp(argv->items[_PyOS_optind], L"-") != 0
3120
0
        && config->run_filename == NULL)
3121
0
    {
3122
0
        config->run_filename = _PyMem_RawWcsdup(argv->items[_PyOS_optind]);
3123
0
        if (config->run_filename == NULL) {
3124
0
            return _PyStatus_NO_MEMORY();
3125
0
        }
3126
0
    }
3127
3128
0
    if (config->run_command != NULL || config->run_module != NULL) {
3129
        /* Backup _PyOS_optind */
3130
0
        _PyOS_optind--;
3131
0
    }
3132
3133
0
    *opt_index = _PyOS_optind;
3134
3135
0
    return _PyStatus_OK();
3136
0
}
3137
3138
3139
#ifdef MS_WINDOWS
3140
#  define WCSTOK wcstok_s
3141
#else
3142
0
#  define WCSTOK wcstok
3143
#endif
3144
3145
/* Get warning options from PYTHONWARNINGS environment variable. */
3146
static PyStatus
3147
config_init_env_warnoptions(PyConfig *config, PyWideStringList *warnoptions)
3148
32
{
3149
32
    PyStatus status;
3150
    /* CONFIG_GET_ENV_DUP requires dest to be initialized to NULL */
3151
32
    wchar_t *env = NULL;
3152
32
    status = CONFIG_GET_ENV_DUP(config, &env,
3153
32
                             L"PYTHONWARNINGS", "PYTHONWARNINGS");
3154
32
    if (_PyStatus_EXCEPTION(status)) {
3155
0
        return status;
3156
0
    }
3157
3158
    /* env var is not set or is empty */
3159
32
    if (env == NULL) {
3160
32
        return _PyStatus_OK();
3161
32
    }
3162
3163
3164
0
    wchar_t *warning, *context = NULL;
3165
0
    for (warning = WCSTOK(env, L",", &context);
3166
0
         warning != NULL;
3167
0
         warning = WCSTOK(NULL, L",", &context))
3168
0
    {
3169
0
        status = PyWideStringList_Append(warnoptions, warning);
3170
0
        if (_PyStatus_EXCEPTION(status)) {
3171
0
            PyMem_RawFree(env);
3172
0
            return status;
3173
0
        }
3174
0
    }
3175
0
    PyMem_RawFree(env);
3176
0
    return _PyStatus_OK();
3177
0
}
3178
3179
3180
static PyStatus
3181
warnoptions_append(PyConfig *config, PyWideStringList *options,
3182
                   const wchar_t *option)
3183
0
{
3184
    /* config_init_warnoptions() add existing config warnoptions at the end:
3185
       ensure that the new option is not already present in this list to
3186
       prevent change the options order when config_init_warnoptions() is
3187
       called twice. */
3188
0
    if (_PyWideStringList_Find(&config->warnoptions, option)) {
3189
        /* Already present: do nothing */
3190
0
        return _PyStatus_OK();
3191
0
    }
3192
0
    if (_PyWideStringList_Find(options, option)) {
3193
        /* Already present: do nothing */
3194
0
        return _PyStatus_OK();
3195
0
    }
3196
0
    return PyWideStringList_Append(options, option);
3197
0
}
3198
3199
3200
static PyStatus
3201
warnoptions_extend(PyConfig *config, PyWideStringList *options,
3202
                   const PyWideStringList *options2)
3203
96
{
3204
96
    const Py_ssize_t len = options2->length;
3205
96
    wchar_t *const *items = options2->items;
3206
3207
96
    for (Py_ssize_t i = 0; i < len; i++) {
3208
0
        PyStatus status = warnoptions_append(config, options, items[i]);
3209
0
        if (_PyStatus_EXCEPTION(status)) {
3210
0
            return status;
3211
0
        }
3212
0
    }
3213
96
    return _PyStatus_OK();
3214
96
}
3215
3216
3217
static PyStatus
3218
config_init_warnoptions(PyConfig *config,
3219
                        const PyWideStringList *cmdline_warnoptions,
3220
                        const PyWideStringList *env_warnoptions,
3221
                        const PyWideStringList *sys_warnoptions)
3222
32
{
3223
32
    PyStatus status;
3224
32
    PyWideStringList options = _PyWideStringList_INIT;
3225
3226
    /* Priority of warnings options, lowest to highest:
3227
     *
3228
     * - any implicit filters added by _warnings.c/warnings.py
3229
     * - PyConfig.dev_mode: "default" filter
3230
     * - PYTHONWARNINGS environment variable
3231
     * - '-W' command line options
3232
     * - PyConfig.bytes_warning ('-b' and '-bb' command line options):
3233
     *   "default::BytesWarning" or "error::BytesWarning" filter
3234
     * - early PySys_AddWarnOption() calls
3235
     * - PyConfig.warnoptions
3236
     *
3237
     * PyConfig.warnoptions is copied to sys.warnoptions. Since the warnings
3238
     * module works on the basis of "the most recently added filter will be
3239
     * checked first", we add the lowest precedence entries first so that later
3240
     * entries override them.
3241
     */
3242
3243
32
    if (config->dev_mode) {
3244
0
        status = warnoptions_append(config, &options, L"default");
3245
0
        if (_PyStatus_EXCEPTION(status)) {
3246
0
            goto error;
3247
0
        }
3248
0
    }
3249
3250
32
    status = warnoptions_extend(config, &options, env_warnoptions);
3251
32
    if (_PyStatus_EXCEPTION(status)) {
3252
0
        goto error;
3253
0
    }
3254
3255
32
    status = warnoptions_extend(config, &options, cmdline_warnoptions);
3256
32
    if (_PyStatus_EXCEPTION(status)) {
3257
0
        goto error;
3258
0
    }
3259
3260
    /* If the bytes_warning_flag isn't set, bytesobject.c and bytearrayobject.c
3261
     * don't even try to emit a warning, so we skip setting the filter in that
3262
     * case.
3263
     */
3264
32
    if (config->bytes_warning) {
3265
0
        const wchar_t *filter;
3266
0
        if (config->bytes_warning> 1) {
3267
0
            filter = L"error::BytesWarning";
3268
0
        }
3269
0
        else {
3270
0
            filter = L"default::BytesWarning";
3271
0
        }
3272
0
        status = warnoptions_append(config, &options, filter);
3273
0
        if (_PyStatus_EXCEPTION(status)) {
3274
0
            goto error;
3275
0
        }
3276
0
    }
3277
3278
32
    status = warnoptions_extend(config, &options, sys_warnoptions);
3279
32
    if (_PyStatus_EXCEPTION(status)) {
3280
0
        goto error;
3281
0
    }
3282
3283
    /* Always add all PyConfig.warnoptions options */
3284
32
    status = _PyWideStringList_Extend(&options, &config->warnoptions);
3285
32
    if (_PyStatus_EXCEPTION(status)) {
3286
0
        goto error;
3287
0
    }
3288
3289
32
    _PyWideStringList_Clear(&config->warnoptions);
3290
32
    config->warnoptions = options;
3291
32
    return _PyStatus_OK();
3292
3293
0
error:
3294
0
    _PyWideStringList_Clear(&options);
3295
0
    return status;
3296
32
}
3297
3298
3299
static PyStatus
3300
config_update_argv(PyConfig *config, Py_ssize_t opt_index)
3301
0
{
3302
0
    const PyWideStringList *cmdline_argv = &config->argv;
3303
0
    PyWideStringList config_argv = _PyWideStringList_INIT;
3304
3305
    /* Copy argv to be able to modify it (to force -c/-m) */
3306
0
    if (cmdline_argv->length <= opt_index) {
3307
        /* Ensure at least one (empty) argument is seen */
3308
0
        PyStatus status = PyWideStringList_Append(&config_argv, L"");
3309
0
        if (_PyStatus_EXCEPTION(status)) {
3310
0
            return status;
3311
0
        }
3312
0
    }
3313
0
    else {
3314
0
        PyWideStringList slice;
3315
0
        slice.length = cmdline_argv->length - opt_index;
3316
0
        slice.items = &cmdline_argv->items[opt_index];
3317
0
        if (_PyWideStringList_Copy(&config_argv, &slice) < 0) {
3318
0
            return _PyStatus_NO_MEMORY();
3319
0
        }
3320
0
    }
3321
0
    assert(config_argv.length >= 1);
3322
3323
0
    wchar_t *arg0 = NULL;
3324
0
    if (config->run_command != NULL) {
3325
        /* Force sys.argv[0] = '-c' */
3326
0
        arg0 = L"-c";
3327
0
    }
3328
0
    else if (config->run_module != NULL) {
3329
        /* Force sys.argv[0] = '-m'*/
3330
0
        arg0 = L"-m";
3331
0
    }
3332
3333
0
    if (arg0 != NULL) {
3334
0
        arg0 = _PyMem_RawWcsdup(arg0);
3335
0
        if (arg0 == NULL) {
3336
0
            _PyWideStringList_Clear(&config_argv);
3337
0
            return _PyStatus_NO_MEMORY();
3338
0
        }
3339
3340
0
        PyMem_RawFree(config_argv.items[0]);
3341
0
        config_argv.items[0] = arg0;
3342
0
    }
3343
3344
0
    _PyWideStringList_Clear(&config->argv);
3345
0
    config->argv = config_argv;
3346
0
    return _PyStatus_OK();
3347
0
}
3348
3349
3350
static PyStatus
3351
core_read_precmdline(PyConfig *config, _PyPreCmdline *precmdline)
3352
32
{
3353
32
    PyStatus status;
3354
3355
32
    if (config->parse_argv == 1) {
3356
0
        if (_PyWideStringList_Copy(&precmdline->argv, &config->argv) < 0) {
3357
0
            return _PyStatus_NO_MEMORY();
3358
0
        }
3359
0
    }
3360
3361
32
    PyPreConfig preconfig;
3362
3363
32
    status = _PyPreConfig_InitFromPreConfig(&preconfig, &_PyRuntime.preconfig);
3364
32
    if (_PyStatus_EXCEPTION(status)) {
3365
0
        return status;
3366
0
    }
3367
3368
32
    _PyPreConfig_GetConfig(&preconfig, config);
3369
3370
32
    status = _PyPreCmdline_Read(precmdline, &preconfig);
3371
32
    if (_PyStatus_EXCEPTION(status)) {
3372
0
        return status;
3373
0
    }
3374
3375
32
    status = _PyPreCmdline_SetConfig(precmdline, config);
3376
32
    if (_PyStatus_EXCEPTION(status)) {
3377
0
        return status;
3378
0
    }
3379
32
    return _PyStatus_OK();
3380
32
}
3381
3382
3383
/* Get run_filename absolute path */
3384
static PyStatus
3385
config_run_filename_abspath(PyConfig *config)
3386
32
{
3387
32
    if (!config->run_filename) {
3388
32
        return _PyStatus_OK();
3389
32
    }
3390
3391
0
#ifndef MS_WINDOWS
3392
0
    if (_Py_isabs(config->run_filename)) {
3393
        /* path is already absolute */
3394
0
        return _PyStatus_OK();
3395
0
    }
3396
0
#endif
3397
3398
0
    wchar_t *abs_filename;
3399
0
    if (_Py_abspath(config->run_filename, &abs_filename) < 0) {
3400
        /* failed to get the absolute path of the command line filename:
3401
           ignore the error, keep the relative path */
3402
0
        return _PyStatus_OK();
3403
0
    }
3404
0
    if (abs_filename == NULL) {
3405
0
        return _PyStatus_NO_MEMORY();
3406
0
    }
3407
3408
0
    PyMem_RawFree(config->run_filename);
3409
0
    config->run_filename = abs_filename;
3410
0
    return _PyStatus_OK();
3411
0
}
3412
3413
3414
static PyStatus
3415
config_read_cmdline(PyConfig *config)
3416
32
{
3417
32
    PyStatus status;
3418
32
    PyWideStringList cmdline_warnoptions = _PyWideStringList_INIT;
3419
32
    PyWideStringList env_warnoptions = _PyWideStringList_INIT;
3420
32
    PyWideStringList sys_warnoptions = _PyWideStringList_INIT;
3421
3422
32
    if (config->parse_argv < 0) {
3423
0
        config->parse_argv = 1;
3424
0
    }
3425
3426
32
    if (config->parse_argv == 1) {
3427
0
        Py_ssize_t opt_index;
3428
0
        status = config_parse_cmdline(config, &cmdline_warnoptions, &opt_index);
3429
0
        if (_PyStatus_EXCEPTION(status)) {
3430
0
            goto done;
3431
0
        }
3432
3433
0
        status = config_run_filename_abspath(config);
3434
0
        if (_PyStatus_EXCEPTION(status)) {
3435
0
            goto done;
3436
0
        }
3437
3438
0
        status = config_update_argv(config, opt_index);
3439
0
        if (_PyStatus_EXCEPTION(status)) {
3440
0
            goto done;
3441
0
        }
3442
0
    }
3443
32
    else {
3444
32
        status = config_run_filename_abspath(config);
3445
32
        if (_PyStatus_EXCEPTION(status)) {
3446
0
            goto done;
3447
0
        }
3448
32
    }
3449
3450
32
    if (config->use_environment) {
3451
32
        status = config_init_env_warnoptions(config, &env_warnoptions);
3452
32
        if (_PyStatus_EXCEPTION(status)) {
3453
0
            goto done;
3454
0
        }
3455
32
    }
3456
3457
    /* Handle early PySys_AddWarnOption() calls */
3458
32
    status = _PySys_ReadPreinitWarnOptions(&sys_warnoptions);
3459
32
    if (_PyStatus_EXCEPTION(status)) {
3460
0
        goto done;
3461
0
    }
3462
3463
32
    status = config_init_warnoptions(config,
3464
32
                                     &cmdline_warnoptions,
3465
32
                                     &env_warnoptions,
3466
32
                                     &sys_warnoptions);
3467
32
    if (_PyStatus_EXCEPTION(status)) {
3468
0
        goto done;
3469
0
    }
3470
3471
32
    status = _PyStatus_OK();
3472
3473
32
done:
3474
32
    _PyWideStringList_Clear(&cmdline_warnoptions);
3475
32
    _PyWideStringList_Clear(&env_warnoptions);
3476
32
    _PyWideStringList_Clear(&sys_warnoptions);
3477
32
    return status;
3478
32
}
3479
3480
3481
PyStatus
3482
_PyConfig_SetPyArgv(PyConfig *config, const _PyArgv *args)
3483
0
{
3484
0
    PyStatus status = _Py_PreInitializeFromConfig(config, args);
3485
0
    if (_PyStatus_EXCEPTION(status)) {
3486
0
        return status;
3487
0
    }
3488
3489
0
    return _PyArgv_AsWstrList(args, &config->argv);
3490
0
}
3491
3492
3493
/* Set config.argv: decode argv using Py_DecodeLocale(). Pre-initialize Python
3494
   if needed to ensure that encodings are properly configured. */
3495
PyStatus
3496
PyConfig_SetBytesArgv(PyConfig *config, Py_ssize_t argc, char * const *argv)
3497
0
{
3498
0
    _PyArgv args = {
3499
0
        .argc = argc,
3500
0
        .use_bytes_argv = 1,
3501
0
        .bytes_argv = argv,
3502
0
        .wchar_argv = NULL};
3503
0
    return _PyConfig_SetPyArgv(config, &args);
3504
0
}
3505
3506
3507
PyStatus
3508
PyConfig_SetArgv(PyConfig *config, Py_ssize_t argc, wchar_t * const *argv)
3509
0
{
3510
0
    _PyArgv args = {
3511
0
        .argc = argc,
3512
0
        .use_bytes_argv = 0,
3513
0
        .bytes_argv = NULL,
3514
0
        .wchar_argv = argv};
3515
0
    return _PyConfig_SetPyArgv(config, &args);
3516
0
}
3517
3518
3519
PyStatus
3520
PyConfig_SetWideStringList(PyConfig *config, PyWideStringList *list,
3521
                           Py_ssize_t length, wchar_t **items)
3522
0
{
3523
0
    PyStatus status = _Py_PreInitializeFromConfig(config, NULL);
3524
0
    if (_PyStatus_EXCEPTION(status)) {
3525
0
        return status;
3526
0
    }
3527
3528
0
    PyWideStringList list2 = {.length = length, .items = items};
3529
0
    if (_PyWideStringList_Copy(list, &list2) < 0) {
3530
0
        return _PyStatus_NO_MEMORY();
3531
0
    }
3532
0
    return _PyStatus_OK();
3533
0
}
3534
3535
3536
/* Read the configuration into PyConfig from:
3537
3538
   * Command line arguments
3539
   * Environment variables
3540
   * Py_xxx global configuration variables
3541
3542
   The only side effects are to modify config and to call _Py_SetArgcArgv(). */
3543
PyStatus
3544
_PyConfig_Read(PyConfig *config, int compute_path_config)
3545
32
{
3546
32
    PyStatus status;
3547
3548
32
    status = _Py_PreInitializeFromConfig(config, NULL);
3549
32
    if (_PyStatus_EXCEPTION(status)) {
3550
0
        return status;
3551
0
    }
3552
3553
32
    config_get_global_vars(config);
3554
3555
32
    if (config->orig_argv.length == 0
3556
32
        && !(config->argv.length == 1
3557
0
             && wcscmp(config->argv.items[0], L"") == 0))
3558
32
    {
3559
32
        if (_PyWideStringList_Copy(&config->orig_argv, &config->argv) < 0) {
3560
0
            return _PyStatus_NO_MEMORY();
3561
0
        }
3562
32
    }
3563
3564
32
    _PyPreCmdline precmdline = _PyPreCmdline_INIT;
3565
32
    status = core_read_precmdline(config, &precmdline);
3566
32
    if (_PyStatus_EXCEPTION(status)) {
3567
0
        goto done;
3568
0
    }
3569
3570
32
    assert(config->isolated >= 0);
3571
32
    if (config->isolated) {
3572
0
        config->safe_path = 1;
3573
0
        config->use_environment = 0;
3574
0
        config->user_site_directory = 0;
3575
0
    }
3576
3577
32
    status = config_read_cmdline(config);
3578
32
    if (_PyStatus_EXCEPTION(status)) {
3579
0
        goto done;
3580
0
    }
3581
3582
    /* Handle early PySys_AddXOption() calls */
3583
32
    status = _PySys_ReadPreinitXOptions(config);
3584
32
    if (_PyStatus_EXCEPTION(status)) {
3585
0
        goto done;
3586
0
    }
3587
3588
32
    status = config_read(config, compute_path_config);
3589
32
    if (_PyStatus_EXCEPTION(status)) {
3590
0
        goto done;
3591
0
    }
3592
3593
32
    assert(config_check_consistency(config));
3594
3595
32
    status = _PyStatus_OK();
3596
3597
32
done:
3598
32
    _PyPreCmdline_Clear(&precmdline);
3599
32
    return status;
3600
32
}
3601
3602
3603
PyStatus
3604
PyConfig_Read(PyConfig *config)
3605
0
{
3606
0
    return _PyConfig_Read(config, 0);
3607
0
}
3608
3609
3610
PyObject*
3611
_Py_GetConfigsAsDict(void)
3612
0
{
3613
0
    PyObject *result = NULL;
3614
0
    PyObject *dict = NULL;
3615
3616
0
    result = PyDict_New();
3617
0
    if (result == NULL) {
3618
0
        goto error;
3619
0
    }
3620
3621
    /* global result */
3622
0
    dict = _Py_GetGlobalVariablesAsDict();
3623
0
    if (dict == NULL) {
3624
0
        goto error;
3625
0
    }
3626
0
    if (PyDict_SetItemString(result, "global_config", dict) < 0) {
3627
0
        goto error;
3628
0
    }
3629
0
    Py_CLEAR(dict);
3630
3631
    /* pre config */
3632
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
3633
0
    const PyPreConfig *pre_config = &interp->runtime->preconfig;
3634
0
    dict = _PyPreConfig_AsDict(pre_config);
3635
0
    if (dict == NULL) {
3636
0
        goto error;
3637
0
    }
3638
0
    if (PyDict_SetItemString(result, "pre_config", dict) < 0) {
3639
0
        goto error;
3640
0
    }
3641
0
    Py_CLEAR(dict);
3642
3643
    /* core config */
3644
0
    const PyConfig *config = _PyInterpreterState_GetConfig(interp);
3645
0
    dict = _PyConfig_AsDict(config);
3646
0
    if (dict == NULL) {
3647
0
        goto error;
3648
0
    }
3649
0
    if (PyDict_SetItemString(result, "config", dict) < 0) {
3650
0
        goto error;
3651
0
    }
3652
0
    Py_CLEAR(dict);
3653
3654
0
    return result;
3655
3656
0
error:
3657
0
    Py_XDECREF(result);
3658
0
    Py_XDECREF(dict);
3659
0
    return NULL;
3660
0
}
3661
3662
3663
static void
3664
init_dump_ascii_wstr(const wchar_t *str)
3665
0
{
3666
0
    if (str == NULL) {
3667
0
        PySys_WriteStderr("(not set)");
3668
0
        return;
3669
0
    }
3670
3671
0
    PySys_WriteStderr("'");
3672
0
    for (; *str != L'\0'; str++) {
3673
0
        unsigned int ch = (unsigned int)*str;
3674
0
        if (ch == L'\'') {
3675
0
            PySys_WriteStderr("\\'");
3676
0
        } else if (0x20 <= ch && ch < 0x7f) {
3677
0
            PySys_WriteStderr("%c", ch);
3678
0
        }
3679
0
        else if (ch <= 0xff) {
3680
0
            PySys_WriteStderr("\\x%02x", ch);
3681
0
        }
3682
0
#if SIZEOF_WCHAR_T > 2
3683
0
        else if (ch > 0xffff) {
3684
0
            PySys_WriteStderr("\\U%08x", ch);
3685
0
        }
3686
0
#endif
3687
0
        else {
3688
0
            PySys_WriteStderr("\\u%04x", ch);
3689
0
        }
3690
0
    }
3691
0
    PySys_WriteStderr("'");
3692
0
}
3693
3694
3695
/* Dump the Python path configuration into sys.stderr */
3696
void
3697
_Py_DumpPathConfig(PyThreadState *tstate)
3698
0
{
3699
0
    PyObject *exc = _PyErr_GetRaisedException(tstate);
3700
3701
0
    PySys_WriteStderr("Python path configuration:\n");
3702
3703
0
#define DUMP_CONFIG(NAME, FIELD) \
3704
0
        do { \
3705
0
            PySys_WriteStderr("  " NAME " = "); \
3706
0
            init_dump_ascii_wstr(config->FIELD); \
3707
0
            PySys_WriteStderr("\n"); \
3708
0
        } while (0)
3709
3710
0
    const PyConfig *config = _PyInterpreterState_GetConfig(tstate->interp);
3711
0
    DUMP_CONFIG("PYTHONHOME", home);
3712
0
    DUMP_CONFIG("PYTHONPATH", pythonpath_env);
3713
0
    DUMP_CONFIG("program name", program_name);
3714
0
    PySys_WriteStderr("  isolated = %i\n", config->isolated);
3715
0
    PySys_WriteStderr("  environment = %i\n", config->use_environment);
3716
0
    PySys_WriteStderr("  user site = %i\n", config->user_site_directory);
3717
0
    PySys_WriteStderr("  safe_path = %i\n", config->safe_path);
3718
0
    PySys_WriteStderr("  import site = %i\n", config->site_import);
3719
0
    PySys_WriteStderr("  is in build tree = %i\n", config->_is_python_build);
3720
0
    DUMP_CONFIG("stdlib dir", stdlib_dir);
3721
0
    DUMP_CONFIG("sys.path[0]", sys_path_0);
3722
0
#undef DUMP_CONFIG
3723
3724
0
#define DUMP_SYS(NAME) \
3725
0
        do { \
3726
0
            PySys_FormatStderr("  sys.%s = ", #NAME); \
3727
0
            if (PySys_GetOptionalAttrString(#NAME, &obj) < 0) { \
3728
0
                PyErr_Clear(); \
3729
0
            } \
3730
0
            if (obj != NULL) { \
3731
0
                PySys_FormatStderr("%A", obj); \
3732
0
                Py_DECREF(obj); \
3733
0
            } \
3734
0
            else { \
3735
0
                PySys_WriteStderr("(not set)"); \
3736
0
            } \
3737
0
            PySys_FormatStderr("\n"); \
3738
0
        } while (0)
3739
3740
0
    PyObject *obj;
3741
0
    DUMP_SYS(_base_executable);
3742
0
    DUMP_SYS(base_prefix);
3743
0
    DUMP_SYS(base_exec_prefix);
3744
0
    DUMP_SYS(platlibdir);
3745
0
    DUMP_SYS(executable);
3746
0
    DUMP_SYS(prefix);
3747
0
    DUMP_SYS(exec_prefix);
3748
0
#undef DUMP_SYS
3749
3750
0
    PyObject *sys_path;
3751
0
    (void) PySys_GetOptionalAttrString("path", &sys_path);
3752
0
    if (sys_path != NULL && PyList_Check(sys_path)) {
3753
0
        PySys_WriteStderr("  sys.path = [\n");
3754
0
        Py_ssize_t len = PyList_GET_SIZE(sys_path);
3755
0
        for (Py_ssize_t i=0; i < len; i++) {
3756
0
            PyObject *path = PyList_GET_ITEM(sys_path, i);
3757
0
            PySys_FormatStderr("    %A,\n", path);
3758
0
        }
3759
0
        PySys_WriteStderr("  ]\n");
3760
0
    }
3761
0
    Py_XDECREF(sys_path);
3762
3763
0
    _PyErr_SetRaisedException(tstate, exc);
3764
0
}
3765
3766
3767
// --- PyInitConfig API ---------------------------------------------------
3768
3769
struct PyInitConfig {
3770
    PyPreConfig preconfig;
3771
    PyConfig config;
3772
    struct _inittab *inittab;
3773
    Py_ssize_t inittab_size;
3774
    PyStatus status;
3775
    char *err_msg;
3776
};
3777
3778
static PyInitConfig*
3779
initconfig_alloc(void)
3780
0
{
3781
0
    return calloc(1, sizeof(PyInitConfig));
3782
0
}
3783
3784
3785
PyInitConfig*
3786
PyInitConfig_Create(void)
3787
0
{
3788
0
    PyInitConfig *config = initconfig_alloc();
3789
0
    if (config == NULL) {
3790
0
        return NULL;
3791
0
    }
3792
0
    PyPreConfig_InitIsolatedConfig(&config->preconfig);
3793
0
    PyConfig_InitIsolatedConfig(&config->config);
3794
0
    config->status = _PyStatus_OK();
3795
0
    return config;
3796
0
}
3797
3798
3799
void
3800
PyInitConfig_Free(PyInitConfig *config)
3801
0
{
3802
0
    if (config == NULL) {
3803
0
        return;
3804
0
    }
3805
3806
0
    initconfig_free_config(&config->config);
3807
0
    PyMem_RawFree(config->inittab);
3808
0
    free(config->err_msg);
3809
0
    free(config);
3810
0
}
3811
3812
3813
int
3814
PyInitConfig_GetError(PyInitConfig* config, const char **perr_msg)
3815
0
{
3816
0
    if (_PyStatus_IS_EXIT(config->status)) {
3817
0
        char buffer[22];  // len("exit code -2147483648\0")
3818
0
        PyOS_snprintf(buffer, sizeof(buffer),
3819
0
                      "exit code %i",
3820
0
                      config->status.exitcode);
3821
3822
0
        if (config->err_msg != NULL) {
3823
0
            free(config->err_msg);
3824
0
        }
3825
0
        config->err_msg = strdup(buffer);
3826
0
        if (config->err_msg != NULL) {
3827
0
            *perr_msg = config->err_msg;
3828
0
            return 1;
3829
0
        }
3830
0
        config->status = _PyStatus_NO_MEMORY();
3831
0
    }
3832
3833
0
    if (_PyStatus_IS_ERROR(config->status) && config->status.err_msg != NULL) {
3834
0
        *perr_msg = config->status.err_msg;
3835
0
        return 1;
3836
0
    }
3837
0
    else {
3838
0
        *perr_msg = NULL;
3839
0
        return 0;
3840
0
    }
3841
0
}
3842
3843
3844
int
3845
PyInitConfig_GetExitCode(PyInitConfig* config, int *exitcode)
3846
0
{
3847
0
    if (_PyStatus_IS_EXIT(config->status)) {
3848
0
        *exitcode = config->status.exitcode;
3849
0
        return 1;
3850
0
    }
3851
0
    else {
3852
0
        return 0;
3853
0
    }
3854
0
}
3855
3856
3857
static void
3858
initconfig_set_error(PyInitConfig *config, const char *err_msg)
3859
0
{
3860
0
    config->status = _PyStatus_ERR(err_msg);
3861
0
}
3862
3863
3864
static const PyConfigSpec*
3865
initconfig_find_spec(const PyConfigSpec *spec, const char *name)
3866
0
{
3867
0
    for (; spec->name != NULL; spec++) {
3868
0
        if (strcmp(name, spec->name) == 0) {
3869
0
            return spec;
3870
0
        }
3871
0
    }
3872
0
    return NULL;
3873
0
}
3874
3875
3876
int
3877
PyInitConfig_HasOption(PyInitConfig *config, const char *name)
3878
0
{
3879
0
    const PyConfigSpec *spec = initconfig_find_spec(PYCONFIG_SPEC, name);
3880
0
    if (spec == NULL) {
3881
0
        spec = initconfig_find_spec(PYPRECONFIG_SPEC, name);
3882
0
    }
3883
0
    return (spec != NULL);
3884
0
}
3885
3886
3887
static const PyConfigSpec*
3888
initconfig_prepare(PyInitConfig *config, const char *name, void **raw_member)
3889
0
{
3890
0
    const PyConfigSpec *spec = initconfig_find_spec(PYCONFIG_SPEC, name);
3891
0
    if (spec != NULL) {
3892
0
        *raw_member = config_get_spec_member(&config->config, spec);
3893
0
        return spec;
3894
0
    }
3895
3896
0
    spec = initconfig_find_spec(PYPRECONFIG_SPEC, name);
3897
0
    if (spec != NULL) {
3898
0
        *raw_member = preconfig_get_spec_member(&config->preconfig, spec);
3899
0
        return spec;
3900
0
    }
3901
3902
0
    initconfig_set_error(config, "unknown config option name");
3903
0
    return NULL;
3904
0
}
3905
3906
3907
int
3908
PyInitConfig_GetInt(PyInitConfig *config, const char *name, int64_t *value)
3909
0
{
3910
0
    void *raw_member;
3911
0
    const PyConfigSpec *spec = initconfig_prepare(config, name, &raw_member);
3912
0
    if (spec == NULL) {
3913
0
        return -1;
3914
0
    }
3915
3916
0
    switch (spec->type) {
3917
0
    case PyConfig_MEMBER_INT:
3918
0
    case PyConfig_MEMBER_UINT:
3919
0
    case PyConfig_MEMBER_BOOL:
3920
0
    {
3921
0
        int *member = raw_member;
3922
0
        *value = *member;
3923
0
        break;
3924
0
    }
3925
3926
0
    case PyConfig_MEMBER_ULONG:
3927
0
    {
3928
0
        unsigned long *member = raw_member;
3929
0
#if SIZEOF_LONG >= 8
3930
0
        if ((unsigned long)INT64_MAX < *member) {
3931
0
            initconfig_set_error(config,
3932
0
                "config option value doesn't fit into int64_t");
3933
0
            return -1;
3934
0
        }
3935
0
#endif
3936
0
        *value = *member;
3937
0
        break;
3938
0
    }
3939
3940
0
    default:
3941
0
        initconfig_set_error(config, "config option type is not int");
3942
0
        return -1;
3943
0
    }
3944
0
    return 0;
3945
0
}
3946
3947
3948
static char*
3949
wstr_to_utf8(PyInitConfig *config, wchar_t *wstr)
3950
0
{
3951
0
    char *utf8;
3952
0
    int res = _Py_EncodeUTF8Ex(wstr, &utf8, NULL, NULL, 1, _Py_ERROR_STRICT);
3953
0
    if (res == -2) {
3954
0
        initconfig_set_error(config, "encoding error");
3955
0
        return NULL;
3956
0
    }
3957
0
    if (res < 0) {
3958
0
        config->status = _PyStatus_NO_MEMORY();
3959
0
        return NULL;
3960
0
    }
3961
3962
    // Copy to use the malloc() memory allocator
3963
0
    size_t size = strlen(utf8) + 1;
3964
0
    char *str = malloc(size);
3965
0
    if (str == NULL) {
3966
0
        PyMem_RawFree(utf8);
3967
0
        config->status = _PyStatus_NO_MEMORY();
3968
0
        return NULL;
3969
0
    }
3970
3971
0
    memcpy(str, utf8, size);
3972
0
    PyMem_RawFree(utf8);
3973
0
    return str;
3974
0
}
3975
3976
3977
int
3978
PyInitConfig_GetStr(PyInitConfig *config, const char *name, char **value)
3979
0
{
3980
0
    void *raw_member;
3981
0
    const PyConfigSpec *spec = initconfig_prepare(config, name, &raw_member);
3982
0
    if (spec == NULL) {
3983
0
        return -1;
3984
0
    }
3985
3986
0
    if (spec->type != PyConfig_MEMBER_WSTR
3987
0
        && spec->type != PyConfig_MEMBER_WSTR_OPT)
3988
0
    {
3989
0
        initconfig_set_error(config, "config option type is not string");
3990
0
        return -1;
3991
0
    }
3992
3993
0
    wchar_t **member = raw_member;
3994
0
    if (*member == NULL) {
3995
0
        *value = NULL;
3996
0
        return 0;
3997
0
    }
3998
3999
0
    *value = wstr_to_utf8(config, *member);
4000
0
    if (*value == NULL) {
4001
0
        return -1;
4002
0
    }
4003
0
    return 0;
4004
0
}
4005
4006
4007
int
4008
PyInitConfig_GetStrList(PyInitConfig *config, const char *name, size_t *length, char ***items)
4009
0
{
4010
0
    void *raw_member;
4011
0
    const PyConfigSpec *spec = initconfig_prepare(config, name, &raw_member);
4012
0
    if (spec == NULL) {
4013
0
        return -1;
4014
0
    }
4015
4016
0
    if (spec->type != PyConfig_MEMBER_WSTR_LIST) {
4017
0
        initconfig_set_error(config, "config option type is not string list");
4018
0
        return -1;
4019
0
    }
4020
4021
0
    PyWideStringList *list = raw_member;
4022
0
    *length = list->length;
4023
4024
0
    *items = malloc(list->length * sizeof(char*));
4025
0
    if (*items == NULL) {
4026
0
        config->status = _PyStatus_NO_MEMORY();
4027
0
        return -1;
4028
0
    }
4029
4030
0
    for (Py_ssize_t i=0; i < list->length; i++) {
4031
0
        (*items)[i] = wstr_to_utf8(config, list->items[i]);
4032
0
        if ((*items)[i] == NULL) {
4033
0
            PyInitConfig_FreeStrList(i, *items);
4034
0
            return -1;
4035
0
        }
4036
0
    }
4037
0
    return 0;
4038
0
}
4039
4040
4041
void
4042
PyInitConfig_FreeStrList(size_t length, char **items)
4043
0
{
4044
0
    for (size_t i=0; i < length; i++) {
4045
0
        free(items[i]);
4046
0
    }
4047
0
    free(items);
4048
0
}
4049
4050
4051
int
4052
PyInitConfig_SetInt(PyInitConfig *config, const char *name, int64_t value)
4053
0
{
4054
0
    void *raw_member;
4055
0
    const PyConfigSpec *spec = initconfig_prepare(config, name, &raw_member);
4056
0
    if (spec == NULL) {
4057
0
        return -1;
4058
0
    }
4059
4060
0
    switch (spec->type) {
4061
0
    case PyConfig_MEMBER_INT:
4062
0
    {
4063
0
        if (value < (int64_t)INT_MIN || (int64_t)INT_MAX < value) {
4064
0
            initconfig_set_error(config,
4065
0
                "config option value is out of int range");
4066
0
            return -1;
4067
0
        }
4068
0
        int int_value = (int)value;
4069
4070
0
        int *member = raw_member;
4071
0
        *member = int_value;
4072
0
        break;
4073
0
    }
4074
4075
0
    case PyConfig_MEMBER_UINT:
4076
0
    case PyConfig_MEMBER_BOOL:
4077
0
    {
4078
0
        if (value < 0 || (uint64_t)UINT_MAX < (uint64_t)value) {
4079
0
            initconfig_set_error(config,
4080
0
                "config option value is out of unsigned int range");
4081
0
            return -1;
4082
0
        }
4083
0
        int int_value = (int)value;
4084
4085
0
        int *member = raw_member;
4086
0
        *member = int_value;
4087
0
        break;
4088
0
    }
4089
4090
0
    case PyConfig_MEMBER_ULONG:
4091
0
    {
4092
0
        if (value < 0 || (uint64_t)ULONG_MAX < (uint64_t)value) {
4093
0
            initconfig_set_error(config,
4094
0
                "config option value is out of unsigned long range");
4095
0
            return -1;
4096
0
        }
4097
0
        unsigned long ulong_value = (unsigned long)value;
4098
4099
0
        unsigned long *member = raw_member;
4100
0
        *member = ulong_value;
4101
0
        break;
4102
0
    }
4103
4104
0
    default:
4105
0
        initconfig_set_error(config, "config option type is not int");
4106
0
        return -1;
4107
0
    }
4108
4109
0
    if (strcmp(name, "hash_seed") == 0) {
4110
0
        config->config.use_hash_seed = 1;
4111
0
    }
4112
4113
0
    return 0;
4114
0
}
4115
4116
4117
static wchar_t*
4118
utf8_to_wstr(PyInitConfig *config, const char *str)
4119
0
{
4120
0
    wchar_t *wstr;
4121
0
    size_t wlen;
4122
0
    int res = _Py_DecodeUTF8Ex(str, strlen(str), &wstr, &wlen, NULL, _Py_ERROR_STRICT);
4123
0
    if (res == -2) {
4124
0
        initconfig_set_error(config, "decoding error");
4125
0
        return NULL;
4126
0
    }
4127
0
    if (res < 0) {
4128
0
        config->status = _PyStatus_NO_MEMORY();
4129
0
        return NULL;
4130
0
    }
4131
4132
    // Copy to use the malloc() memory allocator
4133
0
    size_t size = (wlen + 1) * sizeof(wchar_t);
4134
0
    wchar_t *wstr2 = malloc(size);
4135
0
    if (wstr2 == NULL) {
4136
0
        PyMem_RawFree(wstr);
4137
0
        config->status = _PyStatus_NO_MEMORY();
4138
0
        return NULL;
4139
0
    }
4140
4141
0
    memcpy(wstr2, wstr, size);
4142
0
    PyMem_RawFree(wstr);
4143
0
    return wstr2;
4144
0
}
4145
4146
4147
int
4148
PyInitConfig_SetStr(PyInitConfig *config, const char *name, const char* value)
4149
0
{
4150
0
    void *raw_member;
4151
0
    const PyConfigSpec *spec = initconfig_prepare(config, name, &raw_member);
4152
0
    if (spec == NULL) {
4153
0
        return -1;
4154
0
    }
4155
4156
0
    if (spec->type != PyConfig_MEMBER_WSTR
4157
0
            && spec->type != PyConfig_MEMBER_WSTR_OPT) {
4158
0
        initconfig_set_error(config, "config option type is not string");
4159
0
        return -1;
4160
0
    }
4161
4162
0
    if (value == NULL && spec->type != PyConfig_MEMBER_WSTR_OPT) {
4163
0
        initconfig_set_error(config, "config option string cannot be NULL");
4164
0
    }
4165
4166
0
    wchar_t **member = raw_member;
4167
4168
0
    *member = utf8_to_wstr(config, value);
4169
0
    if (*member == NULL) {
4170
0
        return -1;
4171
0
    }
4172
0
    return 0;
4173
0
}
4174
4175
4176
static void
4177
initconfig_free_wstr(wchar_t *member)
4178
0
{
4179
0
    if (member) {
4180
0
        free(member);
4181
0
    }
4182
0
}
4183
4184
4185
static void
4186
initconfig_free_wstr_list(PyWideStringList *list)
4187
0
{
4188
0
    for (Py_ssize_t i = 0; i < list->length; i++) {
4189
0
        free(list->items[i]);
4190
0
    }
4191
0
    free(list->items);
4192
0
}
4193
4194
4195
static void
4196
initconfig_free_config(const PyConfig *config)
4197
0
{
4198
0
    const PyConfigSpec *spec = PYCONFIG_SPEC;
4199
0
    for (; spec->name != NULL; spec++) {
4200
0
        void *member = config_get_spec_member(config, spec);
4201
0
        if (spec->type == PyConfig_MEMBER_WSTR
4202
0
            || spec->type == PyConfig_MEMBER_WSTR_OPT)
4203
0
        {
4204
0
            wchar_t *wstr = *(wchar_t **)member;
4205
0
            initconfig_free_wstr(wstr);
4206
0
        }
4207
0
        else if (spec->type == PyConfig_MEMBER_WSTR_LIST) {
4208
0
            initconfig_free_wstr_list(member);
4209
0
        }
4210
0
    }
4211
0
}
4212
4213
4214
static int
4215
initconfig_set_str_list(PyInitConfig *config, PyWideStringList *list,
4216
                        Py_ssize_t length, char * const *items)
4217
0
{
4218
0
    PyWideStringList wlist = _PyWideStringList_INIT;
4219
0
    size_t size = sizeof(wchar_t*) * length;
4220
0
    wlist.items = (wchar_t **)malloc(size);
4221
0
    if (wlist.items == NULL) {
4222
0
        config->status = _PyStatus_NO_MEMORY();
4223
0
        return -1;
4224
0
    }
4225
4226
0
    for (Py_ssize_t i = 0; i < length; i++) {
4227
0
        wchar_t *arg = utf8_to_wstr(config, items[i]);
4228
0
        if (arg == NULL) {
4229
0
            initconfig_free_wstr_list(&wlist);
4230
0
            return -1;
4231
0
        }
4232
0
        wlist.items[i] = arg;
4233
0
        wlist.length++;
4234
0
    }
4235
4236
0
    initconfig_free_wstr_list(list);
4237
0
    *list = wlist;
4238
0
    return 0;
4239
0
}
4240
4241
4242
int
4243
PyInitConfig_SetStrList(PyInitConfig *config, const char *name,
4244
                        size_t length, char * const *items)
4245
0
{
4246
0
    void *raw_member;
4247
0
    const PyConfigSpec *spec = initconfig_prepare(config, name, &raw_member);
4248
0
    if (spec == NULL) {
4249
0
        return -1;
4250
0
    }
4251
4252
0
    if (spec->type != PyConfig_MEMBER_WSTR_LIST) {
4253
0
        initconfig_set_error(config, "config option type is not strings list");
4254
0
        return -1;
4255
0
    }
4256
0
    PyWideStringList *list = raw_member;
4257
0
    if (initconfig_set_str_list(config, list, length, items) < 0) {
4258
0
        return -1;
4259
0
    }
4260
4261
0
    if (strcmp(name, "module_search_paths") == 0) {
4262
0
        config->config.module_search_paths_set = 1;
4263
0
    }
4264
0
    return 0;
4265
0
}
4266
4267
4268
int
4269
PyInitConfig_AddModule(PyInitConfig *config, const char *name,
4270
                       PyObject* (*initfunc)(void))
4271
0
{
4272
0
    size_t size = sizeof(struct _inittab) * (config->inittab_size + 2);
4273
0
    struct _inittab *new_inittab = PyMem_RawRealloc(config->inittab, size);
4274
0
    if (new_inittab == NULL) {
4275
0
        config->status = _PyStatus_NO_MEMORY();
4276
0
        return -1;
4277
0
    }
4278
0
    config->inittab = new_inittab;
4279
4280
0
    struct _inittab *entry = &config->inittab[config->inittab_size];
4281
0
    entry->name = name;
4282
0
    entry->initfunc = initfunc;
4283
4284
    // Terminator entry
4285
0
    entry = &config->inittab[config->inittab_size + 1];
4286
0
    entry->name = NULL;
4287
0
    entry->initfunc = NULL;
4288
4289
0
    config->inittab_size++;
4290
0
    return 0;
4291
0
}
4292
4293
4294
int
4295
Py_InitializeFromInitConfig(PyInitConfig *config)
4296
0
{
4297
0
    if (config->inittab_size >= 1) {
4298
0
        if (PyImport_ExtendInittab(config->inittab) < 0) {
4299
0
            config->status = _PyStatus_NO_MEMORY();
4300
0
            return -1;
4301
0
        }
4302
0
    }
4303
4304
0
    _PyPreConfig_GetConfig(&config->preconfig, &config->config);
4305
4306
0
    config->status = Py_PreInitializeFromArgs(
4307
0
        &config->preconfig,
4308
0
        config->config.argv.length,
4309
0
        config->config.argv.items);
4310
0
    if (_PyStatus_EXCEPTION(config->status)) {
4311
0
        return -1;
4312
0
    }
4313
4314
0
    config->status = Py_InitializeFromConfig(&config->config);
4315
0
    if (_PyStatus_EXCEPTION(config->status)) {
4316
0
        return -1;
4317
0
    }
4318
4319
0
    return 0;
4320
0
}
4321
4322
4323
// --- PyConfig_Get() -------------------------------------------------------
4324
4325
static const PyConfigSpec*
4326
config_generic_find_spec(const PyConfigSpec *spec, const char *name)
4327
0
{
4328
0
    for (; spec->name != NULL; spec++) {
4329
0
        if (spec->visibility == PyConfig_MEMBER_INIT_ONLY) {
4330
0
            continue;
4331
0
        }
4332
0
        if (strcmp(name, spec->name) == 0) {
4333
0
            return spec;
4334
0
        }
4335
0
    }
4336
0
    return NULL;
4337
0
}
4338
4339
4340
static const PyConfigSpec*
4341
config_find_spec(const char *name)
4342
0
{
4343
0
    return config_generic_find_spec(PYCONFIG_SPEC, name);
4344
0
}
4345
4346
4347
static const PyConfigSpec*
4348
preconfig_find_spec(const char *name)
4349
0
{
4350
0
    return config_generic_find_spec(PYPRECONFIG_SPEC, name);
4351
0
}
4352
4353
4354
static int
4355
config_add_xoption(PyObject *dict, const wchar_t *str)
4356
0
{
4357
0
    PyObject *name = NULL, *value = NULL;
4358
4359
0
    const wchar_t *name_end = wcschr(str, L'=');
4360
0
    if (!name_end) {
4361
0
        name = PyUnicode_FromWideChar(str, -1);
4362
0
        if (name == NULL) {
4363
0
            goto error;
4364
0
        }
4365
0
        value = Py_NewRef(Py_True);
4366
0
    }
4367
0
    else {
4368
0
        name = PyUnicode_FromWideChar(str, name_end - str);
4369
0
        if (name == NULL) {
4370
0
            goto error;
4371
0
        }
4372
0
        value = PyUnicode_FromWideChar(name_end + 1, -1);
4373
0
        if (value == NULL) {
4374
0
            goto error;
4375
0
        }
4376
0
    }
4377
0
    if (PyDict_SetItem(dict, name, value) < 0) {
4378
0
        goto error;
4379
0
    }
4380
0
    Py_DECREF(name);
4381
0
    Py_DECREF(value);
4382
0
    return 0;
4383
4384
0
error:
4385
0
    Py_XDECREF(name);
4386
0
    Py_XDECREF(value);
4387
0
    return -1;
4388
0
}
4389
4390
4391
PyObject*
4392
_PyConfig_CreateXOptionsDict(const PyConfig *config)
4393
64
{
4394
64
    PyObject *dict = PyDict_New();
4395
64
    if (dict == NULL) {
4396
0
        return NULL;
4397
0
    }
4398
4399
64
    Py_ssize_t nxoption = config->xoptions.length;
4400
64
    wchar_t **xoptions = config->xoptions.items;
4401
64
    for (Py_ssize_t i=0; i < nxoption; i++) {
4402
0
        const wchar_t *option = xoptions[i];
4403
0
        if (config_add_xoption(dict, option) < 0) {
4404
0
            Py_DECREF(dict);
4405
0
            return NULL;
4406
0
        }
4407
0
    }
4408
64
    return dict;
4409
64
}
4410
4411
4412
static int
4413
config_get_sys_write_bytecode(const PyConfig *config, int *value)
4414
0
{
4415
0
    PyObject *attr = PySys_GetAttrString("dont_write_bytecode");
4416
0
    if (attr == NULL) {
4417
0
        return -1;
4418
0
    }
4419
4420
0
    int is_true = PyObject_IsTrue(attr);
4421
0
    Py_DECREF(attr);
4422
0
    if (is_true < 0) {
4423
0
        return -1;
4424
0
    }
4425
0
    *value = (!is_true);
4426
0
    return 0;
4427
0
}
4428
4429
4430
static PyObject*
4431
config_get(const PyConfig *config, const PyConfigSpec *spec,
4432
           int use_sys)
4433
2.27k
{
4434
2.27k
    if (use_sys) {
4435
0
        if (spec->sys.attr != NULL) {
4436
0
            return PySys_GetAttrString(spec->sys.attr);
4437
0
        }
4438
4439
0
        if (strcmp(spec->name, "write_bytecode") == 0) {
4440
0
            int value;
4441
0
            if (config_get_sys_write_bytecode(config, &value) < 0) {
4442
0
                return NULL;
4443
0
            }
4444
0
            return PyBool_FromLong(value);
4445
0
        }
4446
4447
0
        if (strcmp(spec->name, "int_max_str_digits") == 0) {
4448
0
            PyInterpreterState *interp = _PyInterpreterState_GET();
4449
0
            return PyLong_FromLong(interp->long_state.max_str_digits);
4450
0
        }
4451
0
    }
4452
4453
2.27k
    void *member = config_get_spec_member(config, spec);
4454
2.27k
    switch (spec->type) {
4455
128
    case PyConfig_MEMBER_INT:
4456
384
    case PyConfig_MEMBER_UINT:
4457
384
    {
4458
384
        int value = *(int *)member;
4459
384
        return PyLong_FromLong(value);
4460
128
    }
4461
4462
992
    case PyConfig_MEMBER_BOOL:
4463
992
    {
4464
992
        int value = *(int *)member;
4465
992
        return PyBool_FromLong(value != 0);
4466
128
    }
4467
4468
32
    case PyConfig_MEMBER_ULONG:
4469
32
    {
4470
32
        unsigned long value = *(unsigned long *)member;
4471
32
        return PyLong_FromUnsignedLong(value);
4472
128
    }
4473
4474
224
    case PyConfig_MEMBER_WSTR:
4475
704
    case PyConfig_MEMBER_WSTR_OPT:
4476
704
    {
4477
704
        wchar_t *wstr = *(wchar_t **)member;
4478
704
        if (wstr != NULL) {
4479
160
            return PyUnicode_FromWideChar(wstr, -1);
4480
160
        }
4481
544
        else {
4482
544
            return Py_NewRef(Py_None);
4483
544
        }
4484
704
    }
4485
4486
160
    case PyConfig_MEMBER_WSTR_LIST:
4487
160
    {
4488
160
        if (strcmp(spec->name, "xoptions") == 0) {
4489
32
            return _PyConfig_CreateXOptionsDict(config);
4490
32
        }
4491
128
        else {
4492
128
            const PyWideStringList *list = (const PyWideStringList *)member;
4493
128
            return _PyWideStringList_AsTuple(list);
4494
128
        }
4495
160
    }
4496
4497
0
    default:
4498
0
        Py_UNREACHABLE();
4499
2.27k
    }
4500
2.27k
}
4501
4502
4503
static PyObject*
4504
preconfig_get(const PyPreConfig *preconfig, const PyConfigSpec *spec)
4505
0
{
4506
    // The type of all PYPRECONFIG_SPEC members is INT or BOOL.
4507
0
    assert(spec->type == PyConfig_MEMBER_INT
4508
0
           || spec->type == PyConfig_MEMBER_BOOL);
4509
4510
0
    char *member = (char *)preconfig + spec->offset;
4511
0
    int value = *(int *)member;
4512
4513
0
    if (spec->type == PyConfig_MEMBER_BOOL) {
4514
0
        return PyBool_FromLong(value != 0);
4515
0
    }
4516
0
    else {
4517
0
        return PyLong_FromLong(value);
4518
0
    }
4519
0
}
4520
4521
4522
static void
4523
config_unknown_name_error(const char *name)
4524
0
{
4525
0
    PyErr_Format(PyExc_ValueError, "unknown config option name: %s", name);
4526
0
}
4527
4528
4529
PyObject*
4530
PyConfig_Get(const char *name)
4531
0
{
4532
0
    const PyConfigSpec *spec = config_find_spec(name);
4533
0
    if (spec != NULL) {
4534
0
        const PyConfig *config = _Py_GetConfig();
4535
0
        return config_get(config, spec, 1);
4536
0
    }
4537
4538
0
    spec = preconfig_find_spec(name);
4539
0
    if (spec != NULL) {
4540
0
        const PyPreConfig *preconfig = &_PyRuntime.preconfig;
4541
0
        return preconfig_get(preconfig, spec);
4542
0
    }
4543
4544
0
    config_unknown_name_error(name);
4545
0
    return NULL;
4546
0
}
4547
4548
4549
int
4550
PyConfig_GetInt(const char *name, int *value)
4551
0
{
4552
0
    assert(!PyErr_Occurred());
4553
4554
0
    PyObject *obj = PyConfig_Get(name);
4555
0
    if (obj == NULL) {
4556
0
        return -1;
4557
0
    }
4558
4559
0
    if (!PyLong_Check(obj)) {
4560
0
        Py_DECREF(obj);
4561
0
        PyErr_Format(PyExc_TypeError, "config option %s is not an int", name);
4562
0
        return -1;
4563
0
    }
4564
4565
0
    int as_int = PyLong_AsInt(obj);
4566
0
    Py_DECREF(obj);
4567
0
    if (as_int == -1 && PyErr_Occurred()) {
4568
0
        PyErr_Format(PyExc_OverflowError,
4569
0
                     "config option %s value does not fit into a C int", name);
4570
0
        return -1;
4571
0
    }
4572
4573
0
    *value = as_int;
4574
0
    return 0;
4575
0
}
4576
4577
4578
static int
4579
config_names_add(PyObject *names, const PyConfigSpec *spec)
4580
0
{
4581
0
    for (; spec->name != NULL; spec++) {
4582
0
        if (spec->visibility == PyConfig_MEMBER_INIT_ONLY) {
4583
0
            continue;
4584
0
        }
4585
0
        PyObject *name = PyUnicode_FromString(spec->name);
4586
0
        if (name == NULL) {
4587
0
            return -1;
4588
0
        }
4589
0
        int res = PyList_Append(names, name);
4590
0
        Py_DECREF(name);
4591
0
        if (res < 0) {
4592
0
            return -1;
4593
0
        }
4594
0
    }
4595
0
    return 0;
4596
0
}
4597
4598
4599
PyObject*
4600
PyConfig_Names(void)
4601
0
{
4602
0
    PyObject *names = PyList_New(0);
4603
0
    if (names == NULL) {
4604
0
        goto error;
4605
0
    }
4606
4607
0
    if (config_names_add(names, PYCONFIG_SPEC) < 0) {
4608
0
        goto error;
4609
0
    }
4610
0
    if (config_names_add(names, PYPRECONFIG_SPEC) < 0) {
4611
0
        goto error;
4612
0
    }
4613
4614
0
    PyObject *frozen = PyFrozenSet_New(names);
4615
0
    Py_DECREF(names);
4616
0
    return frozen;
4617
4618
0
error:
4619
0
    Py_XDECREF(names);
4620
0
    return NULL;
4621
0
}
4622
4623
4624
// --- PyConfig_Set() -------------------------------------------------------
4625
4626
static int
4627
config_set_sys_flag(const PyConfigSpec *spec, int int_value)
4628
0
{
4629
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
4630
0
    PyConfig *config = &interp->config;
4631
4632
0
    if (spec->type == PyConfig_MEMBER_BOOL) {
4633
0
        if (int_value != 0) {
4634
            // convert values < 0 and values > 1 to 1
4635
0
            int_value = 1;
4636
0
        }
4637
0
    }
4638
4639
0
    PyObject *value;
4640
0
    if (spec->sys.flag_setter) {
4641
0
        value = spec->sys.flag_setter(int_value);
4642
0
    }
4643
0
    else {
4644
0
        value = config_sys_flag_long(int_value);
4645
0
    }
4646
0
    if (value == NULL) {
4647
0
        return -1;
4648
0
    }
4649
4650
    // Set sys.flags.FLAG
4651
0
    Py_ssize_t pos = spec->sys.flag_index;
4652
0
    if (_PySys_SetFlagObj(pos, value) < 0) {
4653
0
        goto error;
4654
0
    }
4655
4656
    // Set PyConfig.ATTR
4657
0
    assert(spec->type == PyConfig_MEMBER_INT
4658
0
           || spec->type == PyConfig_MEMBER_UINT
4659
0
           || spec->type == PyConfig_MEMBER_BOOL);
4660
0
    int *member = config_get_spec_member(config, spec);
4661
0
    *member = int_value;
4662
4663
    // Set sys.dont_write_bytecode attribute
4664
0
    if (strcmp(spec->name, "write_bytecode") == 0) {
4665
0
        if (PySys_SetObject("dont_write_bytecode", value) < 0) {
4666
0
            goto error;
4667
0
        }
4668
0
    }
4669
4670
0
    Py_DECREF(value);
4671
0
    return 0;
4672
4673
0
error:
4674
0
    Py_DECREF(value);
4675
0
    return -1;
4676
0
}
4677
4678
4679
// Set PyConfig.ATTR integer member
4680
static int
4681
config_set_int_attr(const PyConfigSpec *spec, int value)
4682
0
{
4683
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
4684
0
    PyConfig *config = &interp->config;
4685
0
    int *member = config_get_spec_member(config, spec);
4686
0
    *member = value;
4687
0
    return 0;
4688
0
}
4689
4690
4691
int
4692
PyConfig_Set(const char *name, PyObject *value)
4693
0
{
4694
0
    if (PySys_Audit("cpython.PyConfig_Set", "sO", name, value) < 0) {
4695
0
        return -1;
4696
0
    }
4697
4698
0
    const PyConfigSpec *spec = config_find_spec(name);
4699
0
    if (spec == NULL) {
4700
0
        spec = preconfig_find_spec(name);
4701
0
        if (spec == NULL) {
4702
0
            config_unknown_name_error(name);
4703
0
            return -1;
4704
0
        }
4705
0
        assert(spec->visibility != PyConfig_MEMBER_PUBLIC);
4706
0
    }
4707
4708
0
    if (spec->visibility != PyConfig_MEMBER_PUBLIC) {
4709
0
        PyErr_Format(PyExc_ValueError, "cannot set read-only option %s",
4710
0
                     name);
4711
0
        return -1;
4712
0
    }
4713
4714
0
    int int_value = 0;
4715
0
    int has_int_value = 0;
4716
4717
0
    switch (spec->type) {
4718
0
    case PyConfig_MEMBER_INT:
4719
0
    case PyConfig_MEMBER_UINT:
4720
0
    case PyConfig_MEMBER_BOOL:
4721
0
        if (!PyLong_Check(value)) {
4722
0
            PyErr_Format(PyExc_TypeError, "expected int or bool, got %T", value);
4723
0
            return -1;
4724
0
        }
4725
0
        int_value = PyLong_AsInt(value);
4726
0
        if (int_value == -1 && PyErr_Occurred()) {
4727
0
            return -1;
4728
0
        }
4729
0
        if (int_value < 0 && spec->type != PyConfig_MEMBER_INT) {
4730
0
            PyErr_Format(PyExc_ValueError, "value must be >= 0");
4731
0
            return -1;
4732
0
        }
4733
0
        has_int_value = 1;
4734
0
        break;
4735
4736
0
    case PyConfig_MEMBER_ULONG:
4737
        // not implemented: only hash_seed uses this type, and it's read-only
4738
0
        goto cannot_set;
4739
4740
0
    case PyConfig_MEMBER_WSTR:
4741
0
        if (!PyUnicode_CheckExact(value)) {
4742
0
            PyErr_Format(PyExc_TypeError, "expected str, got %T", value);
4743
0
            return -1;
4744
0
        }
4745
0
        break;
4746
4747
0
    case PyConfig_MEMBER_WSTR_OPT:
4748
0
        if (value != Py_None && !PyUnicode_CheckExact(value)) {
4749
0
            PyErr_Format(PyExc_TypeError, "expected str or None, got %T", value);
4750
0
            return -1;
4751
0
        }
4752
0
        break;
4753
4754
0
    case PyConfig_MEMBER_WSTR_LIST:
4755
0
        if (strcmp(spec->name, "xoptions") != 0) {
4756
0
            if (!PyList_Check(value)) {
4757
0
                PyErr_Format(PyExc_TypeError, "expected list[str], got %T",
4758
0
                             value);
4759
0
                return -1;
4760
0
            }
4761
0
            for (Py_ssize_t i=0; i < PyList_GET_SIZE(value); i++) {
4762
0
                PyObject *item = PyList_GET_ITEM(value, i);
4763
0
                if (!PyUnicode_Check(item)) {
4764
0
                    PyErr_Format(PyExc_TypeError,
4765
0
                                 "expected str, list item %zd has type %T",
4766
0
                                 i, item);
4767
0
                    return -1;
4768
0
                }
4769
0
            }
4770
0
        }
4771
0
        else {
4772
            // xoptions type is dict[str, str]
4773
0
            if (!PyDict_Check(value)) {
4774
0
                PyErr_Format(PyExc_TypeError,
4775
0
                             "expected dict[str, str | bool], got %T",
4776
0
                             value);
4777
0
                return -1;
4778
0
            }
4779
4780
0
            Py_ssize_t pos = 0;
4781
0
            PyObject *key, *item;
4782
0
            while (PyDict_Next(value, &pos, &key, &item)) {
4783
0
                if (!PyUnicode_Check(key)) {
4784
0
                    PyErr_Format(PyExc_TypeError,
4785
0
                                 "expected str, "
4786
0
                                 "got dict key type %T", key);
4787
0
                    return -1;
4788
0
                }
4789
0
                if (!PyUnicode_Check(item) && !PyBool_Check(item)) {
4790
0
                    PyErr_Format(PyExc_TypeError,
4791
0
                                 "expected str or bool, "
4792
0
                                 "got dict value type %T", key);
4793
0
                    return -1;
4794
0
                }
4795
0
            }
4796
0
        }
4797
0
        break;
4798
4799
0
    default:
4800
0
        Py_UNREACHABLE();
4801
0
    }
4802
4803
0
    if (spec->sys.attr != NULL) {
4804
        // Set the sys attribute, but don't set PyInterpreterState.config
4805
        // to keep the code simple.
4806
0
        return PySys_SetObject(spec->sys.attr, value);
4807
0
    }
4808
0
    else if (has_int_value) {
4809
0
        if (spec->sys.flag_index >= 0) {
4810
0
            return config_set_sys_flag(spec, int_value);
4811
0
        }
4812
0
        else if (strcmp(spec->name, "int_max_str_digits") == 0) {
4813
0
            return _PySys_SetIntMaxStrDigits(int_value);
4814
0
        }
4815
0
        else {
4816
0
            return config_set_int_attr(spec, int_value);
4817
0
        }
4818
0
    }
4819
4820
0
cannot_set:
4821
0
    PyErr_Format(PyExc_ValueError, "cannot set option %s", name);
4822
0
    return -1;
4823
0
}