Coverage Report

Created: 2025-11-24 06:11

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
56
{
566
56
_Py_COMP_DIAG_PUSH
567
56
_Py_COMP_DIAG_IGNORE_DEPR_DECLS
568
56
    if (Py_IgnoreEnvironmentFlag) {
569
0
        return NULL;
570
0
    }
571
56
    return getenv(name);
572
56
_Py_COMP_DIAG_POP
573
56
}
574
575
/* --- PyStatus ----------------------------------------------- */
576
577
PyStatus PyStatus_Ok(void)
578
84
{ 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
1.40k
{
656
1.40k
    assert(_PyWideStringList_CheckConsistency(list));
657
1.56k
    for (Py_ssize_t i=0; i < list->length; i++) {
658
168
        if (use_default_allocator) {
659
0
            _PyMem_DefaultRawFree(list->items[i]);
660
0
        }
661
168
        else {
662
168
            PyMem_RawFree(list->items[i]);
663
168
        }
664
168
    }
665
1.40k
    if (use_default_allocator) {
666
28
        _PyMem_DefaultRawFree(list->items);
667
28
    }
668
1.37k
    else {
669
1.37k
        PyMem_RawFree(list->items);
670
1.37k
    }
671
1.40k
    list->length = 0;
672
1.40k
    list->items = NULL;
673
1.40k
}
674
675
void
676
_PyWideStringList_Clear(PyWideStringList *list)
677
924
{
678
924
    _PyWideStringList_ClearEx(list, false);
679
924
}
680
681
static int
682
_PyWideStringList_CopyEx(PyWideStringList *list,
683
                         const PyWideStringList *list2,
684
                         bool use_default_allocator)
685
476
{
686
476
    assert(_PyWideStringList_CheckConsistency(list));
687
476
    assert(_PyWideStringList_CheckConsistency(list2));
688
689
476
    if (list2->length == 0) {
690
392
        _PyWideStringList_ClearEx(list, use_default_allocator);
691
392
        return 0;
692
392
    }
693
694
84
    PyWideStringList copy = _PyWideStringList_INIT;
695
696
84
    size_t size = list2->length * sizeof(list2->items[0]);
697
84
    if (use_default_allocator) {
698
0
        copy.items = _PyMem_DefaultRawMalloc(size);
699
0
    }
700
84
    else {
701
84
        copy.items = PyMem_RawMalloc(size);
702
84
    }
703
84
    if (copy.items == NULL) {
704
0
        return -1;
705
0
    }
706
707
224
    for (Py_ssize_t i=0; i < list2->length; i++) {
708
140
        wchar_t *item;
709
140
        if (use_default_allocator) {
710
0
            item = _PyMem_DefaultRawWcsdup(list2->items[i]);
711
0
        }
712
140
        else {
713
140
            item = _PyMem_RawWcsdup(list2->items[i]);
714
140
        }
715
140
        if (item == NULL) {
716
0
            _PyWideStringList_ClearEx(&copy, use_default_allocator);
717
0
            return -1;
718
0
        }
719
140
        copy.items[i] = item;
720
140
        copy.length = i + 1;
721
140
    }
722
723
84
    _PyWideStringList_ClearEx(list, use_default_allocator);
724
84
    *list = copy;
725
84
    return 0;
726
84
}
727
728
int
729
_PyWideStringList_Copy(PyWideStringList *list, const PyWideStringList *list2)
730
448
{
731
448
    return _PyWideStringList_CopyEx(list, list2, false);
732
448
}
733
734
PyStatus
735
PyWideStringList_Insert(PyWideStringList *list,
736
                        Py_ssize_t index, const wchar_t *item)
737
140
{
738
140
    Py_ssize_t len = list->length;
739
140
    if (len == PY_SSIZE_T_MAX) {
740
        /* length+1 would overflow */
741
0
        return _PyStatus_NO_MEMORY();
742
0
    }
743
140
    if (index < 0) {
744
0
        return _PyStatus_ERR("PyWideStringList_Insert index must be >= 0");
745
0
    }
746
140
    if (index > len) {
747
0
        index = len;
748
0
    }
749
750
140
    wchar_t *item2 = _PyMem_RawWcsdup(item);
751
140
    if (item2 == NULL) {
752
0
        return _PyStatus_NO_MEMORY();
753
0
    }
754
755
140
    size_t size = (len + 1) * sizeof(list->items[0]);
756
140
    wchar_t **items2 = (wchar_t **)PyMem_RawRealloc(list->items, size);
757
140
    if (items2 == NULL) {
758
0
        PyMem_RawFree(item2);
759
0
        return _PyStatus_NO_MEMORY();
760
0
    }
761
762
140
    if (index < len) {
763
0
        memmove(&items2[index + 1],
764
0
                &items2[index],
765
0
                (len - index) * sizeof(items2[0]));
766
0
    }
767
768
140
    items2[index] = item2;
769
140
    list->items = items2;
770
140
    list->length++;
771
140
    return _PyStatus_OK();
772
140
}
773
774
775
PyStatus
776
PyWideStringList_Append(PyWideStringList *list, const wchar_t *item)
777
140
{
778
140
    return PyWideStringList_Insert(list, list->length, item);
779
140
}
780
781
782
PyStatus
783
_PyWideStringList_Extend(PyWideStringList *list, const PyWideStringList *list2)
784
56
{
785
56
    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
56
    return _PyStatus_OK();
792
56
}
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
112
{
810
112
    assert(_PyWideStringList_CheckConsistency(list));
811
812
112
    PyObject *pylist = PyList_New(list->length);
813
112
    if (pylist == NULL) {
814
0
        return NULL;
815
0
    }
816
817
224
    for (Py_ssize_t i = 0; i < list->length; i++) {
818
112
        PyObject *item = PyUnicode_FromWideChar(list->items[i], -1);
819
112
        if (item == NULL) {
820
0
            Py_DECREF(pylist);
821
0
            return NULL;
822
0
        }
823
112
        PyList_SET_ITEM(pylist, i, item);
824
112
    }
825
112
    return pylist;
826
112
}
827
828
829
static PyObject*
830
_PyWideStringList_AsTuple(const PyWideStringList *list)
831
112
{
832
112
    assert(_PyWideStringList_CheckConsistency(list));
833
834
112
    PyObject *tuple = PyTuple_New(list->length);
835
112
    if (tuple == NULL) {
836
0
        return NULL;
837
0
    }
838
839
140
    for (Py_ssize_t i = 0; i < list->length; i++) {
840
28
        PyObject *item = PyUnicode_FromWideChar(list->items[i], -1);
841
28
        if (item == NULL) {
842
0
            Py_DECREF(tuple);
843
0
            return NULL;
844
0
        }
845
28
        PyTuple_SET_ITEM(tuple, i, item);
846
28
    }
847
112
    return tuple;
848
112
}
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
28
{
863
28
    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
28
    return _PyWideStringList_CopyEx(&_PyRuntime.orig_argv, &argv_list, true);
868
28
}
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
28
#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
112
{
961
112
#define CLEAR(ATTR) \
962
2.35k
    do { \
963
2.35k
        PyMem_RawFree(ATTR); \
964
2.35k
        ATTR = NULL; \
965
2.35k
    } while (0)
966
967
112
    CLEAR(config->pycache_prefix);
968
112
    CLEAR(config->pythonpath_env);
969
112
    CLEAR(config->home);
970
112
    CLEAR(config->program_name);
971
972
112
    _PyWideStringList_Clear(&config->argv);
973
112
    _PyWideStringList_Clear(&config->warnoptions);
974
112
    _PyWideStringList_Clear(&config->xoptions);
975
112
    _PyWideStringList_Clear(&config->module_search_paths);
976
112
    config->module_search_paths_set = 0;
977
112
    CLEAR(config->stdlib_dir);
978
979
112
    CLEAR(config->executable);
980
112
    CLEAR(config->base_executable);
981
112
    CLEAR(config->prefix);
982
112
    CLEAR(config->base_prefix);
983
112
    CLEAR(config->exec_prefix);
984
112
    CLEAR(config->base_exec_prefix);
985
112
    CLEAR(config->platlibdir);
986
112
    CLEAR(config->sys_path_0);
987
988
112
    CLEAR(config->filesystem_encoding);
989
112
    CLEAR(config->filesystem_errors);
990
112
    CLEAR(config->stdio_encoding);
991
112
    CLEAR(config->stdio_errors);
992
112
    CLEAR(config->run_command);
993
112
    CLEAR(config->run_module);
994
112
    CLEAR(config->run_filename);
995
112
    CLEAR(config->check_hash_pycs_mode);
996
#ifdef Py_DEBUG
997
    CLEAR(config->run_presite);
998
#endif
999
1000
112
    _PyWideStringList_Clear(&config->orig_argv);
1001
112
#undef CLEAR
1002
112
}
1003
1004
1005
void
1006
_PyConfig_InitCompatConfig(PyConfig *config)
1007
84
{
1008
84
    memset(config, 0, sizeof(*config));
1009
1010
84
    config->_config_init = (int)_PyConfig_INIT_COMPAT;
1011
84
    config->import_time = -1;
1012
84
    config->isolated = -1;
1013
84
    config->use_environment = -1;
1014
84
    config->dev_mode = -1;
1015
84
    config->install_signal_handlers = 1;
1016
84
    config->use_hash_seed = -1;
1017
84
    config->faulthandler = -1;
1018
84
    config->tracemalloc = -1;
1019
84
    config->perf_profiling = -1;
1020
84
    config->remote_debug = -1;
1021
84
    config->module_search_paths_set = 0;
1022
84
    config->parse_argv = 0;
1023
84
    config->site_import = -1;
1024
84
    config->bytes_warning = -1;
1025
84
    config->warn_default_encoding = 0;
1026
84
    config->inspect = -1;
1027
84
    config->interactive = -1;
1028
84
    config->optimization_level = -1;
1029
84
    config->parser_debug= -1;
1030
84
    config->write_bytecode = -1;
1031
84
    config->verbose = -1;
1032
84
    config->quiet = -1;
1033
84
    config->user_site_directory = -1;
1034
84
    config->configure_c_stdio = 0;
1035
84
    config->buffered_stdio = -1;
1036
84
    config->_install_importlib = 1;
1037
84
    config->check_hash_pycs_mode = NULL;
1038
84
    config->pathconfig_warnings = -1;
1039
84
    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
84
    config->use_frozen_modules = 1;
1047
84
#endif
1048
84
    config->safe_path = 0;
1049
84
    config->int_max_str_digits = -1;
1050
84
    config->_is_python_build = 0;
1051
84
    config->code_debug_ranges = 1;
1052
84
    config->cpu_count = -1;
1053
#ifdef Py_GIL_DISABLED
1054
    config->thread_inherit_context = 1;
1055
    config->context_aware_warnings = 1;
1056
#else
1057
84
    config->thread_inherit_context = 0;
1058
84
    config->context_aware_warnings = 0;
1059
84
#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
84
}
1068
1069
1070
static void
1071
config_init_defaults(PyConfig *config)
1072
56
{
1073
56
    _PyConfig_InitCompatConfig(config);
1074
1075
56
    config->isolated = 0;
1076
56
    config->use_environment = 1;
1077
56
    config->site_import = 1;
1078
56
    config->bytes_warning = 0;
1079
56
    config->inspect = 0;
1080
56
    config->interactive = 0;
1081
56
    config->optimization_level = 0;
1082
56
    config->parser_debug= 0;
1083
56
    config->write_bytecode = 1;
1084
56
    config->verbose = 0;
1085
56
    config->quiet = 0;
1086
56
    config->user_site_directory = 1;
1087
56
    config->buffered_stdio = 1;
1088
56
    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
56
    config->thread_inherit_context = 0;
1097
56
    config->context_aware_warnings = 0;
1098
56
#endif
1099
#ifdef __APPLE__
1100
    config->use_system_logger = USE_SYSTEM_LOGGER_DEFAULT;
1101
#endif
1102
56
}
1103
1104
1105
void
1106
PyConfig_InitPythonConfig(PyConfig *config)
1107
56
{
1108
56
    config_init_defaults(config);
1109
1110
56
    config->_config_init = (int)_PyConfig_INIT_PYTHON;
1111
56
    config->configure_c_stdio = 1;
1112
56
    config->parse_argv = 1;
1113
56
}
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.98k
{
1151
1.98k
    PyStatus status = _Py_PreInitializeFromConfig(config, NULL);
1152
1.98k
    if (_PyStatus_EXCEPTION(status)) {
1153
0
        return status;
1154
0
    }
1155
1156
1.98k
    wchar_t *str2;
1157
1.98k
    if (str != NULL) {
1158
700
        str2 = _PyMem_RawWcsdup(str);
1159
700
        if (str2 == NULL) {
1160
0
            return _PyStatus_NO_MEMORY();
1161
0
        }
1162
700
    }
1163
1.28k
    else {
1164
1.28k
        str2 = NULL;
1165
1.28k
    }
1166
1.98k
    PyMem_RawFree(*config_str);
1167
1.98k
    *config_str = str2;
1168
1.98k
    return _PyStatus_OK();
1169
1.98k
}
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
9.66k
{
1221
9.66k
    return (char *)config + spec->offset;
1222
9.66k
}
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
56
{
1235
56
    PyConfig_Clear(config);
1236
1237
56
    PyStatus status;
1238
56
    const PyConfigSpec *spec = PYCONFIG_SPEC;
1239
3.92k
    for (; spec->name != NULL; spec++) {
1240
3.86k
        void *member = config_get_spec_member(config, spec);
1241
3.86k
        const void *member2 = config_get_spec_member((PyConfig*)config2, spec);
1242
3.86k
        switch (spec->type) {
1243
168
        case PyConfig_MEMBER_INT:
1244
616
        case PyConfig_MEMBER_UINT:
1245
2.29k
        case PyConfig_MEMBER_BOOL:
1246
2.29k
        {
1247
2.29k
            *(int*)member = *(int*)member2;
1248
2.29k
            break;
1249
616
        }
1250
56
        case PyConfig_MEMBER_ULONG:
1251
56
        {
1252
56
            *(unsigned long*)member = *(unsigned long*)member2;
1253
56
            break;
1254
616
        }
1255
392
        case PyConfig_MEMBER_WSTR:
1256
1.23k
        case PyConfig_MEMBER_WSTR_OPT:
1257
1.23k
        {
1258
1.23k
            const wchar_t *str = *(const wchar_t**)member2;
1259
1.23k
            status = PyConfig_SetString(config, (wchar_t**)member, str);
1260
1.23k
            if (_PyStatus_EXCEPTION(status)) {
1261
0
                return status;
1262
0
            }
1263
1.23k
            break;
1264
1.23k
        }
1265
1.23k
        case PyConfig_MEMBER_WSTR_LIST:
1266
280
        {
1267
280
            if (_PyWideStringList_Copy((PyWideStringList*)member,
1268
280
                                       (const PyWideStringList*)member2) < 0) {
1269
0
                return _PyStatus_NO_MEMORY();
1270
0
            }
1271
280
            break;
1272
280
        }
1273
280
        default:
1274
0
            Py_UNREACHABLE();
1275
3.86k
        }
1276
3.86k
    }
1277
56
    return _PyStatus_OK();
1278
56
}
1279
1280
1281
PyObject *
1282
_PyConfig_AsDict(const PyConfig *config)
1283
28
{
1284
28
    PyObject *dict = PyDict_New();
1285
28
    if (dict == NULL) {
1286
0
        return NULL;
1287
0
    }
1288
1289
28
    const PyConfigSpec *spec = PYCONFIG_SPEC;
1290
1.96k
    for (; spec->name != NULL; spec++) {
1291
1.93k
        PyObject *obj = config_get(config, spec, 0);
1292
1.93k
        if (obj == NULL) {
1293
0
            Py_DECREF(dict);
1294
0
            return NULL;
1295
0
        }
1296
1297
1.93k
        int res = PyDict_SetItemString(dict, spec->name, obj);
1298
1.93k
        Py_DECREF(obj);
1299
1.93k
        if (res < 0) {
1300
0
            Py_DECREF(dict);
1301
0
            return NULL;
1302
0
        }
1303
1.93k
    }
1304
28
    return dict;
1305
28
}
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
1.14k
{
1318
1.14k
    PyObject *item = config_dict_get(dict, name);
1319
1.14k
    if (item == NULL) {
1320
0
        return -1;
1321
0
    }
1322
1.14k
    int value = PyLong_AsInt(item);
1323
1.14k
    Py_DECREF(item);
1324
1.14k
    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
1.14k
    *result = value;
1334
1.14k
    return 0;
1335
1.14k
}
1336
1337
1338
static int
1339
config_dict_get_ulong(PyObject *dict, const char *name, unsigned long *result)
1340
28
{
1341
28
    PyObject *item = config_dict_get(dict, name);
1342
28
    if (item == NULL) {
1343
0
        return -1;
1344
0
    }
1345
28
    unsigned long value = PyLong_AsUnsignedLong(item);
1346
28
    Py_DECREF(item);
1347
28
    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
28
    *result = value;
1357
28
    return 0;
1358
28
}
1359
1360
1361
static int
1362
config_dict_get_wstr(PyObject *dict, const char *name, PyConfig *config,
1363
                     wchar_t **result)
1364
616
{
1365
616
    PyObject *item = config_dict_get(dict, name);
1366
616
    if (item == NULL) {
1367
0
        return -1;
1368
0
    }
1369
1370
616
    PyStatus status;
1371
616
    if (item == Py_None) {
1372
196
        status = PyConfig_SetString(config, result, NULL);
1373
196
    }
1374
420
    else if (!PyUnicode_Check(item)) {
1375
0
        config_dict_invalid_type(name);
1376
0
        goto error;
1377
0
    }
1378
420
    else {
1379
420
        wchar_t *wstr = PyUnicode_AsWideCharString(item, NULL);
1380
420
        if (wstr == NULL) {
1381
0
            goto error;
1382
0
        }
1383
420
        status = PyConfig_SetString(config, result, wstr);
1384
420
        PyMem_Free(wstr);
1385
420
    }
1386
616
    if (_PyStatus_EXCEPTION(status)) {
1387
0
        PyErr_NoMemory();
1388
0
        goto error;
1389
0
    }
1390
616
    Py_DECREF(item);
1391
616
    return 0;
1392
1393
0
error:
1394
0
    Py_DECREF(item);
1395
0
    return -1;
1396
616
}
1397
1398
1399
static int
1400
config_dict_get_wstrlist(PyObject *dict, const char *name, PyConfig *config,
1401
                         PyWideStringList *result)
1402
112
{
1403
112
    PyObject *list = config_dict_get(dict, name);
1404
112
    if (list == NULL) {
1405
0
        return -1;
1406
0
    }
1407
1408
112
    int is_list = PyList_CheckExact(list);
1409
112
    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
112
    PyWideStringList wstrlist = _PyWideStringList_INIT;
1416
112
    Py_ssize_t len = is_list ? PyList_GET_SIZE(list) : PyTuple_GET_SIZE(list);
1417
224
    for (Py_ssize_t i=0; i < len; i++) {
1418
112
        PyObject *item = is_list ? PyList_GET_ITEM(list, i) : PyTuple_GET_ITEM(list, i);
1419
1420
112
        if (item == Py_None) {
1421
0
            config_dict_invalid_value(name);
1422
0
            goto error;
1423
0
        }
1424
112
        else if (!PyUnicode_Check(item)) {
1425
0
            config_dict_invalid_type(name);
1426
0
            goto error;
1427
0
        }
1428
112
        wchar_t *wstr = PyUnicode_AsWideCharString(item, NULL);
1429
112
        if (wstr == NULL) {
1430
0
            goto error;
1431
0
        }
1432
112
        PyStatus status = PyWideStringList_Append(&wstrlist, wstr);
1433
112
        PyMem_Free(wstr);
1434
112
        if (_PyStatus_EXCEPTION(status)) {
1435
0
            PyErr_NoMemory();
1436
0
            goto error;
1437
0
        }
1438
112
    }
1439
1440
112
    if (_PyWideStringList_Copy(result, &wstrlist) < 0) {
1441
0
        PyErr_NoMemory();
1442
0
        goto error;
1443
0
    }
1444
112
    _PyWideStringList_Clear(&wstrlist);
1445
112
    Py_DECREF(list);
1446
112
    return 0;
1447
1448
0
error:
1449
0
    _PyWideStringList_Clear(&wstrlist);
1450
0
    Py_DECREF(list);
1451
0
    return -1;
1452
112
}
1453
1454
1455
static int
1456
config_dict_get_xoptions(PyObject *dict, const char *name, PyConfig *config,
1457
                         PyWideStringList *result)
1458
28
{
1459
28
    PyObject *xoptions = config_dict_get(dict, name);
1460
28
    if (xoptions == NULL) {
1461
0
        return -1;
1462
0
    }
1463
1464
28
    if (!PyDict_CheckExact(xoptions)) {
1465
0
        Py_DECREF(xoptions);
1466
0
        config_dict_invalid_type(name);
1467
0
        return -1;
1468
0
    }
1469
1470
28
    Py_ssize_t pos = 0;
1471
28
    PyObject *key, *value;
1472
28
    PyWideStringList wstrlist = _PyWideStringList_INIT;
1473
28
    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
28
    if (_PyWideStringList_Copy(result, &wstrlist) < 0) {
1501
0
        PyErr_NoMemory();
1502
0
        goto error;
1503
0
    }
1504
28
    _PyWideStringList_Clear(&wstrlist);
1505
28
    Py_DECREF(xoptions);
1506
28
    return 0;
1507
1508
0
error:
1509
0
    _PyWideStringList_Clear(&wstrlist);
1510
0
    Py_DECREF(xoptions);
1511
0
    return -1;
1512
28
}
1513
1514
1515
int
1516
_PyConfig_FromDict(PyConfig *config, PyObject *dict)
1517
28
{
1518
28
    if (!PyDict_Check(dict)) {
1519
0
        PyErr_SetString(PyExc_TypeError, "dict expected");
1520
0
        return -1;
1521
0
    }
1522
1523
28
    const PyConfigSpec *spec = PYCONFIG_SPEC;
1524
1.96k
    for (; spec->name != NULL; spec++) {
1525
1.93k
        char *member = (char *)config + spec->offset;
1526
1.93k
        switch (spec->type) {
1527
84
        case PyConfig_MEMBER_INT:
1528
308
        case PyConfig_MEMBER_UINT:
1529
1.14k
        case PyConfig_MEMBER_BOOL:
1530
1.14k
        {
1531
1.14k
            int value;
1532
1.14k
            if (config_dict_get_int(dict, spec->name, &value) < 0) {
1533
0
                return -1;
1534
0
            }
1535
1.14k
            if (spec->type == PyConfig_MEMBER_BOOL
1536
308
                || spec->type == PyConfig_MEMBER_UINT)
1537
1.06k
            {
1538
1.06k
                if (value < 0) {
1539
0
                    config_dict_invalid_value(spec->name);
1540
0
                    return -1;
1541
0
                }
1542
1.06k
            }
1543
1.14k
            *(int*)member = value;
1544
1.14k
            break;
1545
1.14k
        }
1546
28
        case PyConfig_MEMBER_ULONG:
1547
28
        {
1548
28
            if (config_dict_get_ulong(dict, spec->name,
1549
28
                                      (unsigned long*)member) < 0) {
1550
0
                return -1;
1551
0
            }
1552
28
            break;
1553
28
        }
1554
196
        case PyConfig_MEMBER_WSTR:
1555
196
        {
1556
196
            wchar_t **wstr = (wchar_t**)member;
1557
196
            if (config_dict_get_wstr(dict, spec->name, config, wstr) < 0) {
1558
0
                return -1;
1559
0
            }
1560
196
            if (*wstr == NULL) {
1561
0
                config_dict_invalid_value(spec->name);
1562
0
                return -1;
1563
0
            }
1564
196
            break;
1565
196
        }
1566
420
        case PyConfig_MEMBER_WSTR_OPT:
1567
420
        {
1568
420
            wchar_t **wstr = (wchar_t**)member;
1569
420
            if (config_dict_get_wstr(dict, spec->name, config, wstr) < 0) {
1570
0
                return -1;
1571
0
            }
1572
420
            break;
1573
420
        }
1574
420
        case PyConfig_MEMBER_WSTR_LIST:
1575
140
        {
1576
140
            if (strcmp(spec->name, "xoptions") == 0) {
1577
28
                if (config_dict_get_xoptions(dict, spec->name, config,
1578
28
                                             (PyWideStringList*)member) < 0) {
1579
0
                    return -1;
1580
0
                }
1581
28
            }
1582
112
            else {
1583
112
                if (config_dict_get_wstrlist(dict, spec->name, config,
1584
112
                                             (PyWideStringList*)member) < 0) {
1585
0
                    return -1;
1586
0
                }
1587
112
            }
1588
140
            break;
1589
140
        }
1590
140
        default:
1591
0
            Py_UNREACHABLE();
1592
1.93k
        }
1593
1.93k
    }
1594
1595
28
    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
28
    if (config->hash_seed > MAX_HASH_SEED) {
1604
0
        config_dict_invalid_value("hash_seed");
1605
0
        return -1;
1606
0
    }
1607
28
    return 0;
1608
28
}
1609
1610
1611
static const char*
1612
config_get_env(const PyConfig *config, const char *name)
1613
504
{
1614
504
    return _Py_GetEnv(config->use_environment, name);
1615
504
}
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
140
{
1627
140
    assert(*dest == NULL);
1628
140
    assert(config->use_environment >= 0);
1629
1630
140
    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
140
    const char *var = getenv(name);
1645
140
    if (!var || var[0] == '\0') {
1646
140
        *dest = NULL;
1647
140
        return _PyStatus_OK();
1648
140
    }
1649
1650
0
    return config_set_bytes_string(config, dest, var, decode_err_msg);
1651
140
#endif
1652
140
}
1653
1654
1655
#define CONFIG_GET_ENV_DUP(CONFIG, DEST, WNAME, NAME) \
1656
140
    config_get_env_dup(CONFIG, DEST, WNAME, NAME, "cannot decode " NAME)
1657
1658
1659
static void
1660
config_get_global_vars(PyConfig *config)
1661
28
{
1662
28
_Py_COMP_DIAG_PUSH
1663
28
_Py_COMP_DIAG_IGNORE_DEPR_DECLS
1664
28
    if (config->_config_init != _PyConfig_INIT_COMPAT) {
1665
        /* Python and Isolated configuration ignore global variables */
1666
0
        return;
1667
0
    }
1668
1669
28
#define COPY_FLAG(ATTR, VALUE) \
1670
224
        if (config->ATTR == -1) { \
1671
224
            config->ATTR = VALUE; \
1672
224
        }
1673
28
#define COPY_NOT_FLAG(ATTR, VALUE) \
1674
168
        if (config->ATTR == -1) { \
1675
168
            config->ATTR = !(VALUE); \
1676
168
        }
1677
1678
28
    COPY_FLAG(isolated, Py_IsolatedFlag);
1679
28
    COPY_NOT_FLAG(use_environment, Py_IgnoreEnvironmentFlag);
1680
28
    COPY_FLAG(bytes_warning, Py_BytesWarningFlag);
1681
28
    COPY_FLAG(inspect, Py_InspectFlag);
1682
28
    COPY_FLAG(interactive, Py_InteractiveFlag);
1683
28
    COPY_FLAG(optimization_level, Py_OptimizeFlag);
1684
28
    COPY_FLAG(parser_debug, Py_DebugFlag);
1685
28
    COPY_FLAG(verbose, Py_VerboseFlag);
1686
28
    COPY_FLAG(quiet, Py_QuietFlag);
1687
#ifdef MS_WINDOWS
1688
    COPY_FLAG(legacy_windows_stdio, Py_LegacyWindowsStdioFlag);
1689
#endif
1690
28
    COPY_NOT_FLAG(pathconfig_warnings, Py_FrozenFlag);
1691
1692
28
    COPY_NOT_FLAG(buffered_stdio, Py_UnbufferedStdioFlag);
1693
28
    COPY_NOT_FLAG(site_import, Py_NoSiteFlag);
1694
28
    COPY_NOT_FLAG(write_bytecode, Py_DontWriteBytecodeFlag);
1695
28
    COPY_NOT_FLAG(user_site_directory, Py_NoUserSiteDirectory);
1696
1697
28
#undef COPY_FLAG
1698
28
#undef COPY_NOT_FLAG
1699
28
_Py_COMP_DIAG_POP
1700
28
}
1701
1702
1703
/* Set Py_xxx global configuration variables from 'config' configuration. */
1704
static void
1705
config_set_global_vars(const PyConfig *config)
1706
28
{
1707
28
_Py_COMP_DIAG_PUSH
1708
28
_Py_COMP_DIAG_IGNORE_DEPR_DECLS
1709
28
#define COPY_FLAG(ATTR, VAR) \
1710
224
        if (config->ATTR != -1) { \
1711
224
            VAR = config->ATTR; \
1712
224
        }
1713
28
#define COPY_NOT_FLAG(ATTR, VAR) \
1714
168
        if (config->ATTR != -1) { \
1715
168
            VAR = !config->ATTR; \
1716
168
        }
1717
1718
28
    COPY_FLAG(isolated, Py_IsolatedFlag);
1719
28
    COPY_NOT_FLAG(use_environment, Py_IgnoreEnvironmentFlag);
1720
28
    COPY_FLAG(bytes_warning, Py_BytesWarningFlag);
1721
28
    COPY_FLAG(inspect, Py_InspectFlag);
1722
28
    COPY_FLAG(interactive, Py_InteractiveFlag);
1723
28
    COPY_FLAG(optimization_level, Py_OptimizeFlag);
1724
28
    COPY_FLAG(parser_debug, Py_DebugFlag);
1725
28
    COPY_FLAG(verbose, Py_VerboseFlag);
1726
28
    COPY_FLAG(quiet, Py_QuietFlag);
1727
#ifdef MS_WINDOWS
1728
    COPY_FLAG(legacy_windows_stdio, Py_LegacyWindowsStdioFlag);
1729
#endif
1730
28
    COPY_NOT_FLAG(pathconfig_warnings, Py_FrozenFlag);
1731
1732
28
    COPY_NOT_FLAG(buffered_stdio, Py_UnbufferedStdioFlag);
1733
28
    COPY_NOT_FLAG(site_import, Py_NoSiteFlag);
1734
28
    COPY_NOT_FLAG(write_bytecode, Py_DontWriteBytecodeFlag);
1735
28
    COPY_NOT_FLAG(user_site_directory, Py_NoUserSiteDirectory);
1736
1737
    /* Random or non-zero hash seed */
1738
28
    Py_HashRandomizationFlag = (config->use_hash_seed == 0 ||
1739
0
                                config->hash_seed != 0);
1740
1741
28
#undef COPY_FLAG
1742
28
#undef COPY_NOT_FLAG
1743
28
_Py_COMP_DIAG_POP
1744
28
}
1745
1746
1747
static const wchar_t*
1748
config_get_xoption(const PyConfig *config, wchar_t *name)
1749
448
{
1750
448
    return _Py_get_xoption(&config->xoptions, name);
1751
448
}
1752
1753
static const wchar_t*
1754
config_get_xoption_value(const PyConfig *config, wchar_t *name)
1755
112
{
1756
112
    const wchar_t *xoption = config_get_xoption(config, name);
1757
112
    if (xoption == NULL) {
1758
112
        return NULL;
1759
112
    }
1760
0
    const wchar_t *sep = wcschr(xoption, L'=');
1761
0
    return sep ? sep + 1 : L"";
1762
112
}
1763
1764
1765
static PyStatus
1766
config_init_hash_seed(PyConfig *config)
1767
28
{
1768
28
    static_assert(sizeof(_Py_HashSecret_t) == sizeof(_Py_HashSecret.uc),
1769
28
                  "_Py_HashSecret_t has wrong size");
1770
1771
28
    const char *seed_text = config_get_env(config, "PYTHONHASHSEED");
1772
1773
    /* Convert a text seed to a numeric one */
1774
28
    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
28
    else {
1791
        /* Use a random hash */
1792
28
        config->use_hash_seed = 0;
1793
28
        config->hash_seed = 0;
1794
28
    }
1795
28
    return _PyStatus_OK();
1796
28
}
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
28
{
1842
28
    PyStatus status;
1843
28
    int use_env = config->use_environment;
1844
1845
    /* Get environment variables */
1846
28
    _Py_get_env_flag(use_env, &config->parser_debug, "PYTHONDEBUG");
1847
28
    _Py_get_env_flag(use_env, &config->verbose, "PYTHONVERBOSE");
1848
28
    _Py_get_env_flag(use_env, &config->optimization_level, "PYTHONOPTIMIZE");
1849
28
    _Py_get_env_flag(use_env, &config->inspect, "PYTHONINSPECT");
1850
1851
28
    int dont_write_bytecode = 0;
1852
28
    _Py_get_env_flag(use_env, &dont_write_bytecode, "PYTHONDONTWRITEBYTECODE");
1853
28
    if (dont_write_bytecode) {
1854
0
        config->write_bytecode = 0;
1855
0
    }
1856
1857
28
    int no_user_site_directory = 0;
1858
28
    _Py_get_env_flag(use_env, &no_user_site_directory, "PYTHONNOUSERSITE");
1859
28
    if (no_user_site_directory) {
1860
0
        config->user_site_directory = 0;
1861
0
    }
1862
1863
28
    int unbuffered_stdio = 0;
1864
28
    _Py_get_env_flag(use_env, &unbuffered_stdio, "PYTHONUNBUFFERED");
1865
28
    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
28
    if (config_get_env(config, "PYTHONDUMPREFS")) {
1875
0
        config->dump_refs = 1;
1876
0
    }
1877
28
    if (config_get_env(config, "PYTHONMALLOCSTATS")) {
1878
0
        config->malloc_stats = 1;
1879
0
    }
1880
1881
28
    if (config->dump_refs_file == NULL) {
1882
28
        status = CONFIG_GET_ENV_DUP(config, &config->dump_refs_file,
1883
28
                                    L"PYTHONDUMPREFSFILE", "PYTHONDUMPREFSFILE");
1884
28
        if (_PyStatus_EXCEPTION(status)) {
1885
0
            return status;
1886
0
        }
1887
28
    }
1888
1889
28
    if (config->pythonpath_env == NULL) {
1890
28
        status = CONFIG_GET_ENV_DUP(config, &config->pythonpath_env,
1891
28
                                    L"PYTHONPATH", "PYTHONPATH");
1892
28
        if (_PyStatus_EXCEPTION(status)) {
1893
0
            return status;
1894
0
        }
1895
28
    }
1896
1897
28
    if(config->platlibdir == NULL) {
1898
28
        status = CONFIG_GET_ENV_DUP(config, &config->platlibdir,
1899
28
                                    L"PYTHONPLATLIBDIR", "PYTHONPLATLIBDIR");
1900
28
        if (_PyStatus_EXCEPTION(status)) {
1901
0
            return status;
1902
0
        }
1903
28
    }
1904
1905
28
    if (config->use_hash_seed < 0) {
1906
28
        status = config_init_hash_seed(config);
1907
28
        if (_PyStatus_EXCEPTION(status)) {
1908
0
            return status;
1909
0
        }
1910
28
    }
1911
1912
28
    if (config_get_env(config, "PYTHONSAFEPATH")) {
1913
0
        config->safe_path = 1;
1914
0
    }
1915
1916
28
    const char *gil = config_get_env(config, "PYTHON_GIL");
1917
28
    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
28
    return _PyStatus_OK();
1926
28
}
1927
1928
static PyStatus
1929
config_init_cpu_count(PyConfig *config)
1930
28
{
1931
28
    const char *env = config_get_env(config, "PYTHON_CPU_COUNT");
1932
28
    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
28
    const wchar_t *xoption = config_get_xoption(config, L"cpu_count");
1944
28
    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
28
    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
28
                         "n must be greater than 0");
1965
28
}
1966
1967
static PyStatus
1968
config_init_thread_inherit_context(PyConfig *config)
1969
28
{
1970
28
    const char *env = config_get_env(config, "PYTHON_THREAD_INHERIT_CONTEXT");
1971
28
    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
28
    const wchar_t *xoption = config_get_xoption(config, L"thread_inherit_context");
1981
28
    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
28
    return _PyStatus_OK();
1991
28
}
1992
1993
static PyStatus
1994
config_init_context_aware_warnings(PyConfig *config)
1995
28
{
1996
28
    const char *env = config_get_env(config, "PYTHON_CONTEXT_AWARE_WARNINGS");
1997
28
    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
28
    const wchar_t *xoption = config_get_xoption(config, L"context_aware_warnings");
2007
28
    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
28
    return _PyStatus_OK();
2017
28
}
2018
2019
static PyStatus
2020
config_init_tlbc(PyConfig *config)
2021
28
{
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
28
    return _PyStatus_OK();
2046
28
#endif
2047
28
}
2048
2049
static PyStatus
2050
config_init_perf_profiling(PyConfig *config)
2051
28
{
2052
28
    int active = 0;
2053
28
    const char *env = config_get_env(config, "PYTHONPERFSUPPORT");
2054
28
    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
28
    const wchar_t *xoption = config_get_xoption(config, L"perf");
2063
28
    if (xoption) {
2064
0
        config->perf_profiling = 1;
2065
0
    }
2066
28
    env = config_get_env(config, "PYTHON_PERF_JIT_SUPPORT");
2067
28
    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
28
    xoption = config_get_xoption(config, L"perf_jit");
2076
28
    if (xoption) {
2077
0
        config->perf_profiling = 2;
2078
0
    }
2079
2080
28
    return _PyStatus_OK();
2081
2082
28
}
2083
2084
static PyStatus
2085
config_init_remote_debug(PyConfig *config)
2086
28
{
2087
#ifndef Py_REMOTE_DEBUG
2088
    config->remote_debug = 0;
2089
#else
2090
28
    int active = 1;
2091
28
    const char *env = Py_GETENV("PYTHON_DISABLE_REMOTE_DEBUG");
2092
28
    if (env) {
2093
0
        active = 0;
2094
0
    }
2095
28
    const wchar_t *xoption = config_get_xoption(config, L"disable-remote-debug");
2096
28
    if (xoption) {
2097
0
        active = 0;
2098
0
    }
2099
2100
28
    config->remote_debug = active;
2101
28
#endif
2102
28
    return _PyStatus_OK();
2103
2104
28
}
2105
2106
static PyStatus
2107
config_init_tracemalloc(PyConfig *config)
2108
28
{
2109
28
    int nframe;
2110
28
    int valid;
2111
2112
28
    const char *env = config_get_env(config, "PYTHONTRACEMALLOC");
2113
28
    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
28
    const wchar_t *xoption = config_get_xoption(config, L"tracemalloc");
2127
28
    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
28
    return _PyStatus_OK();
2148
28
}
2149
2150
static PyStatus
2151
config_init_int_max_str_digits(PyConfig *config)
2152
28
{
2153
28
    int maxdigits;
2154
2155
28
    const char *env = config_get_env(config, "PYTHONINTMAXSTRDIGITS");
2156
28
    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
28
    const wchar_t *xoption = config_get_xoption(config, L"int_max_str_digits");
2173
28
    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
28
    if (config->int_max_str_digits < 0) {
2192
28
        config->int_max_str_digits = _PY_LONG_DEFAULT_MAX_STR_DIGITS;
2193
28
    }
2194
28
    return _PyStatus_OK();
2195
28
}
2196
2197
static PyStatus
2198
config_init_pycache_prefix(PyConfig *config)
2199
28
{
2200
28
    assert(config->pycache_prefix == NULL);
2201
2202
28
    const wchar_t *xoption = config_get_xoption(config, L"pycache_prefix");
2203
28
    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
28
    return CONFIG_GET_ENV_DUP(config, &config->pycache_prefix,
2220
28
                              L"PYTHONPYCACHEPREFIX",
2221
28
                              "PYTHONPYCACHEPREFIX");
2222
28
}
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
28
{
2257
28
    int importtime = 0;
2258
2259
28
    const char *env = config_get_env(config, "PYTHONPROFILEIMPORTTIME");
2260
28
    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
28
    const wchar_t *x_value = config_get_xoption_value(config, L"importtime");
2272
28
    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
28
    config->import_time = importtime;
2284
28
    return _PyStatus_OK();
2285
28
}
2286
2287
static PyStatus
2288
config_read_complex_options(PyConfig *config)
2289
28
{
2290
    /* More complex options configured by env var and -X option */
2291
28
    if (config->faulthandler < 0) {
2292
28
        if (config_get_env(config, "PYTHONFAULTHANDLER")
2293
28
           || config_get_xoption(config, L"faulthandler")) {
2294
0
            config->faulthandler = 1;
2295
0
        }
2296
28
    }
2297
28
    if (config_get_env(config, "PYTHONNODEBUGRANGES")
2298
28
       || config_get_xoption(config, L"no_debug_ranges")) {
2299
0
        config->code_debug_ranges = 0;
2300
0
    }
2301
2302
28
    PyStatus status;
2303
28
    if (config->import_time < 0) {
2304
28
        status = config_init_import_time(config);
2305
28
        if (_PyStatus_EXCEPTION(status)) {
2306
0
            return status;
2307
0
        }
2308
28
    }
2309
2310
28
    if (config->tracemalloc < 0) {
2311
28
        status = config_init_tracemalloc(config);
2312
28
        if (_PyStatus_EXCEPTION(status)) {
2313
0
            return status;
2314
0
        }
2315
28
    }
2316
2317
28
    if (config->perf_profiling < 0) {
2318
28
        status = config_init_perf_profiling(config);
2319
28
        if (_PyStatus_EXCEPTION(status)) {
2320
0
            return status;
2321
0
        }
2322
28
    }
2323
2324
28
    if (config->remote_debug < 0) {
2325
28
        status = config_init_remote_debug(config);
2326
28
        if (_PyStatus_EXCEPTION(status)) {
2327
0
            return status;
2328
0
        }
2329
28
    }
2330
2331
28
    if (config->int_max_str_digits < 0) {
2332
28
        status = config_init_int_max_str_digits(config);
2333
28
        if (_PyStatus_EXCEPTION(status)) {
2334
0
            return status;
2335
0
        }
2336
28
    }
2337
2338
28
    if (config->cpu_count < 0) {
2339
28
        status = config_init_cpu_count(config);
2340
28
        if (_PyStatus_EXCEPTION(status)) {
2341
0
            return status;
2342
0
        }
2343
28
    }
2344
2345
28
    if (config->pycache_prefix == NULL) {
2346
28
        status = config_init_pycache_prefix(config);
2347
28
        if (_PyStatus_EXCEPTION(status)) {
2348
0
            return status;
2349
0
        }
2350
28
    }
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
28
    status = config_init_thread_inherit_context(config);
2362
28
    if (_PyStatus_EXCEPTION(status)) {
2363
0
        return status;
2364
0
    }
2365
2366
28
    status = config_init_context_aware_warnings(config);
2367
28
    if (_PyStatus_EXCEPTION(status)) {
2368
0
        return status;
2369
0
    }
2370
2371
28
    status = config_init_tlbc(config);
2372
28
    if (_PyStatus_EXCEPTION(status)) {
2373
0
        return status;
2374
0
    }
2375
2376
28
    return _PyStatus_OK();
2377
28
}
2378
2379
2380
static const wchar_t *
2381
config_get_stdio_errors(const PyPreConfig *preconfig)
2382
28
{
2383
28
    if (preconfig->utf8_mode) {
2384
        /* UTF-8 Mode uses UTF-8/surrogateescape */
2385
28
        return L"surrogateescape";
2386
28
    }
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
28
{
2417
28
    wchar_t *encoding;
2418
28
    if (preconfig->utf8_mode) {
2419
28
        encoding = _PyMem_RawWcsdup(L"utf-8");
2420
28
    }
2421
0
    else {
2422
0
        encoding = _Py_GetLocaleEncoding();
2423
0
    }
2424
28
    if (encoding == NULL) {
2425
0
        return _PyStatus_NO_MEMORY();
2426
0
    }
2427
28
    PyStatus status = PyConfig_SetString(config, locale_encoding, encoding);
2428
28
    PyMem_RawFree(encoding);
2429
28
    return status;
2430
28
}
2431
2432
2433
static PyStatus
2434
config_init_stdio_encoding(PyConfig *config,
2435
                           const PyPreConfig *preconfig)
2436
28
{
2437
28
    PyStatus status;
2438
2439
    // Exit if encoding and errors are defined
2440
28
    if (config->stdio_encoding != NULL && config->stdio_errors != NULL) {
2441
0
        return _PyStatus_OK();
2442
0
    }
2443
2444
    /* PYTHONIOENCODING environment variable */
2445
28
    const char *opt = config_get_env(config, "PYTHONIOENCODING");
2446
28
    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
28
    if (config->stdio_encoding == NULL) {
2497
28
        status = config_get_locale_encoding(config, preconfig,
2498
28
                                            &config->stdio_encoding);
2499
28
        if (_PyStatus_EXCEPTION(status)) {
2500
0
            return status;
2501
0
        }
2502
28
    }
2503
28
    if (config->stdio_errors == NULL) {
2504
28
        const wchar_t *errors = config_get_stdio_errors(preconfig);
2505
28
        assert(errors != NULL);
2506
2507
28
        status = PyConfig_SetString(config, &config->stdio_errors, errors);
2508
28
        if (_PyStatus_EXCEPTION(status)) {
2509
0
            return status;
2510
0
        }
2511
28
    }
2512
2513
28
    return _PyStatus_OK();
2514
28
}
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
28
{
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
28
    if (preconfig->utf8_mode) {
2537
28
        return PyConfig_SetString(config, fs_encoding, L"utf-8");
2538
28
    }
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
28
{
2552
28
    PyStatus status;
2553
2554
28
    if (config->filesystem_encoding == NULL) {
2555
28
        status = config_get_fs_encoding(config, preconfig,
2556
28
                                        &config->filesystem_encoding);
2557
28
        if (_PyStatus_EXCEPTION(status)) {
2558
0
            return status;
2559
0
        }
2560
28
    }
2561
2562
28
    if (config->filesystem_errors == NULL) {
2563
28
        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
28
        errors = L"surrogateescape";
2573
28
#endif
2574
28
        status = PyConfig_SetString(config, &config->filesystem_errors, errors);
2575
28
        if (_PyStatus_EXCEPTION(status)) {
2576
0
            return status;
2577
0
        }
2578
28
    }
2579
28
    return _PyStatus_OK();
2580
28
}
2581
2582
2583
static PyStatus
2584
config_init_import(PyConfig *config, int compute_path_config)
2585
56
{
2586
56
    PyStatus status;
2587
2588
56
    status = _PyConfig_InitPathConfig(config, compute_path_config);
2589
56
    if (_PyStatus_EXCEPTION(status)) {
2590
0
        return status;
2591
0
    }
2592
2593
56
    const char *env = config_get_env(config, "PYTHON_FROZEN_MODULES");
2594
56
    if (env == NULL) {
2595
56
    }
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
56
    const wchar_t *value = config_get_xoption_value(config, L"frozen_modules");
2608
56
    if (value == NULL) {
2609
56
    }
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
56
    assert(config->use_frozen_modules >= 0);
2626
56
    return _PyStatus_OK();
2627
56
}
2628
2629
PyStatus
2630
_PyConfig_InitImportConfig(PyConfig *config)
2631
28
{
2632
28
    return config_init_import(config, 1);
2633
28
}
2634
2635
2636
static PyStatus
2637
config_read(PyConfig *config, int compute_path_config)
2638
28
{
2639
28
    PyStatus status;
2640
28
    const PyPreConfig *preconfig = &_PyRuntime.preconfig;
2641
2642
28
    if (config->use_environment) {
2643
28
        status = config_read_env_vars(config);
2644
28
        if (_PyStatus_EXCEPTION(status)) {
2645
0
            return status;
2646
0
        }
2647
28
    }
2648
2649
    /* -X options */
2650
28
    if (config_get_xoption(config, L"showrefcount")) {
2651
0
        config->show_ref_count = 1;
2652
0
    }
2653
2654
28
    const wchar_t *x_gil = config_get_xoption_value(config, L"gil");
2655
28
    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
28
    status = config_read_complex_options(config);
2676
28
    if (_PyStatus_EXCEPTION(status)) {
2677
0
        return status;
2678
0
    }
2679
2680
28
    if (config->_install_importlib) {
2681
28
        status = config_init_import(config, compute_path_config);
2682
28
        if (_PyStatus_EXCEPTION(status)) {
2683
0
            return status;
2684
0
        }
2685
28
    }
2686
2687
    /* default values */
2688
28
    if (config->dev_mode) {
2689
0
        if (config->faulthandler < 0) {
2690
0
            config->faulthandler = 1;
2691
0
        }
2692
0
    }
2693
28
    if (config->faulthandler < 0) {
2694
28
        config->faulthandler = 0;
2695
28
    }
2696
28
    if (config->tracemalloc < 0) {
2697
28
        config->tracemalloc = 0;
2698
28
    }
2699
28
    if (config->perf_profiling < 0) {
2700
28
        config->perf_profiling = 0;
2701
28
    }
2702
28
    if (config->remote_debug < 0) {
2703
0
        config->remote_debug = -1;
2704
0
    }
2705
28
    if (config->use_hash_seed < 0) {
2706
0
        config->use_hash_seed = 0;
2707
0
        config->hash_seed = 0;
2708
0
    }
2709
2710
28
    if (config->filesystem_encoding == NULL || config->filesystem_errors == NULL) {
2711
28
        status = config_init_fs_encoding(config, preconfig);
2712
28
        if (_PyStatus_EXCEPTION(status)) {
2713
0
            return status;
2714
0
        }
2715
28
    }
2716
2717
28
    status = config_init_stdio_encoding(config, preconfig);
2718
28
    if (_PyStatus_EXCEPTION(status)) {
2719
0
        return status;
2720
0
    }
2721
2722
28
    if (config->argv.length < 1) {
2723
        /* Ensure at least one (empty) argument is seen */
2724
28
        status = PyWideStringList_Append(&config->argv, L"");
2725
28
        if (_PyStatus_EXCEPTION(status)) {
2726
0
            return status;
2727
0
        }
2728
28
    }
2729
2730
28
    if (config->check_hash_pycs_mode == NULL) {
2731
28
        status = PyConfig_SetString(config, &config->check_hash_pycs_mode,
2732
28
                                    L"default");
2733
28
        if (_PyStatus_EXCEPTION(status)) {
2734
0
            return status;
2735
0
        }
2736
28
    }
2737
2738
28
    if (config->configure_c_stdio < 0) {
2739
0
        config->configure_c_stdio = 1;
2740
0
    }
2741
2742
    // Only parse arguments once.
2743
28
    if (config->parse_argv == 1) {
2744
0
        config->parse_argv = 2;
2745
0
    }
2746
2747
28
    return _PyStatus_OK();
2748
28
}
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
28
{
2795
28
    config_set_global_vars(config);
2796
2797
28
    if (config->configure_c_stdio) {
2798
0
        config_init_stdio(config);
2799
0
    }
2800
2801
    /* Write the new pre-configuration into _PyRuntime */
2802
28
    PyPreConfig *preconfig = &runtime->preconfig;
2803
28
    preconfig->isolated = config->isolated;
2804
28
    preconfig->use_environment = config->use_environment;
2805
28
    preconfig->dev_mode = config->dev_mode;
2806
2807
28
    if (_Py_SetArgcArgv(config->orig_argv.length,
2808
28
                        config->orig_argv.items) < 0)
2809
0
    {
2810
0
        return _PyStatus_NO_MEMORY();
2811
0
    }
2812
2813
28
    return _PyStatus_OK();
2814
28
}
2815
2816
2817
/* --- PyConfig command line parser -------------------------- */
2818
2819
static void
2820
config_usage(int error, const wchar_t* program)
2821
0
{
2822
0
    FILE *f = error ? stderr : stdout;
2823
2824
0
    fprintf(f, usage_line, program);
2825
0
    if (error)
2826
0
        fprintf(f, "Try `python -h' for more information.\n");
2827
0
    else {
2828
0
        fputs(usage_help, f);
2829
0
    }
2830
0
}
2831
2832
static void
2833
config_envvars_usage(void)
2834
0
{
2835
0
    printf(usage_envvars, (wint_t)DELIM, (wint_t)DELIM, PYTHONHOMEHELP);
2836
0
}
2837
2838
static void
2839
config_xoptions_usage(void)
2840
0
{
2841
0
    puts(usage_xoptions);
2842
0
}
2843
2844
static void
2845
config_complete_usage(const wchar_t* program)
2846
0
{
2847
0
   config_usage(0, program);
2848
0
   putchar('\n');
2849
0
   config_envvars_usage();
2850
0
   putchar('\n');
2851
0
   config_xoptions_usage();
2852
0
}
2853
2854
2855
/* Parse the command line arguments */
2856
static PyStatus
2857
config_parse_cmdline(PyConfig *config, PyWideStringList *warnoptions,
2858
                     Py_ssize_t *opt_index)
2859
0
{
2860
0
    PyStatus status;
2861
0
    const PyWideStringList *argv = &config->argv;
2862
0
    int print_version = 0;
2863
0
    const wchar_t* program = config->program_name;
2864
0
    if (!program && argv->length >= 1) {
2865
0
        program = argv->items[0];
2866
0
    }
2867
2868
0
    _PyOS_ResetGetOpt();
2869
0
    do {
2870
0
        int longindex = -1;
2871
0
        int c = _PyOS_GetOpt(argv->length, argv->items, &longindex);
2872
0
        if (c == EOF) {
2873
0
            break;
2874
0
        }
2875
2876
0
        if (c == 'c') {
2877
0
            if (config->run_command == NULL) {
2878
                /* -c is the last option; following arguments
2879
                   that look like options are left for the
2880
                   command to interpret. */
2881
0
                size_t len = wcslen(_PyOS_optarg) + 1 + 1;
2882
0
                wchar_t *command = PyMem_RawMalloc(sizeof(wchar_t) * len);
2883
0
                if (command == NULL) {
2884
0
                    return _PyStatus_NO_MEMORY();
2885
0
                }
2886
0
                memcpy(command, _PyOS_optarg, (len - 2) * sizeof(wchar_t));
2887
0
                command[len - 2] = '\n';
2888
0
                command[len - 1] = 0;
2889
0
                config->run_command = command;
2890
0
            }
2891
0
            break;
2892
0
        }
2893
2894
0
        if (c == 'm') {
2895
            /* -m is the last option; following arguments
2896
               that look like options are left for the
2897
               module to interpret. */
2898
0
            if (config->run_module == NULL) {
2899
0
                config->run_module = _PyMem_RawWcsdup(_PyOS_optarg);
2900
0
                if (config->run_module == NULL) {
2901
0
                    return _PyStatus_NO_MEMORY();
2902
0
                }
2903
0
            }
2904
0
            break;
2905
0
        }
2906
2907
0
        switch (c) {
2908
        // Integers represent long options, see Python/getopt.c
2909
0
        case 0:
2910
            // check-hash-based-pycs
2911
0
            if (wcscmp(_PyOS_optarg, L"always") == 0
2912
0
                || wcscmp(_PyOS_optarg, L"never") == 0
2913
0
                || wcscmp(_PyOS_optarg, L"default") == 0)
2914
0
            {
2915
0
                status = PyConfig_SetString(config, &config->check_hash_pycs_mode,
2916
0
                                            _PyOS_optarg);
2917
0
                if (_PyStatus_EXCEPTION(status)) {
2918
0
                    return status;
2919
0
                }
2920
0
            } else {
2921
0
                fprintf(stderr, "--check-hash-based-pycs must be one of "
2922
0
                        "'default', 'always', or 'never'\n");
2923
0
                config_usage(1, program);
2924
0
                return _PyStatus_EXIT(2);
2925
0
            }
2926
0
            break;
2927
2928
0
        case 1:
2929
            // help-all
2930
0
            config_complete_usage(program);
2931
0
            return _PyStatus_EXIT(0);
2932
2933
0
        case 2:
2934
            // help-env
2935
0
            config_envvars_usage();
2936
0
            return _PyStatus_EXIT(0);
2937
2938
0
        case 3:
2939
            // help-xoptions
2940
0
            config_xoptions_usage();
2941
0
            return _PyStatus_EXIT(0);
2942
2943
0
        case 'b':
2944
0
            config->bytes_warning++;
2945
0
            break;
2946
2947
0
        case 'd':
2948
0
            config->parser_debug++;
2949
0
            break;
2950
2951
0
        case 'i':
2952
0
            config->inspect++;
2953
0
            config->interactive++;
2954
0
            break;
2955
2956
0
        case 'E':
2957
0
        case 'I':
2958
0
        case 'X':
2959
            /* option handled by _PyPreCmdline_Read() */
2960
0
            break;
2961
2962
0
        case 'O':
2963
0
            config->optimization_level++;
2964
0
            break;
2965
2966
0
        case 'P':
2967
0
            config->safe_path = 1;
2968
0
            break;
2969
2970
0
        case 'B':
2971
0
            config->write_bytecode = 0;
2972
0
            break;
2973
2974
0
        case 's':
2975
0
            config->user_site_directory = 0;
2976
0
            break;
2977
2978
0
        case 'S':
2979
0
            config->site_import = 0;
2980
0
            break;
2981
2982
0
        case 't':
2983
            /* ignored for backwards compatibility */
2984
0
            break;
2985
2986
0
        case 'u':
2987
0
            config->buffered_stdio = 0;
2988
0
            break;
2989
2990
0
        case 'v':
2991
0
            config->verbose++;
2992
0
            break;
2993
2994
0
        case 'x':
2995
0
            config->skip_source_first_line = 1;
2996
0
            break;
2997
2998
0
        case 'h':
2999
0
        case '?':
3000
0
            config_usage(0, program);
3001
0
            return _PyStatus_EXIT(0);
3002
3003
0
        case 'V':
3004
0
            print_version++;
3005
0
            break;
3006
3007
0
        case 'W':
3008
0
            status = PyWideStringList_Append(warnoptions, _PyOS_optarg);
3009
0
            if (_PyStatus_EXCEPTION(status)) {
3010
0
                return status;
3011
0
            }
3012
0
            break;
3013
3014
0
        case 'q':
3015
0
            config->quiet++;
3016
0
            break;
3017
3018
0
        case 'R':
3019
0
            config->use_hash_seed = 0;
3020
0
            break;
3021
3022
        /* This space reserved for other options */
3023
3024
0
        default:
3025
            /* unknown argument: parsing failed */
3026
0
            config_usage(1, program);
3027
0
            return _PyStatus_EXIT(2);
3028
0
        }
3029
0
    } while (1);
3030
3031
0
    if (print_version) {
3032
0
        printf("Python %s\n",
3033
0
                (print_version >= 2) ? Py_GetVersion() : PY_VERSION);
3034
0
        return _PyStatus_EXIT(0);
3035
0
    }
3036
3037
0
    if (config->run_command == NULL && config->run_module == NULL
3038
0
        && _PyOS_optind < argv->length
3039
0
        && wcscmp(argv->items[_PyOS_optind], L"-") != 0
3040
0
        && config->run_filename == NULL)
3041
0
    {
3042
0
        config->run_filename = _PyMem_RawWcsdup(argv->items[_PyOS_optind]);
3043
0
        if (config->run_filename == NULL) {
3044
0
            return _PyStatus_NO_MEMORY();
3045
0
        }
3046
0
    }
3047
3048
0
    if (config->run_command != NULL || config->run_module != NULL) {
3049
        /* Backup _PyOS_optind */
3050
0
        _PyOS_optind--;
3051
0
    }
3052
3053
0
    *opt_index = _PyOS_optind;
3054
3055
0
    return _PyStatus_OK();
3056
0
}
3057
3058
3059
#ifdef MS_WINDOWS
3060
#  define WCSTOK wcstok_s
3061
#else
3062
0
#  define WCSTOK wcstok
3063
#endif
3064
3065
/* Get warning options from PYTHONWARNINGS environment variable. */
3066
static PyStatus
3067
config_init_env_warnoptions(PyConfig *config, PyWideStringList *warnoptions)
3068
28
{
3069
28
    PyStatus status;
3070
    /* CONFIG_GET_ENV_DUP requires dest to be initialized to NULL */
3071
28
    wchar_t *env = NULL;
3072
28
    status = CONFIG_GET_ENV_DUP(config, &env,
3073
28
                             L"PYTHONWARNINGS", "PYTHONWARNINGS");
3074
28
    if (_PyStatus_EXCEPTION(status)) {
3075
0
        return status;
3076
0
    }
3077
3078
    /* env var is not set or is empty */
3079
28
    if (env == NULL) {
3080
28
        return _PyStatus_OK();
3081
28
    }
3082
3083
3084
0
    wchar_t *warning, *context = NULL;
3085
0
    for (warning = WCSTOK(env, L",", &context);
3086
0
         warning != NULL;
3087
0
         warning = WCSTOK(NULL, L",", &context))
3088
0
    {
3089
0
        status = PyWideStringList_Append(warnoptions, warning);
3090
0
        if (_PyStatus_EXCEPTION(status)) {
3091
0
            PyMem_RawFree(env);
3092
0
            return status;
3093
0
        }
3094
0
    }
3095
0
    PyMem_RawFree(env);
3096
0
    return _PyStatus_OK();
3097
0
}
3098
3099
3100
static PyStatus
3101
warnoptions_append(PyConfig *config, PyWideStringList *options,
3102
                   const wchar_t *option)
3103
0
{
3104
    /* config_init_warnoptions() add existing config warnoptions at the end:
3105
       ensure that the new option is not already present in this list to
3106
       prevent change the options order when config_init_warnoptions() is
3107
       called twice. */
3108
0
    if (_PyWideStringList_Find(&config->warnoptions, option)) {
3109
        /* Already present: do nothing */
3110
0
        return _PyStatus_OK();
3111
0
    }
3112
0
    if (_PyWideStringList_Find(options, option)) {
3113
        /* Already present: do nothing */
3114
0
        return _PyStatus_OK();
3115
0
    }
3116
0
    return PyWideStringList_Append(options, option);
3117
0
}
3118
3119
3120
static PyStatus
3121
warnoptions_extend(PyConfig *config, PyWideStringList *options,
3122
                   const PyWideStringList *options2)
3123
84
{
3124
84
    const Py_ssize_t len = options2->length;
3125
84
    wchar_t *const *items = options2->items;
3126
3127
84
    for (Py_ssize_t i = 0; i < len; i++) {
3128
0
        PyStatus status = warnoptions_append(config, options, items[i]);
3129
0
        if (_PyStatus_EXCEPTION(status)) {
3130
0
            return status;
3131
0
        }
3132
0
    }
3133
84
    return _PyStatus_OK();
3134
84
}
3135
3136
3137
static PyStatus
3138
config_init_warnoptions(PyConfig *config,
3139
                        const PyWideStringList *cmdline_warnoptions,
3140
                        const PyWideStringList *env_warnoptions,
3141
                        const PyWideStringList *sys_warnoptions)
3142
28
{
3143
28
    PyStatus status;
3144
28
    PyWideStringList options = _PyWideStringList_INIT;
3145
3146
    /* Priority of warnings options, lowest to highest:
3147
     *
3148
     * - any implicit filters added by _warnings.c/warnings.py
3149
     * - PyConfig.dev_mode: "default" filter
3150
     * - PYTHONWARNINGS environment variable
3151
     * - '-W' command line options
3152
     * - PyConfig.bytes_warning ('-b' and '-bb' command line options):
3153
     *   "default::BytesWarning" or "error::BytesWarning" filter
3154
     * - early PySys_AddWarnOption() calls
3155
     * - PyConfig.warnoptions
3156
     *
3157
     * PyConfig.warnoptions is copied to sys.warnoptions. Since the warnings
3158
     * module works on the basis of "the most recently added filter will be
3159
     * checked first", we add the lowest precedence entries first so that later
3160
     * entries override them.
3161
     */
3162
3163
28
    if (config->dev_mode) {
3164
0
        status = warnoptions_append(config, &options, L"default");
3165
0
        if (_PyStatus_EXCEPTION(status)) {
3166
0
            goto error;
3167
0
        }
3168
0
    }
3169
3170
28
    status = warnoptions_extend(config, &options, env_warnoptions);
3171
28
    if (_PyStatus_EXCEPTION(status)) {
3172
0
        goto error;
3173
0
    }
3174
3175
28
    status = warnoptions_extend(config, &options, cmdline_warnoptions);
3176
28
    if (_PyStatus_EXCEPTION(status)) {
3177
0
        goto error;
3178
0
    }
3179
3180
    /* If the bytes_warning_flag isn't set, bytesobject.c and bytearrayobject.c
3181
     * don't even try to emit a warning, so we skip setting the filter in that
3182
     * case.
3183
     */
3184
28
    if (config->bytes_warning) {
3185
0
        const wchar_t *filter;
3186
0
        if (config->bytes_warning> 1) {
3187
0
            filter = L"error::BytesWarning";
3188
0
        }
3189
0
        else {
3190
0
            filter = L"default::BytesWarning";
3191
0
        }
3192
0
        status = warnoptions_append(config, &options, filter);
3193
0
        if (_PyStatus_EXCEPTION(status)) {
3194
0
            goto error;
3195
0
        }
3196
0
    }
3197
3198
28
    status = warnoptions_extend(config, &options, sys_warnoptions);
3199
28
    if (_PyStatus_EXCEPTION(status)) {
3200
0
        goto error;
3201
0
    }
3202
3203
    /* Always add all PyConfig.warnoptions options */
3204
28
    status = _PyWideStringList_Extend(&options, &config->warnoptions);
3205
28
    if (_PyStatus_EXCEPTION(status)) {
3206
0
        goto error;
3207
0
    }
3208
3209
28
    _PyWideStringList_Clear(&config->warnoptions);
3210
28
    config->warnoptions = options;
3211
28
    return _PyStatus_OK();
3212
3213
0
error:
3214
0
    _PyWideStringList_Clear(&options);
3215
0
    return status;
3216
28
}
3217
3218
3219
static PyStatus
3220
config_update_argv(PyConfig *config, Py_ssize_t opt_index)
3221
0
{
3222
0
    const PyWideStringList *cmdline_argv = &config->argv;
3223
0
    PyWideStringList config_argv = _PyWideStringList_INIT;
3224
3225
    /* Copy argv to be able to modify it (to force -c/-m) */
3226
0
    if (cmdline_argv->length <= opt_index) {
3227
        /* Ensure at least one (empty) argument is seen */
3228
0
        PyStatus status = PyWideStringList_Append(&config_argv, L"");
3229
0
        if (_PyStatus_EXCEPTION(status)) {
3230
0
            return status;
3231
0
        }
3232
0
    }
3233
0
    else {
3234
0
        PyWideStringList slice;
3235
0
        slice.length = cmdline_argv->length - opt_index;
3236
0
        slice.items = &cmdline_argv->items[opt_index];
3237
0
        if (_PyWideStringList_Copy(&config_argv, &slice) < 0) {
3238
0
            return _PyStatus_NO_MEMORY();
3239
0
        }
3240
0
    }
3241
0
    assert(config_argv.length >= 1);
3242
3243
0
    wchar_t *arg0 = NULL;
3244
0
    if (config->run_command != NULL) {
3245
        /* Force sys.argv[0] = '-c' */
3246
0
        arg0 = L"-c";
3247
0
    }
3248
0
    else if (config->run_module != NULL) {
3249
        /* Force sys.argv[0] = '-m'*/
3250
0
        arg0 = L"-m";
3251
0
    }
3252
3253
0
    if (arg0 != NULL) {
3254
0
        arg0 = _PyMem_RawWcsdup(arg0);
3255
0
        if (arg0 == NULL) {
3256
0
            _PyWideStringList_Clear(&config_argv);
3257
0
            return _PyStatus_NO_MEMORY();
3258
0
        }
3259
3260
0
        PyMem_RawFree(config_argv.items[0]);
3261
0
        config_argv.items[0] = arg0;
3262
0
    }
3263
3264
0
    _PyWideStringList_Clear(&config->argv);
3265
0
    config->argv = config_argv;
3266
0
    return _PyStatus_OK();
3267
0
}
3268
3269
3270
static PyStatus
3271
core_read_precmdline(PyConfig *config, _PyPreCmdline *precmdline)
3272
28
{
3273
28
    PyStatus status;
3274
3275
28
    if (config->parse_argv == 1) {
3276
0
        if (_PyWideStringList_Copy(&precmdline->argv, &config->argv) < 0) {
3277
0
            return _PyStatus_NO_MEMORY();
3278
0
        }
3279
0
    }
3280
3281
28
    PyPreConfig preconfig;
3282
3283
28
    status = _PyPreConfig_InitFromPreConfig(&preconfig, &_PyRuntime.preconfig);
3284
28
    if (_PyStatus_EXCEPTION(status)) {
3285
0
        return status;
3286
0
    }
3287
3288
28
    _PyPreConfig_GetConfig(&preconfig, config);
3289
3290
28
    status = _PyPreCmdline_Read(precmdline, &preconfig);
3291
28
    if (_PyStatus_EXCEPTION(status)) {
3292
0
        return status;
3293
0
    }
3294
3295
28
    status = _PyPreCmdline_SetConfig(precmdline, config);
3296
28
    if (_PyStatus_EXCEPTION(status)) {
3297
0
        return status;
3298
0
    }
3299
28
    return _PyStatus_OK();
3300
28
}
3301
3302
3303
/* Get run_filename absolute path */
3304
static PyStatus
3305
config_run_filename_abspath(PyConfig *config)
3306
28
{
3307
28
    if (!config->run_filename) {
3308
28
        return _PyStatus_OK();
3309
28
    }
3310
3311
0
#ifndef MS_WINDOWS
3312
0
    if (_Py_isabs(config->run_filename)) {
3313
        /* path is already absolute */
3314
0
        return _PyStatus_OK();
3315
0
    }
3316
0
#endif
3317
3318
0
    wchar_t *abs_filename;
3319
0
    if (_Py_abspath(config->run_filename, &abs_filename) < 0) {
3320
        /* failed to get the absolute path of the command line filename:
3321
           ignore the error, keep the relative path */
3322
0
        return _PyStatus_OK();
3323
0
    }
3324
0
    if (abs_filename == NULL) {
3325
0
        return _PyStatus_NO_MEMORY();
3326
0
    }
3327
3328
0
    PyMem_RawFree(config->run_filename);
3329
0
    config->run_filename = abs_filename;
3330
0
    return _PyStatus_OK();
3331
0
}
3332
3333
3334
static PyStatus
3335
config_read_cmdline(PyConfig *config)
3336
28
{
3337
28
    PyStatus status;
3338
28
    PyWideStringList cmdline_warnoptions = _PyWideStringList_INIT;
3339
28
    PyWideStringList env_warnoptions = _PyWideStringList_INIT;
3340
28
    PyWideStringList sys_warnoptions = _PyWideStringList_INIT;
3341
3342
28
    if (config->parse_argv < 0) {
3343
0
        config->parse_argv = 1;
3344
0
    }
3345
3346
28
    if (config->parse_argv == 1) {
3347
0
        Py_ssize_t opt_index;
3348
0
        status = config_parse_cmdline(config, &cmdline_warnoptions, &opt_index);
3349
0
        if (_PyStatus_EXCEPTION(status)) {
3350
0
            goto done;
3351
0
        }
3352
3353
0
        status = config_run_filename_abspath(config);
3354
0
        if (_PyStatus_EXCEPTION(status)) {
3355
0
            goto done;
3356
0
        }
3357
3358
0
        status = config_update_argv(config, opt_index);
3359
0
        if (_PyStatus_EXCEPTION(status)) {
3360
0
            goto done;
3361
0
        }
3362
0
    }
3363
28
    else {
3364
28
        status = config_run_filename_abspath(config);
3365
28
        if (_PyStatus_EXCEPTION(status)) {
3366
0
            goto done;
3367
0
        }
3368
28
    }
3369
3370
28
    if (config->use_environment) {
3371
28
        status = config_init_env_warnoptions(config, &env_warnoptions);
3372
28
        if (_PyStatus_EXCEPTION(status)) {
3373
0
            goto done;
3374
0
        }
3375
28
    }
3376
3377
    /* Handle early PySys_AddWarnOption() calls */
3378
28
    status = _PySys_ReadPreinitWarnOptions(&sys_warnoptions);
3379
28
    if (_PyStatus_EXCEPTION(status)) {
3380
0
        goto done;
3381
0
    }
3382
3383
28
    status = config_init_warnoptions(config,
3384
28
                                     &cmdline_warnoptions,
3385
28
                                     &env_warnoptions,
3386
28
                                     &sys_warnoptions);
3387
28
    if (_PyStatus_EXCEPTION(status)) {
3388
0
        goto done;
3389
0
    }
3390
3391
28
    status = _PyStatus_OK();
3392
3393
28
done:
3394
28
    _PyWideStringList_Clear(&cmdline_warnoptions);
3395
28
    _PyWideStringList_Clear(&env_warnoptions);
3396
28
    _PyWideStringList_Clear(&sys_warnoptions);
3397
28
    return status;
3398
28
}
3399
3400
3401
PyStatus
3402
_PyConfig_SetPyArgv(PyConfig *config, const _PyArgv *args)
3403
0
{
3404
0
    PyStatus status = _Py_PreInitializeFromConfig(config, args);
3405
0
    if (_PyStatus_EXCEPTION(status)) {
3406
0
        return status;
3407
0
    }
3408
3409
0
    return _PyArgv_AsWstrList(args, &config->argv);
3410
0
}
3411
3412
3413
/* Set config.argv: decode argv using Py_DecodeLocale(). Pre-initialize Python
3414
   if needed to ensure that encodings are properly configured. */
3415
PyStatus
3416
PyConfig_SetBytesArgv(PyConfig *config, Py_ssize_t argc, char * const *argv)
3417
0
{
3418
0
    _PyArgv args = {
3419
0
        .argc = argc,
3420
0
        .use_bytes_argv = 1,
3421
0
        .bytes_argv = argv,
3422
0
        .wchar_argv = NULL};
3423
0
    return _PyConfig_SetPyArgv(config, &args);
3424
0
}
3425
3426
3427
PyStatus
3428
PyConfig_SetArgv(PyConfig *config, Py_ssize_t argc, wchar_t * const *argv)
3429
0
{
3430
0
    _PyArgv args = {
3431
0
        .argc = argc,
3432
0
        .use_bytes_argv = 0,
3433
0
        .bytes_argv = NULL,
3434
0
        .wchar_argv = argv};
3435
0
    return _PyConfig_SetPyArgv(config, &args);
3436
0
}
3437
3438
3439
PyStatus
3440
PyConfig_SetWideStringList(PyConfig *config, PyWideStringList *list,
3441
                           Py_ssize_t length, wchar_t **items)
3442
0
{
3443
0
    PyStatus status = _Py_PreInitializeFromConfig(config, NULL);
3444
0
    if (_PyStatus_EXCEPTION(status)) {
3445
0
        return status;
3446
0
    }
3447
3448
0
    PyWideStringList list2 = {.length = length, .items = items};
3449
0
    if (_PyWideStringList_Copy(list, &list2) < 0) {
3450
0
        return _PyStatus_NO_MEMORY();
3451
0
    }
3452
0
    return _PyStatus_OK();
3453
0
}
3454
3455
3456
/* Read the configuration into PyConfig from:
3457
3458
   * Command line arguments
3459
   * Environment variables
3460
   * Py_xxx global configuration variables
3461
3462
   The only side effects are to modify config and to call _Py_SetArgcArgv(). */
3463
PyStatus
3464
_PyConfig_Read(PyConfig *config, int compute_path_config)
3465
28
{
3466
28
    PyStatus status;
3467
3468
28
    status = _Py_PreInitializeFromConfig(config, NULL);
3469
28
    if (_PyStatus_EXCEPTION(status)) {
3470
0
        return status;
3471
0
    }
3472
3473
28
    config_get_global_vars(config);
3474
3475
28
    if (config->orig_argv.length == 0
3476
28
        && !(config->argv.length == 1
3477
0
             && wcscmp(config->argv.items[0], L"") == 0))
3478
28
    {
3479
28
        if (_PyWideStringList_Copy(&config->orig_argv, &config->argv) < 0) {
3480
0
            return _PyStatus_NO_MEMORY();
3481
0
        }
3482
28
    }
3483
3484
28
    _PyPreCmdline precmdline = _PyPreCmdline_INIT;
3485
28
    status = core_read_precmdline(config, &precmdline);
3486
28
    if (_PyStatus_EXCEPTION(status)) {
3487
0
        goto done;
3488
0
    }
3489
3490
28
    assert(config->isolated >= 0);
3491
28
    if (config->isolated) {
3492
0
        config->safe_path = 1;
3493
0
        config->use_environment = 0;
3494
0
        config->user_site_directory = 0;
3495
0
    }
3496
3497
28
    status = config_read_cmdline(config);
3498
28
    if (_PyStatus_EXCEPTION(status)) {
3499
0
        goto done;
3500
0
    }
3501
3502
    /* Handle early PySys_AddXOption() calls */
3503
28
    status = _PySys_ReadPreinitXOptions(config);
3504
28
    if (_PyStatus_EXCEPTION(status)) {
3505
0
        goto done;
3506
0
    }
3507
3508
28
    status = config_read(config, compute_path_config);
3509
28
    if (_PyStatus_EXCEPTION(status)) {
3510
0
        goto done;
3511
0
    }
3512
3513
28
    assert(config_check_consistency(config));
3514
3515
28
    status = _PyStatus_OK();
3516
3517
28
done:
3518
28
    _PyPreCmdline_Clear(&precmdline);
3519
28
    return status;
3520
28
}
3521
3522
3523
PyStatus
3524
PyConfig_Read(PyConfig *config)
3525
0
{
3526
0
    return _PyConfig_Read(config, 0);
3527
0
}
3528
3529
3530
PyObject*
3531
_Py_GetConfigsAsDict(void)
3532
0
{
3533
0
    PyObject *result = NULL;
3534
0
    PyObject *dict = NULL;
3535
3536
0
    result = PyDict_New();
3537
0
    if (result == NULL) {
3538
0
        goto error;
3539
0
    }
3540
3541
    /* global result */
3542
0
    dict = _Py_GetGlobalVariablesAsDict();
3543
0
    if (dict == NULL) {
3544
0
        goto error;
3545
0
    }
3546
0
    if (PyDict_SetItemString(result, "global_config", dict) < 0) {
3547
0
        goto error;
3548
0
    }
3549
0
    Py_CLEAR(dict);
3550
3551
    /* pre config */
3552
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
3553
0
    const PyPreConfig *pre_config = &interp->runtime->preconfig;
3554
0
    dict = _PyPreConfig_AsDict(pre_config);
3555
0
    if (dict == NULL) {
3556
0
        goto error;
3557
0
    }
3558
0
    if (PyDict_SetItemString(result, "pre_config", dict) < 0) {
3559
0
        goto error;
3560
0
    }
3561
0
    Py_CLEAR(dict);
3562
3563
    /* core config */
3564
0
    const PyConfig *config = _PyInterpreterState_GetConfig(interp);
3565
0
    dict = _PyConfig_AsDict(config);
3566
0
    if (dict == NULL) {
3567
0
        goto error;
3568
0
    }
3569
0
    if (PyDict_SetItemString(result, "config", dict) < 0) {
3570
0
        goto error;
3571
0
    }
3572
0
    Py_CLEAR(dict);
3573
3574
0
    return result;
3575
3576
0
error:
3577
0
    Py_XDECREF(result);
3578
0
    Py_XDECREF(dict);
3579
0
    return NULL;
3580
0
}
3581
3582
3583
static void
3584
init_dump_ascii_wstr(const wchar_t *str)
3585
0
{
3586
0
    if (str == NULL) {
3587
0
        PySys_WriteStderr("(not set)");
3588
0
        return;
3589
0
    }
3590
3591
0
    PySys_WriteStderr("'");
3592
0
    for (; *str != L'\0'; str++) {
3593
0
        unsigned int ch = (unsigned int)*str;
3594
0
        if (ch == L'\'') {
3595
0
            PySys_WriteStderr("\\'");
3596
0
        } else if (0x20 <= ch && ch < 0x7f) {
3597
0
            PySys_WriteStderr("%c", ch);
3598
0
        }
3599
0
        else if (ch <= 0xff) {
3600
0
            PySys_WriteStderr("\\x%02x", ch);
3601
0
        }
3602
0
#if SIZEOF_WCHAR_T > 2
3603
0
        else if (ch > 0xffff) {
3604
0
            PySys_WriteStderr("\\U%08x", ch);
3605
0
        }
3606
0
#endif
3607
0
        else {
3608
0
            PySys_WriteStderr("\\u%04x", ch);
3609
0
        }
3610
0
    }
3611
0
    PySys_WriteStderr("'");
3612
0
}
3613
3614
3615
/* Dump the Python path configuration into sys.stderr */
3616
void
3617
_Py_DumpPathConfig(PyThreadState *tstate)
3618
0
{
3619
0
    PyObject *exc = _PyErr_GetRaisedException(tstate);
3620
3621
0
    PySys_WriteStderr("Python path configuration:\n");
3622
3623
0
#define DUMP_CONFIG(NAME, FIELD) \
3624
0
        do { \
3625
0
            PySys_WriteStderr("  " NAME " = "); \
3626
0
            init_dump_ascii_wstr(config->FIELD); \
3627
0
            PySys_WriteStderr("\n"); \
3628
0
        } while (0)
3629
3630
0
    const PyConfig *config = _PyInterpreterState_GetConfig(tstate->interp);
3631
0
    DUMP_CONFIG("PYTHONHOME", home);
3632
0
    DUMP_CONFIG("PYTHONPATH", pythonpath_env);
3633
0
    DUMP_CONFIG("program name", program_name);
3634
0
    PySys_WriteStderr("  isolated = %i\n", config->isolated);
3635
0
    PySys_WriteStderr("  environment = %i\n", config->use_environment);
3636
0
    PySys_WriteStderr("  user site = %i\n", config->user_site_directory);
3637
0
    PySys_WriteStderr("  safe_path = %i\n", config->safe_path);
3638
0
    PySys_WriteStderr("  import site = %i\n", config->site_import);
3639
0
    PySys_WriteStderr("  is in build tree = %i\n", config->_is_python_build);
3640
0
    DUMP_CONFIG("stdlib dir", stdlib_dir);
3641
0
    DUMP_CONFIG("sys.path[0]", sys_path_0);
3642
0
#undef DUMP_CONFIG
3643
3644
0
#define DUMP_SYS(NAME) \
3645
0
        do { \
3646
0
            PySys_FormatStderr("  sys.%s = ", #NAME); \
3647
0
            if (PySys_GetOptionalAttrString(#NAME, &obj) < 0) { \
3648
0
                PyErr_Clear(); \
3649
0
            } \
3650
0
            if (obj != NULL) { \
3651
0
                PySys_FormatStderr("%A", obj); \
3652
0
                Py_DECREF(obj); \
3653
0
            } \
3654
0
            else { \
3655
0
                PySys_WriteStderr("(not set)"); \
3656
0
            } \
3657
0
            PySys_FormatStderr("\n"); \
3658
0
        } while (0)
3659
3660
0
    PyObject *obj;
3661
0
    DUMP_SYS(_base_executable);
3662
0
    DUMP_SYS(base_prefix);
3663
0
    DUMP_SYS(base_exec_prefix);
3664
0
    DUMP_SYS(platlibdir);
3665
0
    DUMP_SYS(executable);
3666
0
    DUMP_SYS(prefix);
3667
0
    DUMP_SYS(exec_prefix);
3668
0
#undef DUMP_SYS
3669
3670
0
    PyObject *sys_path;
3671
0
    (void) PySys_GetOptionalAttrString("path", &sys_path);
3672
0
    if (sys_path != NULL && PyList_Check(sys_path)) {
3673
0
        PySys_WriteStderr("  sys.path = [\n");
3674
0
        Py_ssize_t len = PyList_GET_SIZE(sys_path);
3675
0
        for (Py_ssize_t i=0; i < len; i++) {
3676
0
            PyObject *path = PyList_GET_ITEM(sys_path, i);
3677
0
            PySys_FormatStderr("    %A,\n", path);
3678
0
        }
3679
0
        PySys_WriteStderr("  ]\n");
3680
0
    }
3681
0
    Py_XDECREF(sys_path);
3682
3683
0
    _PyErr_SetRaisedException(tstate, exc);
3684
0
}
3685
3686
3687
// --- PyInitConfig API ---------------------------------------------------
3688
3689
struct PyInitConfig {
3690
    PyPreConfig preconfig;
3691
    PyConfig config;
3692
    struct _inittab *inittab;
3693
    Py_ssize_t inittab_size;
3694
    PyStatus status;
3695
    char *err_msg;
3696
};
3697
3698
static PyInitConfig*
3699
initconfig_alloc(void)
3700
0
{
3701
0
    return calloc(1, sizeof(PyInitConfig));
3702
0
}
3703
3704
3705
PyInitConfig*
3706
PyInitConfig_Create(void)
3707
0
{
3708
0
    PyInitConfig *config = initconfig_alloc();
3709
0
    if (config == NULL) {
3710
0
        return NULL;
3711
0
    }
3712
0
    PyPreConfig_InitIsolatedConfig(&config->preconfig);
3713
0
    PyConfig_InitIsolatedConfig(&config->config);
3714
0
    config->status = _PyStatus_OK();
3715
0
    return config;
3716
0
}
3717
3718
3719
void
3720
PyInitConfig_Free(PyInitConfig *config)
3721
0
{
3722
0
    if (config == NULL) {
3723
0
        return;
3724
0
    }
3725
3726
0
    initconfig_free_config(&config->config);
3727
0
    PyMem_RawFree(config->inittab);
3728
0
    free(config->err_msg);
3729
0
    free(config);
3730
0
}
3731
3732
3733
int
3734
PyInitConfig_GetError(PyInitConfig* config, const char **perr_msg)
3735
0
{
3736
0
    if (_PyStatus_IS_EXIT(config->status)) {
3737
0
        char buffer[22];  // len("exit code -2147483648\0")
3738
0
        PyOS_snprintf(buffer, sizeof(buffer),
3739
0
                      "exit code %i",
3740
0
                      config->status.exitcode);
3741
3742
0
        if (config->err_msg != NULL) {
3743
0
            free(config->err_msg);
3744
0
        }
3745
0
        config->err_msg = strdup(buffer);
3746
0
        if (config->err_msg != NULL) {
3747
0
            *perr_msg = config->err_msg;
3748
0
            return 1;
3749
0
        }
3750
0
        config->status = _PyStatus_NO_MEMORY();
3751
0
    }
3752
3753
0
    if (_PyStatus_IS_ERROR(config->status) && config->status.err_msg != NULL) {
3754
0
        *perr_msg = config->status.err_msg;
3755
0
        return 1;
3756
0
    }
3757
0
    else {
3758
0
        *perr_msg = NULL;
3759
0
        return 0;
3760
0
    }
3761
0
}
3762
3763
3764
int
3765
PyInitConfig_GetExitCode(PyInitConfig* config, int *exitcode)
3766
0
{
3767
0
    if (_PyStatus_IS_EXIT(config->status)) {
3768
0
        *exitcode = config->status.exitcode;
3769
0
        return 1;
3770
0
    }
3771
0
    else {
3772
0
        return 0;
3773
0
    }
3774
0
}
3775
3776
3777
static void
3778
initconfig_set_error(PyInitConfig *config, const char *err_msg)
3779
0
{
3780
0
    config->status = _PyStatus_ERR(err_msg);
3781
0
}
3782
3783
3784
static const PyConfigSpec*
3785
initconfig_find_spec(const PyConfigSpec *spec, const char *name)
3786
0
{
3787
0
    for (; spec->name != NULL; spec++) {
3788
0
        if (strcmp(name, spec->name) == 0) {
3789
0
            return spec;
3790
0
        }
3791
0
    }
3792
0
    return NULL;
3793
0
}
3794
3795
3796
int
3797
PyInitConfig_HasOption(PyInitConfig *config, const char *name)
3798
0
{
3799
0
    const PyConfigSpec *spec = initconfig_find_spec(PYCONFIG_SPEC, name);
3800
0
    if (spec == NULL) {
3801
0
        spec = initconfig_find_spec(PYPRECONFIG_SPEC, name);
3802
0
    }
3803
0
    return (spec != NULL);
3804
0
}
3805
3806
3807
static const PyConfigSpec*
3808
initconfig_prepare(PyInitConfig *config, const char *name, void **raw_member)
3809
0
{
3810
0
    const PyConfigSpec *spec = initconfig_find_spec(PYCONFIG_SPEC, name);
3811
0
    if (spec != NULL) {
3812
0
        *raw_member = config_get_spec_member(&config->config, spec);
3813
0
        return spec;
3814
0
    }
3815
3816
0
    spec = initconfig_find_spec(PYPRECONFIG_SPEC, name);
3817
0
    if (spec != NULL) {
3818
0
        *raw_member = preconfig_get_spec_member(&config->preconfig, spec);
3819
0
        return spec;
3820
0
    }
3821
3822
0
    initconfig_set_error(config, "unknown config option name");
3823
0
    return NULL;
3824
0
}
3825
3826
3827
int
3828
PyInitConfig_GetInt(PyInitConfig *config, const char *name, int64_t *value)
3829
0
{
3830
0
    void *raw_member;
3831
0
    const PyConfigSpec *spec = initconfig_prepare(config, name, &raw_member);
3832
0
    if (spec == NULL) {
3833
0
        return -1;
3834
0
    }
3835
3836
0
    switch (spec->type) {
3837
0
    case PyConfig_MEMBER_INT:
3838
0
    case PyConfig_MEMBER_UINT:
3839
0
    case PyConfig_MEMBER_BOOL:
3840
0
    {
3841
0
        int *member = raw_member;
3842
0
        *value = *member;
3843
0
        break;
3844
0
    }
3845
3846
0
    case PyConfig_MEMBER_ULONG:
3847
0
    {
3848
0
        unsigned long *member = raw_member;
3849
0
#if SIZEOF_LONG >= 8
3850
0
        if ((unsigned long)INT64_MAX < *member) {
3851
0
            initconfig_set_error(config,
3852
0
                "config option value doesn't fit into int64_t");
3853
0
            return -1;
3854
0
        }
3855
0
#endif
3856
0
        *value = *member;
3857
0
        break;
3858
0
    }
3859
3860
0
    default:
3861
0
        initconfig_set_error(config, "config option type is not int");
3862
0
        return -1;
3863
0
    }
3864
0
    return 0;
3865
0
}
3866
3867
3868
static char*
3869
wstr_to_utf8(PyInitConfig *config, wchar_t *wstr)
3870
0
{
3871
0
    char *utf8;
3872
0
    int res = _Py_EncodeUTF8Ex(wstr, &utf8, NULL, NULL, 1, _Py_ERROR_STRICT);
3873
0
    if (res == -2) {
3874
0
        initconfig_set_error(config, "encoding error");
3875
0
        return NULL;
3876
0
    }
3877
0
    if (res < 0) {
3878
0
        config->status = _PyStatus_NO_MEMORY();
3879
0
        return NULL;
3880
0
    }
3881
3882
    // Copy to use the malloc() memory allocator
3883
0
    size_t size = strlen(utf8) + 1;
3884
0
    char *str = malloc(size);
3885
0
    if (str == NULL) {
3886
0
        PyMem_RawFree(utf8);
3887
0
        config->status = _PyStatus_NO_MEMORY();
3888
0
        return NULL;
3889
0
    }
3890
3891
0
    memcpy(str, utf8, size);
3892
0
    PyMem_RawFree(utf8);
3893
0
    return str;
3894
0
}
3895
3896
3897
int
3898
PyInitConfig_GetStr(PyInitConfig *config, const char *name, char **value)
3899
0
{
3900
0
    void *raw_member;
3901
0
    const PyConfigSpec *spec = initconfig_prepare(config, name, &raw_member);
3902
0
    if (spec == NULL) {
3903
0
        return -1;
3904
0
    }
3905
3906
0
    if (spec->type != PyConfig_MEMBER_WSTR
3907
0
        && spec->type != PyConfig_MEMBER_WSTR_OPT)
3908
0
    {
3909
0
        initconfig_set_error(config, "config option type is not string");
3910
0
        return -1;
3911
0
    }
3912
3913
0
    wchar_t **member = raw_member;
3914
0
    if (*member == NULL) {
3915
0
        *value = NULL;
3916
0
        return 0;
3917
0
    }
3918
3919
0
    *value = wstr_to_utf8(config, *member);
3920
0
    if (*value == NULL) {
3921
0
        return -1;
3922
0
    }
3923
0
    return 0;
3924
0
}
3925
3926
3927
int
3928
PyInitConfig_GetStrList(PyInitConfig *config, const char *name, size_t *length, char ***items)
3929
0
{
3930
0
    void *raw_member;
3931
0
    const PyConfigSpec *spec = initconfig_prepare(config, name, &raw_member);
3932
0
    if (spec == NULL) {
3933
0
        return -1;
3934
0
    }
3935
3936
0
    if (spec->type != PyConfig_MEMBER_WSTR_LIST) {
3937
0
        initconfig_set_error(config, "config option type is not string list");
3938
0
        return -1;
3939
0
    }
3940
3941
0
    PyWideStringList *list = raw_member;
3942
0
    *length = list->length;
3943
3944
0
    *items = malloc(list->length * sizeof(char*));
3945
0
    if (*items == NULL) {
3946
0
        config->status = _PyStatus_NO_MEMORY();
3947
0
        return -1;
3948
0
    }
3949
3950
0
    for (Py_ssize_t i=0; i < list->length; i++) {
3951
0
        (*items)[i] = wstr_to_utf8(config, list->items[i]);
3952
0
        if ((*items)[i] == NULL) {
3953
0
            PyInitConfig_FreeStrList(i, *items);
3954
0
            return -1;
3955
0
        }
3956
0
    }
3957
0
    return 0;
3958
0
}
3959
3960
3961
void
3962
PyInitConfig_FreeStrList(size_t length, char **items)
3963
0
{
3964
0
    for (size_t i=0; i < length; i++) {
3965
0
        free(items[i]);
3966
0
    }
3967
0
    free(items);
3968
0
}
3969
3970
3971
int
3972
PyInitConfig_SetInt(PyInitConfig *config, const char *name, int64_t value)
3973
0
{
3974
0
    void *raw_member;
3975
0
    const PyConfigSpec *spec = initconfig_prepare(config, name, &raw_member);
3976
0
    if (spec == NULL) {
3977
0
        return -1;
3978
0
    }
3979
3980
0
    switch (spec->type) {
3981
0
    case PyConfig_MEMBER_INT:
3982
0
    {
3983
0
        if (value < (int64_t)INT_MIN || (int64_t)INT_MAX < value) {
3984
0
            initconfig_set_error(config,
3985
0
                "config option value is out of int range");
3986
0
            return -1;
3987
0
        }
3988
0
        int int_value = (int)value;
3989
3990
0
        int *member = raw_member;
3991
0
        *member = int_value;
3992
0
        break;
3993
0
    }
3994
3995
0
    case PyConfig_MEMBER_UINT:
3996
0
    case PyConfig_MEMBER_BOOL:
3997
0
    {
3998
0
        if (value < 0 || (uint64_t)UINT_MAX < (uint64_t)value) {
3999
0
            initconfig_set_error(config,
4000
0
                "config option value is out of unsigned int range");
4001
0
            return -1;
4002
0
        }
4003
0
        int int_value = (int)value;
4004
4005
0
        int *member = raw_member;
4006
0
        *member = int_value;
4007
0
        break;
4008
0
    }
4009
4010
0
    case PyConfig_MEMBER_ULONG:
4011
0
    {
4012
0
        if (value < 0 || (uint64_t)ULONG_MAX < (uint64_t)value) {
4013
0
            initconfig_set_error(config,
4014
0
                "config option value is out of unsigned long range");
4015
0
            return -1;
4016
0
        }
4017
0
        unsigned long ulong_value = (unsigned long)value;
4018
4019
0
        unsigned long *member = raw_member;
4020
0
        *member = ulong_value;
4021
0
        break;
4022
0
    }
4023
4024
0
    default:
4025
0
        initconfig_set_error(config, "config option type is not int");
4026
0
        return -1;
4027
0
    }
4028
4029
0
    if (strcmp(name, "hash_seed") == 0) {
4030
0
        config->config.use_hash_seed = 1;
4031
0
    }
4032
4033
0
    return 0;
4034
0
}
4035
4036
4037
static wchar_t*
4038
utf8_to_wstr(PyInitConfig *config, const char *str)
4039
0
{
4040
0
    wchar_t *wstr;
4041
0
    size_t wlen;
4042
0
    int res = _Py_DecodeUTF8Ex(str, strlen(str), &wstr, &wlen, NULL, _Py_ERROR_STRICT);
4043
0
    if (res == -2) {
4044
0
        initconfig_set_error(config, "decoding error");
4045
0
        return NULL;
4046
0
    }
4047
0
    if (res < 0) {
4048
0
        config->status = _PyStatus_NO_MEMORY();
4049
0
        return NULL;
4050
0
    }
4051
4052
    // Copy to use the malloc() memory allocator
4053
0
    size_t size = (wlen + 1) * sizeof(wchar_t);
4054
0
    wchar_t *wstr2 = malloc(size);
4055
0
    if (wstr2 == NULL) {
4056
0
        PyMem_RawFree(wstr);
4057
0
        config->status = _PyStatus_NO_MEMORY();
4058
0
        return NULL;
4059
0
    }
4060
4061
0
    memcpy(wstr2, wstr, size);
4062
0
    PyMem_RawFree(wstr);
4063
0
    return wstr2;
4064
0
}
4065
4066
4067
int
4068
PyInitConfig_SetStr(PyInitConfig *config, const char *name, const char* value)
4069
0
{
4070
0
    void *raw_member;
4071
0
    const PyConfigSpec *spec = initconfig_prepare(config, name, &raw_member);
4072
0
    if (spec == NULL) {
4073
0
        return -1;
4074
0
    }
4075
4076
0
    if (spec->type != PyConfig_MEMBER_WSTR
4077
0
            && spec->type != PyConfig_MEMBER_WSTR_OPT) {
4078
0
        initconfig_set_error(config, "config option type is not string");
4079
0
        return -1;
4080
0
    }
4081
4082
0
    if (value == NULL && spec->type != PyConfig_MEMBER_WSTR_OPT) {
4083
0
        initconfig_set_error(config, "config option string cannot be NULL");
4084
0
    }
4085
4086
0
    wchar_t **member = raw_member;
4087
4088
0
    *member = utf8_to_wstr(config, value);
4089
0
    if (*member == NULL) {
4090
0
        return -1;
4091
0
    }
4092
0
    return 0;
4093
0
}
4094
4095
4096
static void
4097
initconfig_free_wstr(wchar_t *member)
4098
0
{
4099
0
    if (member) {
4100
0
        free(member);
4101
0
    }
4102
0
}
4103
4104
4105
static void
4106
initconfig_free_wstr_list(PyWideStringList *list)
4107
0
{
4108
0
    for (Py_ssize_t i = 0; i < list->length; i++) {
4109
0
        free(list->items[i]);
4110
0
    }
4111
0
    free(list->items);
4112
0
}
4113
4114
4115
static void
4116
initconfig_free_config(const PyConfig *config)
4117
0
{
4118
0
    const PyConfigSpec *spec = PYCONFIG_SPEC;
4119
0
    for (; spec->name != NULL; spec++) {
4120
0
        void *member = config_get_spec_member(config, spec);
4121
0
        if (spec->type == PyConfig_MEMBER_WSTR
4122
0
            || spec->type == PyConfig_MEMBER_WSTR_OPT)
4123
0
        {
4124
0
            wchar_t *wstr = *(wchar_t **)member;
4125
0
            initconfig_free_wstr(wstr);
4126
0
        }
4127
0
        else if (spec->type == PyConfig_MEMBER_WSTR_LIST) {
4128
0
            initconfig_free_wstr_list(member);
4129
0
        }
4130
0
    }
4131
0
}
4132
4133
4134
static int
4135
initconfig_set_str_list(PyInitConfig *config, PyWideStringList *list,
4136
                        Py_ssize_t length, char * const *items)
4137
0
{
4138
0
    PyWideStringList wlist = _PyWideStringList_INIT;
4139
0
    size_t size = sizeof(wchar_t*) * length;
4140
0
    wlist.items = (wchar_t **)malloc(size);
4141
0
    if (wlist.items == NULL) {
4142
0
        config->status = _PyStatus_NO_MEMORY();
4143
0
        return -1;
4144
0
    }
4145
4146
0
    for (Py_ssize_t i = 0; i < length; i++) {
4147
0
        wchar_t *arg = utf8_to_wstr(config, items[i]);
4148
0
        if (arg == NULL) {
4149
0
            initconfig_free_wstr_list(&wlist);
4150
0
            return -1;
4151
0
        }
4152
0
        wlist.items[i] = arg;
4153
0
        wlist.length++;
4154
0
    }
4155
4156
0
    initconfig_free_wstr_list(list);
4157
0
    *list = wlist;
4158
0
    return 0;
4159
0
}
4160
4161
4162
int
4163
PyInitConfig_SetStrList(PyInitConfig *config, const char *name,
4164
                        size_t length, char * const *items)
4165
0
{
4166
0
    void *raw_member;
4167
0
    const PyConfigSpec *spec = initconfig_prepare(config, name, &raw_member);
4168
0
    if (spec == NULL) {
4169
0
        return -1;
4170
0
    }
4171
4172
0
    if (spec->type != PyConfig_MEMBER_WSTR_LIST) {
4173
0
        initconfig_set_error(config, "config option type is not strings list");
4174
0
        return -1;
4175
0
    }
4176
0
    PyWideStringList *list = raw_member;
4177
0
    if (initconfig_set_str_list(config, list, length, items) < 0) {
4178
0
        return -1;
4179
0
    }
4180
4181
0
    if (strcmp(name, "module_search_paths") == 0) {
4182
0
        config->config.module_search_paths_set = 1;
4183
0
    }
4184
0
    return 0;
4185
0
}
4186
4187
4188
int
4189
PyInitConfig_AddModule(PyInitConfig *config, const char *name,
4190
                       PyObject* (*initfunc)(void))
4191
0
{
4192
0
    size_t size = sizeof(struct _inittab) * (config->inittab_size + 2);
4193
0
    struct _inittab *new_inittab = PyMem_RawRealloc(config->inittab, size);
4194
0
    if (new_inittab == NULL) {
4195
0
        config->status = _PyStatus_NO_MEMORY();
4196
0
        return -1;
4197
0
    }
4198
0
    config->inittab = new_inittab;
4199
4200
0
    struct _inittab *entry = &config->inittab[config->inittab_size];
4201
0
    entry->name = name;
4202
0
    entry->initfunc = initfunc;
4203
4204
    // Terminator entry
4205
0
    entry = &config->inittab[config->inittab_size + 1];
4206
0
    entry->name = NULL;
4207
0
    entry->initfunc = NULL;
4208
4209
0
    config->inittab_size++;
4210
0
    return 0;
4211
0
}
4212
4213
4214
int
4215
Py_InitializeFromInitConfig(PyInitConfig *config)
4216
0
{
4217
0
    if (config->inittab_size >= 1) {
4218
0
        if (PyImport_ExtendInittab(config->inittab) < 0) {
4219
0
            config->status = _PyStatus_NO_MEMORY();
4220
0
            return -1;
4221
0
        }
4222
0
    }
4223
4224
0
    _PyPreConfig_GetConfig(&config->preconfig, &config->config);
4225
4226
0
    config->status = Py_PreInitializeFromArgs(
4227
0
        &config->preconfig,
4228
0
        config->config.argv.length,
4229
0
        config->config.argv.items);
4230
0
    if (_PyStatus_EXCEPTION(config->status)) {
4231
0
        return -1;
4232
0
    }
4233
4234
0
    config->status = Py_InitializeFromConfig(&config->config);
4235
0
    if (_PyStatus_EXCEPTION(config->status)) {
4236
0
        return -1;
4237
0
    }
4238
4239
0
    return 0;
4240
0
}
4241
4242
4243
// --- PyConfig_Get() -------------------------------------------------------
4244
4245
static const PyConfigSpec*
4246
config_generic_find_spec(const PyConfigSpec *spec, const char *name)
4247
0
{
4248
0
    for (; spec->name != NULL; spec++) {
4249
0
        if (spec->visibility == PyConfig_MEMBER_INIT_ONLY) {
4250
0
            continue;
4251
0
        }
4252
0
        if (strcmp(name, spec->name) == 0) {
4253
0
            return spec;
4254
0
        }
4255
0
    }
4256
0
    return NULL;
4257
0
}
4258
4259
4260
static const PyConfigSpec*
4261
config_find_spec(const char *name)
4262
0
{
4263
0
    return config_generic_find_spec(PYCONFIG_SPEC, name);
4264
0
}
4265
4266
4267
static const PyConfigSpec*
4268
preconfig_find_spec(const char *name)
4269
0
{
4270
0
    return config_generic_find_spec(PYPRECONFIG_SPEC, name);
4271
0
}
4272
4273
4274
static int
4275
config_add_xoption(PyObject *dict, const wchar_t *str)
4276
0
{
4277
0
    PyObject *name = NULL, *value = NULL;
4278
4279
0
    const wchar_t *name_end = wcschr(str, L'=');
4280
0
    if (!name_end) {
4281
0
        name = PyUnicode_FromWideChar(str, -1);
4282
0
        if (name == NULL) {
4283
0
            goto error;
4284
0
        }
4285
0
        value = Py_NewRef(Py_True);
4286
0
    }
4287
0
    else {
4288
0
        name = PyUnicode_FromWideChar(str, name_end - str);
4289
0
        if (name == NULL) {
4290
0
            goto error;
4291
0
        }
4292
0
        value = PyUnicode_FromWideChar(name_end + 1, -1);
4293
0
        if (value == NULL) {
4294
0
            goto error;
4295
0
        }
4296
0
    }
4297
0
    if (PyDict_SetItem(dict, name, value) < 0) {
4298
0
        goto error;
4299
0
    }
4300
0
    Py_DECREF(name);
4301
0
    Py_DECREF(value);
4302
0
    return 0;
4303
4304
0
error:
4305
0
    Py_XDECREF(name);
4306
0
    Py_XDECREF(value);
4307
0
    return -1;
4308
0
}
4309
4310
4311
PyObject*
4312
_PyConfig_CreateXOptionsDict(const PyConfig *config)
4313
56
{
4314
56
    PyObject *dict = PyDict_New();
4315
56
    if (dict == NULL) {
4316
0
        return NULL;
4317
0
    }
4318
4319
56
    Py_ssize_t nxoption = config->xoptions.length;
4320
56
    wchar_t **xoptions = config->xoptions.items;
4321
56
    for (Py_ssize_t i=0; i < nxoption; i++) {
4322
0
        const wchar_t *option = xoptions[i];
4323
0
        if (config_add_xoption(dict, option) < 0) {
4324
0
            Py_DECREF(dict);
4325
0
            return NULL;
4326
0
        }
4327
0
    }
4328
56
    return dict;
4329
56
}
4330
4331
4332
static int
4333
config_get_sys_write_bytecode(const PyConfig *config, int *value)
4334
0
{
4335
0
    PyObject *attr = PySys_GetAttrString("dont_write_bytecode");
4336
0
    if (attr == NULL) {
4337
0
        return -1;
4338
0
    }
4339
4340
0
    int is_true = PyObject_IsTrue(attr);
4341
0
    Py_DECREF(attr);
4342
0
    if (is_true < 0) {
4343
0
        return -1;
4344
0
    }
4345
0
    *value = (!is_true);
4346
0
    return 0;
4347
0
}
4348
4349
4350
static PyObject*
4351
config_get(const PyConfig *config, const PyConfigSpec *spec,
4352
           int use_sys)
4353
1.93k
{
4354
1.93k
    if (use_sys) {
4355
0
        if (spec->sys.attr != NULL) {
4356
0
            return PySys_GetAttrString(spec->sys.attr);
4357
0
        }
4358
4359
0
        if (strcmp(spec->name, "write_bytecode") == 0) {
4360
0
            int value;
4361
0
            if (config_get_sys_write_bytecode(config, &value) < 0) {
4362
0
                return NULL;
4363
0
            }
4364
0
            return PyBool_FromLong(value);
4365
0
        }
4366
4367
0
        if (strcmp(spec->name, "int_max_str_digits") == 0) {
4368
0
            PyInterpreterState *interp = _PyInterpreterState_GET();
4369
0
            return PyLong_FromLong(interp->long_state.max_str_digits);
4370
0
        }
4371
0
    }
4372
4373
1.93k
    void *member = config_get_spec_member(config, spec);
4374
1.93k
    switch (spec->type) {
4375
84
    case PyConfig_MEMBER_INT:
4376
308
    case PyConfig_MEMBER_UINT:
4377
308
    {
4378
308
        int value = *(int *)member;
4379
308
        return PyLong_FromLong(value);
4380
84
    }
4381
4382
840
    case PyConfig_MEMBER_BOOL:
4383
840
    {
4384
840
        int value = *(int *)member;
4385
840
        return PyBool_FromLong(value != 0);
4386
84
    }
4387
4388
28
    case PyConfig_MEMBER_ULONG:
4389
28
    {
4390
28
        unsigned long value = *(unsigned long *)member;
4391
28
        return PyLong_FromUnsignedLong(value);
4392
84
    }
4393
4394
196
    case PyConfig_MEMBER_WSTR:
4395
616
    case PyConfig_MEMBER_WSTR_OPT:
4396
616
    {
4397
616
        wchar_t *wstr = *(wchar_t **)member;
4398
616
        if (wstr != NULL) {
4399
140
            return PyUnicode_FromWideChar(wstr, -1);
4400
140
        }
4401
476
        else {
4402
476
            return Py_NewRef(Py_None);
4403
476
        }
4404
616
    }
4405
4406
140
    case PyConfig_MEMBER_WSTR_LIST:
4407
140
    {
4408
140
        if (strcmp(spec->name, "xoptions") == 0) {
4409
28
            return _PyConfig_CreateXOptionsDict(config);
4410
28
        }
4411
112
        else {
4412
112
            const PyWideStringList *list = (const PyWideStringList *)member;
4413
112
            return _PyWideStringList_AsTuple(list);
4414
112
        }
4415
140
    }
4416
4417
0
    default:
4418
0
        Py_UNREACHABLE();
4419
1.93k
    }
4420
1.93k
}
4421
4422
4423
static PyObject*
4424
preconfig_get(const PyPreConfig *preconfig, const PyConfigSpec *spec)
4425
0
{
4426
    // The type of all PYPRECONFIG_SPEC members is INT or BOOL.
4427
0
    assert(spec->type == PyConfig_MEMBER_INT
4428
0
           || spec->type == PyConfig_MEMBER_BOOL);
4429
4430
0
    char *member = (char *)preconfig + spec->offset;
4431
0
    int value = *(int *)member;
4432
4433
0
    if (spec->type == PyConfig_MEMBER_BOOL) {
4434
0
        return PyBool_FromLong(value != 0);
4435
0
    }
4436
0
    else {
4437
0
        return PyLong_FromLong(value);
4438
0
    }
4439
0
}
4440
4441
4442
static void
4443
config_unknown_name_error(const char *name)
4444
0
{
4445
0
    PyErr_Format(PyExc_ValueError, "unknown config option name: %s", name);
4446
0
}
4447
4448
4449
PyObject*
4450
PyConfig_Get(const char *name)
4451
0
{
4452
0
    const PyConfigSpec *spec = config_find_spec(name);
4453
0
    if (spec != NULL) {
4454
0
        const PyConfig *config = _Py_GetConfig();
4455
0
        return config_get(config, spec, 1);
4456
0
    }
4457
4458
0
    spec = preconfig_find_spec(name);
4459
0
    if (spec != NULL) {
4460
0
        const PyPreConfig *preconfig = &_PyRuntime.preconfig;
4461
0
        return preconfig_get(preconfig, spec);
4462
0
    }
4463
4464
0
    config_unknown_name_error(name);
4465
0
    return NULL;
4466
0
}
4467
4468
4469
int
4470
PyConfig_GetInt(const char *name, int *value)
4471
0
{
4472
0
    assert(!PyErr_Occurred());
4473
4474
0
    PyObject *obj = PyConfig_Get(name);
4475
0
    if (obj == NULL) {
4476
0
        return -1;
4477
0
    }
4478
4479
0
    if (!PyLong_Check(obj)) {
4480
0
        Py_DECREF(obj);
4481
0
        PyErr_Format(PyExc_TypeError, "config option %s is not an int", name);
4482
0
        return -1;
4483
0
    }
4484
4485
0
    int as_int = PyLong_AsInt(obj);
4486
0
    Py_DECREF(obj);
4487
0
    if (as_int == -1 && PyErr_Occurred()) {
4488
0
        PyErr_Format(PyExc_OverflowError,
4489
0
                     "config option %s value does not fit into a C int", name);
4490
0
        return -1;
4491
0
    }
4492
4493
0
    *value = as_int;
4494
0
    return 0;
4495
0
}
4496
4497
4498
static int
4499
config_names_add(PyObject *names, const PyConfigSpec *spec)
4500
0
{
4501
0
    for (; spec->name != NULL; spec++) {
4502
0
        if (spec->visibility == PyConfig_MEMBER_INIT_ONLY) {
4503
0
            continue;
4504
0
        }
4505
0
        PyObject *name = PyUnicode_FromString(spec->name);
4506
0
        if (name == NULL) {
4507
0
            return -1;
4508
0
        }
4509
0
        int res = PyList_Append(names, name);
4510
0
        Py_DECREF(name);
4511
0
        if (res < 0) {
4512
0
            return -1;
4513
0
        }
4514
0
    }
4515
0
    return 0;
4516
0
}
4517
4518
4519
PyObject*
4520
PyConfig_Names(void)
4521
0
{
4522
0
    PyObject *names = PyList_New(0);
4523
0
    if (names == NULL) {
4524
0
        goto error;
4525
0
    }
4526
4527
0
    if (config_names_add(names, PYCONFIG_SPEC) < 0) {
4528
0
        goto error;
4529
0
    }
4530
0
    if (config_names_add(names, PYPRECONFIG_SPEC) < 0) {
4531
0
        goto error;
4532
0
    }
4533
4534
0
    PyObject *frozen = PyFrozenSet_New(names);
4535
0
    Py_DECREF(names);
4536
0
    return frozen;
4537
4538
0
error:
4539
0
    Py_XDECREF(names);
4540
0
    return NULL;
4541
0
}
4542
4543
4544
// --- PyConfig_Set() -------------------------------------------------------
4545
4546
static int
4547
config_set_sys_flag(const PyConfigSpec *spec, int int_value)
4548
0
{
4549
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
4550
0
    PyConfig *config = &interp->config;
4551
4552
0
    if (spec->type == PyConfig_MEMBER_BOOL) {
4553
0
        if (int_value != 0) {
4554
            // convert values < 0 and values > 1 to 1
4555
0
            int_value = 1;
4556
0
        }
4557
0
    }
4558
4559
0
    PyObject *value;
4560
0
    if (spec->sys.flag_setter) {
4561
0
        value = spec->sys.flag_setter(int_value);
4562
0
    }
4563
0
    else {
4564
0
        value = config_sys_flag_long(int_value);
4565
0
    }
4566
0
    if (value == NULL) {
4567
0
        return -1;
4568
0
    }
4569
4570
    // Set sys.flags.FLAG
4571
0
    Py_ssize_t pos = spec->sys.flag_index;
4572
0
    if (_PySys_SetFlagObj(pos, value) < 0) {
4573
0
        goto error;
4574
0
    }
4575
4576
    // Set PyConfig.ATTR
4577
0
    assert(spec->type == PyConfig_MEMBER_INT
4578
0
           || spec->type == PyConfig_MEMBER_UINT
4579
0
           || spec->type == PyConfig_MEMBER_BOOL);
4580
0
    int *member = config_get_spec_member(config, spec);
4581
0
    *member = int_value;
4582
4583
    // Set sys.dont_write_bytecode attribute
4584
0
    if (strcmp(spec->name, "write_bytecode") == 0) {
4585
0
        if (PySys_SetObject("dont_write_bytecode", value) < 0) {
4586
0
            goto error;
4587
0
        }
4588
0
    }
4589
4590
0
    Py_DECREF(value);
4591
0
    return 0;
4592
4593
0
error:
4594
0
    Py_DECREF(value);
4595
0
    return -1;
4596
0
}
4597
4598
4599
// Set PyConfig.ATTR integer member
4600
static int
4601
config_set_int_attr(const PyConfigSpec *spec, int value)
4602
0
{
4603
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
4604
0
    PyConfig *config = &interp->config;
4605
0
    int *member = config_get_spec_member(config, spec);
4606
0
    *member = value;
4607
0
    return 0;
4608
0
}
4609
4610
4611
int
4612
PyConfig_Set(const char *name, PyObject *value)
4613
0
{
4614
0
    if (PySys_Audit("cpython.PyConfig_Set", "sO", name, value) < 0) {
4615
0
        return -1;
4616
0
    }
4617
4618
0
    const PyConfigSpec *spec = config_find_spec(name);
4619
0
    if (spec == NULL) {
4620
0
        spec = preconfig_find_spec(name);
4621
0
        if (spec == NULL) {
4622
0
            config_unknown_name_error(name);
4623
0
            return -1;
4624
0
        }
4625
0
        assert(spec->visibility != PyConfig_MEMBER_PUBLIC);
4626
0
    }
4627
4628
0
    if (spec->visibility != PyConfig_MEMBER_PUBLIC) {
4629
0
        PyErr_Format(PyExc_ValueError, "cannot set read-only option %s",
4630
0
                     name);
4631
0
        return -1;
4632
0
    }
4633
4634
0
    int int_value = 0;
4635
0
    int has_int_value = 0;
4636
4637
0
    switch (spec->type) {
4638
0
    case PyConfig_MEMBER_INT:
4639
0
    case PyConfig_MEMBER_UINT:
4640
0
    case PyConfig_MEMBER_BOOL:
4641
0
        if (!PyLong_Check(value)) {
4642
0
            PyErr_Format(PyExc_TypeError, "expected int or bool, got %T", value);
4643
0
            return -1;
4644
0
        }
4645
0
        int_value = PyLong_AsInt(value);
4646
0
        if (int_value == -1 && PyErr_Occurred()) {
4647
0
            return -1;
4648
0
        }
4649
0
        if (int_value < 0 && spec->type != PyConfig_MEMBER_INT) {
4650
0
            PyErr_Format(PyExc_ValueError, "value must be >= 0");
4651
0
            return -1;
4652
0
        }
4653
0
        has_int_value = 1;
4654
0
        break;
4655
4656
0
    case PyConfig_MEMBER_ULONG:
4657
        // not implemented: only hash_seed uses this type, and it's read-only
4658
0
        goto cannot_set;
4659
4660
0
    case PyConfig_MEMBER_WSTR:
4661
0
        if (!PyUnicode_CheckExact(value)) {
4662
0
            PyErr_Format(PyExc_TypeError, "expected str, got %T", value);
4663
0
            return -1;
4664
0
        }
4665
0
        break;
4666
4667
0
    case PyConfig_MEMBER_WSTR_OPT:
4668
0
        if (value != Py_None && !PyUnicode_CheckExact(value)) {
4669
0
            PyErr_Format(PyExc_TypeError, "expected str or None, got %T", value);
4670
0
            return -1;
4671
0
        }
4672
0
        break;
4673
4674
0
    case PyConfig_MEMBER_WSTR_LIST:
4675
0
        if (strcmp(spec->name, "xoptions") != 0) {
4676
0
            if (!PyList_Check(value)) {
4677
0
                PyErr_Format(PyExc_TypeError, "expected list[str], got %T",
4678
0
                             value);
4679
0
                return -1;
4680
0
            }
4681
0
            for (Py_ssize_t i=0; i < PyList_GET_SIZE(value); i++) {
4682
0
                PyObject *item = PyList_GET_ITEM(value, i);
4683
0
                if (!PyUnicode_Check(item)) {
4684
0
                    PyErr_Format(PyExc_TypeError,
4685
0
                                 "expected str, list item %zd has type %T",
4686
0
                                 i, item);
4687
0
                    return -1;
4688
0
                }
4689
0
            }
4690
0
        }
4691
0
        else {
4692
            // xoptions type is dict[str, str]
4693
0
            if (!PyDict_Check(value)) {
4694
0
                PyErr_Format(PyExc_TypeError,
4695
0
                             "expected dict[str, str | bool], got %T",
4696
0
                             value);
4697
0
                return -1;
4698
0
            }
4699
4700
0
            Py_ssize_t pos = 0;
4701
0
            PyObject *key, *item;
4702
0
            while (PyDict_Next(value, &pos, &key, &item)) {
4703
0
                if (!PyUnicode_Check(key)) {
4704
0
                    PyErr_Format(PyExc_TypeError,
4705
0
                                 "expected str, "
4706
0
                                 "got dict key type %T", key);
4707
0
                    return -1;
4708
0
                }
4709
0
                if (!PyUnicode_Check(item) && !PyBool_Check(item)) {
4710
0
                    PyErr_Format(PyExc_TypeError,
4711
0
                                 "expected str or bool, "
4712
0
                                 "got dict value type %T", key);
4713
0
                    return -1;
4714
0
                }
4715
0
            }
4716
0
        }
4717
0
        break;
4718
4719
0
    default:
4720
0
        Py_UNREACHABLE();
4721
0
    }
4722
4723
0
    if (spec->sys.attr != NULL) {
4724
        // Set the sys attribute, but don't set PyInterpreterState.config
4725
        // to keep the code simple.
4726
0
        return PySys_SetObject(spec->sys.attr, value);
4727
0
    }
4728
0
    else if (has_int_value) {
4729
0
        if (spec->sys.flag_index >= 0) {
4730
0
            return config_set_sys_flag(spec, int_value);
4731
0
        }
4732
0
        else if (strcmp(spec->name, "int_max_str_digits") == 0) {
4733
0
            return _PySys_SetIntMaxStrDigits(int_value);
4734
0
        }
4735
0
        else {
4736
0
            return config_set_int_attr(spec, int_value);
4737
0
        }
4738
0
    }
4739
4740
0
cannot_set:
4741
0
    PyErr_Format(PyExc_ValueError, "cannot set option %s", name);
4742
0
    return -1;
4743
0
}