Coverage Report

Created: 2025-10-10 06:33

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