Coverage Report

Created: 2026-01-17 06:16

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
224
{
566
224
_Py_COMP_DIAG_PUSH
567
224
_Py_COMP_DIAG_IGNORE_DEPR_DECLS
568
224
    if (Py_IgnoreEnvironmentFlag) {
569
0
        return NULL;
570
0
    }
571
224
    return getenv(name);
572
224
_Py_COMP_DIAG_POP
573
224
}
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
    if (!config->inspect && _Py_GetEnv(use_env, "PYTHONINSPECT")) {
1850
0
        config->inspect = 1;
1851
0
    }
1852
1853
28
    int dont_write_bytecode = 0;
1854
28
    _Py_get_env_flag(use_env, &dont_write_bytecode, "PYTHONDONTWRITEBYTECODE");
1855
28
    if (dont_write_bytecode) {
1856
0
        config->write_bytecode = 0;
1857
0
    }
1858
1859
28
    int no_user_site_directory = 0;
1860
28
    _Py_get_env_flag(use_env, &no_user_site_directory, "PYTHONNOUSERSITE");
1861
28
    if (no_user_site_directory) {
1862
0
        config->user_site_directory = 0;
1863
0
    }
1864
1865
28
    int unbuffered_stdio = 0;
1866
28
    _Py_get_env_flag(use_env, &unbuffered_stdio, "PYTHONUNBUFFERED");
1867
28
    if (unbuffered_stdio) {
1868
0
        config->buffered_stdio = 0;
1869
0
    }
1870
1871
#ifdef MS_WINDOWS
1872
    _Py_get_env_flag(use_env, &config->legacy_windows_stdio,
1873
                     "PYTHONLEGACYWINDOWSSTDIO");
1874
#endif
1875
1876
28
    if (config_get_env(config, "PYTHONDUMPREFS")) {
1877
0
        config->dump_refs = 1;
1878
0
    }
1879
28
    if (config_get_env(config, "PYTHONMALLOCSTATS")) {
1880
0
        config->malloc_stats = 1;
1881
0
    }
1882
1883
28
    if (config->dump_refs_file == NULL) {
1884
28
        status = CONFIG_GET_ENV_DUP(config, &config->dump_refs_file,
1885
28
                                    L"PYTHONDUMPREFSFILE", "PYTHONDUMPREFSFILE");
1886
28
        if (_PyStatus_EXCEPTION(status)) {
1887
0
            return status;
1888
0
        }
1889
28
    }
1890
1891
28
    if (config->pythonpath_env == NULL) {
1892
28
        status = CONFIG_GET_ENV_DUP(config, &config->pythonpath_env,
1893
28
                                    L"PYTHONPATH", "PYTHONPATH");
1894
28
        if (_PyStatus_EXCEPTION(status)) {
1895
0
            return status;
1896
0
        }
1897
28
    }
1898
1899
28
    if(config->platlibdir == NULL) {
1900
28
        status = CONFIG_GET_ENV_DUP(config, &config->platlibdir,
1901
28
                                    L"PYTHONPLATLIBDIR", "PYTHONPLATLIBDIR");
1902
28
        if (_PyStatus_EXCEPTION(status)) {
1903
0
            return status;
1904
0
        }
1905
28
    }
1906
1907
28
    if (config->use_hash_seed < 0) {
1908
28
        status = config_init_hash_seed(config);
1909
28
        if (_PyStatus_EXCEPTION(status)) {
1910
0
            return status;
1911
0
        }
1912
28
    }
1913
1914
28
    if (config_get_env(config, "PYTHONSAFEPATH")) {
1915
0
        config->safe_path = 1;
1916
0
    }
1917
1918
28
    const char *gil = config_get_env(config, "PYTHON_GIL");
1919
28
    if (gil != NULL) {
1920
0
        size_t len = strlen(gil);
1921
0
        status = config_read_gil(config, len, gil[0]);
1922
0
        if (_PyStatus_EXCEPTION(status)) {
1923
0
            return status;
1924
0
        }
1925
0
    }
1926
1927
28
    return _PyStatus_OK();
1928
28
}
1929
1930
static PyStatus
1931
config_init_cpu_count(PyConfig *config)
1932
28
{
1933
28
    const char *env = config_get_env(config, "PYTHON_CPU_COUNT");
1934
28
    if (env) {
1935
0
        int cpu_count = -1;
1936
0
        if (strcmp(env, "default") == 0) {
1937
0
            cpu_count = -1;
1938
0
        }
1939
0
        else if (_Py_str_to_int(env, &cpu_count) < 0 || cpu_count < 1) {
1940
0
            goto error;
1941
0
        }
1942
0
        config->cpu_count = cpu_count;
1943
0
    }
1944
1945
28
    const wchar_t *xoption = config_get_xoption(config, L"cpu_count");
1946
28
    if (xoption) {
1947
0
        int cpu_count = -1;
1948
0
        const wchar_t *sep = wcschr(xoption, L'=');
1949
0
        if (sep) {
1950
0
            if (wcscmp(sep + 1, L"default") == 0) {
1951
0
                cpu_count = -1;
1952
0
            }
1953
0
            else if (config_wstr_to_int(sep + 1, &cpu_count) < 0 || cpu_count < 1) {
1954
0
                goto error;
1955
0
            }
1956
0
        }
1957
0
        else {
1958
0
            goto error;
1959
0
        }
1960
0
        config->cpu_count = cpu_count;
1961
0
    }
1962
28
    return _PyStatus_OK();
1963
1964
0
error:
1965
0
    return _PyStatus_ERR("-X cpu_count=n option: n is missing or an invalid number, "
1966
28
                         "n must be greater than 0");
1967
28
}
1968
1969
static PyStatus
1970
config_init_thread_inherit_context(PyConfig *config)
1971
28
{
1972
28
    const char *env = config_get_env(config, "PYTHON_THREAD_INHERIT_CONTEXT");
1973
28
    if (env) {
1974
0
        int enabled;
1975
0
        if (_Py_str_to_int(env, &enabled) < 0 || (enabled < 0) || (enabled > 1)) {
1976
0
            return _PyStatus_ERR(
1977
0
                "PYTHON_THREAD_INHERIT_CONTEXT=N: N is missing or invalid");
1978
0
        }
1979
0
        config->thread_inherit_context = enabled;
1980
0
    }
1981
1982
28
    const wchar_t *xoption = config_get_xoption(config, L"thread_inherit_context");
1983
28
    if (xoption) {
1984
0
        int enabled;
1985
0
        const wchar_t *sep = wcschr(xoption, L'=');
1986
0
        if (!sep || (config_wstr_to_int(sep + 1, &enabled) < 0) || (enabled < 0) || (enabled > 1)) {
1987
0
            return _PyStatus_ERR(
1988
0
                "-X thread_inherit_context=n: n is missing or invalid");
1989
0
        }
1990
0
        config->thread_inherit_context = enabled;
1991
0
    }
1992
28
    return _PyStatus_OK();
1993
28
}
1994
1995
static PyStatus
1996
config_init_context_aware_warnings(PyConfig *config)
1997
28
{
1998
28
    const char *env = config_get_env(config, "PYTHON_CONTEXT_AWARE_WARNINGS");
1999
28
    if (env) {
2000
0
        int enabled;
2001
0
        if (_Py_str_to_int(env, &enabled) < 0 || (enabled < 0) || (enabled > 1)) {
2002
0
            return _PyStatus_ERR(
2003
0
                "PYTHON_CONTEXT_AWARE_WARNINGS=N: N is missing or invalid");
2004
0
        }
2005
0
        config->context_aware_warnings = enabled;
2006
0
    }
2007
2008
28
    const wchar_t *xoption = config_get_xoption(config, L"context_aware_warnings");
2009
28
    if (xoption) {
2010
0
        int enabled;
2011
0
        const wchar_t *sep = wcschr(xoption, L'=');
2012
0
        if (!sep || (config_wstr_to_int(sep + 1, &enabled) < 0) || (enabled < 0) || (enabled > 1)) {
2013
0
            return _PyStatus_ERR(
2014
0
                "-X context_aware_warnings=n: n is missing or invalid");
2015
0
        }
2016
0
        config->context_aware_warnings = enabled;
2017
0
    }
2018
28
    return _PyStatus_OK();
2019
28
}
2020
2021
static PyStatus
2022
config_init_tlbc(PyConfig *config)
2023
28
{
2024
#ifdef Py_GIL_DISABLED
2025
    const char *env = config_get_env(config, "PYTHON_TLBC");
2026
    if (env) {
2027
        int enabled;
2028
        if (_Py_str_to_int(env, &enabled) < 0 || (enabled < 0) || (enabled > 1)) {
2029
            return _PyStatus_ERR(
2030
                "PYTHON_TLBC=N: N is missing or invalid");
2031
        }
2032
        config->tlbc_enabled = enabled;
2033
    }
2034
2035
    const wchar_t *xoption = config_get_xoption(config, L"tlbc");
2036
    if (xoption) {
2037
        int enabled;
2038
        const wchar_t *sep = wcschr(xoption, L'=');
2039
        if (!sep || (config_wstr_to_int(sep + 1, &enabled) < 0) || (enabled < 0) || (enabled > 1)) {
2040
            return _PyStatus_ERR(
2041
                "-X tlbc=n: n is missing or invalid");
2042
        }
2043
        config->tlbc_enabled = enabled;
2044
    }
2045
    return _PyStatus_OK();
2046
#else
2047
28
    return _PyStatus_OK();
2048
28
#endif
2049
28
}
2050
2051
static PyStatus
2052
config_init_perf_profiling(PyConfig *config)
2053
28
{
2054
28
    int active = 0;
2055
28
    const char *env = config_get_env(config, "PYTHONPERFSUPPORT");
2056
28
    if (env) {
2057
0
        if (_Py_str_to_int(env, &active) != 0) {
2058
0
            active = 0;
2059
0
        }
2060
0
        if (active) {
2061
0
            config->perf_profiling = 1;
2062
0
        }
2063
0
    }
2064
28
    const wchar_t *xoption = config_get_xoption(config, L"perf");
2065
28
    if (xoption) {
2066
0
        config->perf_profiling = 1;
2067
0
    }
2068
28
    env = config_get_env(config, "PYTHON_PERF_JIT_SUPPORT");
2069
28
    if (env) {
2070
0
        if (_Py_str_to_int(env, &active) != 0) {
2071
0
            active = 0;
2072
0
        }
2073
0
        if (active) {
2074
0
            config->perf_profiling = 2;
2075
0
        }
2076
0
    }
2077
28
    xoption = config_get_xoption(config, L"perf_jit");
2078
28
    if (xoption) {
2079
0
        config->perf_profiling = 2;
2080
0
    }
2081
2082
28
    return _PyStatus_OK();
2083
2084
28
}
2085
2086
static PyStatus
2087
config_init_remote_debug(PyConfig *config)
2088
28
{
2089
#ifndef Py_REMOTE_DEBUG
2090
    config->remote_debug = 0;
2091
#else
2092
28
    int active = 1;
2093
28
    const char *env = Py_GETENV("PYTHON_DISABLE_REMOTE_DEBUG");
2094
28
    if (env) {
2095
0
        active = 0;
2096
0
    }
2097
28
    const wchar_t *xoption = config_get_xoption(config, L"disable-remote-debug");
2098
28
    if (xoption) {
2099
0
        active = 0;
2100
0
    }
2101
2102
28
    config->remote_debug = active;
2103
28
#endif
2104
28
    return _PyStatus_OK();
2105
2106
28
}
2107
2108
static PyStatus
2109
config_init_tracemalloc(PyConfig *config)
2110
28
{
2111
28
    int nframe;
2112
28
    int valid;
2113
2114
28
    const char *env = config_get_env(config, "PYTHONTRACEMALLOC");
2115
28
    if (env) {
2116
0
        if (!_Py_str_to_int(env, &nframe)) {
2117
0
            valid = (nframe >= 0);
2118
0
        }
2119
0
        else {
2120
0
            valid = 0;
2121
0
        }
2122
0
        if (!valid) {
2123
0
            return _PyStatus_ERR("PYTHONTRACEMALLOC: invalid number of frames");
2124
0
        }
2125
0
        config->tracemalloc = nframe;
2126
0
    }
2127
2128
28
    const wchar_t *xoption = config_get_xoption(config, L"tracemalloc");
2129
28
    if (xoption) {
2130
0
        const wchar_t *sep = wcschr(xoption, L'=');
2131
0
        if (sep) {
2132
0
            if (!config_wstr_to_int(sep + 1, &nframe)) {
2133
0
                valid = (nframe >= 0);
2134
0
            }
2135
0
            else {
2136
0
                valid = 0;
2137
0
            }
2138
0
            if (!valid) {
2139
0
                return _PyStatus_ERR("-X tracemalloc=NFRAME: "
2140
0
                                     "invalid number of frames");
2141
0
            }
2142
0
        }
2143
0
        else {
2144
            /* -X tracemalloc behaves as -X tracemalloc=1 */
2145
0
            nframe = 1;
2146
0
        }
2147
0
        config->tracemalloc = nframe;
2148
0
    }
2149
28
    return _PyStatus_OK();
2150
28
}
2151
2152
static PyStatus
2153
config_init_int_max_str_digits(PyConfig *config)
2154
28
{
2155
28
    int maxdigits;
2156
2157
28
    const char *env = config_get_env(config, "PYTHONINTMAXSTRDIGITS");
2158
28
    if (env) {
2159
0
        bool valid = 0;
2160
0
        if (!_Py_str_to_int(env, &maxdigits)) {
2161
0
            valid = ((maxdigits == 0) || (maxdigits >= _PY_LONG_MAX_STR_DIGITS_THRESHOLD));
2162
0
        }
2163
0
        if (!valid) {
2164
0
#define STRINGIFY(VAL) _STRINGIFY(VAL)
2165
0
#define _STRINGIFY(VAL) #VAL
2166
0
            return _PyStatus_ERR(
2167
0
                    "PYTHONINTMAXSTRDIGITS: invalid limit; must be >= "
2168
0
                    STRINGIFY(_PY_LONG_MAX_STR_DIGITS_THRESHOLD)
2169
0
                    " or 0 for unlimited.");
2170
0
        }
2171
0
        config->int_max_str_digits = maxdigits;
2172
0
    }
2173
2174
28
    const wchar_t *xoption = config_get_xoption(config, L"int_max_str_digits");
2175
28
    if (xoption) {
2176
0
        const wchar_t *sep = wcschr(xoption, L'=');
2177
0
        bool valid = 0;
2178
0
        if (sep) {
2179
0
            if (!config_wstr_to_int(sep + 1, &maxdigits)) {
2180
0
                valid = ((maxdigits == 0) || (maxdigits >= _PY_LONG_MAX_STR_DIGITS_THRESHOLD));
2181
0
            }
2182
0
        }
2183
0
        if (!valid) {
2184
0
            return _PyStatus_ERR(
2185
0
                    "-X int_max_str_digits: invalid limit; must be >= "
2186
0
                    STRINGIFY(_PY_LONG_MAX_STR_DIGITS_THRESHOLD)
2187
0
                    " or 0 for unlimited.");
2188
0
#undef _STRINGIFY
2189
0
#undef STRINGIFY
2190
0
        }
2191
0
        config->int_max_str_digits = maxdigits;
2192
0
    }
2193
28
    if (config->int_max_str_digits < 0) {
2194
28
        config->int_max_str_digits = _PY_LONG_DEFAULT_MAX_STR_DIGITS;
2195
28
    }
2196
28
    return _PyStatus_OK();
2197
28
}
2198
2199
static PyStatus
2200
config_init_pycache_prefix(PyConfig *config)
2201
28
{
2202
28
    assert(config->pycache_prefix == NULL);
2203
2204
28
    const wchar_t *xoption = config_get_xoption(config, L"pycache_prefix");
2205
28
    if (xoption) {
2206
0
        const wchar_t *sep = wcschr(xoption, L'=');
2207
0
        if (sep && wcslen(sep) > 1) {
2208
0
            config->pycache_prefix = _PyMem_RawWcsdup(sep + 1);
2209
0
            if (config->pycache_prefix == NULL) {
2210
0
                return _PyStatus_NO_MEMORY();
2211
0
            }
2212
0
        }
2213
0
        else {
2214
            // PYTHONPYCACHEPREFIX env var ignored
2215
            // if "-X pycache_prefix=" option is used
2216
0
            config->pycache_prefix = NULL;
2217
0
        }
2218
0
        return _PyStatus_OK();
2219
0
    }
2220
2221
28
    return CONFIG_GET_ENV_DUP(config, &config->pycache_prefix,
2222
28
                              L"PYTHONPYCACHEPREFIX",
2223
28
                              "PYTHONPYCACHEPREFIX");
2224
28
}
2225
2226
2227
#ifdef Py_DEBUG
2228
static PyStatus
2229
config_init_run_presite(PyConfig *config)
2230
{
2231
    assert(config->run_presite == NULL);
2232
2233
    const wchar_t *xoption = config_get_xoption(config, L"presite");
2234
    if (xoption) {
2235
        const wchar_t *sep = wcschr(xoption, L'=');
2236
        if (sep && wcslen(sep) > 1) {
2237
            config->run_presite = _PyMem_RawWcsdup(sep + 1);
2238
            if (config->run_presite == NULL) {
2239
                return _PyStatus_NO_MEMORY();
2240
            }
2241
        }
2242
        else {
2243
            // PYTHON_PRESITE env var ignored
2244
            // if "-X presite=" option is used
2245
            config->run_presite = NULL;
2246
        }
2247
        return _PyStatus_OK();
2248
    }
2249
2250
    return CONFIG_GET_ENV_DUP(config, &config->run_presite,
2251
                              L"PYTHON_PRESITE",
2252
                              "PYTHON_PRESITE");
2253
}
2254
#endif
2255
2256
static PyStatus
2257
config_init_import_time(PyConfig *config)
2258
28
{
2259
28
    int importtime = 0;
2260
2261
28
    const char *env = config_get_env(config, "PYTHONPROFILEIMPORTTIME");
2262
28
    if (env) {
2263
0
        if (_Py_str_to_int(env, &importtime) != 0) {
2264
0
            importtime = 1;
2265
0
        }
2266
0
        if (importtime < 0 || importtime > 2) {
2267
0
            return _PyStatus_ERR(
2268
0
                "PYTHONPROFILEIMPORTTIME: numeric values other than 1 and 2 "
2269
0
                "are reserved for future use.");
2270
0
        }
2271
0
    }
2272
2273
28
    const wchar_t *x_value = config_get_xoption_value(config, L"importtime");
2274
28
    if (x_value) {
2275
0
        if (*x_value == 0 || config_wstr_to_int(x_value, &importtime) != 0) {
2276
0
            importtime = 1;
2277
0
        }
2278
0
        if (importtime < 0 || importtime > 2) {
2279
0
            return _PyStatus_ERR(
2280
0
                "-X importtime: values other than 1 and 2 "
2281
0
                "are reserved for future use.");
2282
0
        }
2283
0
    }
2284
2285
28
    config->import_time = importtime;
2286
28
    return _PyStatus_OK();
2287
28
}
2288
2289
static PyStatus
2290
config_read_complex_options(PyConfig *config)
2291
28
{
2292
    /* More complex options configured by env var and -X option */
2293
28
    if (config->faulthandler < 0) {
2294
28
        if (config_get_env(config, "PYTHONFAULTHANDLER")
2295
28
           || config_get_xoption(config, L"faulthandler")) {
2296
0
            config->faulthandler = 1;
2297
0
        }
2298
28
    }
2299
28
    if (config_get_env(config, "PYTHONNODEBUGRANGES")
2300
28
       || config_get_xoption(config, L"no_debug_ranges")) {
2301
0
        config->code_debug_ranges = 0;
2302
0
    }
2303
2304
28
    PyStatus status;
2305
28
    if (config->import_time < 0) {
2306
28
        status = config_init_import_time(config);
2307
28
        if (_PyStatus_EXCEPTION(status)) {
2308
0
            return status;
2309
0
        }
2310
28
    }
2311
2312
28
    if (config->tracemalloc < 0) {
2313
28
        status = config_init_tracemalloc(config);
2314
28
        if (_PyStatus_EXCEPTION(status)) {
2315
0
            return status;
2316
0
        }
2317
28
    }
2318
2319
28
    if (config->perf_profiling < 0) {
2320
28
        status = config_init_perf_profiling(config);
2321
28
        if (_PyStatus_EXCEPTION(status)) {
2322
0
            return status;
2323
0
        }
2324
28
    }
2325
2326
28
    if (config->remote_debug < 0) {
2327
28
        status = config_init_remote_debug(config);
2328
28
        if (_PyStatus_EXCEPTION(status)) {
2329
0
            return status;
2330
0
        }
2331
28
    }
2332
2333
28
    if (config->int_max_str_digits < 0) {
2334
28
        status = config_init_int_max_str_digits(config);
2335
28
        if (_PyStatus_EXCEPTION(status)) {
2336
0
            return status;
2337
0
        }
2338
28
    }
2339
2340
28
    if (config->cpu_count < 0) {
2341
28
        status = config_init_cpu_count(config);
2342
28
        if (_PyStatus_EXCEPTION(status)) {
2343
0
            return status;
2344
0
        }
2345
28
    }
2346
2347
28
    if (config->pycache_prefix == NULL) {
2348
28
        status = config_init_pycache_prefix(config);
2349
28
        if (_PyStatus_EXCEPTION(status)) {
2350
0
            return status;
2351
0
        }
2352
28
    }
2353
2354
#ifdef Py_DEBUG
2355
    if (config->run_presite == NULL) {
2356
        status = config_init_run_presite(config);
2357
        if (_PyStatus_EXCEPTION(status)) {
2358
            return status;
2359
        }
2360
    }
2361
#endif
2362
2363
28
    status = config_init_thread_inherit_context(config);
2364
28
    if (_PyStatus_EXCEPTION(status)) {
2365
0
        return status;
2366
0
    }
2367
2368
28
    status = config_init_context_aware_warnings(config);
2369
28
    if (_PyStatus_EXCEPTION(status)) {
2370
0
        return status;
2371
0
    }
2372
2373
28
    status = config_init_tlbc(config);
2374
28
    if (_PyStatus_EXCEPTION(status)) {
2375
0
        return status;
2376
0
    }
2377
2378
28
    return _PyStatus_OK();
2379
28
}
2380
2381
2382
static const wchar_t *
2383
config_get_stdio_errors(const PyPreConfig *preconfig)
2384
28
{
2385
28
    if (preconfig->utf8_mode) {
2386
        /* UTF-8 Mode uses UTF-8/surrogateescape */
2387
28
        return L"surrogateescape";
2388
28
    }
2389
2390
0
#ifndef MS_WINDOWS
2391
0
    const char *loc = setlocale(LC_CTYPE, NULL);
2392
0
    if (loc != NULL) {
2393
        /* surrogateescape is the default in the legacy C and POSIX locales */
2394
0
        if (strcmp(loc, "C") == 0 || strcmp(loc, "POSIX") == 0) {
2395
0
            return L"surrogateescape";
2396
0
        }
2397
2398
0
#ifdef PY_COERCE_C_LOCALE
2399
        /* surrogateescape is the default in locale coercion target locales */
2400
0
        if (_Py_IsLocaleCoercionTarget(loc)) {
2401
0
            return L"surrogateescape";
2402
0
        }
2403
0
#endif
2404
0
    }
2405
2406
0
    return L"strict";
2407
#else
2408
    /* On Windows, always use surrogateescape by default */
2409
    return L"surrogateescape";
2410
#endif
2411
0
}
2412
2413
2414
// See also config_get_fs_encoding()
2415
static PyStatus
2416
config_get_locale_encoding(PyConfig *config, const PyPreConfig *preconfig,
2417
                           wchar_t **locale_encoding)
