Coverage Report

Created: 2026-03-23 06:45

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