2418
28
{
2419
28
    wchar_t *encoding;
2420
28
    if (preconfig->utf8_mode) {
2421
28
        encoding = _PyMem_RawWcsdup(L"utf-8");
2422
28
    }
2423
0
    else {
2424
0
        encoding = _Py_GetLocaleEncoding();
2425
0
    }
2426
28
    if (encoding == NULL) {
2427
0
        return _PyStatus_NO_MEMORY();
2428
0
    }
2429
28
    PyStatus status = PyConfig_SetString(config, locale_encoding, encoding);
2430
28
    PyMem_RawFree(encoding);
2431
28
    return status;
2432
28
}
2433
2434
2435
static PyStatus
2436
config_init_stdio_encoding(PyConfig *config,
2437
                           const PyPreConfig *preconfig)
2438
28
{
2439
28
    PyStatus status;
2440
2441
    // Exit if encoding and errors are defined
2442
28
    if (config->stdio_encoding != NULL && config->stdio_errors != NULL) {
2443
0
        return _PyStatus_OK();
2444
0
    }
2445
2446
    /* PYTHONIOENCODING environment variable */
2447
28
    const char *opt = config_get_env(config, "PYTHONIOENCODING");
2448
28
    if (opt) {
2449
0
        char *pythonioencoding = _PyMem_RawStrdup(opt);
2450
0
        if (pythonioencoding == NULL) {
2451
0
            return _PyStatus_NO_MEMORY();
2452
0
        }
2453
2454
0
        char *errors = strchr(pythonioencoding, ':');
2455
0
        if (errors) {
2456
0
            *errors = '\0';
2457
0
            errors++;
2458
0
            if (!errors[0]) {
2459
0
                errors = NULL;
2460
0
            }
2461
0
        }
2462
2463
        /* Does PYTHONIOENCODING contain an encoding? */
2464
0
        if (pythonioencoding[0]) {
2465
0
            if (config->stdio_encoding == NULL) {
2466
0
                status = CONFIG_SET_BYTES_STR(config, &config->stdio_encoding,
2467
0
                                              pythonioencoding,
2468
0
                                              "PYTHONIOENCODING environment variable");
2469
0
                if (_PyStatus_EXCEPTION(status)) {
2470
0
                    PyMem_RawFree(pythonioencoding);
2471
0
                    return status;
2472
0
                }
2473
0
            }
2474
2475
            /* If the encoding is set but not the error handler,
2476
               use "strict" error handler by default.
2477
               PYTHONIOENCODING=latin1 behaves as
2478
               PYTHONIOENCODING=latin1:strict. */
2479
0
            if (!errors) {
2480
0
                errors = "strict";
2481
0
            }
2482
0
        }
2483
2484
0
        if (config->stdio_errors == NULL && errors != NULL) {
2485
0
            status = CONFIG_SET_BYTES_STR(config, &config->stdio_errors,
2486
0
                                          errors,
2487
0
                                          "PYTHONIOENCODING environment variable");
2488
0
            if (_PyStatus_EXCEPTION(status)) {
2489
0
                PyMem_RawFree(pythonioencoding);
2490
0
                return status;
2491
0
            }
2492
0
        }
2493
2494
0
        PyMem_RawFree(pythonioencoding);
2495
0
    }
2496
2497
    /* Choose the default error handler based on the current locale. */
2498
28
    if (config->stdio_encoding == NULL) {
2499
28
        status = config_get_locale_encoding(config, preconfig,
2500
28
                                            &config->stdio_encoding);
2501
28
        if (_PyStatus_EXCEPTION(status)) {
2502
0
            return status;
2503
0
        }
2504
28
    }
2505
28
    if (config->stdio_errors == NULL) {
2506
28
        const wchar_t *errors = config_get_stdio_errors(preconfig);
2507
28
        assert(errors != NULL);
2508
2509
28
        status = PyConfig_SetString(config, &config->stdio_errors, errors);
2510
28
        if (_PyStatus_EXCEPTION(status)) {
2511
0
            return status;
2512
0
        }
2513
28
    }
2514
2515
28
    return _PyStatus_OK();
2516
28
}
2517
2518
2519
// See also config_get_locale_encoding()
2520
static PyStatus
2521
config_get_fs_encoding(PyConfig *config, const PyPreConfig *preconfig,
2522
                       wchar_t **fs_encoding)
2523
28
{
2524
#ifdef _Py_FORCE_UTF8_FS_ENCODING
2525
    return PyConfig_SetString(config, fs_encoding, L"utf-8");
2526
#elif defined(MS_WINDOWS)
2527
    const wchar_t *encoding;
2528
    if (preconfig->legacy_windows_fs_encoding) {
2529
        // Legacy Windows filesystem encoding: mbcs/replace
2530
        encoding = L"mbcs";
2531
    }
2532
    else {
2533
        // Windows defaults to utf-8/surrogatepass (PEP 529)
2534
        encoding = L"utf-8";
2535
    }
2536
     return PyConfig_SetString(config, fs_encoding, encoding);
2537
#else  // !MS_WINDOWS
2538
28
    if (preconfig->utf8_mode) {
2539
28
        return PyConfig_SetString(config, fs_encoding, L"utf-8");
2540
28
    }
2541
2542
0
    if (_Py_GetForceASCII()) {
2543
0
        return PyConfig_SetString(config, fs_encoding, L"ascii");
2544
0
    }
2545
2546
0
    return config_get_locale_encoding(config, preconfig, fs_encoding);
2547
0
#endif  // !MS_WINDOWS
2548
0
}
2549
2550
2551
static PyStatus
2552
config_init_fs_encoding(PyConfig *config, const PyPreConfig *preconfig)
2553
28
{
2554
28
    PyStatus status;
2555
2556
28
    if (config->filesystem_encoding == NULL) {
2557
28
        status = config_get_fs_encoding(config, preconfig,
2558
28
                                        &config->filesystem_encoding);
2559
28
        if (_PyStatus_EXCEPTION(status)) {
2560
0
            return status;
2561
0
        }
2562
28
    }
2563
2564
28
    if (config->filesystem_errors == NULL) {
2565
28
        const wchar_t *errors;
2566
#ifdef MS_WINDOWS
2567
        if (preconfig->legacy_windows_fs_encoding) {
2568
            errors = L"replace";
2569
        }
2570
        else {
2571
            errors = L"surrogatepass";
2572
        }
2573
#else
2574
28
        errors = L"surrogateescape";
2575
28
#endif
2576
28
        status = PyConfig_SetString(config, &config->filesystem_errors, errors);
2577
28
        if (_PyStatus_EXCEPTION(status)) {
2578
0
            return status;
2579
0
        }
2580
28
    }
2581
28
    return _PyStatus_OK();
2582
28
}
2583
2584
2585
static PyStatus
2586
config_init_import(PyConfig *config, int compute_path_config)
2587
56
{
2588
56
    PyStatus status;
2589
2590
56
    status = _PyConfig_InitPathConfig(config, compute_path_config);
2591
56
    if (_PyStatus_EXCEPTION(status)) {
2592
0
        return status;
2593
0
    }
2594
2595
56
    const char *env = config_get_env(config, "PYTHON_FROZEN_MODULES");
2596
56
    if (env == NULL) {
2597
56
    }
2598
0
    else if (strcmp(env, "on") == 0) {
2599
0
        config->use_frozen_modules = 1;
2600
0
    }
2601
0
    else if (strcmp(env, "off") == 0) {
2602
0
        config->use_frozen_modules = 0;
2603
0
    } else {
2604
0
        return PyStatus_Error("bad value for PYTHON_FROZEN_MODULES "
2605
0
                              "(expected \"on\" or \"off\")");
2606
0
    }
2607
2608
    /* -X frozen_modules=[on|off] */
2609
56
    const wchar_t *value = config_get_xoption_value(config, L"frozen_modules");
2610
56
    if (value == NULL) {
2611
56
    }
2612
0
    else if (wcscmp(value, L"on") == 0) {
2613
0
        config->use_frozen_modules = 1;
2614
0
    }
2615
0
    else if (wcscmp(value, L"off") == 0) {
2616
0
        config->use_frozen_modules = 0;
2617
0
    }
2618
0
    else if (wcslen(value) == 0) {
2619
        // "-X frozen_modules" and "-X frozen_modules=" both imply "on".
2620
0
        config->use_frozen_modules = 1;
2621
0
    }
2622
0
    else {
2623
0
        return PyStatus_Error("bad value for option -X frozen_modules "
2624
0
                              "(expected \"on\" or \"off\")");
2625
0
    }
2626
2627
56
    assert(config->use_frozen_modules >= 0);
2628
56
    return _PyStatus_OK();
2629
56
}
2630
2631
PyStatus
2632
_PyConfig_InitImportConfig(PyConfig *config)
2633
28
{
2634
28
    return config_init_import(config, 1);
2635
28
}
2636
2637
2638
static PyStatus
2639
config_read(PyConfig *config, int compute_path_config)
2640
28
{
2641
28
    PyStatus status;
2642
28
    const PyPreConfig *preconfig = &_PyRuntime.preconfig;
2643
2644
28
    if (config->use_environment) {
2645
28
        status = config_read_env_vars(config);
2646
28
        if (_PyStatus_EXCEPTION(status)) {
2647
0
            return status;
2648
0
        }
2649
28
    }
2650
2651
    /* -X options */
2652
28
    if (config_get_xoption(config, L"showrefcount")) {
2653
0
        config->show_ref_count = 1;
2654
0
    }
2655
2656
28
    const wchar_t *x_gil = config_get_xoption_value(config, L"gil");
2657
28
    if (x_gil != NULL) {
2658
0
        size_t len = wcslen(x_gil);
2659
0
        status = config_read_gil(config, len, x_gil[0]);
2660
0
        if (_PyStatus_EXCEPTION(status)) {
2661
0
            return status;
2662
0
        }
2663
0
    }
2664
2665
#ifdef Py_STATS
2666
    if (config_get_xoption(config, L"pystats")) {
2667
        config->_pystats = 1;
2668
    }
2669
    else if (config_get_env(config, "PYTHONSTATS")) {
2670
        config->_pystats = 1;
2671
    }
2672
    if (config->_pystats < 0) {
2673
        config->_pystats = 0;
2674
    }
2675
#endif
2676
2677
28
    status = config_read_complex_options(config);
2678
28
    if (_PyStatus_EXCEPTION(status)) {
2679
0
        return status;
2680
0
    }
2681
2682
28
    if (config->_install_importlib) {
2683
28
        status = config_init_import(config, compute_path_config);
2684
28
        if (_PyStatus_EXCEPTION(status)) {
2685
0
            return status;
2686
0
        }
2687
28
    }
2688
2689
    /* default values */
2690
28
    if (config->dev_mode) {
2691
0
        if (config->faulthandler < 0) {
2692
0
            config->faulthandler = 1;
2693
0
        }
2694
0
    }
2695
28
    if (config->faulthandler < 0) {
2696
28
        config->faulthandler = 0;
2697
28
    }
2698
28
    if (config->tracemalloc < 0) {
2699
28
        config->tracemalloc = 0;
2700
28
    }
2701
28
    if (config->perf_profiling < 0) {
2702
28
        config->perf_profiling = 0;
2703
28
    }
2704
28
    if (config->remote_debug < 0) {
2705
0
        config->remote_debug = -1;
2706
0
    }
2707
28
    if (config->use_hash_seed < 0) {
2708
0
        config->use_hash_seed = 0;
2709
0
        config->hash_seed = 0;
2710
0
    }
2711
2712
28
    if (config->filesystem_encoding == NULL || config->filesystem_errors == NULL) {
2713
28
        status = config_init_fs_encoding(config, preconfig);
2714
28
        if (_PyStatus_EXCEPTION(status)) {
2715
0
            return status;
2716
0
        }
2717
28
    }
2718
2719
28
    status = config_init_stdio_encoding(config, preconfig);
2720
28
    if (_PyStatus_EXCEPTION(status)) {
2721
0
        return status;
2722
0
    }
2723
2724
28
    if (config->argv.length < 1) {
2725
        /* Ensure at least one (empty) argument is seen */
2726
28
        status = PyWideStringList_Append(&config->argv, L"");
2727
28
        if (_PyStatus_EXCEPTION(status)) {
2728
0
            return status;
2729
0
        }
2730
28
    }
2731
2732
28
    if (config->check_hash_pycs_mode == NULL) {
2733
28
        status = PyConfig_SetString(config, &config->check_hash_pycs_mode,
2734
28
                                    L"default");
2735
28
        if (_PyStatus_EXCEPTION(status)) {
2736
0
            return status;
2737
0
        }
2738
28
    }
2739
2740
28
    if (config->configure_c_stdio < 0) {
2741
0
        config->configure_c_stdio = 1;
2742
0
    }
2743
2744
    // Only parse arguments once.
2745
28
    if (config->parse_argv == 1) {
2746
0
        config->parse_argv = 2;
2747
0
    }
2748
2749
28
    return _PyStatus_OK();
2750
28
}
2751
2752
2753
static void
2754
config_init_stdio(const PyConfig *config)
2755
0
{
2756
#if defined(MS_WINDOWS) || defined(__CYGWIN__)
2757
    /* don't translate newlines (\r\n <=> \n) */
2758
    _setmode(fileno(stdin), O_BINARY);
2759
    _setmode(fileno(stdout), O_BINARY);
2760
    _setmode(fileno(stderr), O_BINARY);
2761
#endif
2762
2763
0
    if (!config->buffered_stdio) {
2764
0
#ifdef HAVE_SETVBUF
2765
0
        setvbuf(stdin,  (char *)NULL, _IONBF, BUFSIZ);
2766
0
        setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ);
2767
0
        setvbuf(stderr, (char *)NULL, _IONBF, BUFSIZ);
2768
#else /* !HAVE_SETVBUF */
2769
        setbuf(stdin,  (char *)NULL);
2770
        setbuf(stdout, (char *)NULL);
2771
        setbuf(stderr, (char *)NULL);
2772
#endif /* !HAVE_SETVBUF */
2773
0
    }
2774
0
    else if (config->interactive) {
2775
#ifdef MS_WINDOWS
2776
        /* Doesn't have to have line-buffered -- use unbuffered */
2777
        /* Any set[v]buf(stdin, ...) screws up Tkinter :-( */
2778
        setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ);
2779
#else /* !MS_WINDOWS */
2780
0
#ifdef HAVE_SETVBUF
2781
0
        setvbuf(stdin,  (char *)NULL, _IOLBF, BUFSIZ);
2782
0
        setvbuf(stdout, (char *)NULL, _IOLBF, BUFSIZ);
2783
0
#endif /* HAVE_SETVBUF */
2784
0
#endif /* !MS_WINDOWS */
2785
        /* Leave stderr alone - it should be unbuffered anyway. */
2786
0
    }
2787
0
}
2788
2789
2790
/* Write the configuration:
2791
2792
   - set Py_xxx global configuration variables
2793
   - initialize C standard streams (stdin, stdout, stderr) */
2794
PyStatus
2795
_PyConfig_Write(const PyConfig *config, _PyRuntimeState *runtime)
2796
28
{
2797
28
    config_set_global_vars(config);
2798
2799
28
    if (config->configure_c_stdio) {
2800
0
        config_init_stdio(config);
2801
0
    }
2802
2803
    /* Write the new pre-configuration into _PyRuntime */
2804
28
    PyPreConfig *preconfig = &runtime->preconfig;
2805
28
    preconfig->isolated = config->isolated;
2806
28
    preconfig->use_environment = config->use_environment;
2807
28
    preconfig->dev_mode = config->dev_mode;
2808
2809
28
    if (_Py_SetArgcArgv(config->orig_argv.length,
2810
28
                        config->orig_argv.items) < 0)
2811
0
    {
2812
0
        return _PyStatus_NO_MEMORY();
2813
0
    }
2814
2815
28
    return _PyStatus_OK();
2816
28
}
2817
2818
2819
/* --- PyConfig command line parser -------------------------- */
2820
2821
static void
2822
config_usage(int error, const wchar_t* program)
2823
0
{
2824
0
    FILE *f = error ? stderr : stdout;
2825
2826
0
    fprintf(f, usage_line, program);
2827
0
    if (error)
2828
0
        fprintf(f, "Try `python -h' for more information.\n");
2829
0
    else {
2830
0
        fputs(usage_help, f);
2831
0
    }
2832
0
}
2833
2834
static void
2835
config_envvars_usage(void)
2836
0
{
2837
0
    printf(usage_envvars, (wint_t)DELIM, (wint_t)DELIM, PYTHONHOMEHELP);
2838
0
}
2839
2840
static void
2841
config_xoptions_usage(void)
2842
0
{
2843
0
    puts(usage_xoptions);
2844
0
}
2845
2846
static void
2847
config_complete_usage(const wchar_t* program)
2848
0
{
2849
0
   config_usage(0, program);
2850
0
   putchar('\n');
2851
0
   config_envvars_usage();
2852
0
   putchar('\n');
2853
0
   config_xoptions_usage();
2854
0
}
2855
2856
2857
/* Parse the command line arguments */
2858
static PyStatus
2859
config_parse_cmdline(PyConfig *config, PyWideStringList *warnoptions,
2860
                     Py_ssize_t *opt_index)
2861
0
{
2862
0
    PyStatus status;
2863
0
    const PyWideStringList *argv = &config->argv;
2864
0
    int print_version = 0;
2865
0
    const wchar_t* program = config->program_name;
2866
0
    if (!program && argv->length >= 1) {
2867
0
        program = argv->items[0];
2868
0
    }
2869
2870
0
    _PyOS_ResetGetOpt();
2871
0
    do {
2872
0
        int longindex = -1;
2873
0
        int c = _PyOS_GetOpt(argv->length, argv->items, &longindex);
2874
0
        if (c == EOF) {
2875
0
            break;
2876
0
        }
2877
2878
0
        if (c == 'c') {
2879
0
            if (config->run_command == NULL) {
2880
                /* -c is the last option; following arguments
2881
                   that look like options are left for the
2882
                   command to interpret. */
2883
0
                size_t len = wcslen(_PyOS_optarg) + 1 + 1;
2884
0
                wchar_t *command = PyMem_RawMalloc(sizeof(wchar_t) * len);
2885
0
                if (command == NULL) {
2886
0
                    return _PyStatus_NO_MEMORY();
2887
0
                }
2888
0
                memcpy(command, _PyOS_optarg, (len - 2) * sizeof(wchar_t));
2889
0
                command[len - 2] = '\n';
2890
0
                command[len - 1] = 0;
2891
0
                config->run_command = command;
2892
0
            }
2893
0
            break;
2894
0
        }
2895
2896
0
        if (c == 'm') {
2897
            /* -m is the last option; following arguments
2898
               that look like options are left for the
2899
               module to interpret. */
2900
0
            if (config->run_module == NULL) {
2901
0
                config->run_module = _PyMem_RawWcsdup(_PyOS_optarg);
2902
0
                if (config->run_module == NULL) {
2903
0
                    return _PyStatus_NO_MEMORY();
2904
0
                }
2905
0
            }
2906
0
            break;
2907
0
        }
2908
2909
0
        switch (c) {
2910
        // Integers represent long options, see Python/getopt.c
2911
0
        case 0:
2912
            // check-hash-based-pycs
2913
0
            if (wcscmp(_PyOS_optarg, L"always") == 0
2914
0
                || wcscmp(_PyOS_optarg, L"never") == 0
2915
0
                || wcscmp(_PyOS_optarg, L"default") == 0)
2916
0
            {
2917
0
                status = PyConfig_SetString(config, &config->check_hash_pycs_mode,
2918
0
                                            _PyOS_optarg);
2919
0
                if (_PyStatus_EXCEPTION(status)) {
2920
0
                    return status;
2921
0
                }
2922
0
            } else {
2923
0
                fprintf(stderr, "--check-hash-based-pycs must be one of "
2924
0
                        "'default', 'always', or 'never'\n");
2925
0
                config_usage(1, program);
2926
0
                return _PyStatus_EXIT(2);
2927
0
            }
2928
0
            break;
2929
2930
0
        case 1:
2931
            // help-all
2932
0
            config_complete_usage(program);
2933
0
            return _PyStatus_EXIT(0);
2934
2935
0
        case 2:
2936
            // help-env
2937
0
            config_envvars_usage();
2938
0
            return _PyStatus_EXIT(0);
2939
2940
0
        case 3:
2941
            // help-xoptions
2942
0
            config_xoptions_usage();
2943
0
            return _PyStatus_EXIT(0);
2944
2945
0
        case 'b':
2946
0
            config->bytes_warning++;
2947
0
            break;
2948
2949
0
        case 'd':
2950
0
            config->parser_debug++;
2951
0
            break;
2952
2953
0
        case 'i':
2954
0
            config->inspect++;
2955
0
            config->interactive++;
2956
0
            break;
2957
2958
0
        case 'E':
2959
0
        case 'I':
2960
0
        case 'X':
2961
            /* option handled by _PyPreCmdline_Read() */
2962
0
            break;
2963
2964
0
        case 'O':
2965
0
            config->optimization_level++;
2966
0
            break;
2967
2968
0
        case 'P':
2969
0
            config->safe_path = 1;
2970
0
            break;
2971
2972
0
        case 'B':
2973
0
            config->write_bytecode = 0;
2974
0
            break;
2975
2976
0
        case 's':
2977
0
            config->user_site_directory = 0;
2978
0
            break;
2979
2980
0
        case 'S':
2981
0
            config->site_import = 0;
2982
0
            break;
2983
2984
0
        case 't':
2985
            /* ignored for backwards compatibility */
2986
0
            break;
2987
2988
0
        case 'u':
2989
0
            config->buffered_stdio = 0;
2990
0
            break;
2991
2992
0
        case 'v':
2993
0
            config->verbose++;
2994
0
            break;
2995
2996
0
        case 'x':
2997
0
            config->skip_source_first_line = 1;
2998
0
            break;
2999
3000
0
        case 'h':
3001
0
        case '?':
3002
0
            config_usage(0, program);
3003
0
            return _PyStatus_EXIT(0);
3004
3005
0
        case 'V':
3006
0
            print_version++;
3007
0
            break;
3008
3009
0
        case 'W':
3010
0
            status = PyWideStringList_Append(warnoptions, _PyOS_optarg);
3011
0
            if (_PyStatus_EXCEPTION(status)) {
3012
0
                return status;
3013
0
            }
3014
0
            break;
3015
3016
0
        case 'q':
3017
0
            config->quiet++;
3018
0
            break;
3019
3020
0
        case 'R':
3021
0
            config->use_hash_seed = 0;
3022
0
            break;
3023
3024
        /* This space reserved for other options */
3025
3026
0
        default:
3027
            /* unknown argument: parsing failed */
3028
0
            config_usage(1, program);
3029
0
            return _PyStatus_EXIT(2);
3030
0
        }
3031
0
    } while (1);
3032
3033
0
    if (print_version) {
3034
0
        printf("Python %s\n",
3035
0
                (print_version >= 2) ? Py_GetVersion() : PY_VERSION);
3036
0
        return _PyStatus_EXIT(0);
3037
0
    }
3038
3039
0
    if (config->run_command == NULL && config->run_module == NULL
3040
0
        && _PyOS_optind < argv->length
3041
0
        && wcscmp(argv->items[_PyOS_optind], L"-") != 0
3042
0
        && config->run_filename == NULL)
3043
0
    {
3044
0
        config->run_filename = _PyMem_RawWcsdup(argv->items[_PyOS_optind]);
3045
0
        if (config->run_filename == NULL) {
3046
0
            return _PyStatus_NO_MEMORY();
3047
0
        }
3048
0
    }
3049
3050
0
    if (config->run_command != NULL || config->run_module != NULL) {
3051
        /* Backup _PyOS_optind */
3052
0
        _PyOS_optind--;
3053
0
    }
3054
3055
0
    *opt_index = _PyOS_optind;
3056
3057
0
    return _PyStatus_OK();
3058
0
}
3059
3060
3061
#ifdef MS_WINDOWS
3062
#  define WCSTOK wcstok_s
3063
#else
3064
0
#  define WCSTOK wcstok
3065
#endif
3066
3067
/* Get warning options from PYTHONWARNINGS environment variable. */
3068
static PyStatus
3069
config_init_env_warnoptions(PyConfig *config, PyWideStringList *warnoptions)
3070
28
{
3071
28
    PyStatus status;
3072
    /* CONFIG_GET_ENV_DUP requires dest to be initialized to NULL */
3073
28
    wchar_t *env = NULL;
3074
28
    status = CONFIG_GET_ENV_DUP(config, &env,
3075
28
                             L"PYTHONWARNINGS", "PYTHONWARNINGS");
3076
28
    if (_PyStatus_EXCEPTION(status)) {
3077
0
        return status;
3078
0
    }
3079
3080
    /* env var is not set or is empty */
3081
28
    if (env == NULL) {
3082
28
        return _PyStatus_OK();
3083
28
    }
3084
3085
3086
0
    wchar_t *warning, *context = NULL;
3087
0
    for (warning = WCSTOK(env, L",", &context);
3088
0
         warning != NULL;
3089
0
         warning = WCSTOK(NULL, L",", &context))
3090
0
    {
3091
0
        status = PyWideStringList_Append(warnoptions, warning);
3092
0
        if (_PyStatus_EXCEPTION(status)) {
3093
0
            PyMem_RawFree(env);
3094
0
            return status;
3095
0
        }
3096
0
    }
3097
0
    PyMem_RawFree(env);
3098
0
    return _PyStatus_OK();
3099
0
}
3100
3101
3102
static PyStatus
3103
warnoptions_append(PyConfig *config, PyWideStringList *options,
3104
                   const wchar_t *option)
3105
0
{
3106
    /* config_init_warnoptions() add existing config warnoptions at the end:
3107
       ensure that the new option is not already present in this list to
3108
       prevent change the options order when config_init_warnoptions() is
3109
       called twice. */
3110
0
    if (_PyWideStringList_Find(&config->warnoptions, option)) {
3111
        /* Already present: do nothing */
3112
0
        return _PyStatus_OK();
3113
0
    }
3114
0
    if (_PyWideStringList_Find(options, option)) {
3115
        /* Already present: do nothing */
3116
0
        return _PyStatus_OK();
3117
0
    }
3118
0
    return PyWideStringList_Append(options, option);
3119
0
}
3120
3121
3122
static PyStatus
3123
warnoptions_extend(PyConfig *config, PyWideStringList *options,
3124
                   const PyWideStringList *options2)
3125
84
{
3126
84
    const Py_ssize_t len = options2->length;
3127
84
    wchar_t *const *items = options2->items;
3128
3129
84
    for (Py_ssize_t i = 0; i < len; i++) {
3130
0
        PyStatus status = warnoptions_append(config, options, items[i]);
3131
0
        if (_PyStatus_EXCEPTION(status)) {
3132
0
            return status;
3133
0
        }
3134
0
    }
3135
84
    return _PyStatus_OK();
3136
84
}
3137
3138
3139
static PyStatus
3140
config_init_warnoptions(PyConfig *config,
3141
                        const PyWideStringList *cmdline_warnoptions,
3142
                        const PyWideStringList *env_warnoptions,
3143
                        const PyWideStringList *sys_warnoptions)
3144
28
{
3145
28
    PyStatus status;
3146
28
    PyWideStringList options = _PyWideStringList_INIT;
3147
3148
    /* Priority of warnings options, lowest to highest:
3149
     *
3150
     * - any implicit filters added by _warnings.c/warnings.py
3151
     * - PyConfig.dev_mode: "default" filter
3152
     * - PYTHONWARNINGS environment variable
3153
     * - '-W' command line options
3154
     * - PyConfig.bytes_warning ('-b' and '-bb' command line options):
3155
     *   "default::BytesWarning" or "error::BytesWarning" filter
3156
     * - early PySys_AddWarnOption() calls
3157
     * - PyConfig.warnoptions
3158
     *
3159
     * PyConfig.warnoptions is copied to sys.warnoptions. Since the warnings
3160
     * module works on the basis of "the most recently added filter will be
3161
     * checked first", we add the lowest precedence entries first so that later
3162
     * entries override them.
3163
     */
3164
3165
28
    if (config->dev_mode) {
3166
0
        status = warnoptions_append(config, &options, L"default");
3167
0
        if (_PyStatus_EXCEPTION(status)) {
3168
0
            goto error;
3169
0
        }
3170
0
    }
3171
3172
28
    status = warnoptions_extend(config, &options, env_warnoptions);
3173
28
    if (_PyStatus_EXCEPTION(status)) {
3174
0
        goto error;
3175
0
    }
3176
3177
28
    status = warnoptions_extend(config, &options, cmdline_warnoptions);
3178
28
    if (_PyStatus_EXCEPTION(status)) {
3179
0
        goto error;
3180
0
    }
3181
3182
    /* If the bytes_warning_flag isn't set, bytesobject.c and bytearrayobject.c
3183
     * don't even try to emit a warning, so we skip setting the filter in that
3184
     * case.
3185
     */
3186
28
    if (config->bytes_warning) {
3187
0
        const wchar_t *filter;
3188
0
        if (config->bytes_warning> 1) {
3189
0
            filter = L"error::BytesWarning";
3190
0
        }
3191
0
        else {
3192
0
            filter = L"default::BytesWarning";
3193
0
        }
3194
0
        status = warnoptions_append(config, &options, filter);
3195
0
        if (_PyStatus_EXCEPTION(status)) {
3196
0
            goto error;
3197
0
        }
3198
0
    }
3199
3200
28
    status = warnoptions_extend(config, &options, sys_warnoptions);
3201
28
    if (_PyStatus_EXCEPTION(status)) {
3202
0
        goto error;
3203
0
    }
3204
3205
    /* Always add all PyConfig.warnoptions options */
3206
28
    status = _PyWideStringList_Extend(&options, &config->warnoptions);
3207
28
    if (_PyStatus_EXCEPTION(status)) {
3208
0
        goto error;
3209
0
    }
3210
3211
28
    _PyWideStringList_Clear(&config->warnoptions);
3212
28
    config->warnoptions = options;
3213
28
    return _PyStatus_OK();
3214
3215
0
error:
3216
0
    _PyWideStringList_Clear(&options);
3217
0
    return status;
3218
28
}
3219
3220
3221
static PyStatus
3222
config_update_argv(PyConfig *config, Py_ssize_t opt_index)
3223
0
{
3224
0
    const PyWideStringList *cmdline_argv = &config->argv;
3225
0
    PyWideStringList config_argv = _PyWideStringList_INIT;
3226
3227
    /* Copy argv to be able to modify it (to force -c/-m) */
3228
0
    if (cmdline_argv->length <= opt_index) {
3229
        /* Ensure at least one (empty) argument is seen */
3230
0
        PyStatus status = PyWideStringList_Append(&config_argv, L"");
3231
0
        if (_PyStatus_EXCEPTION(status)) {
3232
0
            return status;
3233
0
        }
3234
0
    }
3235
0
    else {
3236
0
        PyWideStringList slice;
3237
0
        slice.length = cmdline_argv->length - opt_index;
3238
0
        slice.items = &cmdline_argv->items[opt_index];
3239
0
        if (_PyWideStringList_Copy(&config_argv, &slice) < 0) {
3240
0
            return _PyStatus_NO_MEMORY();
3241
0
        }
3242
0
    }
3243
0
    assert(config_argv.length >= 1);
3244
3245
0
    wchar_t *arg0 = NULL;
3246
0
    if (config->run_command != NULL) {
3247
        /* Force sys.argv[0] = '-c' */
3248
0
        arg0 = L"-c";
3249
0
    }
3250
0
    else if (config->run_module != NULL) {
3251
        /* Force sys.argv[0] = '-m'*/
3252
0
        arg0 = L"-m";
3253
0
    }
3254
3255
0
    if (arg0 != NULL) {
3256
0
        arg0 = _PyMem_RawWcsdup(arg0);
3257
0
        if (arg0 == NULL) {
3258
0
            _PyWideStringList_Clear(&config_argv);
3259
0
            return _PyStatus_NO_MEMORY();
3260
0
        }
3261
3262
0
        PyMem_RawFree(config_argv.items[0]);
3263
0
        config_argv.items[0] = arg0;
3264
0
    }
3265
3266
0
    _PyWideStringList_Clear(&config->argv);
3267
0
    config->argv = config_argv;
3268
0
    return _PyStatus_OK();
3269
0
}
3270
3271
3272
static PyStatus
3273
core_read_precmdline(PyConfig *config, _PyPreCmdline *precmdline)
3274
28
{
3275
28
    PyStatus status;
3276
3277
28
    if (config->parse_argv == 1) {
3278
0
        if (_PyWideStringList_Copy(&precmdline->argv, &config->argv) < 0) {
3279
0
            return _PyStatus_NO_MEMORY();
3280
0
        }
3281
0
    }
3282
3283
28
    PyPreConfig preconfig;
3284
3285
28
    status = _PyPreConfig_InitFromPreConfig(&preconfig, &_PyRuntime.preconfig);
3286
28
    if (_PyStatus_EXCEPTION(status)) {
3287
0
        return status;
3288
0
    }
3289
3290
28
    _PyPreConfig_GetConfig(&preconfig, config);
3291
3292
28
    status = _PyPreCmdline_Read(precmdline, &preconfig);
3293
28
    if (_PyStatus_EXCEPTION(status)) {
3294
0
        return status;
3295
0
    }
3296
3297
28
    status = _PyPreCmdline_SetConfig(precmdline, config);
3298
28
    if (_PyStatus_EXCEPTION(status)) {
3299
0
        return status;
3300
0
    }
3301
28
    return _PyStatus_OK();
3302
28
}
3303
3304
3305
/* Get run_filename absolute path */
3306
static PyStatus
3307
config_run_filename_abspath(PyConfig *config)
3308
28
{
3309
28
    if (!config->run_filename) {
3310
28
        return _PyStatus_OK();
3311
28
    }
3312
3313
0
#ifndef MS_WINDOWS
3314
0
    if (_Py_isabs(config->run_filename)) {
3315
        /* path is already absolute */
3316
0
        return _PyStatus_OK();
3317
0
    }
3318
0
#endif
3319
3320
0
    wchar_t *abs_filename;
3321
0
    if (_Py_abspath(config->run_filename, &abs_filename) < 0) {
3322
        /* failed to get the absolute path of the command line filename:
3323
           ignore the error, keep the relative path */
3324
0
        return _PyStatus_OK();
3325
0
    }
3326
0
    if (abs_filename == NULL) {
3327
0
        return _PyStatus_NO_MEMORY();
3328
0
    }
3329
3330
0
    PyMem_RawFree(config->run_filename);
3331
0
    config->run_filename = abs_filename;
3332
0
    return _PyStatus_OK();
3333
0
}
3334
3335
3336
static PyStatus
3337
config_read_cmdline(PyConfig *config)
3338
28
{
3339
28
    PyStatus status;
3340
28
    PyWideStringList cmdline_warnoptions = _PyWideStringList_INIT;
3341
28
    PyWideStringList env_warnoptions = _PyWideStringList_INIT;
3342
28
    PyWideStringList sys_warnoptions = _PyWideStringList_INIT;
3343
3344
28
    if (config->parse_argv < 0) {
3345
0
        config->parse_argv = 1;
3346
0
    }
3347
3348
28
    if (config->parse_argv == 1) {
3349
0
        Py_ssize_t opt_index;
3350
0
        status = config_parse_cmdline(config, &cmdline_warnoptions, &opt_index);
3351
0
        if (_PyStatus_EXCEPTION(status)) {
3352
0
            goto done;
3353
0
        }
3354
3355
0
        status = config_run_filename_abspath(config);
3356
0
        if (_PyStatus_EXCEPTION(status)) {
3357
0
            goto done;
3358
0
        }
3359
3360
0
        status = config_update_argv(config, opt_index);
3361
0
        if (_PyStatus_EXCEPTION(status)) {
3362
0
            goto done;
3363
0
        }
3364
0
    }
3365
28
    else {
3366
28
        status = config_run_filename_abspath(config);
3367
28
        if (_PyStatus_EXCEPTION(status)) {
3368
0
            goto done;
3369
0
        }
3370
28
    }
3371
3372
28
    if (config->use_environment) {
3373
28
        status = config_init_env_warnoptions(config, &env_warnoptions);
3374
28
        if (_PyStatus_EXCEPTION(status)) {
3375
0
            goto done;
3376
0
        }
3377
28
    }
3378
3379
    /* Handle early PySys_AddWarnOption() calls */
3380
28
    status = _PySys_ReadPreinitWarnOptions(&sys_warnoptions);
3381
28
    if (_PyStatus_EXCEPTION(status)) {
3382
0
        goto done;
3383
0
    }
3384
3385
28
    status = config_init_warnoptions(config,
3386
28
                                     &cmdline_warnoptions,
3387
28
                                     &env_warnoptions,
3388
28
                                     &sys_warnoptions);
3389
28
    if (_PyStatus_EXCEPTION(status)) {
3390
0
        goto done;
3391
0
    }
3392
3393
28
    status = _PyStatus_OK();
3394
3395
28
done:
3396
28
    _PyWideStringList_Clear(&cmdline_warnoptions);
3397
28
    _PyWideStringList_Clear(&env_warnoptions);
3398
28
    _PyWideStringList_Clear(&sys_warnoptions);
3399
28
    return status;
3400
28
}
3401
3402
3403
PyStatus
3404
_PyConfig_SetPyArgv(PyConfig *config, const _PyArgv *args)
3405
0
{
3406
0
    PyStatus status = _Py_PreInitializeFromConfig(config, args);
3407
0
    if (_PyStatus_EXCEPTION(status)) {
3408
0
        return status;
3409
0
    }
3410
3411
0
    return _PyArgv_AsWstrList(args, &config->argv);
3412
0
}
3413
3414
3415
/* Set config.argv: decode argv using Py_DecodeLocale(). Pre-initialize Python
3416
   if needed to ensure that encodings are properly configured. */
3417
PyStatus
3418
PyConfig_SetBytesArgv(PyConfig *config, Py_ssize_t argc, char * const *argv)
3419
0
{
3420
0
    _PyArgv args = {
3421
0
        .argc = argc,
3422
0
        .use_bytes_argv = 1,
3423
0
        .bytes_argv = argv,
3424
0
        .wchar_argv = NULL};
3425
0
    return _PyConfig_SetPyArgv(config, &args);
3426
0
}
3427
3428
3429
PyStatus
3430
PyConfig_SetArgv(PyConfig *config, Py_ssize_t argc, wchar_t * const *argv)
3431
0
{
3432
0
    _PyArgv args = {
3433
0
        .argc = argc,
3434
0
        .use_bytes_argv = 0,
3435
0
        .bytes_argv = NULL,
3436
0
        .wchar_argv = argv};
3437
0
    return _PyConfig_SetPyArgv(config, &args);
3438
0
}
3439
3440
3441
PyStatus
3442
PyConfig_SetWideStringList(PyConfig *config, PyWideStringList *list,
3443
                           Py_ssize_t length, wchar_t **items)
3444
0
{
3445
0
    PyStatus status = _Py_PreInitializeFromConfig(config, NULL);
3446
0
    if (_PyStatus_EXCEPTION(status)) {
3447
0
        return status;
3448
0
    }
3449
3450
0
    PyWideStringList list2 = {.length = length, .items = items};
3451
0
    if (_PyWideStringList_Copy(list, &list2) < 0) {
3452
0
        return _PyStatus_NO_MEMORY();
3453
0
    }
3454
0
    return _PyStatus_OK();
3455
0
}
3456
3457
3458
/* Read the configuration into PyConfig from:
3459
3460
   * Command line arguments
3461
   * Environment variables
3462
   * Py_xxx global configuration variables
3463
3464
   The only side effects are to modify config and to call _Py_SetArgcArgv(). */
3465
PyStatus
3466
_PyConfig_Read(PyConfig *config, int compute_path_config)
3467
28
{
3468
28
    PyStatus status;
3469
3470
28
    status = _Py_PreInitializeFromConfig(config, NULL);
3471
28
    if (_PyStatus_EXCEPTION(status)) {
3472
0
        return status;
3473
0
    }
3474
3475
28
    config_get_global_vars(config);
3476
3477
28
    if (config->orig_argv.length == 0
3478
28
        && !(config->argv.length == 1
3479
0
             && wcscmp(config->argv.items[0], L"") == 0))
3480
28
    {
3481
28
        if (_PyWideStringList_Copy(&config->orig_argv, &config->argv) < 0) {
3482
0
            return _PyStatus_NO_MEMORY();
3483
0
        }
3484
28
    }
3485
3486
28
    _PyPreCmdline precmdline = _PyPreCmdline_INIT;
3487
28
    status = core_read_precmdline(config, &precmdline);
3488
28
    if (_PyStatus_EXCEPTION(status)) {
3489
0
        goto done;
3490
0
    }
3491
3492
28
    assert(config->isolated >= 0);
3493
28
    if (config->isolated) {
3494
0
        config->safe_path = 1;
3495
0
        config->use_environment = 0;
3496
0
        config->user_site_directory = 0;
3497
0
    }
3498
3499
28
    status = config_read_cmdline(config);
3500
28
    if (_PyStatus_EXCEPTION(status)) {
3501
0
        goto done;
3502
0
    }
3503
3504
    /* Handle early PySys_AddXOption() calls */
3505
28
    status = _PySys_ReadPreinitXOptions(config);
3506
28
    if (_PyStatus_EXCEPTION(status)) {
3507
0
        goto done;
3508
0
    }
3509
3510
28
    status = config_read(config, compute_path_config);
3511
28
    if (_PyStatus_EXCEPTION(status)) {
3512
0
        goto done;
3513
0
    }
3514
3515
28
    assert(config_check_consistency(config));
3516
3517
28
    status = _PyStatus_OK();
3518
3519
28
done:
3520
28
    _PyPreCmdline_Clear(&precmdline);
3521
28
    return status;
3522
28
}
3523
3524
3525
PyStatus
3526
PyConfig_Read(PyConfig *config)
3527
0
{
3528
0
    return _PyConfig_Read(config, 0);
3529
0
}
3530
3531
3532
PyObject*
3533
_Py_GetConfigsAsDict(void)
3534
0
{
3535
0
    PyObject *result = NULL;
3536
0
    PyObject *dict = NULL;
3537
3538
0
    result = PyDict_New();
3539
0
    if (result == NULL) {
3540
0
        goto error;
3541
0
    }
3542
3543
    /* global result */
3544
0
    dict = _Py_GetGlobalVariablesAsDict();
3545
0
    if (dict == NULL) {
3546
0
        goto error;
3547
0
    }
3548
0
    if (PyDict_SetItemString(result, "global_config", dict) < 0) {
3549
0
        goto error;
3550
0
    }
3551
0
    Py_CLEAR(dict);
3552
3553
    /* pre config */
3554
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
3555
0
    const PyPreConfig *pre_config = &interp->runtime->preconfig;
3556
0
    dict = _PyPreConfig_AsDict(pre_config);
3557
0
    if (dict == NULL) {
3558
0
        goto error;
3559
0
    }
3560
0
    if (PyDict_SetItemString(result, "pre_config", dict) < 0) {
3561
0
        goto error;
3562
0
    }
3563
0
    Py_CLEAR(dict);
3564
3565
    /* core config */
3566
0
    const PyConfig *config = _PyInterpreterState_GetConfig(interp);
3567
0
    dict = _PyConfig_AsDict(config);
3568
0
    if (dict == NULL) {
3569
0
        goto error;
3570
0
    }
3571
0
    if (PyDict_SetItemString(result, "config", dict) < 0) {
3572
0
        goto error;
3573
0
    }
3574
0
    Py_CLEAR(dict);
3575
3576
0
    return result;
3577
3578
0
error:
3579
0
    Py_XDECREF(result);
3580
0
    Py_XDECREF(dict);
3581
0
    return NULL;
3582
0
}
3583
3584
3585
static void
3586
init_dump_ascii_wstr(const wchar_t *str)
3587
0
{
3588
0
    if (str == NULL) {
3589
0
        PySys_WriteStderr("(not set)");
3590
0
        return;
3591
0
    }
3592
3593
0
    PySys_WriteStderr("'");
3594
0
    for (; *str != L'\0'; str++) {
3595
0
        unsigned int ch = (unsigned int)*str;
3596
0
        if (ch == L'\'') {
3597
0
            PySys_WriteStderr("\\'");
3598
0
        } else if (0x20 <= ch && ch < 0x7f) {
3599
0
            PySys_WriteStderr("%c", ch);
3600
0
        }
3601
0
        else if (ch <= 0xff) {
3602
0
            PySys_WriteStderr("\\x%02x", ch);
3603
0
        }
3604
0
#if SIZEOF_WCHAR_T > 2
3605
0
        else if (ch > 0xffff) {
3606
0
            PySys_WriteStderr("\\U%08x", ch);
3607
0
        }
3608
0
#endif
3609
0
        else {
3610
0
            PySys_WriteStderr("\\u%04x", ch);
3611
0
        }
3612
0
    }
3613
0
    PySys_WriteStderr("'");
3614
0
}
3615
3616
3617
/* Dump the Python path configuration into sys.stderr */
3618
void
3619
_Py_DumpPathConfig(PyThreadState *tstate)
3620
0
{
3621
0
    PyObject *exc = _PyErr_GetRaisedException(tstate);
3622
3623
0
    PySys_WriteStderr("Python path configuration:\n");
3624
3625
0
#define DUMP_CONFIG(NAME, FIELD) \
3626
0
        do { \
3627
0
            PySys_WriteStderr("  " NAME " = "); \
3628
0
            init_dump_ascii_wstr(config->FIELD); \
3629
0
            PySys_WriteStderr("\n"); \
3630
0
        } while (0)
3631
3632
0
    const PyConfig *config = _PyInterpreterState_GetConfig(tstate->interp);
3633
0
    DUMP_CONFIG("PYTHONHOME", home);
3634
0
    DUMP_CONFIG("PYTHONPATH", pythonpath_env);
3635
0
    DUMP_CONFIG("program name", program_name);
3636
0
    PySys_WriteStderr("  isolated = %i\n", config->isolated);
3637
0
    PySys_WriteStderr("  environment = %i\n", config->use_environment);
3638
0
    PySys_WriteStderr("  user site = %i\n", config->user_site_directory);
3639
0
    PySys_WriteStderr("  safe_path = %i\n", config->safe_path);
3640
0
    PySys_WriteStderr("  import site = %i\n", config->site_import);
3641
0
    PySys_WriteStderr("  is in build tree = %i\n", config->_is_python_build);
3642
0
    DUMP_CONFIG("stdlib dir", stdlib_dir);
3643
0
    DUMP_CONFIG("sys.path[0]", sys_path_0);
3644
0
#undef DUMP_CONFIG
3645
3646
0
#define DUMP_SYS(NAME) \
3647
0
        do { \
3648
0
            PySys_FormatStderr("  sys.%s = ", #NAME); \
3649
0
            if (PySys_GetOptionalAttrString(#NAME, &obj) < 0) { \
3650
0
                PyErr_Clear(); \
3651
0
            } \
3652
0
            if (obj != NULL) { \
3653
0
                PySys_FormatStderr("%A", obj); \
3654
0
                Py_DECREF(obj); \
3655
0
            } \
3656
0
            else { \
3657
0
                PySys_WriteStderr("(not set)"); \
3658
0
            } \
3659
0
            PySys_FormatStderr("\n"); \
3660
0
        } while (0)
3661
3662
0
    PyObject *obj;
3663
0
    DUMP_SYS(_base_executable);
3664
0
    DUMP_SYS(base_prefix);
3665
0
    DUMP_SYS(base_exec_prefix);
3666
0
    DUMP_SYS(platlibdir);
3667
0
    DUMP_SYS(executable);
3668
0
    DUMP_SYS(prefix);
3669
0
    DUMP_SYS(exec_prefix);
3670
0
#undef DUMP_SYS
3671
3672
0
    PyObject *sys_path;
3673
0
    (void) PySys_GetOptionalAttrString("path", &sys_path);
3674
0
    if (sys_path != NULL && PyList_Check(sys_path)) {
3675
0
        PySys_WriteStderr("  sys.path = [\n");
3676
0
        Py_ssize_t len = PyList_GET_SIZE(sys_path);
3677
0
        for (Py_ssize_t i=0; i < len; i++) {
3678
0
            PyObject *path = PyList_GET_ITEM(sys_path, i);
3679
0
            PySys_FormatStderr("    %A,\n", path);
3680
0
        }
3681
0
        PySys_WriteStderr("  ]\n");
3682
0
    }
3683
0
    Py_XDECREF(sys_path);
3684
3685
0
    _PyErr_SetRaisedException(tstate, exc);
3686
0
}
3687
3688
3689
// --- PyInitConfig API ---------------------------------------------------
3690
3691
struct PyInitConfig {
3692
    PyPreConfig preconfig;
3693
    PyConfig config;
3694
    struct _inittab *inittab;
3695
    Py_ssize_t inittab_size;
3696
    PyStatus status;
3697
    char *err_msg;
3698
};
3699
3700
static PyInitConfig*
3701
initconfig_alloc(void)
3702
0
{
3703
0
    return calloc(1, sizeof(PyInitConfig));
3704
0
}
3705
3706
3707
PyInitConfig*
3708
PyInitConfig_Create(void)
3709
0
{
3710
0
    PyInitConfig *config = initconfig_alloc();
3711
0
    if (config == NULL) {
3712
0
        return NULL;
3713
0
    }
3714
0
    PyPreConfig_InitIsolatedConfig(&config->preconfig);
3715
0
    PyConfig_InitIsolatedConfig(&config->config);
3716
0
    config->status = _PyStatus_OK();
3717
0
    return config;
3718
0
}
3719
3720
3721
void
3722
PyInitConfig_Free(PyInitConfig *config)
3723
0
{
3724
0
    if (config == NULL) {
3725
0
        return;
3726
0
    }
3727
3728
0
    initconfig_free_config(&config->config);
3729
0
    PyMem_RawFree(config->inittab);
3730
0
    free(config->err_msg);
3731
0
    free(config);
3732
0
}
3733
3734
3735
int
3736
PyInitConfig_GetError(PyInitConfig* config, const char **perr_msg)
3737
0
{
3738
0
    if (_PyStatus_IS_EXIT(config->status)) {
3739
0
        char buffer[22];  // len("exit code -2147483648\0")
3740
0
        PyOS_snprintf(buffer, sizeof(buffer),
3741
0
                      "exit code %i",
3742
0
                      config->status.exitcode);
3743
3744
0
        if (config->err_msg != NULL) {
3745
0
            free(config->err_msg);
3746
0
        }
3747
0
        config->err_msg = strdup(buffer);
3748
0
        if (config->err_msg != NULL) {
3749
0
            *perr_msg = config->err_msg;
3750
0
            return 1;
3751
0
        }
3752
0
        config->status = _PyStatus_NO_MEMORY();
3753
0
    }
3754
3755
0
    if (_PyStatus_IS_ERROR(config->status) && config->status.err_msg != NULL) {
3756
0
        *perr_msg = config->status.err_msg;
3757
0
        return 1;
3758
0
    }
3759
0
    else {
3760
0
        *perr_msg = NULL;
3761
0
        return 0;
3762
0
    }
3763
0
}
3764
3765
3766
int
3767
PyInitConfig_GetExitCode(PyInitConfig* config, int *exitcode)
3768
0
{
3769
0
    if (_PyStatus_IS_EXIT(config->status)) {
3770
0
        *exitcode = config->status.exitcode;
3771
0
        return 1;
3772
0
    }
3773
0
    else {
3774
0
        return 0;
3775
0
    }
3776
0
}
3777
3778
3779
static void
3780
initconfig_set_error(PyInitConfig *config, const char *err_msg)
3781
0
{
3782
0
    config->status = _PyStatus_ERR(err_msg);
3783
0
}
3784
3785
3786
static const PyConfigSpec*
3787
initconfig_find_spec(const PyConfigSpec *spec, const char *name)
3788
0
{
3789
0
    for (; spec->name != NULL; spec++) {
3790
0
        if (strcmp(name, spec->name) == 0) {
3791
0
            return spec;
3792
0
        }
3793
0
    }
3794
0
    return NULL;
3795
0
}
3796
3797
3798
int
3799
PyInitConfig_HasOption(PyInitConfig *config, const char *name)
3800
0
{
3801
0
    const PyConfigSpec *spec = initconfig_find_spec(PYCONFIG_SPEC, name);
3802
0
    if (spec == NULL) {
3803
0
        spec = initconfig_find_spec(PYPRECONFIG_SPEC, name);
3804
0
    }
3805
0
    return (spec != NULL);
3806
0
}
3807
3808
3809
static const PyConfigSpec*
3810
initconfig_prepare(PyInitConfig *config, const char *name, void **raw_member)
3811
0
{
3812
0
    const PyConfigSpec *spec = initconfig_find_spec(PYCONFIG_SPEC, name);
3813
0
    if (spec != NULL) {
3814
0
        *raw_member = config_get_spec_member(&config->config, spec);
3815
0
        return spec;
3816
0
    }
3817
3818
0
    spec = initconfig_find_spec(PYPRECONFIG_SPEC, name);
3819
0
    if (spec != NULL) {
3820
0
        *raw_member = preconfig_get_spec_member(&config->preconfig, spec);
3821
0
        return spec;
3822
0
    }
3823
3824
0
    initconfig_set_error(config, "unknown config option name");
3825
0
    return NULL;
3826
0
}
3827
3828
3829
int
3830
PyInitConfig_GetInt(PyInitConfig *config, const char *name, int64_t *value)
3831
0
{
3832
0
    void *raw_member;
3833
0
    const PyConfigSpec *spec = initconfig_prepare(config, name, &raw_member);
3834
0
    if (spec == NULL) {
3835
0
        return -1;
3836
0
    }
3837
3838
0
    switch (spec->type) {
3839
0
    case PyConfig_MEMBER_INT:
3840
0
    case PyConfig_MEMBER_UINT:
3841
0
    case PyConfig_MEMBER_BOOL:
3842
0
    {
3843
0
        int *member = raw_member;
3844
0
        *value = *member;
3845
0
        break;
3846
0
    }
3847
3848
0
    case PyConfig_MEMBER_ULONG:
3849
0
    {
3850
0
        unsigned long *member = raw_member;
3851
0
#if SIZEOF_LONG >= 8
3852
0
        if ((unsigned long)INT64_MAX < *member) {
3853
0
            initconfig_set_error(config,
3854
0
                "config option value doesn't fit into int64_t");
3855
0
            return -1;
3856
0
        }
3857
0
#endif
3858
0
        *value = *member;
3859
0
        break;
3860
0
    }
3861
3862
0
    default:
3863
0
        initconfig_set_error(config, "config option type is not int");
3864
0
        return -1;
3865
0
    }
3866
0
    return 0;
3867
0
}
3868
3869
3870
static char*
3871
wstr_to_utf8(PyInitConfig *config, wchar_t *wstr)
3872
0
{
3873
0
    char *utf8;
3874
0
    int res = _Py_EncodeUTF8Ex(wstr, &utf8, NULL, NULL, 1, _Py_ERROR_STRICT);
3875
0
    if (res == -2) {
3876
0
        initconfig_set_error(config, "encoding error");
3877
0
        return NULL;
3878
0
    }
3879
0
    if (res < 0) {
3880
0
        config->status = _PyStatus_NO_MEMORY();
3881
0
        return NULL;
3882
0
    }
3883
3884
    // Copy to use the malloc() memory allocator
3885
0
    size_t size = strlen(utf8) + 1;
3886
0
    char *str = malloc(size);
3887
0
    if (str == NULL) {
3888
0
        PyMem_RawFree(utf8);
3889
0
        config->status = _PyStatus_NO_MEMORY();
3890
0
        return NULL;
3891
0
    }
3892
3893
0
    memcpy(str, utf8, size);
3894
0
    PyMem_RawFree(utf8);
3895
0
    return str;
3896
0
}
3897
3898
3899
int
3900
PyInitConfig_GetStr(PyInitConfig *config, const char *name, char **value)
3901
0
{
3902
0
    void *raw_member;
3903
0
    const PyConfigSpec *spec = initconfig_prepare(config, name, &raw_member);
3904
0
    if (spec == NULL) {
3905
0
        return -1;
3906
0
    }
3907
3908
0
    if (spec->type != PyConfig_MEMBER_WSTR
3909
0
        && spec->type != PyConfig_MEMBER_WSTR_OPT)
3910
0
    {
3911
0
        initconfig_set_error(config, "config option type is not string");
3912
0
        return -1;
3913
0
    }
3914
3915
0
    wchar_t **member = raw_member;
3916
0
    if (*member == NULL) {
3917
0
        *value = NULL;
3918
0
        return 0;
3919
0
    }
3920
3921
0
    *value = wstr_to_utf8(config, *member);
3922
0
    if (*value == NULL) {
3923
0
        return -1;
3924
0
    }
3925
0
    return 0;
3926
0
}
3927
3928
3929
int
3930
PyInitConfig_GetStrList(PyInitConfig *config, const char *name, size_t *length, char ***items)
3931
0
{
3932
0
    void *raw_member;
3933
0
    const PyConfigSpec *spec = initconfig_prepare(config, name, &raw_member);
3934
0
    if (spec == NULL) {
3935
0
        return -1;
3936
0
    }
3937
3938
0
    if (spec->type != PyConfig_MEMBER_WSTR_LIST) {
3939
0
        initconfig_set_error(config, "config option type is not string list");
3940
0
        return -1;
3941
0
    }
3942
3943
0
    PyWideStringList *list = raw_member;
3944
0
    *length = list->length;
3945
3946
0
    *items = malloc(list->length * sizeof(char*));
3947
0
    if (*items == NULL) {
3948
0
        config->status = _PyStatus_NO_MEMORY();
3949
0
        return -1;
3950
0
    }
3951
3952
0
    for (Py_ssize_t i=0; i < list->length; i++) {
3953
0
        (*items)[i] = wstr_to_utf8(config, list->items[i]);
3954
0
        if ((*items)[i] == NULL) {
3955
0
            PyInitConfig_FreeStrList(i, *items);
3956
0
            return -1;
3957
0
        }
3958
0
    }
3959
0
    return 0;
3960
0
}
3961
3962
3963
void
3964
PyInitConfig_FreeStrList(size_t length, char **items)
3965
0
{
3966
0
    for (size_t i=0; i < length; i++) {
3967
0
        free(items[i]);
3968
0
    }
3969
0
    free(items);
3970
0
}
3971
3972
3973
int
3974
PyInitConfig_SetInt(PyInitConfig *config, const char *name, int64_t value)
3975
0
{
3976
0
    void *raw_member;
3977
0
    const PyConfigSpec *spec = initconfig_prepare(config, name, &raw_member);
3978
0
    if (spec == NULL) {
3979
0
        return -1;
3980
0
    }
3981
3982
0
    switch (spec->type) {
3983
0
    case PyConfig_MEMBER_INT:
3984
0
    {
3985
0
        if (value < (int64_t)INT_MIN || (int64_t)INT_MAX < value) {
3986
0
            initconfig_set_error(config,
3987
0
                "config option value is out of int range");
3988
0
            return -1;
3989
0
        }
3990
0
        int int_value = (int)value;
3991
3992
0
        int *member = raw_member;
3993
0
        *member = int_value;
3994
0
        break;
3995
0
    }
3996
3997
0
    case PyConfig_MEMBER_UINT:
3998
0
    case PyConfig_MEMBER_BOOL:
3999
0
    {
4000
0
        if (value < 0 || (uint64_t)UINT_MAX < (uint64_t)value) {
4001
0
            initconfig_set_error(config,
4002
0
                "config option value is out of unsigned int range");
4003
0
            return -1;
4004
0
        }
4005
0
        int int_value = (int)value;
4006
4007
0
        int *member = raw_member;
4008
0
        *member = int_value;
4009
0
        break;
4010
0
    }
4011
4012
0
    case PyConfig_MEMBER_ULONG:
4013
0
    {
4014
0
        if (value < 0 || (uint64_t)ULONG_MAX < (uint64_t)value) {
4015
0
            initconfig_set_error(config,
4016
0
                "config option value is out of unsigned long range");
4017
0
            return -1;
4018
0
        }
4019
0
        unsigned long ulong_value = (unsigned long)value;
4020
4021
0
        unsigned long *member = raw_member;
4022
0
        *member = ulong_value;
4023
0
        break;
4024
0
    }
4025
4026
0
    default:
4027
0
        initconfig_set_error(config, "config option type is not int");
4028
0
        return -1;
4029
0
    }
4030
4031
0
    if (strcmp(name, "hash_seed") == 0) {
4032
0
        config->config.use_hash_seed = 1;
4033
0
    }
4034
4035
0
    return 0;
4036
0
}
4037
4038
4039
static wchar_t*
4040
utf8_to_wstr(PyInitConfig *config, const char *str)
4041
0
{
4042
0
    wchar_t *wstr;
4043
0
    size_t wlen;
4044
0
    int res = _Py_DecodeUTF8Ex(str, strlen(str), &wstr, &wlen, NULL, _Py_ERROR_STRICT);
4045
0
    if (res == -2) {
4046
0
        initconfig_set_error(config, "decoding error");
4047
0
        return NULL;
4048
0
    }
4049
0
    if (res < 0) {
4050
0
        config->status = _PyStatus_NO_MEMORY();
4051
0
        return NULL;
4052
0
    }
4053
4054
    // Copy to use the malloc() memory allocator
4055
0
    size_t size = (wlen + 1) * sizeof(wchar_t);
4056
0
    wchar_t *wstr2 = malloc(size);
4057
0
    if (wstr2 == NULL) {
4058
0
        PyMem_RawFree(wstr);
4059
0
        config->status = _PyStatus_NO_MEMORY();
4060
0
        return NULL;
4061
0
    }
4062
4063
0
    memcpy(wstr2, wstr, size);
4064
0
    PyMem_RawFree(wstr);
4065
0
    return wstr2;
4066
0
}
4067
4068
4069
int
4070
PyInitConfig_SetStr(PyInitConfig *config, const char *name, const char* value)
4071
0
{
4072
0
    void *raw_member;
4073
0
    const PyConfigSpec *spec = initconfig_prepare(config, name, &raw_member);
4074
0
    if (spec == NULL) {
4075
0
        return -1;
4076
0
    }
4077
4078
0
    if (spec->type != PyConfig_MEMBER_WSTR
4079
0
            && spec->type != PyConfig_MEMBER_WSTR_OPT) {
4080
0
        initconfig_set_error(config, "config option type is not string");
4081
0
        return -1;
4082
0
    }
4083
4084
0
    if (value == NULL && spec->type != PyConfig_MEMBER_WSTR_OPT) {
4085
0
        initconfig_set_error(config, "config option string cannot be NULL");
4086
0
    }
4087
4088
0
    wchar_t **member = raw_member;
4089
4090
0
    *member = utf8_to_wstr(config, value);
4091
0
    if (*member == NULL) {
4092
0
        return -1;
4093
0
    }
4094
0
    return 0;
4095
0
}
4096
4097
4098
static void
4099
initconfig_free_wstr(wchar_t *member)
4100
0
{
4101
0
    if (member) {
4102
0
        free(member);
4103
0
    }
4104
0
}
4105
4106
4107
static void
4108
initconfig_free_wstr_list(PyWideStringList *list)
4109
0
{
4110
0
    for (Py_ssize_t i = 0; i < list->length; i++) {
4111
0
        free(list->items[i]);
4112
0
    }
4113
0
    free(list->items);
4114
0
}
4115
4116
4117
static void
4118
initconfig_free_config(const PyConfig *config)
4119
0
{
4120
0
    const PyConfigSpec *spec = PYCONFIG_SPEC;
4121
0
    for (; spec->name != NULL; spec++) {
4122
0
        void *member = config_get_spec_member(config, spec);
4123
0
        if (spec->type == PyConfig_MEMBER_WSTR
4124
0
            || spec->type == PyConfig_MEMBER_WSTR_OPT)
4125
0
        {
4126
0
            wchar_t *wstr = *(wchar_t **)member;
4127
0
            initconfig_free_wstr(wstr);
4128
0
        }
4129
0
        else if (spec->type == PyConfig_MEMBER_WSTR_LIST) {
4130
0
            initconfig_free_wstr_list(member);
4131
0
        }
4132
0
    }
4133
0
}
4134
4135
4136
static int
4137
initconfig_set_str_list(PyInitConfig *config, PyWideStringList *list,
4138
                        Py_ssize_t length, char * const *items)
4139
0
{
4140
0
    PyWideStringList wlist = _PyWideStringList_INIT;
4141
0
    size_t size = sizeof(wchar_t*) * length;
4142
0
    wlist.items = (wchar_t **)malloc(size);
4143
0
    if (wlist.items == NULL) {
4144
0
        config->status = _PyStatus_NO_MEMORY();
4145
0
        return -1;
4146
0
    }
4147
4148
0
    for (Py_ssize_t i = 0; i < length; i++) {
4149
0
        wchar_t *arg = utf8_to_wstr(config, items[i]);
4150
0
        if (arg == NULL) {
4151
0
            initconfig_free_wstr_list(&wlist);
4152
0
            return -1;
4153
0
        }
4154
0
        wlist.items[i] = arg;
4155
0
        wlist.length++;
4156
0
    }
4157
4158
0
    initconfig_free_wstr_list(list);
4159
0
    *list = wlist;
4160
0
    return 0;
4161
0
}
4162
4163
4164
int
4165
PyInitConfig_SetStrList(PyInitConfig *config, const char *name,
4166
                        size_t length, char * const *items)
4167
0
{
4168
0
    void *raw_member;
4169
0
    const PyConfigSpec *spec = initconfig_prepare(config, name, &raw_member);
4170
0
    if (spec == NULL) {
4171
0
        return -1;
4172
0
    }
4173
4174
0
    if (spec->type != PyConfig_MEMBER_WSTR_LIST) {
4175
0
        initconfig_set_error(config, "config option type is not strings list");
4176
0
        return -1;
4177
0
    }
4178
0
    PyWideStringList *list = raw_member;
4179
0
    if (initconfig_set_str_list(config, list, length, items) < 0) {
4180
0
        return -1;
4181
0
    }
4182
4183
0
    if (strcmp(name, "module_search_paths") == 0) {
4184
0
        config->config.module_search_paths_set = 1;
4185
0
    }
4186
0
    return 0;
4187
0
}
4188
4189
4190
int
4191
PyInitConfig_AddModule(PyInitConfig *config, const char *name,
4192
                       PyObject* (*initfunc)(void))
4193
0
{
4194
0
    size_t size = sizeof(struct _inittab) * (config->inittab_size + 2);
4195
0
    struct _inittab *new_inittab = PyMem_RawRealloc(config->inittab, size);
4196
0
    if (new_inittab == NULL) {
4197
0
        config->status = _PyStatus_NO_MEMORY();
4198
0
        return -1;
4199
0
    }
4200
0
    config->inittab = new_inittab;
4201
4202
0
    struct _inittab *entry = &config->inittab[config->inittab_size];
4203
0
    entry->name = name;
4204
0
    entry->initfunc = initfunc;
4205
4206
    // Terminator entry
4207
0
    entry = &config->inittab[config->inittab_size + 1];
4208
0
    entry->name = NULL;
4209
0
    entry->initfunc = NULL;
4210
4211
0
    config->inittab_size++;
4212
0
    return 0;
4213
0
}
4214
4215
4216
int
4217
Py_InitializeFromInitConfig(PyInitConfig *config)
4218
0
{
4219
0
    if (config->inittab_size >= 1) {
4220
0
        if (PyImport_ExtendInittab(config->inittab) < 0) {
4221
0
            config->status = _PyStatus_NO_MEMORY();
4222
0
            return -1;
4223
0
        }
4224
0
    }
4225
4226
0
    _PyPreConfig_GetConfig(&config->preconfig, &config->config);
4227
4228
0
    config->status = Py_PreInitializeFromArgs(
4229
0
        &config->preconfig,
4230
0
        config->config.argv.length,
4231
0
        config->config.argv.items);
4232
0
    if (_PyStatus_EXCEPTION(config->status)) {
4233
0
        return -1;
4234
0
    }
4235
4236
0
    config->status = Py_InitializeFromConfig(&config->config);
4237
0
    if (_PyStatus_EXCEPTION(config->status)) {
4238
0
        return -1;
4239
0
    }
4240
4241
0
    return 0;
4242
0
}
4243
4244
4245
// --- PyConfig_Get() -------------------------------------------------------
4246
4247
static const PyConfigSpec*
4248
config_generic_find_spec(const PyConfigSpec *spec, const char *name)
4249
0
{
4250
0
    for (; spec->name != NULL; spec++) {
4251
0
        if (spec->visibility == PyConfig_MEMBER_INIT_ONLY) {
4252
0
            continue;
4253
0
        }
4254
0
        if (strcmp(name, spec->name) == 0) {
4255
0
            return spec;
4256
0
        }
4257
0
    }
4258
0
    return NULL;
4259
0
}
4260
4261
4262
static const PyConfigSpec*
4263
config_find_spec(const char *name)
4264
0
{
4265
0
    return config_generic_find_spec(PYCONFIG_SPEC, name);
4266
0
}
4267
4268
4269
static const PyConfigSpec*
4270
preconfig_find_spec(const char *name)
4271
0
{
4272
0
    return config_generic_find_spec(PYPRECONFIG_SPEC, name);
4273
0
}
4274
4275
4276
static int
4277
config_add_xoption(PyObject *dict, const wchar_t *str)
4278
0
{
4279
0
    PyObject *name = NULL, *value = NULL;
4280
4281
0
    const wchar_t *name_end = wcschr(str, L'=');
4282
0
    if (!name_end) {
4283
0
        name = PyUnicode_FromWideChar(str, -1);
4284
0
        if (name == NULL) {
4285
0
            goto error;
4286
0
        }
4287
0
        value = Py_NewRef(Py_True);
4288
0
    }
4289
0
    else {
4290
0
        name = PyUnicode_FromWideChar(str, name_end - str);
4291
0
        if (name == NULL) {
4292
0
            goto error;
4293
0
        }
4294
0
        value = PyUnicode_FromWideChar(name_end + 1, -1);
4295
0
        if (value == NULL) {
4296
0
            goto error;
4297
0
        }
4298
0
    }
4299
0
    if (PyDict_SetItem(dict, name, value) < 0) {
4300
0
        goto error;
4301
0
    }
4302
0
    Py_DECREF(name);
4303
0
    Py_DECREF(value);
4304
0
    return 0;
4305
4306
0
error:
4307
0
    Py_XDECREF(name);
4308
0
    Py_XDECREF(value);
4309
0
    return -1;
4310
0
}
4311
4312
4313
PyObject*
4314
_PyConfig_CreateXOptionsDict(const PyConfig *config)
4315
56
{
4316
56
    PyObject *dict = PyDict_New();
4317
56
    if (dict == NULL) {
4318
0
        return NULL;
4319
0
    }
4320
4321
56
    Py_ssize_t nxoption = config->xoptions.length;
4322
56
    wchar_t **xoptions = config->xoptions.items;
4323
56
    for (Py_ssize_t i=0; i < nxoption; i++) {
4324
0
        const wchar_t *option = xoptions[i];
4325
0
        if (config_add_xoption(dict, option) < 0) {
4326
0
            Py_DECREF(dict);
4327
0
            return NULL;
4328
0
        }
4329
0
    }
4330
56
    return dict;
4331
56
}
4332
4333
4334
static int
4335
config_get_sys_write_bytecode(const PyConfig *config, int *value)
4336
0
{
4337
0
    PyObject *attr = PySys_GetAttrString("dont_write_bytecode");
4338
0
    if (attr == NULL) {
4339
0
        return -1;
4340
0
    }
4341
4342
0
    int is_true = PyObject_IsTrue(attr);
4343
0
    Py_DECREF(attr);
4344
0
    if (is_true < 0) {
4345
0
        return -1;
4346
0
    }
4347
0
    *value = (!is_true);
4348
0
    return 0;
4349
0
}
4350
4351
4352
static PyObject*
4353
config_get(const PyConfig *config, const PyConfigSpec *spec,
4354
           int use_sys)
4355
1.93k
{
4356
1.93k
    if (use_sys) {
4357
0
        if (spec->sys.attr != NULL) {
4358
0
            return PySys_GetAttrString(spec->sys.attr);
4359
0
        }
4360
4361
0
        if (strcmp(spec->name, "write_bytecode") == 0) {
4362
0
            int value;
4363
0
            if (config_get_sys_write_bytecode(config, &value) < 0) {
4364
0
                return NULL;
4365
0
            }
4366
0
            return PyBool_FromLong(value);
4367
0
        }
4368
4369
0
        if (strcmp(spec->name, "int_max_str_digits") == 0) {
4370
0
            PyInterpreterState *interp = _PyInterpreterState_GET();
4371
0
            return PyLong_FromLong(interp->long_state.max_str_digits);
4372
0
        }
4373
0
    }
4374
4375
1.93k
    void *member = config_get_spec_member(config, spec);
4376
1.93k
    switch (spec->type) {
4377
84
    case PyConfig_MEMBER_INT:
4378
308
    case PyConfig_MEMBER_UINT:
4379
308
    {
4380
308
        int value = *(int *)member;
4381
308
        return PyLong_FromLong(value);
4382
84
    }
4383
4384
840
    case PyConfig_MEMBER_BOOL:
4385
840
    {
4386
840
        int value = *(int *)member;
4387
840
        return PyBool_FromLong(value != 0);
4388
84
    }
4389
4390
28
    case PyConfig_MEMBER_ULONG:
4391
28
    {
4392
28
        unsigned long value = *(unsigned long *)member;
4393
28
        return PyLong_FromUnsignedLong(value);
4394
84
    }
4395
4396
196
    case PyConfig_MEMBER_WSTR:
4397
616
    case PyConfig_MEMBER_WSTR_OPT:
4398
616
    {
4399
616
        wchar_t *wstr = *(wchar_t **)member;
4400
616
        if (wstr != NULL) {
4401
140
            return PyUnicode_FromWideChar(wstr, -1);
4402
140
        }
4403
476
        else {
4404
476
            return Py_NewRef(Py_None);
4405
476
        }
4406
616
    }
4407
4408
140
    case PyConfig_MEMBER_WSTR_LIST:
4409
140
    {
4410
140
        if (strcmp(spec->name, "xoptions") == 0) {
4411
28
            return _PyConfig_CreateXOptionsDict(config);
4412
28
        }
4413
112
        else {
4414
112
            const PyWideStringList *list = (const PyWideStringList *)member;
4415
112
            return _PyWideStringList_AsTuple(list);
4416
112
        }
4417
140
    }
4418
4419
0
    default:
4420
0
        Py_UNREACHABLE();
4421
1.93k
    }
4422
1.93k
}
4423
4424
4425
static PyObject*
4426
preconfig_get(const PyPreConfig *preconfig, const PyConfigSpec *spec)
4427
0
{
4428
    // The type of all PYPRECONFIG_SPEC members is INT or BOOL.
4429
0
    assert(spec->type == PyConfig_MEMBER_INT
4430
0
           || spec->type == PyConfig_MEMBER_BOOL);
4431
4432
0
    char *member = (char *)preconfig + spec->offset;
4433
0
    int value = *(int *)member;
4434
4435
0
    if (spec->type == PyConfig_MEMBER_BOOL) {
4436
0
        return PyBool_FromLong(value != 0);
4437
0
    }
4438
0
    else {
4439
0
        return PyLong_FromLong(value);
4440
0
    }
4441
0
}
4442
4443
4444
static void
4445
config_unknown_name_error(const char *name)
4446
0
{
4447
0
    PyErr_Format(PyExc_ValueError, "unknown config option name: %s", name);
4448
0
}
4449
4450
4451
PyObject*
4452
PyConfig_Get(const char *name)
4453
0
{
4454
0
    const PyConfigSpec *spec = config_find_spec(name);
4455
0
    if (spec != NULL) {
4456
0
        const PyConfig *config = _Py_GetConfig();
4457
0
        return config_get(config, spec, 1);
4458
0
    }
4459
4460
0
    spec = preconfig_find_spec(name);
4461
0
    if (spec != NULL) {
4462
0
        const PyPreConfig *preconfig = &_PyRuntime.preconfig;
4463
0
        return preconfig_get(preconfig, spec);
4464
0
    }
4465
4466
0
    config_unknown_name_error(name);
4467
0
    return NULL;
4468
0
}
4469
4470
4471
int
4472
PyConfig_GetInt(const char *name, int *value)
4473
0
{
4474
0
    assert(!PyErr_Occurred());
4475
4476
0
    PyObject *obj = PyConfig_Get(name);
4477
0
    if (obj == NULL) {
4478
0
        return -1;
4479
0
    }
4480
4481
0
    if (!PyLong_Check(obj)) {
4482
0
        Py_DECREF(obj);
4483
0
        PyErr_Format(PyExc_TypeError, "config option %s is not an int", name);
4484
0
        return -1;
4485
0
    }
4486
4487
0
    int as_int = PyLong_AsInt(obj);
4488
0
    Py_DECREF(obj);
4489
0
    if (as_int == -1 && PyErr_Occurred()) {
4490
0
        PyErr_Format(PyExc_OverflowError,
4491
0
                     "config option %s value does not fit into a C int", name);
4492
0
        return -1;
4493
0
    }
4494
4495
0
    *value = as_int;
4496
0
    return 0;
4497
0
}
4498
4499
4500
static int
4501
config_names_add(PyObject *names, const PyConfigSpec *spec)
4502
0
{
4503
0
    for (; spec->name != NULL; spec++) {
4504
0
        if (spec->visibility == PyConfig_MEMBER_INIT_ONLY) {
4505
0
            continue;
4506
0
        }
4507
0
        PyObject *name = PyUnicode_FromString(spec->name);
4508
0
        if (name == NULL) {
4509
0
            return -1;
4510
0
        }
4511
0
        int res = PyList_Append(names, name);
4512
0
        Py_DECREF(name);
4513
0
        if (res < 0) {
4514
0
            return -1;
4515
0
        }
4516
0
    }
4517
0
    return 0;
4518
0
}
4519
4520
4521
PyObject*
4522
PyConfig_Names(void)
4523
0
{
4524
0
    PyObject *names = PyList_New(0);
4525
0
    if (names == NULL) {
4526
0
        goto error;
4527
0
    }
4528
4529
0
    if (config_names_add(names, PYCONFIG_SPEC) < 0) {
4530
0
        goto error;
4531
0
    }
4532
0
    if (config_names_add(names, PYPRECONFIG_SPEC) < 0) {
4533
0
        goto error;
4534
0
    }
4535
4536
0
    PyObject *frozen = PyFrozenSet_New(names);
4537
0
    Py_DECREF(names);
4538
0
    return frozen;
4539
4540
0
error:
4541
0
    Py_XDECREF(names);
4542
0
    return NULL;
4543
0
}
4544
4545
4546
// --- PyConfig_Set() -------------------------------------------------------
4547
4548
static int
4549
config_set_sys_flag(const PyConfigSpec *spec, int int_value)
4550
0
{
4551
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
4552
0
    PyConfig *config = &interp->config;
4553
4554
0
    if (spec->type == PyConfig_MEMBER_BOOL) {
4555
0
        if (int_value != 0) {
4556
            // convert values < 0 and values > 1 to 1
4557
0
            int_value = 1;
4558
0
        }
4559
0
    }
4560
4561
0
    PyObject *value;
4562
0
    if (spec->sys.flag_setter) {
4563
0
        value = spec->sys.flag_setter(int_value);
4564
0
    }
4565
0
    else {
4566
0
        value = config_sys_flag_long(int_value);
4567
0
    }
4568
0
    if (value == NULL) {
4569
0
        return -1;
4570
0
    }
4571
4572
    // Set sys.flags.FLAG
4573
0
    Py_ssize_t pos = spec->sys.flag_index;
4574
0
    if (_PySys_SetFlagObj(pos, value) < 0) {
4575
0
        goto error;
4576
0
    }
4577
4578
    // Set PyConfig.ATTR
4579
0
    assert(spec->type == PyConfig_MEMBER_INT
4580
0
           || spec->type == PyConfig_MEMBER_UINT
4581
0
           || spec->type == PyConfig_MEMBER_BOOL);
4582
0
    int *member = config_get_spec_member(config, spec);
4583
0
    *member = int_value;
4584
4585
    // Set sys.dont_write_bytecode attribute
4586
0
    if (strcmp(spec->name, "write_bytecode") == 0) {
4587
0
        if (PySys_SetObject("dont_write_bytecode", value) < 0) {
4588
0
            goto error;
4589
0
        }
4590
0
    }
4591
4592
0
    Py_DECREF(value);
4593
0
    return 0;
4594
4595
0
error:
4596
0
    Py_DECREF(value);
4597
0
    return -1;
4598
0
}
4599
4600
4601
// Set PyConfig.ATTR integer member
4602
static int
4603
config_set_int_attr(const PyConfigSpec *spec, int value)
4604
0
{
4605
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
4606
0
    PyConfig *config = &interp->config;
4607
0
    int *member = config_get_spec_member(config, spec);
4608
0
    *member = value;
4609
0
    return 0;
4610
0
}
4611
4612
4613
int
4614
PyConfig_Set(const char *name, PyObject *value)
4615
0
{
4616
0
    if (PySys_Audit("cpython.PyConfig_Set", "sO", name, value) < 0) {
4617
0
        return -1;
4618
0
    }
4619
4620
0
    const PyConfigSpec *spec = config_find_spec(name);
4621
0
    if (spec == NULL) {
4622
0
        spec = preconfig_find_spec(name);
4623
0
        if (spec == NULL) {
4624
0
            config_unknown_name_error(name);
4625
0
            return -1;
4626
0
        }
4627
0
        assert(spec->visibility != PyConfig_MEMBER_PUBLIC);
4628
0
    }
4629
4630
0
    if (spec->visibility != PyConfig_MEMBER_PUBLIC) {
4631
0
        PyErr_Format(PyExc_ValueError, "cannot set read-only option %s",
4632
0
                     name);
4633
0
        return -1;
4634
0
    }
4635
4636
0
    int int_value = 0;
4637
0
    int has_int_value = 0;
4638
4639
0
    switch (spec->type) {
4640
0
    case PyConfig_MEMBER_INT:
4641
0
    case PyConfig_MEMBER_UINT:
4642
0
    case PyConfig_MEMBER_BOOL:
4643
0
        if (!PyLong_Check(value)) {
4644
0
            PyErr_Format(PyExc_TypeError, "expected int or bool, got %T", value);
4645
0
            return -1;
4646
0
        }
4647
0
        int_value = PyLong_AsInt(value);
4648
0
        if (int_value == -1 && PyErr_Occurred()) {
4649
0
            return -1;
4650
0
        }
4651
0
        if (int_value < 0 && spec->type != PyConfig_MEMBER_INT) {
4652
0
            PyErr_Format(PyExc_ValueError, "value must be >= 0");
4653
0
            return -1;
4654
0
        }
4655
0
        has_int_value = 1;
4656
0
        break;
4657
4658
0
    case PyConfig_MEMBER_ULONG:
4659
        // not implemented: only hash_seed uses this type, and it's read-only
4660
0
        goto cannot_set;
4661
4662
0
    case PyConfig_MEMBER_WSTR:
4663
0
        if (!PyUnicode_CheckExact(value)) {
4664
0
            PyErr_Format(PyExc_TypeError, "expected str, got %T", value);
4665
0
            return -1;
4666
0
        }
4667
0
        break;
4668
4669
0
    case PyConfig_MEMBER_WSTR_OPT:
4670
0
        if (value != Py_None && !PyUnicode_CheckExact(value)) {
4671
0
            PyErr_Format(PyExc_TypeError, "expected str or None, got %T", value);
4672
0
            return -1;
4673
0
        }
4674
0
        break;
4675
4676
0
    case PyConfig_MEMBER_WSTR_LIST:
4677
0
        if (strcmp(spec->name, "xoptions") != 0) {
4678
0
            if (!PyList_Check(value)) {
4679
0
                PyErr_Format(PyExc_TypeError, "expected list[str], got %T",
4680
0
                             value);
4681
0
                return -1;
4682
0
            }
4683
0
            for (Py_ssize_t i=0; i < PyList_GET_SIZE(value); i++) {
4684
0
                PyObject *item = PyList_GET_ITEM(value, i);
4685
0
                if (!PyUnicode_Check(item)) {
4686
0
                    PyErr_Format(PyExc_TypeError,
4687
0
                                 "expected str, list item %zd has type %T",
4688
0
                                 i, item);
4689
0
                    return -1;
4690
0
                }
4691
0
            }
4692
0
        }
4693
0
        else {
4694
            // xoptions type is dict[str, str]
4695
0
            if (!PyDict_Check(value)) {
4696
0
                PyErr_Format(PyExc_TypeError,
4697
0
                             "expected dict[str, str | bool], got %T",
4698
0
                             value);
4699
0
                return -1;
4700
0
            }
4701
4702
0
            Py_ssize_t pos = 0;
4703
0
            PyObject *key, *item;
4704
0
            while (PyDict_Next(value, &pos, &key, &item)) {
4705
0
                if (!PyUnicode_Check(key)) {
4706
0
                    PyErr_Format(PyExc_TypeError,
4707
0
                                 "expected str, "
4708
0
                                 "got dict key type %T", key);
4709
0
                    return -1;
4710
0
                }
4711
0
                if (!PyUnicode_Check(item) && !PyBool_Check(item)) {
4712
0
                    PyErr_Format(PyExc_TypeError,
4713
0
                                 "expected str or bool, "
4714
0
                                 "got dict value type %T", key);
4715
0
                    return -1;
4716
0
                }
4717
0
            }
4718
0
        }
4719
0
        break;
4720
4721
0
    default:
4722
0
        Py_UNREACHABLE();
4723
0
    }
4724
4725
0
    if (spec->sys.attr != NULL) {
4726
        // Set the sys attribute, but don't set PyInterpreterState.config
4727
        // to keep the code simple.
4728
0
        return PySys_SetObject(spec->sys.attr, value);
4729
0
    }
4730
0
    else if (has_int_value) {
4731
0
        if (spec->sys.flag_index >= 0) {
4732
0
            return config_set_sys_flag(spec, int_value);
4733
0
        }
4734
0
        else if (strcmp(spec->name, "int_max_str_digits") == 0) {
4735
0
            return _PySys_SetIntMaxStrDigits(int_value);
4736
0
        }
4737
0
        else {
4738
0
            return config_set_int_attr(spec, int_value);
4739
0
        }
4740
0
    }
4741
4742
0
cannot_set:
4743
0
    PyErr_Format(PyExc_ValueError, "cannot set option %s", name);
4744
0
    return -1;
4745
0
}