blob: 12b1bd7711d5b807c73036881e2fbfa01cd62d2c [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* System module */
3
4/*
5Various bits of information used by the interpreter are collected in
6module 'sys'.
Guido van Rossum3f5da241990-12-20 15:06:42 +00007Function member:
Guido van Rossumcc8914f1995-03-20 15:09:40 +00008- exit(sts): raise SystemExit
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00009Data members:
10- stdin, stdout, stderr: standard file objects
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000011- modules: the table of modules (dictionary)
Guido van Rossum3f5da241990-12-20 15:06:42 +000012- path: module search path (list of strings)
13- argv: script arguments (list of strings)
14- ps1, ps2: optional primary and secondary prompts (strings)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000015*/
16
Guido van Rossum65bf9f21997-04-29 18:33:38 +000017#include "Python.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000018#include "code.h"
Barry Warsawb6a54d22000-12-06 21:47:46 +000019#include "frameobject.h"
Victor Stinner331a6a52019-05-27 16:39:22 +020020#include "pycore_initconfig.h"
Victor Stinner621cebe2018-11-12 16:53:38 +010021#include "pycore_pylifecycle.h"
22#include "pycore_pymem.h"
Victor Stinnera1c249c2018-11-01 03:15:58 +010023#include "pycore_pathconfig.h"
Victor Stinner621cebe2018-11-12 16:53:38 +010024#include "pycore_pystate.h"
Steve Dowerb82e17e2019-05-23 08:45:22 -070025#include "pycore_tupleobject.h"
Victor Stinnerd5c355c2011-04-30 14:53:09 +020026#include "pythread.h"
Steve Dowerb82e17e2019-05-23 08:45:22 -070027#include "pydtrace.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000028
Guido van Rossume2437a11992-03-23 18:20:18 +000029#include "osdefs.h"
Stefan Krah1845d142016-04-25 21:38:53 +020030#include <locale.h>
Guido van Rossum3f5da241990-12-20 15:06:42 +000031
Mark Hammond8696ebc2002-10-08 02:44:31 +000032#ifdef MS_WINDOWS
33#define WIN32_LEAN_AND_MEAN
Amaury Forgeot d'Arc06cfe952007-11-10 13:55:44 +000034#include <windows.h>
Mark Hammond8696ebc2002-10-08 02:44:31 +000035#endif /* MS_WINDOWS */
36
Guido van Rossum9b38a141996-09-11 23:12:24 +000037#ifdef MS_COREDLL
Guido van Rossumc606fe11996-04-09 02:37:57 +000038extern void *PyWin_DLLhModule;
Guido van Rossum6c1e5f21997-09-29 23:34:23 +000039/* A string loaded from the DLL at startup: */
40extern const char *PyWin_DLLVersionString;
Guido van Rossumc606fe11996-04-09 02:37:57 +000041#endif
42
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -080043/*[clinic input]
44module sys
45[clinic start generated code]*/
46/*[clinic end generated code: output=da39a3ee5e6b4b0d input=3726b388feee8cea]*/
47
48#include "clinic/sysmodule.c.h"
49
Victor Stinnerbd303c12013-11-07 23:07:29 +010050_Py_IDENTIFIER(_);
51_Py_IDENTIFIER(__sizeof__);
Eric Snowdae02762017-09-14 00:35:58 -070052_Py_IDENTIFIER(_xoptions);
Victor Stinnerbd303c12013-11-07 23:07:29 +010053_Py_IDENTIFIER(buffer);
54_Py_IDENTIFIER(builtins);
55_Py_IDENTIFIER(encoding);
56_Py_IDENTIFIER(path);
57_Py_IDENTIFIER(stdout);
58_Py_IDENTIFIER(stderr);
Eric Snowdae02762017-09-14 00:35:58 -070059_Py_IDENTIFIER(warnoptions);
Victor Stinnerbd303c12013-11-07 23:07:29 +010060_Py_IDENTIFIER(write);
61
Guido van Rossum65bf9f21997-04-29 18:33:38 +000062PyObject *
Victor Stinnerd67bd452013-11-06 22:36:40 +010063_PySys_GetObjectId(_Py_Identifier *key)
64{
Victor Stinnercaba55b2018-08-03 15:33:52 +020065 PyObject *sd = _PyInterpreterState_GET_UNSAFE()->sysdict;
66 if (sd == NULL) {
Victor Stinnerd67bd452013-11-06 22:36:40 +010067 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +020068 }
Victor Stinnerd67bd452013-11-06 22:36:40 +010069 return _PyDict_GetItemId(sd, key);
70}
71
72PyObject *
Neal Norwitzf3081322007-08-25 00:32:45 +000073PySys_GetObject(const char *name)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000074{
Victor Stinnercaba55b2018-08-03 15:33:52 +020075 PyObject *sd = _PyInterpreterState_GET_UNSAFE()->sysdict;
76 if (sd == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000077 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +020078 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000079 return PyDict_GetItemString(sd, name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000080}
81
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000082int
Victor Stinnerd67bd452013-11-06 22:36:40 +010083_PySys_SetObjectId(_Py_Identifier *key, PyObject *v)
84{
Victor Stinnercaba55b2018-08-03 15:33:52 +020085 PyObject *sd = _PyInterpreterState_GET_UNSAFE()->sysdict;
Victor Stinnerd67bd452013-11-06 22:36:40 +010086 if (v == NULL) {
Victor Stinnercaba55b2018-08-03 15:33:52 +020087 if (_PyDict_GetItemId(sd, key) == NULL) {
Victor Stinnerd67bd452013-11-06 22:36:40 +010088 return 0;
Victor Stinnercaba55b2018-08-03 15:33:52 +020089 }
90 else {
Victor Stinnerd67bd452013-11-06 22:36:40 +010091 return _PyDict_DelItemId(sd, key);
Victor Stinnercaba55b2018-08-03 15:33:52 +020092 }
Victor Stinnerd67bd452013-11-06 22:36:40 +010093 }
Victor Stinnercaba55b2018-08-03 15:33:52 +020094 else {
Victor Stinnerd67bd452013-11-06 22:36:40 +010095 return _PyDict_SetItemId(sd, key, v);
Victor Stinnercaba55b2018-08-03 15:33:52 +020096 }
Victor Stinnerd67bd452013-11-06 22:36:40 +010097}
98
99int
Neal Norwitzf3081322007-08-25 00:32:45 +0000100PySys_SetObject(const char *name, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000101{
Victor Stinnercaba55b2018-08-03 15:33:52 +0200102 PyObject *sd = _PyInterpreterState_GET_UNSAFE()->sysdict;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000103 if (v == NULL) {
Victor Stinnercaba55b2018-08-03 15:33:52 +0200104 if (PyDict_GetItemString(sd, name) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000105 return 0;
Victor Stinnercaba55b2018-08-03 15:33:52 +0200106 }
107 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000108 return PyDict_DelItemString(sd, name);
Victor Stinnercaba55b2018-08-03 15:33:52 +0200109 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000110 }
Victor Stinnercaba55b2018-08-03 15:33:52 +0200111 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000112 return PyDict_SetItemString(sd, name, v);
Victor Stinnercaba55b2018-08-03 15:33:52 +0200113 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000114}
115
Steve Dowerb82e17e2019-05-23 08:45:22 -0700116static int
117should_audit(void)
118{
119 PyThreadState *ts = _PyThreadState_GET();
120 if (!ts) {
121 return 0;
122 }
Victor Stinner0fd2c302019-06-04 03:15:09 +0200123 PyInterpreterState *is = ts ? ts->interp : NULL;
124 return _PyRuntime.audit_hook_head
Steve Dowerb82e17e2019-05-23 08:45:22 -0700125 || (is && is->audit_hooks)
126 || PyDTrace_AUDIT_ENABLED();
127}
128
129int
130PySys_Audit(const char *event, const char *argFormat, ...)
131{
132 PyObject *eventName = NULL;
133 PyObject *eventArgs = NULL;
134 PyObject *hooks = NULL;
135 PyObject *hook = NULL;
136 int res = -1;
137
138 /* N format is inappropriate, because you do not know
139 whether the reference is consumed by the call.
140 Assert rather than exception for perf reasons */
141 assert(!argFormat || !strchr(argFormat, 'N'));
142
143 /* Early exit when no hooks are registered */
144 if (!should_audit()) {
145 return 0;
146 }
147
148 _Py_AuditHookEntry *e = _PyRuntime.audit_hook_head;
149 PyThreadState *ts = _PyThreadState_GET();
150 PyInterpreterState *is = ts ? ts->interp : NULL;
151 int dtrace = PyDTrace_AUDIT_ENABLED();
152
153 PyObject *exc_type, *exc_value, *exc_tb;
154 if (ts) {
155 PyErr_Fetch(&exc_type, &exc_value, &exc_tb);
156 }
157
158 /* Initialize event args now */
159 if (argFormat && argFormat[0]) {
160 va_list args;
161 va_start(args, argFormat);
162 eventArgs = Py_VaBuildValue(argFormat, args);
163 if (eventArgs && !PyTuple_Check(eventArgs)) {
164 PyObject *argTuple = PyTuple_Pack(1, eventArgs);
165 Py_DECREF(eventArgs);
166 eventArgs = argTuple;
167 }
168 } else {
169 eventArgs = PyTuple_New(0);
170 }
171 if (!eventArgs) {
172 goto exit;
173 }
174
175 /* Call global hooks */
176 for (; e; e = e->next) {
177 if (e->hookCFunction(event, eventArgs, e->userData) < 0) {
178 goto exit;
179 }
180 }
181
182 /* Dtrace USDT point */
183 if (dtrace) {
184 PyDTrace_AUDIT(event, (void *)eventArgs);
185 }
186
187 /* Call interpreter hooks */
188 if (is && is->audit_hooks) {
189 eventName = PyUnicode_FromString(event);
190 if (!eventName) {
191 goto exit;
192 }
193
194 hooks = PyObject_GetIter(is->audit_hooks);
195 if (!hooks) {
196 goto exit;
197 }
198
199 /* Disallow tracing in hooks unless explicitly enabled */
200 ts->tracing++;
201 ts->use_tracing = 0;
202 while ((hook = PyIter_Next(hooks)) != NULL) {
203 PyObject *o;
204 int canTrace = -1;
205 o = PyObject_GetAttrString(hook, "__cantrace__");
206 if (o) {
207 canTrace = PyObject_IsTrue(o);
208 Py_DECREF(o);
209 } else if (PyErr_Occurred() &&
210 PyErr_ExceptionMatches(PyExc_AttributeError)) {
211 PyErr_Clear();
212 canTrace = 0;
213 }
214 if (canTrace < 0) {
215 break;
216 }
217 if (canTrace) {
218 ts->use_tracing = (ts->c_tracefunc || ts->c_profilefunc);
219 ts->tracing--;
220 }
221 o = PyObject_CallFunctionObjArgs(hook, eventName,
222 eventArgs, NULL);
223 if (canTrace) {
224 ts->tracing++;
225 ts->use_tracing = 0;
226 }
227 if (!o) {
228 break;
229 }
230 Py_DECREF(o);
231 Py_CLEAR(hook);
232 }
233 ts->use_tracing = (ts->c_tracefunc || ts->c_profilefunc);
234 ts->tracing--;
235 if (PyErr_Occurred()) {
236 goto exit;
237 }
238 }
239
240 res = 0;
241
242exit:
243 Py_XDECREF(hook);
244 Py_XDECREF(hooks);
245 Py_XDECREF(eventName);
246 Py_XDECREF(eventArgs);
247
248 if (ts) {
249 if (!res) {
250 PyErr_Restore(exc_type, exc_value, exc_tb);
251 } else {
252 assert(PyErr_Occurred());
253 Py_XDECREF(exc_type);
254 Py_XDECREF(exc_value);
255 Py_XDECREF(exc_tb);
256 }
257 }
258
259 return res;
260}
261
262/* We expose this function primarily for our own cleanup during
263 * finalization. In general, it should not need to be called,
264 * and as such it is not defined in any header files.
265 */
266void _PySys_ClearAuditHooks(void) {
267 /* Must be finalizing to clear hooks */
268 _PyRuntimeState *runtime = &_PyRuntime;
269 PyThreadState *ts = _PyRuntimeState_GetThreadState(runtime);
270 assert(!ts || _Py_CURRENTLY_FINALIZING(runtime, ts));
271 if (!ts || !_Py_CURRENTLY_FINALIZING(runtime, ts))
272 return;
273
274 if (Py_VerboseFlag) {
275 PySys_WriteStderr("# clear sys.audit hooks\n");
276 }
277
278 /* Hooks can abort later hooks for this event, but cannot
279 abort the clear operation itself. */
280 PySys_Audit("cpython._PySys_ClearAuditHooks", NULL);
281 PyErr_Clear();
282
Victor Stinner0fd2c302019-06-04 03:15:09 +0200283 _Py_AuditHookEntry *e = _PyRuntime.audit_hook_head, *n;
284 _PyRuntime.audit_hook_head = NULL;
Steve Dowerb82e17e2019-05-23 08:45:22 -0700285 while (e) {
286 n = e->next;
287 PyMem_RawFree(e);
288 e = n;
289 }
290}
291
292int
293PySys_AddAuditHook(Py_AuditHookFunction hook, void *userData)
294{
295 /* Invoke existing audit hooks to allow them an opportunity to abort. */
296 /* Cannot invoke hooks until we are initialized */
297 if (Py_IsInitialized()) {
298 if (PySys_Audit("sys.addaudithook", NULL) < 0) {
299 if (PyErr_ExceptionMatches(PyExc_Exception)) {
300 /* We do not report errors derived from Exception */
301 PyErr_Clear();
302 return 0;
303 }
304 return -1;
305 }
306 }
307
Victor Stinner0fd2c302019-06-04 03:15:09 +0200308 _Py_AuditHookEntry *e = _PyRuntime.audit_hook_head;
Steve Dowerb82e17e2019-05-23 08:45:22 -0700309 if (!e) {
310 e = (_Py_AuditHookEntry*)PyMem_RawMalloc(sizeof(_Py_AuditHookEntry));
Victor Stinner0fd2c302019-06-04 03:15:09 +0200311 _PyRuntime.audit_hook_head = e;
Steve Dowerb82e17e2019-05-23 08:45:22 -0700312 } else {
313 while (e->next)
314 e = e->next;
315 e = e->next = (_Py_AuditHookEntry*)PyMem_RawMalloc(
316 sizeof(_Py_AuditHookEntry));
317 }
318
319 if (!e) {
320 if (Py_IsInitialized())
321 PyErr_NoMemory();
322 return -1;
323 }
324
325 e->next = NULL;
326 e->hookCFunction = (Py_AuditHookFunction)hook;
327 e->userData = userData;
328
329 return 0;
330}
331
332/*[clinic input]
333sys.addaudithook
334
335 hook: object
336
337Adds a new audit hook callback.
338[clinic start generated code]*/
339
340static PyObject *
341sys_addaudithook_impl(PyObject *module, PyObject *hook)
342/*[clinic end generated code: output=4f9c17aaeb02f44e input=0f3e191217a45e34]*/
343{
344 /* Invoke existing audit hooks to allow them an opportunity to abort. */
345 if (PySys_Audit("sys.addaudithook", NULL) < 0) {
346 if (PyErr_ExceptionMatches(PyExc_Exception)) {
347 /* We do not report errors derived from Exception */
348 PyErr_Clear();
349 Py_RETURN_NONE;
350 }
351 return NULL;
352 }
353
354 PyInterpreterState *is = _PyInterpreterState_Get();
355
356 if (is->audit_hooks == NULL) {
357 is->audit_hooks = PyList_New(0);
358 if (is->audit_hooks == NULL) {
359 return NULL;
360 }
361 }
362
363 if (PyList_Append(is->audit_hooks, hook) < 0) {
364 return NULL;
365 }
366
367 Py_RETURN_NONE;
368}
369
370PyDoc_STRVAR(audit_doc,
371"audit(event, *args)\n\
372\n\
373Passes the event to any audit hooks that are attached.");
374
375static PyObject *
376sys_audit(PyObject *self, PyObject *const *args, Py_ssize_t argc)
377{
378 if (argc == 0) {
379 PyErr_SetString(PyExc_TypeError, "audit() missing 1 required positional argument: 'event'");
380 return NULL;
381 }
382
383 if (!should_audit()) {
384 Py_RETURN_NONE;
385 }
386
387 PyObject *auditEvent = args[0];
388 if (!auditEvent) {
389 PyErr_SetString(PyExc_TypeError, "expected str for argument 'event'");
390 return NULL;
391 }
392 if (!PyUnicode_Check(auditEvent)) {
393 PyErr_Format(PyExc_TypeError, "expected str for argument 'event', not %.200s",
394 Py_TYPE(auditEvent)->tp_name);
395 return NULL;
396 }
397 const char *event = PyUnicode_AsUTF8(auditEvent);
398 if (!event) {
399 return NULL;
400 }
401
402 PyObject *auditArgs = _PyTuple_FromArray(args + 1, argc - 1);
403 if (!auditArgs) {
404 return NULL;
405 }
406
407 int res = PySys_Audit(event, "O", auditArgs);
408 Py_DECREF(auditArgs);
409
410 if (res < 0) {
411 return NULL;
412 }
413
414 Py_RETURN_NONE;
415}
416
417
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400418static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +0200419sys_breakpointhook(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *keywords)
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400420{
421 assert(!PyErr_Occurred());
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300422 char *envar = Py_GETENV("PYTHONBREAKPOINT");
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400423
424 if (envar == NULL || strlen(envar) == 0) {
425 envar = "pdb.set_trace";
426 }
427 else if (!strcmp(envar, "0")) {
428 /* The breakpoint is explicitly no-op'd. */
429 Py_RETURN_NONE;
430 }
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300431 /* According to POSIX the string returned by getenv() might be invalidated
432 * or the string content might be overwritten by a subsequent call to
433 * getenv(). Since importing a module can performs the getenv() calls,
434 * we need to save a copy of envar. */
435 envar = _PyMem_RawStrdup(envar);
436 if (envar == NULL) {
437 PyErr_NoMemory();
438 return NULL;
439 }
Serhiy Storchaka4ae06c52017-12-12 13:55:04 +0200440 const char *last_dot = strrchr(envar, '.');
441 const char *attrname = NULL;
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400442 PyObject *modulepath = NULL;
443
444 if (last_dot == NULL) {
445 /* The breakpoint is a built-in, e.g. PYTHONBREAKPOINT=int */
446 modulepath = PyUnicode_FromString("builtins");
447 attrname = envar;
448 }
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200449 else if (last_dot != envar) {
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400450 /* Split on the last dot; */
451 modulepath = PyUnicode_FromStringAndSize(envar, last_dot - envar);
452 attrname = last_dot + 1;
453 }
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200454 else {
455 goto warn;
456 }
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400457 if (modulepath == NULL) {
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300458 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400459 return NULL;
460 }
461
Anthony Sottiledce345c2018-11-01 10:25:05 -0700462 PyObject *module = PyImport_Import(modulepath);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400463 Py_DECREF(modulepath);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400464
465 if (module == NULL) {
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200466 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
467 goto warn;
468 }
469 PyMem_RawFree(envar);
470 return NULL;
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400471 }
472
473 PyObject *hook = PyObject_GetAttrString(module, attrname);
474 Py_DECREF(module);
475
476 if (hook == NULL) {
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200477 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
478 goto warn;
479 }
480 PyMem_RawFree(envar);
481 return NULL;
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400482 }
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300483 PyMem_RawFree(envar);
Jeroen Demeyeraacc77f2019-05-29 20:31:52 +0200484 PyObject *retval = _PyObject_Vectorcall(hook, args, nargs, keywords);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400485 Py_DECREF(hook);
486 return retval;
487
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200488 warn:
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400489 /* If any of the imports went wrong, then warn and ignore. */
490 PyErr_Clear();
491 int status = PyErr_WarnFormat(
492 PyExc_RuntimeWarning, 0,
493 "Ignoring unimportable $PYTHONBREAKPOINT: \"%s\"", envar);
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300494 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400495 if (status < 0) {
496 /* Printing the warning raised an exception. */
497 return NULL;
498 }
499 /* The warning was (probably) issued. */
500 Py_RETURN_NONE;
501}
502
503PyDoc_STRVAR(breakpointhook_doc,
504"breakpointhook(*args, **kws)\n"
505"\n"
506"This hook function is called by built-in breakpoint().\n"
507);
508
Victor Stinner13d49ee2010-12-04 17:24:33 +0000509/* Write repr(o) to sys.stdout using sys.stdout.encoding and 'backslashreplace'
510 error handler. If sys.stdout has a buffer attribute, use
511 sys.stdout.buffer.write(encoded), otherwise redecode the string and use
512 sys.stdout.write(redecoded).
513
514 Helper function for sys_displayhook(). */
515static int
516sys_displayhook_unencodable(PyObject *outf, PyObject *o)
517{
518 PyObject *stdout_encoding = NULL;
519 PyObject *encoded, *escaped_str, *repr_str, *buffer, *result;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200520 const char *stdout_encoding_str;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000521 int ret;
522
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200523 stdout_encoding = _PyObject_GetAttrId(outf, &PyId_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000524 if (stdout_encoding == NULL)
525 goto error;
Serhiy Storchaka06515832016-11-20 09:13:07 +0200526 stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000527 if (stdout_encoding_str == NULL)
528 goto error;
529
530 repr_str = PyObject_Repr(o);
531 if (repr_str == NULL)
532 goto error;
533 encoded = PyUnicode_AsEncodedString(repr_str,
534 stdout_encoding_str,
535 "backslashreplace");
536 Py_DECREF(repr_str);
537 if (encoded == NULL)
538 goto error;
539
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200540 buffer = _PyObject_GetAttrId(outf, &PyId_buffer);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000541 if (buffer) {
Victor Stinner7e425412016-12-09 00:36:19 +0100542 result = _PyObject_CallMethodIdObjArgs(buffer, &PyId_write, encoded, NULL);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000543 Py_DECREF(buffer);
544 Py_DECREF(encoded);
545 if (result == NULL)
546 goto error;
547 Py_DECREF(result);
548 }
549 else {
550 PyErr_Clear();
551 escaped_str = PyUnicode_FromEncodedObject(encoded,
552 stdout_encoding_str,
553 "strict");
554 Py_DECREF(encoded);
555 if (PyFile_WriteObject(escaped_str, outf, Py_PRINT_RAW) != 0) {
556 Py_DECREF(escaped_str);
557 goto error;
558 }
559 Py_DECREF(escaped_str);
560 }
561 ret = 0;
562 goto finally;
563
564error:
565 ret = -1;
566finally:
567 Py_XDECREF(stdout_encoding);
568 return ret;
569}
570
Tal Einatede0b6f2018-12-31 17:12:08 +0200571/*[clinic input]
572sys.displayhook
573
574 object as o: object
575 /
576
577Print an object to sys.stdout and also save it in builtins._
578[clinic start generated code]*/
579
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000580static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200581sys_displayhook(PyObject *module, PyObject *o)
582/*[clinic end generated code: output=347477d006df92ed input=08ba730166d7ef72]*/
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000583{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 PyObject *outf;
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100585 PyObject *builtins;
586 static PyObject *newline = NULL;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000587 int err;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000588
Eric Snow3f9eee62017-09-15 16:35:20 -0600589 builtins = _PyImport_GetModuleId(&PyId_builtins);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 if (builtins == NULL) {
Stefan Krah027b09c2019-03-25 21:50:58 +0100591 if (!PyErr_Occurred()) {
592 PyErr_SetString(PyExc_RuntimeError, "lost builtins module");
593 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 return NULL;
595 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600596 Py_DECREF(builtins);
Moshe Zadka03897ea2001-07-23 13:32:43 +0000597
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 /* Print value except if None */
599 /* After printing, also assign to '_' */
600 /* Before, set '_' to None to avoid recursion */
601 if (o == Py_None) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200602 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 }
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200604 if (_PyObject_SetAttrId(builtins, &PyId__, Py_None) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000605 return NULL;
Victor Stinnerbd303c12013-11-07 23:07:29 +0100606 outf = _PySys_GetObjectId(&PyId_stdout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 if (outf == NULL || outf == Py_None) {
608 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
609 return NULL;
610 }
Victor Stinner13d49ee2010-12-04 17:24:33 +0000611 if (PyFile_WriteObject(o, outf, 0) != 0) {
612 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
613 /* repr(o) is not encodable to sys.stdout.encoding with
614 * sys.stdout.errors error handler (which is probably 'strict') */
615 PyErr_Clear();
616 err = sys_displayhook_unencodable(outf, o);
617 if (err)
618 return NULL;
619 }
620 else {
621 return NULL;
622 }
623 }
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100624 if (newline == NULL) {
625 newline = PyUnicode_FromString("\n");
626 if (newline == NULL)
627 return NULL;
628 }
629 if (PyFile_WriteObject(newline, outf, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 return NULL;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200631 if (_PyObject_SetAttrId(builtins, &PyId__, o) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200633 Py_RETURN_NONE;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000634}
635
Tal Einatede0b6f2018-12-31 17:12:08 +0200636
637/*[clinic input]
638sys.excepthook
639
640 exctype: object
641 value: object
642 traceback: object
643 /
644
645Handle an exception by displaying it with a traceback on sys.stderr.
646[clinic start generated code]*/
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000647
648static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200649sys_excepthook_impl(PyObject *module, PyObject *exctype, PyObject *value,
650 PyObject *traceback)
651/*[clinic end generated code: output=18d99fdda21b6b5e input=ecf606fa826f19d9]*/
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000652{
Tal Einatede0b6f2018-12-31 17:12:08 +0200653 PyErr_Display(exctype, value, traceback);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200654 Py_RETURN_NONE;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000655}
656
Tal Einatede0b6f2018-12-31 17:12:08 +0200657
658/*[clinic input]
659sys.exc_info
660
661Return current exception information: (type, value, traceback).
662
663Return information about the most recent exception caught by an except
664clause in the current stack frame or in an older stack frame.
665[clinic start generated code]*/
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000666
667static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200668sys_exc_info_impl(PyObject *module)
669/*[clinic end generated code: output=3afd0940cf3a4d30 input=b5c5bf077788a3e5]*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000670{
Victor Stinner50b48572018-11-01 01:51:40 +0100671 _PyErr_StackItem *err_info = _PyErr_GetTopmostException(_PyThreadState_GET());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 return Py_BuildValue(
673 "(OOO)",
Mark Shannonae3087c2017-10-22 22:41:51 +0100674 err_info->exc_type != NULL ? err_info->exc_type : Py_None,
675 err_info->exc_value != NULL ? err_info->exc_value : Py_None,
676 err_info->exc_traceback != NULL ?
677 err_info->exc_traceback : Py_None);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000678}
679
Tal Einatede0b6f2018-12-31 17:12:08 +0200680
681/*[clinic input]
Victor Stinneref9d9b62019-05-22 11:28:22 +0200682sys.unraisablehook
683
684 unraisable: object
685 /
686
687Handle an unraisable exception.
688
689The unraisable argument has the following attributes:
690
691* exc_type: Exception type.
Victor Stinner71c52e32019-05-27 08:57:14 +0200692* exc_value: Exception value, can be None.
693* exc_traceback: Exception traceback, can be None.
694* err_msg: Error message, can be None.
695* object: Object causing the exception, can be None.
Victor Stinneref9d9b62019-05-22 11:28:22 +0200696[clinic start generated code]*/
697
698static PyObject *
699sys_unraisablehook(PyObject *module, PyObject *unraisable)
Victor Stinner71c52e32019-05-27 08:57:14 +0200700/*[clinic end generated code: output=bb92838b32abaa14 input=ec3af148294af8d3]*/
Victor Stinneref9d9b62019-05-22 11:28:22 +0200701{
702 return _PyErr_WriteUnraisableDefaultHook(unraisable);
703}
704
705
706/*[clinic input]
Tal Einatede0b6f2018-12-31 17:12:08 +0200707sys.exit
708
709 status: object = NULL
710 /
711
712Exit the interpreter by raising SystemExit(status).
713
714If the status is omitted or None, it defaults to zero (i.e., success).
715If the status is an integer, it will be used as the system exit status.
716If it is another kind of object, it will be printed and the system
717exit status will be one (i.e., failure).
718[clinic start generated code]*/
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000719
720static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200721sys_exit_impl(PyObject *module, PyObject *status)
722/*[clinic end generated code: output=13870986c1ab2ec0 input=a737351f86685e9c]*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000723{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000724 /* Raise SystemExit so callers may catch it or clean up. */
Tal Einatede0b6f2018-12-31 17:12:08 +0200725 PyErr_SetObject(PyExc_SystemExit, status);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000727}
728
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000729
Martin v. Löwis107b7da2001-11-09 20:59:39 +0000730
Tal Einatede0b6f2018-12-31 17:12:08 +0200731/*[clinic input]
732sys.getdefaultencoding
733
734Return the current default encoding used by the Unicode implementation.
735[clinic start generated code]*/
736
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000737static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200738sys_getdefaultencoding_impl(PyObject *module)
739/*[clinic end generated code: output=256d19dfcc0711e6 input=d416856ddbef6909]*/
Fred Drake8b4d01d2000-05-09 19:57:01 +0000740{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000741 return PyUnicode_FromString(PyUnicode_GetDefaultEncoding());
Fred Drake8b4d01d2000-05-09 19:57:01 +0000742}
743
Tal Einatede0b6f2018-12-31 17:12:08 +0200744/*[clinic input]
745sys.getfilesystemencoding
746
747Return the encoding used to convert Unicode filenames to OS filenames.
748[clinic start generated code]*/
Fred Drake8b4d01d2000-05-09 19:57:01 +0000749
750static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200751sys_getfilesystemencoding_impl(PyObject *module)
752/*[clinic end generated code: output=1dc4bdbe9be44aa7 input=8475f8649b8c7d8c]*/
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000753{
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200754 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Victor Stinner331a6a52019-05-27 16:39:22 +0200755 const PyConfig *config = &interp->config;
Victor Stinner709d23d2019-05-02 14:56:30 -0400756 return PyUnicode_FromWideChar(config->filesystem_encoding, -1);
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000757}
758
Tal Einatede0b6f2018-12-31 17:12:08 +0200759/*[clinic input]
760sys.getfilesystemencodeerrors
761
762Return the error mode used Unicode to OS filename conversion.
763[clinic start generated code]*/
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000764
Martin v. Löwis04dc25c2008-10-03 16:09:28 +0000765static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200766sys_getfilesystemencodeerrors_impl(PyObject *module)
767/*[clinic end generated code: output=ba77b36bbf7c96f5 input=22a1e8365566f1e5]*/
Steve Dowercc16be82016-09-08 10:35:16 -0700768{
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200769 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Victor Stinner331a6a52019-05-27 16:39:22 +0200770 const PyConfig *config = &interp->config;
Victor Stinner709d23d2019-05-02 14:56:30 -0400771 return PyUnicode_FromWideChar(config->filesystem_errors, -1);
Steve Dowercc16be82016-09-08 10:35:16 -0700772}
773
Tal Einatede0b6f2018-12-31 17:12:08 +0200774/*[clinic input]
775sys.intern
776
777 string as s: unicode
778 /
779
780``Intern'' the given string.
781
782This enters the string in the (global) table of interned strings whose
783purpose is to speed up dictionary lookups. Return the string itself or
784the previously interned string object with the same value.
785[clinic start generated code]*/
Steve Dowercc16be82016-09-08 10:35:16 -0700786
787static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200788sys_intern_impl(PyObject *module, PyObject *s)
789/*[clinic end generated code: output=be680c24f5c9e5d6 input=849483c006924e2f]*/
Georg Brandl66a796e2006-12-19 20:50:34 +0000790{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 if (PyUnicode_CheckExact(s)) {
792 Py_INCREF(s);
793 PyUnicode_InternInPlace(&s);
794 return s;
795 }
796 else {
797 PyErr_Format(PyExc_TypeError,
Tal Einatede0b6f2018-12-31 17:12:08 +0200798 "can't intern %.400s", s->ob_type->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 return NULL;
800 }
Georg Brandl66a796e2006-12-19 20:50:34 +0000801}
802
Georg Brandl66a796e2006-12-19 20:50:34 +0000803
Fred Drake5755ce62001-06-27 19:19:46 +0000804/*
805 * Cached interned string objects used for calling the profile and
806 * trace functions. Initialized by trace_init().
807 */
Nick Coghlan5a851672017-09-08 10:14:16 +1000808static PyObject *whatstrings[8] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
Fred Drake5755ce62001-06-27 19:19:46 +0000809
810static int
811trace_init(void)
812{
Nick Coghlan5a851672017-09-08 10:14:16 +1000813 static const char * const whatnames[8] = {
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200814 "call", "exception", "line", "return",
Nick Coghlan5a851672017-09-08 10:14:16 +1000815 "c_call", "c_exception", "c_return",
816 "opcode"
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200817 };
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000818 PyObject *name;
819 int i;
Nick Coghlan5a851672017-09-08 10:14:16 +1000820 for (i = 0; i < 8; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 if (whatstrings[i] == NULL) {
822 name = PyUnicode_InternFromString(whatnames[i]);
823 if (name == NULL)
824 return -1;
825 whatstrings[i] = name;
826 }
827 }
828 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000829}
830
831
832static PyObject *
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100833call_trampoline(PyObject* callback,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 PyFrameObject *frame, int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000835{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 PyObject *result;
Victor Stinner78da82b2016-08-20 01:22:57 +0200837 PyObject *stack[3];
Fred Drake5755ce62001-06-27 19:19:46 +0000838
Victor Stinner78da82b2016-08-20 01:22:57 +0200839 if (PyFrame_FastToLocalsWithError(frame) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 return NULL;
Victor Stinner78da82b2016-08-20 01:22:57 +0200841 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100842
Victor Stinner78da82b2016-08-20 01:22:57 +0200843 stack[0] = (PyObject *)frame;
844 stack[1] = whatstrings[what];
845 stack[2] = (arg != NULL) ? arg : Py_None;
Fred Drake5755ce62001-06-27 19:19:46 +0000846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 /* call the Python-level function */
Victor Stinner559bb6a2016-08-22 22:48:54 +0200848 result = _PyObject_FastCall(callback, stack, 3);
Fred Drake5755ce62001-06-27 19:19:46 +0000849
Victor Stinner78da82b2016-08-20 01:22:57 +0200850 PyFrame_LocalsToFast(frame, 1);
851 if (result == NULL) {
852 PyTraceBack_Here(frame);
853 }
854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 return result;
Fred Drake5755ce62001-06-27 19:19:46 +0000856}
857
858static int
859profile_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000861{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 if (arg == NULL)
865 arg = Py_None;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100866 result = call_trampoline(self, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 if (result == NULL) {
868 PyEval_SetProfile(NULL, NULL);
869 return -1;
870 }
871 Py_DECREF(result);
872 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000873}
874
875static int
876trace_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000878{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 PyObject *callback;
880 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 if (what == PyTrace_CALL)
883 callback = self;
884 else
885 callback = frame->f_trace;
886 if (callback == NULL)
887 return 0;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100888 result = call_trampoline(callback, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 if (result == NULL) {
890 PyEval_SetTrace(NULL, NULL);
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200891 Py_CLEAR(frame->f_trace);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 return -1;
893 }
894 if (result != Py_None) {
Serhiy Storchakaec397562016-04-06 09:50:03 +0300895 Py_XSETREF(frame->f_trace, result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 }
897 else {
898 Py_DECREF(result);
899 }
900 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000901}
Fred Draked0838392001-06-16 21:02:31 +0000902
Fred Drake8b4d01d2000-05-09 19:57:01 +0000903static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000904sys_settrace(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000905{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 if (trace_init() == -1)
907 return NULL;
908 if (args == Py_None)
909 PyEval_SetTrace(NULL, NULL);
910 else
911 PyEval_SetTrace(trace_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200912 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000913}
914
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000915PyDoc_STRVAR(settrace_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000916"settrace(function)\n\
917\n\
918Set the global debug tracing function. It will be called on each\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000919function call. See the debugger chapter in the library manual."
920);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000921
Tal Einatede0b6f2018-12-31 17:12:08 +0200922/*[clinic input]
923sys.gettrace
924
925Return the global debug tracing function set with sys.settrace.
926
927See the debugger chapter in the library manual.
928[clinic start generated code]*/
929
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000930static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200931sys_gettrace_impl(PyObject *module)
932/*[clinic end generated code: output=e97e3a4d8c971b6e input=373b51bb2147f4d8]*/
Christian Heimes9bd667a2008-01-20 15:14:11 +0000933{
Victor Stinner50b48572018-11-01 01:51:40 +0100934 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 PyObject *temp = tstate->c_traceobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000936
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 if (temp == NULL)
938 temp = Py_None;
939 Py_INCREF(temp);
940 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000941}
942
Christian Heimes9bd667a2008-01-20 15:14:11 +0000943static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000944sys_setprofile(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000945{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 if (trace_init() == -1)
947 return NULL;
948 if (args == Py_None)
949 PyEval_SetProfile(NULL, NULL);
950 else
951 PyEval_SetProfile(profile_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200952 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000953}
954
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000955PyDoc_STRVAR(setprofile_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000956"setprofile(function)\n\
957\n\
958Set the profiling function. It will be called on each function call\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000959and return. See the profiler chapter in the library manual."
960);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000961
Tal Einatede0b6f2018-12-31 17:12:08 +0200962/*[clinic input]
963sys.getprofile
964
965Return the profiling function set with sys.setprofile.
966
967See the profiler chapter in the library manual.
968[clinic start generated code]*/
969
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000970static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200971sys_getprofile_impl(PyObject *module)
972/*[clinic end generated code: output=579b96b373448188 input=1b3209d89a32965d]*/
Christian Heimes9bd667a2008-01-20 15:14:11 +0000973{
Victor Stinner50b48572018-11-01 01:51:40 +0100974 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 PyObject *temp = tstate->c_profileobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 if (temp == NULL)
978 temp = Py_None;
979 Py_INCREF(temp);
980 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000981}
982
Tal Einatede0b6f2018-12-31 17:12:08 +0200983/*[clinic input]
984sys.setcheckinterval
985
986 n: int
987 /
988
989Set the async event check interval to n instructions.
990
991This tells the Python interpreter to check for asynchronous events
992every n instructions.
993
994This also affects how often thread switches occur.
995[clinic start generated code]*/
Christian Heimes9bd667a2008-01-20 15:14:11 +0000996
997static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200998sys_setcheckinterval_impl(PyObject *module, int n)
999/*[clinic end generated code: output=3f686cef07e6e178 input=7a35b17bf22a6227]*/
Guido van Rossuma0d7a231995-01-09 17:46:13 +00001000{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1002 "sys.getcheckinterval() and sys.setcheckinterval() "
1003 "are deprecated. Use sys.setswitchinterval() "
1004 "instead.", 1) < 0)
1005 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +02001006
Victor Stinnercaba55b2018-08-03 15:33:52 +02001007 PyInterpreterState *interp = _PyInterpreterState_Get();
Tal Einatede0b6f2018-12-31 17:12:08 +02001008 interp->check_interval = n;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001009 Py_RETURN_NONE;
Guido van Rossuma0d7a231995-01-09 17:46:13 +00001010}
1011
Tal Einatede0b6f2018-12-31 17:12:08 +02001012/*[clinic input]
1013sys.getcheckinterval
1014
1015Return the current check interval; see sys.setcheckinterval().
1016[clinic start generated code]*/
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001017
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001018static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001019sys_getcheckinterval_impl(PyObject *module)
1020/*[clinic end generated code: output=1b5060bf2b23a47c input=4b6589cbcca1db4e]*/
Tim Peterse5e065b2003-07-06 18:36:54 +00001021{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1023 "sys.getcheckinterval() and sys.setcheckinterval() "
1024 "are deprecated. Use sys.getswitchinterval() "
1025 "instead.", 1) < 0)
1026 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +02001027 PyInterpreterState *interp = _PyInterpreterState_Get();
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001028 return PyLong_FromLong(interp->check_interval);
Tim Peterse5e065b2003-07-06 18:36:54 +00001029}
1030
Tal Einatede0b6f2018-12-31 17:12:08 +02001031/*[clinic input]
1032sys.setswitchinterval
1033
1034 interval: double
1035 /
1036
1037Set the ideal thread switching delay inside the Python interpreter.
1038
1039The actual frequency of switching threads can be lower if the
1040interpreter executes long sequences of uninterruptible code
1041(this is implementation-specific and workload-dependent).
1042
1043The parameter must represent the desired switching delay in seconds
1044A typical value is 0.005 (5 milliseconds).
1045[clinic start generated code]*/
Tim Peterse5e065b2003-07-06 18:36:54 +00001046
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001047static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001048sys_setswitchinterval_impl(PyObject *module, double interval)
1049/*[clinic end generated code: output=65a19629e5153983 input=561b477134df91d9]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001050{
Tal Einatede0b6f2018-12-31 17:12:08 +02001051 if (interval <= 0.0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 PyErr_SetString(PyExc_ValueError,
1053 "switch interval must be strictly positive");
1054 return NULL;
1055 }
Tal Einatede0b6f2018-12-31 17:12:08 +02001056 _PyEval_SetSwitchInterval((unsigned long) (1e6 * interval));
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001057 Py_RETURN_NONE;
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001058}
1059
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001060
Tal Einatede0b6f2018-12-31 17:12:08 +02001061/*[clinic input]
1062sys.getswitchinterval -> double
1063
1064Return the current thread switch interval; see sys.setswitchinterval().
1065[clinic start generated code]*/
1066
1067static double
1068sys_getswitchinterval_impl(PyObject *module)
1069/*[clinic end generated code: output=a38c277c85b5096d input=bdf9d39c0ebbbb6f]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001070{
Tal Einatede0b6f2018-12-31 17:12:08 +02001071 return 1e-6 * _PyEval_GetSwitchInterval();
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001072}
1073
Tal Einatede0b6f2018-12-31 17:12:08 +02001074/*[clinic input]
1075sys.setrecursionlimit
1076
1077 limit as new_limit: int
1078 /
1079
1080Set the maximum depth of the Python interpreter stack to n.
1081
1082This limit prevents infinite recursion from causing an overflow of the C
1083stack and crashing Python. The highest possible limit is platform-
1084dependent.
1085[clinic start generated code]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001086
Tim Peterse5e065b2003-07-06 18:36:54 +00001087static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001088sys_setrecursionlimit_impl(PyObject *module, int new_limit)
1089/*[clinic end generated code: output=35e1c64754800ace input=b0f7a23393924af3]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001090{
Tal Einatede0b6f2018-12-31 17:12:08 +02001091 int mark;
Victor Stinner50856d52015-10-13 00:11:21 +02001092 PyThreadState *tstate;
1093
Victor Stinner50856d52015-10-13 00:11:21 +02001094 if (new_limit < 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 PyErr_SetString(PyExc_ValueError,
Victor Stinner50856d52015-10-13 00:11:21 +02001096 "recursion limit must be greater or equal than 1");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 return NULL;
1098 }
Victor Stinner50856d52015-10-13 00:11:21 +02001099
1100 /* Issue #25274: When the recursion depth hits the recursion limit in
1101 _Py_CheckRecursiveCall(), the overflowed flag of the thread state is
1102 set to 1 and a RecursionError is raised. The overflowed flag is reset
1103 to 0 when the recursion depth goes below the low-water mark: see
1104 Py_LeaveRecursiveCall().
1105
1106 Reject too low new limit if the current recursion depth is higher than
1107 the new low-water mark. Otherwise it may not be possible anymore to
1108 reset the overflowed flag to 0. */
1109 mark = _Py_RecursionLimitLowerWaterMark(new_limit);
Victor Stinner50b48572018-11-01 01:51:40 +01001110 tstate = _PyThreadState_GET();
Victor Stinner50856d52015-10-13 00:11:21 +02001111 if (tstate->recursion_depth >= mark) {
1112 PyErr_Format(PyExc_RecursionError,
1113 "cannot set the recursion limit to %i at "
1114 "the recursion depth %i: the limit is too low",
1115 new_limit, tstate->recursion_depth);
1116 return NULL;
1117 }
1118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 Py_SetRecursionLimit(new_limit);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001120 Py_RETURN_NONE;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001121}
1122
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001123/*[clinic input]
1124sys.set_coroutine_origin_tracking_depth
1125
1126 depth: int
1127
1128Enable or disable origin tracking for coroutine objects in this thread.
1129
Tal Einatede0b6f2018-12-31 17:12:08 +02001130Coroutine objects will track 'depth' frames of traceback information
1131about where they came from, available in their cr_origin attribute.
1132
1133Set a depth of 0 to disable.
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001134[clinic start generated code]*/
1135
1136static PyObject *
1137sys_set_coroutine_origin_tracking_depth_impl(PyObject *module, int depth)
Tal Einatede0b6f2018-12-31 17:12:08 +02001138/*[clinic end generated code: output=0a2123c1cc6759c5 input=a1d0a05f89d2c426]*/
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001139{
1140 if (depth < 0) {
1141 PyErr_SetString(PyExc_ValueError, "depth must be >= 0");
1142 return NULL;
1143 }
1144 _PyEval_SetCoroutineOriginTrackingDepth(depth);
1145 Py_RETURN_NONE;
1146}
1147
1148/*[clinic input]
1149sys.get_coroutine_origin_tracking_depth -> int
1150
1151Check status of origin tracking for coroutine objects in this thread.
1152[clinic start generated code]*/
1153
1154static int
1155sys_get_coroutine_origin_tracking_depth_impl(PyObject *module)
1156/*[clinic end generated code: output=3699f7be95a3afb8 input=335266a71205b61a]*/
1157{
1158 return _PyEval_GetCoroutineOriginTrackingDepth();
1159}
1160
Yury Selivanoveb636452016-09-08 22:01:51 -07001161static PyTypeObject AsyncGenHooksType;
1162
1163PyDoc_STRVAR(asyncgen_hooks_doc,
1164"asyncgen_hooks\n\
1165\n\
1166A struct sequence providing information about asynhronous\n\
1167generators hooks. The attributes are read only.");
1168
1169static PyStructSequence_Field asyncgen_hooks_fields[] = {
1170 {"firstiter", "Hook to intercept first iteration"},
1171 {"finalizer", "Hook to intercept finalization"},
1172 {0}
1173};
1174
1175static PyStructSequence_Desc asyncgen_hooks_desc = {
1176 "asyncgen_hooks", /* name */
1177 asyncgen_hooks_doc, /* doc */
1178 asyncgen_hooks_fields , /* fields */
1179 2
1180};
1181
Yury Selivanoveb636452016-09-08 22:01:51 -07001182static PyObject *
1183sys_set_asyncgen_hooks(PyObject *self, PyObject *args, PyObject *kw)
1184{
1185 static char *keywords[] = {"firstiter", "finalizer", NULL};
1186 PyObject *firstiter = NULL;
1187 PyObject *finalizer = NULL;
1188
1189 if (!PyArg_ParseTupleAndKeywords(
1190 args, kw, "|OO", keywords,
1191 &firstiter, &finalizer)) {
1192 return NULL;
1193 }
1194
1195 if (finalizer && finalizer != Py_None) {
1196 if (!PyCallable_Check(finalizer)) {
1197 PyErr_Format(PyExc_TypeError,
1198 "callable finalizer expected, got %.50s",
1199 Py_TYPE(finalizer)->tp_name);
1200 return NULL;
1201 }
1202 _PyEval_SetAsyncGenFinalizer(finalizer);
1203 }
1204 else if (finalizer == Py_None) {
1205 _PyEval_SetAsyncGenFinalizer(NULL);
1206 }
1207
1208 if (firstiter && firstiter != Py_None) {
1209 if (!PyCallable_Check(firstiter)) {
1210 PyErr_Format(PyExc_TypeError,
1211 "callable firstiter expected, got %.50s",
1212 Py_TYPE(firstiter)->tp_name);
1213 return NULL;
1214 }
1215 _PyEval_SetAsyncGenFirstiter(firstiter);
1216 }
1217 else if (firstiter == Py_None) {
1218 _PyEval_SetAsyncGenFirstiter(NULL);
1219 }
1220
1221 Py_RETURN_NONE;
1222}
1223
1224PyDoc_STRVAR(set_asyncgen_hooks_doc,
Tal Einatede0b6f2018-12-31 17:12:08 +02001225"set_asyncgen_hooks(* [, firstiter] [, finalizer])\n\
Yury Selivanoveb636452016-09-08 22:01:51 -07001226\n\
1227Set a finalizer for async generators objects."
1228);
1229
Tal Einatede0b6f2018-12-31 17:12:08 +02001230/*[clinic input]
1231sys.get_asyncgen_hooks
1232
1233Return the installed asynchronous generators hooks.
1234
1235This returns a namedtuple of the form (firstiter, finalizer).
1236[clinic start generated code]*/
1237
Yury Selivanoveb636452016-09-08 22:01:51 -07001238static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001239sys_get_asyncgen_hooks_impl(PyObject *module)
1240/*[clinic end generated code: output=53a253707146f6cf input=3676b9ea62b14625]*/
Yury Selivanoveb636452016-09-08 22:01:51 -07001241{
1242 PyObject *res;
1243 PyObject *firstiter = _PyEval_GetAsyncGenFirstiter();
1244 PyObject *finalizer = _PyEval_GetAsyncGenFinalizer();
1245
1246 res = PyStructSequence_New(&AsyncGenHooksType);
1247 if (res == NULL) {
1248 return NULL;
1249 }
1250
1251 if (firstiter == NULL) {
1252 firstiter = Py_None;
1253 }
1254
1255 if (finalizer == NULL) {
1256 finalizer = Py_None;
1257 }
1258
1259 Py_INCREF(firstiter);
1260 PyStructSequence_SET_ITEM(res, 0, firstiter);
1261
1262 Py_INCREF(finalizer);
1263 PyStructSequence_SET_ITEM(res, 1, finalizer);
1264
1265 return res;
1266}
1267
Yury Selivanoveb636452016-09-08 22:01:51 -07001268
Mark Dickinsondc787d22010-05-23 13:33:13 +00001269static PyTypeObject Hash_InfoType;
1270
1271PyDoc_STRVAR(hash_info_doc,
1272"hash_info\n\
1273\n\
1274A struct sequence providing parameters used for computing\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +01001275hashes. The attributes are read only.");
Mark Dickinsondc787d22010-05-23 13:33:13 +00001276
1277static PyStructSequence_Field hash_info_fields[] = {
1278 {"width", "width of the type used for hashing, in bits"},
1279 {"modulus", "prime number giving the modulus on which the hash "
1280 "function is based"},
1281 {"inf", "value to be used for hash of a positive infinity"},
1282 {"nan", "value to be used for hash of a nan"},
1283 {"imag", "multiplier used for the imaginary part of a complex number"},
Christian Heimes985ecdc2013-11-20 11:46:18 +01001284 {"algorithm", "name of the algorithm for hashing of str, bytes and "
1285 "memoryviews"},
1286 {"hash_bits", "internal output size of hash algorithm"},
1287 {"seed_bits", "seed size of hash algorithm"},
1288 {"cutoff", "small string optimization cutoff"},
Mark Dickinsondc787d22010-05-23 13:33:13 +00001289 {NULL, NULL}
1290};
1291
1292static PyStructSequence_Desc hash_info_desc = {
1293 "sys.hash_info",
1294 hash_info_doc,
1295 hash_info_fields,
Christian Heimes985ecdc2013-11-20 11:46:18 +01001296 9,
Mark Dickinsondc787d22010-05-23 13:33:13 +00001297};
1298
Matthias Klosed885e952010-07-06 10:53:30 +00001299static PyObject *
Mark Dickinsondc787d22010-05-23 13:33:13 +00001300get_hash_info(void)
1301{
1302 PyObject *hash_info;
1303 int field = 0;
Christian Heimes985ecdc2013-11-20 11:46:18 +01001304 PyHash_FuncDef *hashfunc;
Mark Dickinsondc787d22010-05-23 13:33:13 +00001305 hash_info = PyStructSequence_New(&Hash_InfoType);
1306 if (hash_info == NULL)
1307 return NULL;
Christian Heimes985ecdc2013-11-20 11:46:18 +01001308 hashfunc = PyHash_GetFuncDef();
Mark Dickinsondc787d22010-05-23 13:33:13 +00001309 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001310 PyLong_FromLong(8*sizeof(Py_hash_t)));
Mark Dickinsondc787d22010-05-23 13:33:13 +00001311 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8035bc52010-10-23 16:20:50 +00001312 PyLong_FromSsize_t(_PyHASH_MODULUS));
Mark Dickinsondc787d22010-05-23 13:33:13 +00001313 PyStructSequence_SET_ITEM(hash_info, field++,
1314 PyLong_FromLong(_PyHASH_INF));
1315 PyStructSequence_SET_ITEM(hash_info, field++,
1316 PyLong_FromLong(_PyHASH_NAN));
1317 PyStructSequence_SET_ITEM(hash_info, field++,
1318 PyLong_FromLong(_PyHASH_IMAG));
Christian Heimes985ecdc2013-11-20 11:46:18 +01001319 PyStructSequence_SET_ITEM(hash_info, field++,
1320 PyUnicode_FromString(hashfunc->name));
1321 PyStructSequence_SET_ITEM(hash_info, field++,
1322 PyLong_FromLong(hashfunc->hash_bits));
1323 PyStructSequence_SET_ITEM(hash_info, field++,
1324 PyLong_FromLong(hashfunc->seed_bits));
1325 PyStructSequence_SET_ITEM(hash_info, field++,
1326 PyLong_FromLong(Py_HASH_CUTOFF));
Mark Dickinsondc787d22010-05-23 13:33:13 +00001327 if (PyErr_Occurred()) {
1328 Py_CLEAR(hash_info);
1329 return NULL;
1330 }
1331 return hash_info;
1332}
Tal Einatede0b6f2018-12-31 17:12:08 +02001333/*[clinic input]
1334sys.getrecursionlimit
Mark Dickinsondc787d22010-05-23 13:33:13 +00001335
Tal Einatede0b6f2018-12-31 17:12:08 +02001336Return the current value of the recursion limit.
Mark Dickinsondc787d22010-05-23 13:33:13 +00001337
Tal Einatede0b6f2018-12-31 17:12:08 +02001338The recursion limit is the maximum depth of the Python interpreter
1339stack. This limit prevents infinite recursion from causing an overflow
1340of the C stack and crashing Python.
1341[clinic start generated code]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001342
1343static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001344sys_getrecursionlimit_impl(PyObject *module)
1345/*[clinic end generated code: output=d571fb6b4549ef2e input=1c6129fd2efaeea8]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001346{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 return PyLong_FromLong(Py_GetRecursionLimit());
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001348}
1349
Mark Hammond8696ebc2002-10-08 02:44:31 +00001350#ifdef MS_WINDOWS
Mark Hammond8696ebc2002-10-08 02:44:31 +00001351
Eric Smithf7bb5782010-01-27 00:44:57 +00001352static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};
1353
1354static PyStructSequence_Field windows_version_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 {"major", "Major version number"},
1356 {"minor", "Minor version number"},
1357 {"build", "Build number"},
1358 {"platform", "Operating system platform"},
1359 {"service_pack", "Latest Service Pack installed on the system"},
1360 {"service_pack_major", "Service Pack major version number"},
1361 {"service_pack_minor", "Service Pack minor version number"},
1362 {"suite_mask", "Bit mask identifying available product suites"},
1363 {"product_type", "System product type"},
Steve Dower74f4af72016-09-17 17:27:48 -07001364 {"platform_version", "Diagnostic version number"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001365 {0}
Eric Smithf7bb5782010-01-27 00:44:57 +00001366};
1367
1368static PyStructSequence_Desc windows_version_desc = {
Tal Einatede0b6f2018-12-31 17:12:08 +02001369 "sys.getwindowsversion", /* name */
1370 sys_getwindowsversion__doc__, /* doc */
1371 windows_version_fields, /* fields */
1372 5 /* For backward compatibility,
1373 only the first 5 items are accessible
1374 via indexing, the rest are name only */
Eric Smithf7bb5782010-01-27 00:44:57 +00001375};
1376
Steve Dower3e96f322015-03-02 08:01:10 -08001377/* Disable deprecation warnings about GetVersionEx as the result is
1378 being passed straight through to the caller, who is responsible for
1379 using it correctly. */
1380#pragma warning(push)
1381#pragma warning(disable:4996)
1382
Tal Einatede0b6f2018-12-31 17:12:08 +02001383/*[clinic input]
1384sys.getwindowsversion
1385
1386Return info about the running version of Windows as a named tuple.
1387
1388The members are named: major, minor, build, platform, service_pack,
1389service_pack_major, service_pack_minor, suite_mask, product_type and
1390platform_version. For backward compatibility, only the first 5 items
1391are available by indexing. All elements are numbers, except
1392service_pack and platform_type which are strings, and platform_version
1393which is a 3-tuple. Platform is always 2. Product_type may be 1 for a
1394workstation, 2 for a domain controller, 3 for a server.
1395Platform_version is a 3-tuple containing a version number that is
1396intended for identifying the OS rather than feature detection.
1397[clinic start generated code]*/
1398
Mark Hammond8696ebc2002-10-08 02:44:31 +00001399static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001400sys_getwindowsversion_impl(PyObject *module)
1401/*[clinic end generated code: output=1ec063280b932857 input=73a228a328fee63a]*/
Mark Hammond8696ebc2002-10-08 02:44:31 +00001402{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 PyObject *version;
1404 int pos = 0;
Minmin Gong8ebc6452019-02-02 20:26:55 -08001405 OSVERSIONINFOEXW ver;
Steve Dower74f4af72016-09-17 17:27:48 -07001406 DWORD realMajor, realMinor, realBuild;
1407 HANDLE hKernel32;
1408 wchar_t kernel32_path[MAX_PATH];
1409 LPVOID verblock;
1410 DWORD verblock_size;
1411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 ver.dwOSVersionInfoSize = sizeof(ver);
Minmin Gong8ebc6452019-02-02 20:26:55 -08001413 if (!GetVersionExW((OSVERSIONINFOW*) &ver))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 return PyErr_SetFromWindowsErr(0);
Eric Smithf7bb5782010-01-27 00:44:57 +00001415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001416 version = PyStructSequence_New(&WindowsVersionType);
1417 if (version == NULL)
1418 return NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +00001419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001420 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion));
1421 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion));
1422 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber));
1423 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId));
Minmin Gong8ebc6452019-02-02 20:26:55 -08001424 PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromWideChar(ver.szCSDVersion, -1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor));
1426 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor));
1427 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask));
1428 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType));
Eric Smithf7bb5782010-01-27 00:44:57 +00001429
Steve Dower74f4af72016-09-17 17:27:48 -07001430 realMajor = ver.dwMajorVersion;
1431 realMinor = ver.dwMinorVersion;
1432 realBuild = ver.dwBuildNumber;
1433
1434 // GetVersion will lie if we are running in a compatibility mode.
1435 // We need to read the version info from a system file resource
1436 // to accurately identify the OS version. If we fail for any reason,
1437 // just return whatever GetVersion said.
Tony Roberts4860f012019-02-02 18:16:42 +01001438 Py_BEGIN_ALLOW_THREADS
Steve Dower74f4af72016-09-17 17:27:48 -07001439 hKernel32 = GetModuleHandleW(L"kernel32.dll");
Tony Roberts4860f012019-02-02 18:16:42 +01001440 Py_END_ALLOW_THREADS
Steve Dower74f4af72016-09-17 17:27:48 -07001441 if (hKernel32 && GetModuleFileNameW(hKernel32, kernel32_path, MAX_PATH) &&
1442 (verblock_size = GetFileVersionInfoSizeW(kernel32_path, NULL)) &&
1443 (verblock = PyMem_RawMalloc(verblock_size))) {
1444 VS_FIXEDFILEINFO *ffi;
1445 UINT ffi_len;
1446
1447 if (GetFileVersionInfoW(kernel32_path, 0, verblock_size, verblock) &&
1448 VerQueryValueW(verblock, L"", (LPVOID)&ffi, &ffi_len)) {
1449 realMajor = HIWORD(ffi->dwProductVersionMS);
1450 realMinor = LOWORD(ffi->dwProductVersionMS);
1451 realBuild = HIWORD(ffi->dwProductVersionLS);
1452 }
1453 PyMem_RawFree(verblock);
1454 }
Segev Finer48fb7662017-06-04 20:52:27 +03001455 PyStructSequence_SET_ITEM(version, pos++, Py_BuildValue("(kkk)",
1456 realMajor,
1457 realMinor,
1458 realBuild
Steve Dower74f4af72016-09-17 17:27:48 -07001459 ));
1460
Serhiy Storchaka48d761e2013-12-17 15:11:24 +02001461 if (PyErr_Occurred()) {
1462 Py_DECREF(version);
1463 return NULL;
1464 }
Steve Dower74f4af72016-09-17 17:27:48 -07001465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001466 return version;
Mark Hammond8696ebc2002-10-08 02:44:31 +00001467}
1468
Steve Dower3e96f322015-03-02 08:01:10 -08001469#pragma warning(pop)
1470
Tal Einatede0b6f2018-12-31 17:12:08 +02001471/*[clinic input]
1472sys._enablelegacywindowsfsencoding
1473
1474Changes the default filesystem encoding to mbcs:replace.
1475
1476This is done for consistency with earlier versions of Python. See PEP
1477529 for more information.
1478
1479This is equivalent to defining the PYTHONLEGACYWINDOWSFSENCODING
1480environment variable before launching Python.
1481[clinic start generated code]*/
Steve Dowercc16be82016-09-08 10:35:16 -07001482
1483static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001484sys__enablelegacywindowsfsencoding_impl(PyObject *module)
1485/*[clinic end generated code: output=f5c3855b45e24fe9 input=2bfa931a20704492]*/
Steve Dowercc16be82016-09-08 10:35:16 -07001486{
Victor Stinner709d23d2019-05-02 14:56:30 -04001487 if (_PyUnicode_EnableLegacyWindowsFSEncoding() < 0) {
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001488 return NULL;
1489 }
Steve Dowercc16be82016-09-08 10:35:16 -07001490 Py_RETURN_NONE;
1491}
1492
Mark Hammond8696ebc2002-10-08 02:44:31 +00001493#endif /* MS_WINDOWS */
1494
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001495#ifdef HAVE_DLOPEN
Tal Einatede0b6f2018-12-31 17:12:08 +02001496
1497/*[clinic input]
1498sys.setdlopenflags
1499
1500 flags as new_val: int
1501 /
1502
1503Set the flags used by the interpreter for dlopen calls.
1504
1505This is used, for example, when the interpreter loads extension
1506modules. Among other things, this will enable a lazy resolving of
1507symbols when importing a module, if called as sys.setdlopenflags(0).
1508To share symbols across extension modules, call as
1509sys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag
1510modules can be found in the os module (RTLD_xxx constants, e.g.
1511os.RTLD_LAZY).
1512[clinic start generated code]*/
1513
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001514static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001515sys_setdlopenflags_impl(PyObject *module, int new_val)
1516/*[clinic end generated code: output=ec918b7fe0a37281 input=4c838211e857a77f]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001517{
Victor Stinnercaba55b2018-08-03 15:33:52 +02001518 PyInterpreterState *interp = _PyInterpreterState_Get();
1519 interp->dlopenflags = new_val;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001520 Py_RETURN_NONE;
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001521}
1522
Tal Einatede0b6f2018-12-31 17:12:08 +02001523
1524/*[clinic input]
1525sys.getdlopenflags
1526
1527Return the current value of the flags that are used for dlopen calls.
1528
1529The flag constants are defined in the os module.
1530[clinic start generated code]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001531
1532static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001533sys_getdlopenflags_impl(PyObject *module)
1534/*[clinic end generated code: output=e92cd1bc5005da6e input=dc4ea0899c53b4b6]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001535{
Victor Stinnercaba55b2018-08-03 15:33:52 +02001536 PyInterpreterState *interp = _PyInterpreterState_Get();
1537 return PyLong_FromLong(interp->dlopenflags);
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001538}
1539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001540#endif /* HAVE_DLOPEN */
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001541
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001542#ifdef USE_MALLOPT
1543/* Link with -lmalloc (or -lmpc) on an SGI */
1544#include <malloc.h>
1545
Tal Einatede0b6f2018-12-31 17:12:08 +02001546/*[clinic input]
1547sys.mdebug
1548
1549 flag: int
1550 /
1551[clinic start generated code]*/
1552
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001553static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001554sys_mdebug_impl(PyObject *module, int flag)
1555/*[clinic end generated code: output=5431d545847c3637 input=151d150ae1636f8a]*/
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001556{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001557 int flag;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 mallopt(M_DEBUG, flag);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001559 Py_RETURN_NONE;
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001560}
1561#endif /* USE_MALLOPT */
1562
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001563size_t
1564_PySys_GetSizeOf(PyObject *o)
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001565{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001566 PyObject *res = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001567 PyObject *method;
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001568 Py_ssize_t size;
Benjamin Petersona5758c02009-05-09 18:15:04 +00001569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 /* Make sure the type is initialized. float gets initialized late */
1571 if (PyType_Ready(Py_TYPE(o)) < 0)
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001572 return (size_t)-1;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001573
Benjamin Petersonce798522012-01-22 11:24:29 -05001574 method = _PyObject_LookupSpecial(o, &PyId___sizeof__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001575 if (method == NULL) {
1576 if (!PyErr_Occurred())
1577 PyErr_Format(PyExc_TypeError,
1578 "Type %.100s doesn't define __sizeof__",
1579 Py_TYPE(o)->tp_name);
1580 }
1581 else {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001582 res = _PyObject_CallNoArg(method);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 Py_DECREF(method);
1584 }
1585
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001586 if (res == NULL)
1587 return (size_t)-1;
1588
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001589 size = PyLong_AsSsize_t(res);
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001590 Py_DECREF(res);
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001591 if (size == -1 && PyErr_Occurred())
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001592 return (size_t)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001593
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001594 if (size < 0) {
1595 PyErr_SetString(PyExc_ValueError, "__sizeof__() should return >= 0");
1596 return (size_t)-1;
1597 }
1598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001599 /* add gc_head size */
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001600 if (PyObject_IS_GC(o))
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001601 return ((size_t)size) + sizeof(PyGC_Head);
1602 return (size_t)size;
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001603}
1604
1605static PyObject *
1606sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
1607{
1608 static char *kwlist[] = {"object", "default", 0};
1609 size_t size;
1610 PyObject *o, *dflt = NULL;
1611
1612 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
1613 kwlist, &o, &dflt))
1614 return NULL;
1615
1616 size = _PySys_GetSizeOf(o);
1617
1618 if (size == (size_t)-1 && PyErr_Occurred()) {
1619 /* Has a default value been given */
1620 if (dflt != NULL && PyErr_ExceptionMatches(PyExc_TypeError)) {
1621 PyErr_Clear();
1622 Py_INCREF(dflt);
1623 return dflt;
1624 }
1625 else
1626 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001627 }
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001628
1629 return PyLong_FromSize_t(size);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001630}
1631
1632PyDoc_STRVAR(getsizeof_doc,
Tal Einatede0b6f2018-12-31 17:12:08 +02001633"getsizeof(object [, default]) -> int\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001634\n\
1635Return the size of object in bytes.");
1636
Tal Einatede0b6f2018-12-31 17:12:08 +02001637/*[clinic input]
1638sys.getrefcount -> Py_ssize_t
1639
1640 object: object
1641 /
1642
1643Return the reference count of object.
1644
1645The count returned is generally one higher than you might expect,
1646because it includes the (temporary) reference as an argument to
1647getrefcount().
1648[clinic start generated code]*/
1649
1650static Py_ssize_t
1651sys_getrefcount_impl(PyObject *module, PyObject *object)
1652/*[clinic end generated code: output=5fd477f2264b85b2 input=bf474efd50a21535]*/
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001653{
Tal Einatede0b6f2018-12-31 17:12:08 +02001654 return object->ob_refcnt;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001655}
1656
Tim Peters4be93d02002-07-07 19:59:50 +00001657#ifdef Py_REF_DEBUG
Tal Einatede0b6f2018-12-31 17:12:08 +02001658/*[clinic input]
1659sys.gettotalrefcount -> Py_ssize_t
1660[clinic start generated code]*/
1661
1662static Py_ssize_t
1663sys_gettotalrefcount_impl(PyObject *module)
1664/*[clinic end generated code: output=4103886cf17c25bc input=53b744faa5d2e4f6]*/
Mark Hammond440d8982000-06-20 08:12:48 +00001665{
Tal Einatede0b6f2018-12-31 17:12:08 +02001666 return _Py_GetRefTotal();
Mark Hammond440d8982000-06-20 08:12:48 +00001667}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001668#endif /* Py_REF_DEBUG */
Mark Hammond440d8982000-06-20 08:12:48 +00001669
Tal Einatede0b6f2018-12-31 17:12:08 +02001670/*[clinic input]
1671sys.getallocatedblocks -> Py_ssize_t
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001672
Tal Einatede0b6f2018-12-31 17:12:08 +02001673Return the number of memory blocks currently allocated.
1674[clinic start generated code]*/
1675
1676static Py_ssize_t
1677sys_getallocatedblocks_impl(PyObject *module)
1678/*[clinic end generated code: output=f0c4e873f0b6dcf7 input=dab13ee346a0673e]*/
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001679{
Tal Einatede0b6f2018-12-31 17:12:08 +02001680 return _Py_GetAllocatedBlocks();
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001681}
1682
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001683#ifdef COUNT_ALLOCS
Tal Einatede0b6f2018-12-31 17:12:08 +02001684/*[clinic input]
1685sys.getcounts
1686[clinic start generated code]*/
1687
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001688static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001689sys_getcounts_impl(PyObject *module)
1690/*[clinic end generated code: output=20df00bc164f43cb input=ad2ec7bda5424953]*/
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001691{
Pablo Galindo49c75a82018-10-28 15:02:17 +00001692 extern PyObject *_Py_get_counts(void);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001693
Pablo Galindo49c75a82018-10-28 15:02:17 +00001694 return _Py_get_counts();
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001695}
1696#endif
1697
Tal Einatede0b6f2018-12-31 17:12:08 +02001698/*[clinic input]
1699sys._getframe
1700
1701 depth: int = 0
1702 /
1703
1704Return a frame object from the call stack.
1705
1706If optional integer depth is given, return the frame object that many
1707calls below the top of the stack. If that is deeper than the call
1708stack, ValueError is raised. The default for depth is zero, returning
1709the frame at the top of the call stack.
1710
1711This function should be used for internal and specialized purposes
1712only.
1713[clinic start generated code]*/
Barry Warsawb6a54d22000-12-06 21:47:46 +00001714
1715static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001716sys__getframe_impl(PyObject *module, int depth)
1717/*[clinic end generated code: output=d438776c04d59804 input=c1be8a6464b11ee5]*/
Barry Warsawb6a54d22000-12-06 21:47:46 +00001718{
Victor Stinner50b48572018-11-01 01:51:40 +01001719 PyFrameObject *f = _PyThreadState_GET()->frame;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001720
Steve Dowerb82e17e2019-05-23 08:45:22 -07001721 if (PySys_Audit("sys._getframe", "O", f) < 0) {
1722 return NULL;
1723 }
1724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 while (depth > 0 && f != NULL) {
1726 f = f->f_back;
1727 --depth;
1728 }
1729 if (f == NULL) {
1730 PyErr_SetString(PyExc_ValueError,
1731 "call stack is not deep enough");
1732 return NULL;
1733 }
1734 Py_INCREF(f);
1735 return (PyObject*)f;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001736}
1737
Tal Einatede0b6f2018-12-31 17:12:08 +02001738/*[clinic input]
1739sys._current_frames
1740
1741Return a dict mapping each thread's thread id to its current stack frame.
1742
1743This function should be used for specialized purposes only.
1744[clinic start generated code]*/
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001745
1746static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001747sys__current_frames_impl(PyObject *module)
1748/*[clinic end generated code: output=d2a41ac0a0a3809a input=2a9049c5f5033691]*/
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001749{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001750 return _PyThread_CurrentFrames();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001751}
1752
Tal Einatede0b6f2018-12-31 17:12:08 +02001753/*[clinic input]
1754sys.call_tracing
1755
1756 func: object
1757 args as funcargs: object(subclass_of='&PyTuple_Type')
1758 /
1759
1760Call func(*args), while tracing is enabled.
1761
1762The tracing state is saved, and restored afterwards. This is intended
1763to be called from a debugger from a checkpoint, to recursively debug
1764some other code.
1765[clinic start generated code]*/
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001766
1767static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001768sys_call_tracing_impl(PyObject *module, PyObject *func, PyObject *funcargs)
1769/*[clinic end generated code: output=7e4999853cd4e5a6 input=5102e8b11049f92f]*/
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001770{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001771 return _PyEval_CallTracing(func, funcargs);
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001772}
1773
Tal Einatede0b6f2018-12-31 17:12:08 +02001774/*[clinic input]
1775sys.callstats
1776
1777Return a tuple of function call statistics.
1778
1779A tuple is returned only if CALL_PROFILE was defined when Python was
1780built. Otherwise, this returns None.
1781
1782When enabled, this function returns detailed, implementation-specific
1783details about the number of function calls executed. The return value
1784is a 11-tuple where the entries in the tuple are counts of:
17850. all function calls
17861. calls to PyFunction_Type objects
17872. PyFunction calls that do not create an argument tuple
17883. PyFunction calls that do not create an argument tuple
1789 and bypass PyEval_EvalCodeEx()
17904. PyMethod calls
17915. PyMethod calls on bound methods
17926. PyType calls
17937. PyCFunction calls
17948. generator calls
17959. All other calls
179610. Number of stack pops performed by call_function()
1797[clinic start generated code]*/
Barry Warsawb6a54d22000-12-06 21:47:46 +00001798
Victor Stinner048afd92016-11-28 11:59:04 +01001799static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001800sys_callstats_impl(PyObject *module)
1801/*[clinic end generated code: output=edc4a74957fa8def input=d447d8d224d5d175]*/
Victor Stinner048afd92016-11-28 11:59:04 +01001802{
1803 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1804 "sys.callstats() has been deprecated in Python 3.7 "
1805 "and will be removed in the future", 1) < 0) {
1806 return NULL;
1807 }
1808
1809 Py_RETURN_NONE;
1810}
1811
1812
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001813#ifdef __cplusplus
1814extern "C" {
1815#endif
1816
Tal Einatede0b6f2018-12-31 17:12:08 +02001817/*[clinic input]
1818sys._debugmallocstats
1819
1820Print summary info to stderr about the state of pymalloc's structures.
1821
1822In Py_DEBUG mode, also perform some expensive internal consistency
1823checks.
1824[clinic start generated code]*/
1825
David Malcolm49526f42012-06-22 14:55:41 -04001826static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001827sys__debugmallocstats_impl(PyObject *module)
1828/*[clinic end generated code: output=ec3565f8c7cee46a input=33c0c9c416f98424]*/
David Malcolm49526f42012-06-22 14:55:41 -04001829{
1830#ifdef WITH_PYMALLOC
Victor Stinner6bf992a2017-12-06 17:26:10 +01001831 if (_PyObject_DebugMallocStats(stderr)) {
Victor Stinner34be8072016-03-14 12:04:26 +01001832 fputc('\n', stderr);
1833 }
David Malcolm49526f42012-06-22 14:55:41 -04001834#endif
1835 _PyObject_DebugTypeStats(stderr);
1836
1837 Py_RETURN_NONE;
1838}
David Malcolm49526f42012-06-22 14:55:41 -04001839
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001840#ifdef Py_TRACE_REFS
Guido van Rossumded690f1996-05-24 20:48:31 +00001841/* Defined in objects.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001842extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001843#endif
Guido van Rossumded690f1996-05-24 20:48:31 +00001844
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001845#ifdef DYNAMIC_EXECUTION_PROFILE
1846/* Defined in ceval.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001847extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001848#endif
1849
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001850#ifdef __cplusplus
1851}
1852#endif
1853
Tal Einatede0b6f2018-12-31 17:12:08 +02001854
1855/*[clinic input]
1856sys._clear_type_cache
1857
1858Clear the internal type lookup cache.
1859[clinic start generated code]*/
1860
Christian Heimes15ebc882008-02-04 18:48:49 +00001861static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001862sys__clear_type_cache_impl(PyObject *module)
1863/*[clinic end generated code: output=20e48ca54a6f6971 input=127f3e04a8d9b555]*/
Christian Heimes15ebc882008-02-04 18:48:49 +00001864{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 PyType_ClearCache();
1866 Py_RETURN_NONE;
Christian Heimes15ebc882008-02-04 18:48:49 +00001867}
1868
Tal Einatede0b6f2018-12-31 17:12:08 +02001869/*[clinic input]
1870sys.is_finalizing
1871
1872Return True if Python is exiting.
1873[clinic start generated code]*/
1874
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001875static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001876sys_is_finalizing_impl(PyObject *module)
1877/*[clinic end generated code: output=735b5ff7962ab281 input=f0df747a039948a5]*/
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001878{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001879 return PyBool_FromLong(_Py_IsFinalizing());
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001880}
1881
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001882#ifdef ANDROID_API_LEVEL
Tal Einatede0b6f2018-12-31 17:12:08 +02001883/*[clinic input]
1884sys.getandroidapilevel
1885
1886Return the build time API version of Android as an integer.
1887[clinic start generated code]*/
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001888
1889static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001890sys_getandroidapilevel_impl(PyObject *module)
1891/*[clinic end generated code: output=214abf183a1c70c1 input=3e6d6c9fcdd24ac6]*/
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001892{
1893 return PyLong_FromLong(ANDROID_API_LEVEL);
1894}
1895#endif /* ANDROID_API_LEVEL */
1896
1897
Steve Dowerb82e17e2019-05-23 08:45:22 -07001898
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001899static PyMethodDef sys_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001900 /* Might as well keep this in alphabetic order */
Steve Dowerb82e17e2019-05-23 08:45:22 -07001901 SYS_ADDAUDITHOOK_METHODDEF
1902 {"audit", (PyCFunction)(void(*)(void))sys_audit, METH_FASTCALL, audit_doc },
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001903 {"breakpointhook", (PyCFunction)(void(*)(void))sys_breakpointhook,
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04001904 METH_FASTCALL | METH_KEYWORDS, breakpointhook_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001905 SYS_CALLSTATS_METHODDEF
1906 SYS__CLEAR_TYPE_CACHE_METHODDEF
1907 SYS__CURRENT_FRAMES_METHODDEF
1908 SYS_DISPLAYHOOK_METHODDEF
1909 SYS_EXC_INFO_METHODDEF
1910 SYS_EXCEPTHOOK_METHODDEF
1911 SYS_EXIT_METHODDEF
1912 SYS_GETDEFAULTENCODING_METHODDEF
1913 SYS_GETDLOPENFLAGS_METHODDEF
1914 SYS_GETALLOCATEDBLOCKS_METHODDEF
1915 SYS_GETCOUNTS_METHODDEF
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001916#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001917 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001918#endif
Tal Einatede0b6f2018-12-31 17:12:08 +02001919 SYS_GETFILESYSTEMENCODING_METHODDEF
1920 SYS_GETFILESYSTEMENCODEERRORS_METHODDEF
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001921#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001922 {"getobjects", _Py_GetObjects, METH_VARARGS},
Tim Peters4be93d02002-07-07 19:59:50 +00001923#endif
Tal Einatede0b6f2018-12-31 17:12:08 +02001924 SYS_GETTOTALREFCOUNT_METHODDEF
1925 SYS_GETREFCOUNT_METHODDEF
1926 SYS_GETRECURSIONLIMIT_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001927 {"getsizeof", (PyCFunction)(void(*)(void))sys_getsizeof,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001928 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001929 SYS__GETFRAME_METHODDEF
1930 SYS_GETWINDOWSVERSION_METHODDEF
1931 SYS__ENABLELEGACYWINDOWSFSENCODING_METHODDEF
1932 SYS_INTERN_METHODDEF
1933 SYS_IS_FINALIZING_METHODDEF
1934 SYS_MDEBUG_METHODDEF
1935 SYS_SETCHECKINTERVAL_METHODDEF
1936 SYS_GETCHECKINTERVAL_METHODDEF
1937 SYS_SETSWITCHINTERVAL_METHODDEF
1938 SYS_GETSWITCHINTERVAL_METHODDEF
1939 SYS_SETDLOPENFLAGS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001940 {"setprofile", sys_setprofile, METH_O, setprofile_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001941 SYS_GETPROFILE_METHODDEF
1942 SYS_SETRECURSIONLIMIT_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001943 {"settrace", sys_settrace, METH_O, settrace_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001944 SYS_GETTRACE_METHODDEF
1945 SYS_CALL_TRACING_METHODDEF
1946 SYS__DEBUGMALLOCSTATS_METHODDEF
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001947 SYS_SET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
1948 SYS_GET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001949 {"set_asyncgen_hooks", (PyCFunction)(void(*)(void))sys_set_asyncgen_hooks,
Yury Selivanoveb636452016-09-08 22:01:51 -07001950 METH_VARARGS | METH_KEYWORDS, set_asyncgen_hooks_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001951 SYS_GET_ASYNCGEN_HOOKS_METHODDEF
1952 SYS_GETANDROIDAPILEVEL_METHODDEF
Victor Stinneref9d9b62019-05-22 11:28:22 +02001953 SYS_UNRAISABLEHOOK_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001954 {NULL, NULL} /* sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +00001955};
1956
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001957static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001958list_builtin_module_names(void)
Guido van Rossum34679b71993-01-26 13:33:44 +00001959{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001960 PyObject *list = PyList_New(0);
1961 int i;
1962 if (list == NULL)
1963 return NULL;
1964 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1965 PyObject *name = PyUnicode_FromString(
1966 PyImport_Inittab[i].name);
1967 if (name == NULL)
1968 break;
1969 PyList_Append(list, name);
1970 Py_DECREF(name);
1971 }
1972 if (PyList_Sort(list) != 0) {
1973 Py_DECREF(list);
1974 list = NULL;
1975 }
1976 if (list) {
1977 PyObject *v = PyList_AsTuple(list);
1978 Py_DECREF(list);
1979 list = v;
1980 }
1981 return list;
Guido van Rossum34679b71993-01-26 13:33:44 +00001982}
1983
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001984/* Pre-initialization support for sys.warnoptions and sys._xoptions
1985 *
1986 * Modern internal code paths:
1987 * These APIs get called after _Py_InitializeCore and get to use the
1988 * regular CPython list, dict, and unicode APIs.
1989 *
1990 * Legacy embedding code paths:
1991 * The multi-phase initialization API isn't public yet, so embedding
1992 * apps still need to be able configure sys.warnoptions and sys._xoptions
1993 * before they call Py_Initialize. To support this, we stash copies of
1994 * the supplied wchar * sequences in linked lists, and then migrate the
1995 * contents of those lists to the sys module in _PyInitializeCore.
1996 *
1997 */
1998
1999struct _preinit_entry {
2000 wchar_t *value;
2001 struct _preinit_entry *next;
2002};
2003
2004typedef struct _preinit_entry *_Py_PreInitEntry;
2005
2006static _Py_PreInitEntry _preinit_warnoptions = NULL;
2007static _Py_PreInitEntry _preinit_xoptions = NULL;
2008
2009static _Py_PreInitEntry
2010_alloc_preinit_entry(const wchar_t *value)
2011{
2012 /* To get this to work, we have to initialize the runtime implicitly */
2013 _PyRuntime_Initialize();
2014
2015 /* Force default allocator, so we can ensure that it also gets used to
2016 * destroy the linked list in _clear_preinit_entries.
2017 */
2018 PyMemAllocatorEx old_alloc;
2019 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2020
2021 _Py_PreInitEntry node = PyMem_RawCalloc(1, sizeof(*node));
2022 if (node != NULL) {
2023 node->value = _PyMem_RawWcsdup(value);
2024 if (node->value == NULL) {
2025 PyMem_RawFree(node);
2026 node = NULL;
2027 };
2028 };
2029
2030 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2031 return node;
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002032}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002033
2034static int
2035_append_preinit_entry(_Py_PreInitEntry *optionlist, const wchar_t *value)
2036{
2037 _Py_PreInitEntry new_entry = _alloc_preinit_entry(value);
2038 if (new_entry == NULL) {
2039 return -1;
2040 }
2041 /* We maintain the linked list in this order so it's easy to play back
2042 * the add commands in the same order later on in _Py_InitializeCore
2043 */
2044 _Py_PreInitEntry last_entry = *optionlist;
2045 if (last_entry == NULL) {
2046 *optionlist = new_entry;
2047 } else {
2048 while (last_entry->next != NULL) {
2049 last_entry = last_entry->next;
2050 }
2051 last_entry->next = new_entry;
2052 }
2053 return 0;
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002054}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002055
2056static void
2057_clear_preinit_entries(_Py_PreInitEntry *optionlist)
2058{
2059 _Py_PreInitEntry current = *optionlist;
2060 *optionlist = NULL;
2061 /* Deallocate the nodes and their contents using the default allocator */
2062 PyMemAllocatorEx old_alloc;
2063 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2064 while (current != NULL) {
2065 _Py_PreInitEntry next = current->next;
2066 PyMem_RawFree(current->value);
2067 PyMem_RawFree(current);
2068 current = next;
2069 }
2070 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002071}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002072
2073static void
2074_clear_all_preinit_options(void)
2075{
2076 _clear_preinit_entries(&_preinit_warnoptions);
2077 _clear_preinit_entries(&_preinit_xoptions);
2078}
2079
2080static int
2081_PySys_ReadPreInitOptions(void)
2082{
2083 /* Rerun the add commands with the actual sys module available */
Victor Stinner50b48572018-11-01 01:51:40 +01002084 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002085 if (tstate == NULL) {
2086 /* Still don't have a thread state, so something is wrong! */
2087 return -1;
2088 }
2089 _Py_PreInitEntry entry = _preinit_warnoptions;
2090 while (entry != NULL) {
2091 PySys_AddWarnOption(entry->value);
2092 entry = entry->next;
2093 }
2094 entry = _preinit_xoptions;
2095 while (entry != NULL) {
2096 PySys_AddXOption(entry->value);
2097 entry = entry->next;
2098 }
2099
2100 _clear_all_preinit_options();
2101 return 0;
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002102}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002103
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002104static PyObject *
2105get_warnoptions(void)
2106{
Eric Snowdae02762017-09-14 00:35:58 -07002107 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002108 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002109 /* PEP432 TODO: we can reach this if warnoptions is NULL in the main
2110 * interpreter config. When that happens, we need to properly set
2111 * the `warnoptions` reference in the main interpreter config as well.
2112 *
2113 * For Python 3.7, we shouldn't be able to get here due to the
2114 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
2115 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
2116 * call optional for embedding applications, thus making this
2117 * reachable again.
2118 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002119 warnoptions = PyList_New(0);
2120 if (warnoptions == NULL)
2121 return NULL;
Eric Snowdae02762017-09-14 00:35:58 -07002122 if (_PySys_SetObjectId(&PyId_warnoptions, warnoptions)) {
2123 Py_DECREF(warnoptions);
2124 return NULL;
2125 }
2126 Py_DECREF(warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002127 }
2128 return warnoptions;
2129}
Guido van Rossum23fff912000-12-15 22:02:05 +00002130
2131void
2132PySys_ResetWarnOptions(void)
2133{
Victor Stinner50b48572018-11-01 01:51:40 +01002134 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002135 if (tstate == NULL) {
2136 _clear_preinit_entries(&_preinit_warnoptions);
2137 return;
2138 }
2139
Eric Snowdae02762017-09-14 00:35:58 -07002140 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 if (warnoptions == NULL || !PyList_Check(warnoptions))
2142 return;
2143 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
Guido van Rossum23fff912000-12-15 22:02:05 +00002144}
2145
Victor Stinnere1b29952018-10-30 14:31:42 +01002146static int
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002147_PySys_AddWarnOptionWithError(PyObject *option)
Guido van Rossum23fff912000-12-15 22:02:05 +00002148{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002149 PyObject *warnoptions = get_warnoptions();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002150 if (warnoptions == NULL) {
2151 return -1;
2152 }
2153 if (PyList_Append(warnoptions, option)) {
2154 return -1;
2155 }
2156 return 0;
2157}
2158
2159void
2160PySys_AddWarnOptionUnicode(PyObject *option)
2161{
Victor Stinnere1b29952018-10-30 14:31:42 +01002162 if (_PySys_AddWarnOptionWithError(option) < 0) {
2163 /* No return value, therefore clear error state if possible */
2164 if (_PyThreadState_UncheckedGet()) {
2165 PyErr_Clear();
2166 }
2167 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00002168}
2169
2170void
2171PySys_AddWarnOption(const wchar_t *s)
2172{
Victor Stinner50b48572018-11-01 01:51:40 +01002173 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002174 if (tstate == NULL) {
2175 _append_preinit_entry(&_preinit_warnoptions, s);
2176 return;
2177 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00002178 PyObject *unicode;
2179 unicode = PyUnicode_FromWideChar(s, -1);
2180 if (unicode == NULL)
2181 return;
2182 PySys_AddWarnOptionUnicode(unicode);
2183 Py_DECREF(unicode);
Guido van Rossum23fff912000-12-15 22:02:05 +00002184}
2185
Christian Heimes33fe8092008-04-13 13:53:33 +00002186int
2187PySys_HasWarnOptions(void)
2188{
Eric Snowdae02762017-09-14 00:35:58 -07002189 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Serhiy Storchakadffccc62018-12-10 13:50:22 +02002190 return (warnoptions != NULL && PyList_Check(warnoptions)
2191 && PyList_GET_SIZE(warnoptions) > 0);
Christian Heimes33fe8092008-04-13 13:53:33 +00002192}
2193
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002194static PyObject *
2195get_xoptions(void)
2196{
Eric Snowdae02762017-09-14 00:35:58 -07002197 PyObject *xoptions = _PySys_GetObjectId(&PyId__xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002198 if (xoptions == NULL || !PyDict_Check(xoptions)) {
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002199 /* PEP432 TODO: we can reach this if xoptions is NULL in the main
2200 * interpreter config. When that happens, we need to properly set
2201 * the `xoptions` reference in the main interpreter config as well.
2202 *
2203 * For Python 3.7, we shouldn't be able to get here due to the
2204 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
2205 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
2206 * call optional for embedding applications, thus making this
2207 * reachable again.
2208 */
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002209 xoptions = PyDict_New();
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002210 if (xoptions == NULL)
2211 return NULL;
Eric Snowdae02762017-09-14 00:35:58 -07002212 if (_PySys_SetObjectId(&PyId__xoptions, xoptions)) {
2213 Py_DECREF(xoptions);
2214 return NULL;
2215 }
2216 Py_DECREF(xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002217 }
2218 return xoptions;
2219}
2220
Victor Stinnere1b29952018-10-30 14:31:42 +01002221static int
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002222_PySys_AddXOptionWithError(const wchar_t *s)
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002223{
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002224 PyObject *name = NULL, *value = NULL;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002225
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002226 PyObject *opts = get_xoptions();
2227 if (opts == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002228 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002229 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002230
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002231 const wchar_t *name_end = wcschr(s, L'=');
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002232 if (!name_end) {
2233 name = PyUnicode_FromWideChar(s, -1);
2234 value = Py_True;
2235 Py_INCREF(value);
2236 }
2237 else {
2238 name = PyUnicode_FromWideChar(s, name_end - s);
2239 value = PyUnicode_FromWideChar(name_end + 1, -1);
2240 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002241 if (name == NULL || value == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002242 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002243 }
2244 if (PyDict_SetItem(opts, name, value) < 0) {
2245 goto error;
2246 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002247 Py_DECREF(name);
2248 Py_DECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002249 return 0;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002250
2251error:
2252 Py_XDECREF(name);
2253 Py_XDECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002254 return -1;
2255}
2256
2257void
2258PySys_AddXOption(const wchar_t *s)
2259{
Victor Stinner50b48572018-11-01 01:51:40 +01002260 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002261 if (tstate == NULL) {
2262 _append_preinit_entry(&_preinit_xoptions, s);
2263 return;
2264 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002265 if (_PySys_AddXOptionWithError(s) < 0) {
2266 /* No return value, therefore clear error state if possible */
2267 if (_PyThreadState_UncheckedGet()) {
2268 PyErr_Clear();
2269 }
Victor Stinner0cae6092016-11-11 01:43:56 +01002270 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002271}
2272
2273PyObject *
2274PySys_GetXOptions(void)
2275{
2276 return get_xoptions();
2277}
2278
Guido van Rossum40552d01998-08-06 03:34:39 +00002279/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
2280 Two literals concatenated works just fine. If you have a K&R compiler
2281 or other abomination that however *does* understand longer strings,
2282 get rid of the !!! comment in the middle and the quotes that surround it. */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002283PyDoc_VAR(sys_doc) =
2284PyDoc_STR(
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002285"This module provides access to some objects used or maintained by the\n\
2286interpreter and to functions that interact strongly with the interpreter.\n\
2287\n\
2288Dynamic objects:\n\
2289\n\
2290argv -- command line arguments; argv[0] is the script pathname if known\n\
2291path -- module search path; path[0] is the script directory, else ''\n\
2292modules -- dictionary of loaded modules\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002293\n\
2294displayhook -- called to show results in an interactive session\n\
2295excepthook -- called to handle any uncaught exception other than SystemExit\n\
2296 To customize printing in an interactive session or to install a custom\n\
2297 top-level exception handler, assign other functions to replace these.\n\
2298\n\
Benjamin Peterson06157a42008-07-15 00:28:36 +00002299stdin -- standard input file object; used by input()\n\
Georg Brandl88fc6642007-02-09 21:28:07 +00002300stdout -- standard output file object; used by print()\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002301stderr -- standard error object; used for error messages\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002302 By assigning other file objects (or objects that behave like files)\n\
2303 to these, it is possible to redirect all of the interpreter's I/O.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002304\n\
2305last_type -- type of last uncaught exception\n\
2306last_value -- value of last uncaught exception\n\
2307last_traceback -- traceback of last uncaught exception\n\
2308 These three are only available in an interactive session after a\n\
2309 traceback has been printed.\n\
Guido van Rossuma71b5f41999-01-14 19:07:00 +00002310"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002311)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002312/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002313PyDoc_STR(
Guido van Rossuma71b5f41999-01-14 19:07:00 +00002314"\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002315Static objects:\n\
2316\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002317builtin_module_names -- tuple of module names built into this interpreter\n\
2318copyright -- copyright notice pertaining to this interpreter\n\
2319exec_prefix -- prefix used to find the machine-specific Python library\n\
Petri Lehtinen4b0eab62012-02-02 21:23:15 +02002320executable -- absolute path of the executable binary of the Python interpreter\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002321float_info -- a struct sequence with information about the float implementation.\n\
2322float_repr_style -- string indicating the style of repr() output for floats\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +01002323hash_info -- a struct sequence with information about the hash algorithm.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002324hexversion -- version information encoded as a single integer\n\
Barry Warsaw409da152012-06-03 16:18:47 -04002325implementation -- Python implementation information.\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00002326int_info -- a struct sequence with information about the int implementation.\n\
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00002327maxsize -- the largest supported length of containers.\n\
Serhiy Storchakad3faf432015-01-18 11:28:37 +02002328maxunicode -- the value of the largest Unicode code point\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002329platform -- platform identifier\n\
2330prefix -- prefix used to find the Python library\n\
2331thread_info -- a struct sequence with information about the thread implementation.\n\
Fred Drake801c08d2000-04-13 15:29:10 +00002332version -- the version of this interpreter as a string\n\
Eric Smith0e5b5622009-02-06 01:32:42 +00002333version_info -- version information as a named tuple\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002334"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002335)
Steve Dowercc16be82016-09-08 10:35:16 -07002336#ifdef MS_COREDLL
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002337/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002338PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002339"dllhandle -- [Windows only] integer handle of the Python DLL\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002340winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002341"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002342)
Steve Dowercc16be82016-09-08 10:35:16 -07002343#endif /* MS_COREDLL */
2344#ifdef MS_WINDOWS
2345/* concatenating string here */
2346PyDoc_STR(
oldkaa0735f2018-02-02 16:52:55 +08002347"_enablelegacywindowsfsencoding -- [Windows only]\n\
Steve Dowercc16be82016-09-08 10:35:16 -07002348"
2349)
2350#endif
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002351PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002352"__stdin__ -- the original stdin; don't touch!\n\
2353__stdout__ -- the original stdout; don't touch!\n\
2354__stderr__ -- the original stderr; don't touch!\n\
2355__displayhook__ -- the original displayhook; don't touch!\n\
2356__excepthook__ -- the original excepthook; don't touch!\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002357\n\
2358Functions:\n\
2359\n\
Georg Brandl1a3284e2007-12-02 09:40:06 +00002360displayhook() -- print an object to the screen, and save it in builtins._\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002361excepthook() -- print an exception and its traceback to sys.stderr\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002362exc_info() -- return thread-safe information about the current exception\n\
2363exit() -- exit the interpreter by raising SystemExit\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002364getdlopenflags() -- returns flags to be used for dlopen() calls\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002365getprofile() -- get the global profiling function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002366getrefcount() -- return the reference count for an object (plus one :-)\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002367getrecursionlimit() -- return the max recursion depth for the interpreter\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002368getsizeof() -- return the size of an object in bytes\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002369gettrace() -- get the global debug tracing function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002370setcheckinterval() -- control how often the interpreter checks for events\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002371setdlopenflags() -- set the flags to be used for dlopen() calls\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002372setprofile() -- set the global profiling function\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002373setrecursionlimit() -- set the max recursion depth for the interpreter\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002374settrace() -- set the global debug tracing function\n\
Fred Drakeccede592000-08-14 20:59:57 +00002375"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002376)
Fred Drakeccede592000-08-14 20:59:57 +00002377/* end of sys_doc */ ;
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002378
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002379
2380PyDoc_STRVAR(flags__doc__,
2381"sys.flags\n\
2382\n\
2383Flags provided through command line arguments or environment vars.");
2384
2385static PyTypeObject FlagsType;
2386
2387static PyStructSequence_Field flags_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 {"debug", "-d"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002389 {"inspect", "-i"},
2390 {"interactive", "-i"},
2391 {"optimize", "-O or -OO"},
2392 {"dont_write_bytecode", "-B"},
2393 {"no_user_site", "-s"},
2394 {"no_site", "-S"},
2395 {"ignore_environment", "-E"},
2396 {"verbose", "-v"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002397 /* {"unbuffered", "-u"}, */
2398 /* {"skip_first", "-x"}, */
Georg Brandl8aa7e992010-12-28 18:30:18 +00002399 {"bytes_warning", "-b"},
2400 {"quiet", "-q"},
Georg Brandl09a7c722012-02-20 21:31:46 +01002401 {"hash_randomization", "-R"},
Christian Heimesad73a9c2013-08-10 16:36:18 +02002402 {"isolated", "-I"},
Victor Stinner5e3806f2017-11-30 11:40:24 +01002403 {"dev_mode", "-X dev"},
Victor Stinner91106cd2017-12-13 12:29:09 +01002404 {"utf8_mode", "-X utf8"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002405 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002406};
2407
2408static PyStructSequence_Desc flags_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002409 "sys.flags", /* name */
2410 flags__doc__, /* doc */
2411 flags_fields, /* fields */
Victor Stinner91106cd2017-12-13 12:29:09 +01002412 15
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002413};
2414
2415static PyObject*
Victor Stinner0fd2c302019-06-04 03:15:09 +02002416make_flags(_PyRuntimeState *runtime, PyInterpreterState *interp)
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002417{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002418 int pos = 0;
2419 PyObject *seq;
Victor Stinner331a6a52019-05-27 16:39:22 +02002420 const PyPreConfig *preconfig = &runtime->preconfig;
2421 const PyConfig *config = &interp->config;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002423 seq = PyStructSequence_New(&FlagsType);
2424 if (seq == NULL)
2425 return NULL;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002426
2427#define SetFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002428 PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002429
Victor Stinnerfbca9082018-08-30 00:50:45 +02002430 SetFlag(config->parser_debug);
2431 SetFlag(config->inspect);
2432 SetFlag(config->interactive);
2433 SetFlag(config->optimization_level);
2434 SetFlag(!config->write_bytecode);
2435 SetFlag(!config->user_site_directory);
2436 SetFlag(!config->site_import);
Victor Stinner20004952019-03-26 02:31:11 +01002437 SetFlag(!config->use_environment);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002438 SetFlag(config->verbose);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002439 /* SetFlag(saw_unbuffered_flag); */
2440 /* SetFlag(skipfirstline); */
Victor Stinnerfbca9082018-08-30 00:50:45 +02002441 SetFlag(config->bytes_warning);
2442 SetFlag(config->quiet);
2443 SetFlag(config->use_hash_seed == 0 || config->hash_seed != 0);
Victor Stinner20004952019-03-26 02:31:11 +01002444 SetFlag(config->isolated);
2445 PyStructSequence_SET_ITEM(seq, pos++, PyBool_FromLong(config->dev_mode));
2446 SetFlag(preconfig->utf8_mode);
Victor Stinner91106cd2017-12-13 12:29:09 +01002447#undef SetFlag
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002449 if (PyErr_Occurred()) {
Serhiy Storchaka87a854d2013-12-17 14:59:42 +02002450 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002451 return NULL;
2452 }
2453 return seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002454}
2455
Eric Smith0e5b5622009-02-06 01:32:42 +00002456PyDoc_STRVAR(version_info__doc__,
2457"sys.version_info\n\
2458\n\
2459Version information as a named tuple.");
2460
2461static PyTypeObject VersionInfoType;
2462
2463static PyStructSequence_Field version_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002464 {"major", "Major release number"},
2465 {"minor", "Minor release number"},
2466 {"micro", "Patch release number"},
Ned Deilyda4887a2016-11-04 17:03:34 -04002467 {"releaselevel", "'alpha', 'beta', 'candidate', or 'final'"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002468 {"serial", "Serial release number"},
2469 {0}
Eric Smith0e5b5622009-02-06 01:32:42 +00002470};
2471
2472static PyStructSequence_Desc version_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002473 "sys.version_info", /* name */
2474 version_info__doc__, /* doc */
2475 version_info_fields, /* fields */
2476 5
Eric Smith0e5b5622009-02-06 01:32:42 +00002477};
2478
2479static PyObject *
2480make_version_info(void)
2481{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002482 PyObject *version_info;
2483 char *s;
2484 int pos = 0;
Eric Smith0e5b5622009-02-06 01:32:42 +00002485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002486 version_info = PyStructSequence_New(&VersionInfoType);
2487 if (version_info == NULL) {
2488 return NULL;
2489 }
Eric Smith0e5b5622009-02-06 01:32:42 +00002490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002491 /*
2492 * These release level checks are mutually exclusive and cover
2493 * the field, so don't get too fancy with the pre-processor!
2494 */
Eric Smith0e5b5622009-02-06 01:32:42 +00002495#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002496 s = "alpha";
Eric Smith0e5b5622009-02-06 01:32:42 +00002497#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002498 s = "beta";
Eric Smith0e5b5622009-02-06 01:32:42 +00002499#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002500 s = "candidate";
Eric Smith0e5b5622009-02-06 01:32:42 +00002501#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002502 s = "final";
Eric Smith0e5b5622009-02-06 01:32:42 +00002503#endif
2504
2505#define SetIntItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002506 PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002507#define SetStrItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002508 PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002510 SetIntItem(PY_MAJOR_VERSION);
2511 SetIntItem(PY_MINOR_VERSION);
2512 SetIntItem(PY_MICRO_VERSION);
2513 SetStrItem(s);
2514 SetIntItem(PY_RELEASE_SERIAL);
Eric Smith0e5b5622009-02-06 01:32:42 +00002515#undef SetIntItem
2516#undef SetStrItem
2517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002518 if (PyErr_Occurred()) {
2519 Py_CLEAR(version_info);
2520 return NULL;
2521 }
2522 return version_info;
Eric Smith0e5b5622009-02-06 01:32:42 +00002523}
2524
Brett Cannon3adc7b72012-07-09 14:22:12 -04002525/* sys.implementation values */
2526#define NAME "cpython"
2527const char *_PySys_ImplName = NAME;
Victor Stinnercf01b682015-11-05 11:21:38 +01002528#define MAJOR Py_STRINGIFY(PY_MAJOR_VERSION)
2529#define MINOR Py_STRINGIFY(PY_MINOR_VERSION)
Ned Deily529ea5d2014-06-30 23:31:14 -07002530#define TAG NAME "-" MAJOR MINOR
Brett Cannon3adc7b72012-07-09 14:22:12 -04002531const char *_PySys_ImplCacheTag = TAG;
2532#undef NAME
Brett Cannon3adc7b72012-07-09 14:22:12 -04002533#undef MAJOR
2534#undef MINOR
2535#undef TAG
2536
Barry Warsaw409da152012-06-03 16:18:47 -04002537static PyObject *
2538make_impl_info(PyObject *version_info)
2539{
2540 int res;
2541 PyObject *impl_info, *value, *ns;
2542
2543 impl_info = PyDict_New();
2544 if (impl_info == NULL)
2545 return NULL;
2546
2547 /* populate the dict */
2548
Brett Cannon3adc7b72012-07-09 14:22:12 -04002549 value = PyUnicode_FromString(_PySys_ImplName);
Barry Warsaw409da152012-06-03 16:18:47 -04002550 if (value == NULL)
2551 goto error;
2552 res = PyDict_SetItemString(impl_info, "name", value);
2553 Py_DECREF(value);
2554 if (res < 0)
2555 goto error;
2556
Brett Cannon3adc7b72012-07-09 14:22:12 -04002557 value = PyUnicode_FromString(_PySys_ImplCacheTag);
Barry Warsaw409da152012-06-03 16:18:47 -04002558 if (value == NULL)
2559 goto error;
2560 res = PyDict_SetItemString(impl_info, "cache_tag", value);
2561 Py_DECREF(value);
2562 if (res < 0)
2563 goto error;
Barry Warsaw409da152012-06-03 16:18:47 -04002564
2565 res = PyDict_SetItemString(impl_info, "version", version_info);
2566 if (res < 0)
2567 goto error;
2568
2569 value = PyLong_FromLong(PY_VERSION_HEX);
2570 if (value == NULL)
2571 goto error;
2572 res = PyDict_SetItemString(impl_info, "hexversion", value);
2573 Py_DECREF(value);
2574 if (res < 0)
2575 goto error;
2576
doko@ubuntu.com55532312016-06-14 08:55:19 +02002577#ifdef MULTIARCH
2578 value = PyUnicode_FromString(MULTIARCH);
2579 if (value == NULL)
2580 goto error;
2581 res = PyDict_SetItemString(impl_info, "_multiarch", value);
2582 Py_DECREF(value);
2583 if (res < 0)
2584 goto error;
2585#endif
2586
Barry Warsaw409da152012-06-03 16:18:47 -04002587 /* dict ready */
2588
2589 ns = _PyNamespace_New(impl_info);
2590 Py_DECREF(impl_info);
2591 return ns;
2592
2593error:
2594 Py_CLEAR(impl_info);
2595 return NULL;
2596}
2597
Martin v. Löwis1a214512008-06-11 05:26:20 +00002598static struct PyModuleDef sysmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002599 PyModuleDef_HEAD_INIT,
2600 "sys",
2601 sys_doc,
2602 -1, /* multiple "initialization" just copies the module dict. */
2603 sys_methods,
2604 NULL,
2605 NULL,
2606 NULL,
2607 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002608};
2609
Eric Snow6b4be192017-05-22 21:36:03 -07002610/* Updating the sys namespace, returning NULL pointer on error */
Victor Stinner8fea2522013-10-27 17:15:42 +01002611#define SET_SYS_FROM_STRING_BORROW(key, value) \
Victor Stinner58049602013-07-22 22:40:00 +02002612 do { \
Victor Stinner58049602013-07-22 22:40:00 +02002613 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002614 if (v == NULL) { \
2615 goto err_occurred; \
2616 } \
Victor Stinner58049602013-07-22 22:40:00 +02002617 res = PyDict_SetItemString(sysdict, key, v); \
2618 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002619 goto err_occurred; \
Victor Stinner8fea2522013-10-27 17:15:42 +01002620 } \
2621 } while (0)
2622#define SET_SYS_FROM_STRING(key, value) \
2623 do { \
Victor Stinner8fea2522013-10-27 17:15:42 +01002624 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002625 if (v == NULL) { \
2626 goto err_occurred; \
2627 } \
Victor Stinner8fea2522013-10-27 17:15:42 +01002628 res = PyDict_SetItemString(sysdict, key, v); \
2629 Py_DECREF(v); \
2630 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002631 goto err_occurred; \
Victor Stinner58049602013-07-22 22:40:00 +02002632 } \
2633 } while (0)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002634
Victor Stinner331a6a52019-05-27 16:39:22 +02002635static PyStatus
Victor Stinner0fd2c302019-06-04 03:15:09 +02002636_PySys_InitCore(_PyRuntimeState *runtime, PyInterpreterState *interp,
2637 PyObject *sysdict)
Eric Snow6b4be192017-05-22 21:36:03 -07002638{
Victor Stinnerab672812019-01-23 15:04:40 +01002639 PyObject *version_info;
Eric Snow6b4be192017-05-22 21:36:03 -07002640 int res;
2641
Nick Coghland6009512014-11-20 21:39:37 +10002642 /* stdin/stdout/stderr are set in pylifecycle.c */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002643
Victor Stinner8fea2522013-10-27 17:15:42 +01002644 SET_SYS_FROM_STRING_BORROW("__displayhook__",
2645 PyDict_GetItemString(sysdict, "displayhook"));
2646 SET_SYS_FROM_STRING_BORROW("__excepthook__",
2647 PyDict_GetItemString(sysdict, "excepthook"));
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04002648 SET_SYS_FROM_STRING_BORROW(
2649 "__breakpointhook__",
2650 PyDict_GetItemString(sysdict, "breakpointhook"));
Victor Stinneref9d9b62019-05-22 11:28:22 +02002651 SET_SYS_FROM_STRING_BORROW("__unraisablehook__",
2652 PyDict_GetItemString(sysdict, "unraisablehook"));
2653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002654 SET_SYS_FROM_STRING("version",
2655 PyUnicode_FromString(Py_GetVersion()));
2656 SET_SYS_FROM_STRING("hexversion",
2657 PyLong_FromLong(PY_VERSION_HEX));
Ned Deily5c4b0d02017-03-04 00:19:55 -05002658 SET_SYS_FROM_STRING("_git",
2659 Py_BuildValue("(szz)", "CPython", _Py_gitidentifier(),
2660 _Py_gitversion()));
INADA Naoki6b42eb12017-06-29 15:31:38 +09002661 SET_SYS_FROM_STRING("_framework", PyUnicode_FromString(_PYTHONFRAMEWORK));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002662 SET_SYS_FROM_STRING("api_version",
2663 PyLong_FromLong(PYTHON_API_VERSION));
2664 SET_SYS_FROM_STRING("copyright",
2665 PyUnicode_FromString(Py_GetCopyright()));
2666 SET_SYS_FROM_STRING("platform",
2667 PyUnicode_FromString(Py_GetPlatform()));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002668 SET_SYS_FROM_STRING("maxsize",
2669 PyLong_FromSsize_t(PY_SSIZE_T_MAX));
2670 SET_SYS_FROM_STRING("float_info",
2671 PyFloat_GetInfo());
2672 SET_SYS_FROM_STRING("int_info",
2673 PyLong_GetInfo());
Mark Dickinsondc787d22010-05-23 13:33:13 +00002674 /* initialize hash_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002675 if (Hash_InfoType.tp_name == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002676 if (PyStructSequence_InitType2(&Hash_InfoType, &hash_info_desc) < 0) {
2677 goto type_init_failed;
2678 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002679 }
Mark Dickinsondc787d22010-05-23 13:33:13 +00002680 SET_SYS_FROM_STRING("hash_info",
2681 get_hash_info());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002682 SET_SYS_FROM_STRING("maxunicode",
Ezio Melotti48a2f8f2011-09-29 00:18:19 +03002683 PyLong_FromLong(0x10FFFF));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002684 SET_SYS_FROM_STRING("builtin_module_names",
2685 list_builtin_module_names());
Christian Heimes743e0cd2012-10-17 23:52:17 +02002686#if PY_BIG_ENDIAN
2687 SET_SYS_FROM_STRING("byteorder",
2688 PyUnicode_FromString("big"));
2689#else
2690 SET_SYS_FROM_STRING("byteorder",
2691 PyUnicode_FromString("little"));
2692#endif
Fred Drake099325e2000-08-14 15:47:03 +00002693
Guido van Rossum8b9ea871996-08-23 18:14:47 +00002694#ifdef MS_COREDLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002695 SET_SYS_FROM_STRING("dllhandle",
2696 PyLong_FromVoidPtr(PyWin_DLLhModule));
2697 SET_SYS_FROM_STRING("winver",
2698 PyUnicode_FromString(PyWin_DLLVersionString));
Guido van Rossumc606fe11996-04-09 02:37:57 +00002699#endif
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00002700#ifdef ABIFLAGS
2701 SET_SYS_FROM_STRING("abiflags",
2702 PyUnicode_FromString(ABIFLAGS));
2703#endif
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002705 /* version_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002706 if (VersionInfoType.tp_name == NULL) {
2707 if (PyStructSequence_InitType2(&VersionInfoType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002708 &version_info_desc) < 0) {
2709 goto type_init_failed;
2710 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002711 }
Barry Warsaw409da152012-06-03 16:18:47 -04002712 version_info = make_version_info();
2713 SET_SYS_FROM_STRING("version_info", version_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002714 /* prevent user from creating new instances */
2715 VersionInfoType.tp_init = NULL;
2716 VersionInfoType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002717 res = PyDict_DelItemString(VersionInfoType.tp_dict, "__new__");
2718 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
2719 PyErr_Clear();
Eric Smith0e5b5622009-02-06 01:32:42 +00002720
Barry Warsaw409da152012-06-03 16:18:47 -04002721 /* implementation */
2722 SET_SYS_FROM_STRING("implementation", make_impl_info(version_info));
2723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002724 /* flags */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002725 if (FlagsType.tp_name == 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002726 if (PyStructSequence_InitType2(&FlagsType, &flags_desc) < 0) {
2727 goto type_init_failed;
2728 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002729 }
Victor Stinner43125222019-04-24 18:23:53 +02002730 /* Set flags to their default values (updated by _PySys_InitMain()) */
Victor Stinner0fd2c302019-06-04 03:15:09 +02002731 SET_SYS_FROM_STRING("flags", make_flags(runtime, interp));
Eric Smithf7bb5782010-01-27 00:44:57 +00002732
2733#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002734 /* getwindowsversion */
2735 if (WindowsVersionType.tp_name == 0)
Victor Stinner1c8f0592013-07-22 22:24:54 +02002736 if (PyStructSequence_InitType2(&WindowsVersionType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002737 &windows_version_desc) < 0) {
2738 goto type_init_failed;
2739 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002740 /* prevent user from creating new instances */
2741 WindowsVersionType.tp_init = NULL;
2742 WindowsVersionType.tp_new = NULL;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002743 assert(!PyErr_Occurred());
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002744 res = PyDict_DelItemString(WindowsVersionType.tp_dict, "__new__");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002745 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError)) {
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002746 PyErr_Clear();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002747 }
Eric Smithf7bb5782010-01-27 00:44:57 +00002748#endif
2749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002750 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002751#ifndef PY_NO_SHORT_FLOAT_REPR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002752 SET_SYS_FROM_STRING("float_repr_style",
2753 PyUnicode_FromString("short"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002754#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002755 SET_SYS_FROM_STRING("float_repr_style",
2756 PyUnicode_FromString("legacy"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002757#endif
2758
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002759 SET_SYS_FROM_STRING("thread_info", PyThread_GetInfo());
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002760
Yury Selivanoveb636452016-09-08 22:01:51 -07002761 /* initialize asyncgen_hooks */
2762 if (AsyncGenHooksType.tp_name == NULL) {
2763 if (PyStructSequence_InitType2(
2764 &AsyncGenHooksType, &asyncgen_hooks_desc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002765 goto type_init_failed;
Yury Selivanoveb636452016-09-08 22:01:51 -07002766 }
2767 }
2768
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002769 if (PyErr_Occurred()) {
2770 goto err_occurred;
2771 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002772 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002773
2774type_init_failed:
Victor Stinner331a6a52019-05-27 16:39:22 +02002775 return _PyStatus_ERR("failed to initialize a type");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002776
2777err_occurred:
Victor Stinner331a6a52019-05-27 16:39:22 +02002778 return _PyStatus_ERR("can't initialize sys module");
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002779}
2780
Eric Snow6b4be192017-05-22 21:36:03 -07002781#undef SET_SYS_FROM_STRING
Eric Snow6b4be192017-05-22 21:36:03 -07002782
2783/* Updating the sys namespace, returning integer error codes */
Eric Snow6b4be192017-05-22 21:36:03 -07002784#define SET_SYS_FROM_STRING_INT_RESULT(key, value) \
2785 do { \
2786 PyObject *v = (value); \
2787 if (v == NULL) \
2788 return -1; \
2789 res = PyDict_SetItemString(sysdict, key, v); \
2790 Py_DECREF(v); \
2791 if (res < 0) { \
2792 return res; \
2793 } \
2794 } while (0)
2795
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002796
2797static int
2798sys_add_xoption(PyObject *opts, const wchar_t *s)
2799{
2800 PyObject *name, *value;
2801
2802 const wchar_t *name_end = wcschr(s, L'=');
2803 if (!name_end) {
2804 name = PyUnicode_FromWideChar(s, -1);
2805 value = Py_True;
2806 Py_INCREF(value);
2807 }
2808 else {
2809 name = PyUnicode_FromWideChar(s, name_end - s);
2810 value = PyUnicode_FromWideChar(name_end + 1, -1);
2811 }
2812 if (name == NULL || value == NULL) {
2813 goto error;
2814 }
2815 if (PyDict_SetItem(opts, name, value) < 0) {
2816 goto error;
2817 }
2818 Py_DECREF(name);
2819 Py_DECREF(value);
2820 return 0;
2821
2822error:
2823 Py_XDECREF(name);
2824 Py_XDECREF(value);
2825 return -1;
2826}
2827
2828
2829static PyObject*
Victor Stinner331a6a52019-05-27 16:39:22 +02002830sys_create_xoptions_dict(const PyConfig *config)
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002831{
2832 Py_ssize_t nxoption = config->xoptions.length;
2833 wchar_t * const * xoptions = config->xoptions.items;
2834 PyObject *dict = PyDict_New();
2835 if (dict == NULL) {
2836 return NULL;
2837 }
2838
2839 for (Py_ssize_t i=0; i < nxoption; i++) {
2840 const wchar_t *option = xoptions[i];
2841 if (sys_add_xoption(dict, option) < 0) {
2842 Py_DECREF(dict);
2843 return NULL;
2844 }
2845 }
2846
2847 return dict;
2848}
2849
2850
Eric Snow6b4be192017-05-22 21:36:03 -07002851int
Victor Stinner0fd2c302019-06-04 03:15:09 +02002852_PySys_InitMain(_PyRuntimeState *runtime, PyInterpreterState *interp)
Eric Snow6b4be192017-05-22 21:36:03 -07002853{
Victor Stinnerab672812019-01-23 15:04:40 +01002854 PyObject *sysdict = interp->sysdict;
Victor Stinner331a6a52019-05-27 16:39:22 +02002855 const PyConfig *config = &interp->config;
Eric Snow6b4be192017-05-22 21:36:03 -07002856 int res;
2857
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002858#define COPY_LIST(KEY, VALUE) \
Victor Stinner37cd9822018-11-16 11:55:35 +01002859 do { \
Victor Stinner331a6a52019-05-27 16:39:22 +02002860 PyObject *list = _PyWideStringList_AsList(&(VALUE)); \
Victor Stinner37cd9822018-11-16 11:55:35 +01002861 if (list == NULL) { \
2862 return -1; \
2863 } \
2864 SET_SYS_FROM_STRING_BORROW(KEY, list); \
2865 Py_DECREF(list); \
2866 } while (0)
2867
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002868#define SET_SYS_FROM_WSTR(KEY, VALUE) \
2869 do { \
2870 PyObject *str = PyUnicode_FromWideChar(VALUE, -1); \
2871 if (str == NULL) { \
2872 return -1; \
2873 } \
2874 SET_SYS_FROM_STRING_BORROW(KEY, str); \
2875 Py_DECREF(str); \
2876 } while (0)
Victor Stinner37cd9822018-11-16 11:55:35 +01002877
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002878 COPY_LIST("path", config->module_search_paths);
2879
2880 SET_SYS_FROM_WSTR("executable", config->executable);
2881 SET_SYS_FROM_WSTR("prefix", config->prefix);
2882 SET_SYS_FROM_WSTR("base_prefix", config->base_prefix);
2883 SET_SYS_FROM_WSTR("exec_prefix", config->exec_prefix);
2884 SET_SYS_FROM_WSTR("base_exec_prefix", config->base_exec_prefix);
Victor Stinner41264f12017-12-15 02:05:29 +01002885
Carl Meyerb193fa92018-06-15 22:40:56 -06002886 if (config->pycache_prefix != NULL) {
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002887 SET_SYS_FROM_WSTR("pycache_prefix", config->pycache_prefix);
Carl Meyerb193fa92018-06-15 22:40:56 -06002888 } else {
2889 PyDict_SetItemString(sysdict, "pycache_prefix", Py_None);
2890 }
2891
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002892 COPY_LIST("argv", config->argv);
2893 COPY_LIST("warnoptions", config->warnoptions);
2894
2895 PyObject *xoptions = sys_create_xoptions_dict(config);
2896 if (xoptions == NULL) {
2897 return -1;
Victor Stinner41264f12017-12-15 02:05:29 +01002898 }
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002899 SET_SYS_FROM_STRING_BORROW("_xoptions", xoptions);
Pablo Galindo34ef64f2019-03-27 12:43:47 +00002900 Py_DECREF(xoptions);
Victor Stinner41264f12017-12-15 02:05:29 +01002901
Victor Stinner37cd9822018-11-16 11:55:35 +01002902#undef COPY_LIST
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002903#undef SET_SYS_FROM_WSTR
Victor Stinner37cd9822018-11-16 11:55:35 +01002904
Eric Snow6b4be192017-05-22 21:36:03 -07002905 /* Set flags to their final values */
Victor Stinner0fd2c302019-06-04 03:15:09 +02002906 SET_SYS_FROM_STRING_INT_RESULT("flags", make_flags(runtime, interp));
Eric Snow6b4be192017-05-22 21:36:03 -07002907 /* prevent user from creating new instances */
2908 FlagsType.tp_init = NULL;
2909 FlagsType.tp_new = NULL;
2910 res = PyDict_DelItemString(FlagsType.tp_dict, "__new__");
2911 if (res < 0) {
2912 if (!PyErr_ExceptionMatches(PyExc_KeyError)) {
2913 return res;
2914 }
2915 PyErr_Clear();
2916 }
2917
2918 SET_SYS_FROM_STRING_INT_RESULT("dont_write_bytecode",
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002919 PyBool_FromLong(!config->write_bytecode));
Eric Snow6b4be192017-05-22 21:36:03 -07002920
Eric Snowdae02762017-09-14 00:35:58 -07002921 if (get_warnoptions() == NULL)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002922 return -1;
Victor Stinner865de272017-06-08 13:27:47 +02002923
Eric Snowdae02762017-09-14 00:35:58 -07002924 if (get_xoptions() == NULL)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002925 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002926
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002927 /* Transfer any sys.warnoptions and sys._xoptions set directly
2928 * by an embedding application from the linked list to the module. */
2929 if (_PySys_ReadPreInitOptions() != 0)
2930 return -1;
2931
Eric Snow6b4be192017-05-22 21:36:03 -07002932 if (PyErr_Occurred())
2933 return -1;
2934 return 0;
Victor Stinner41264f12017-12-15 02:05:29 +01002935
2936err_occurred:
2937 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002938}
2939
Victor Stinner41264f12017-12-15 02:05:29 +01002940#undef SET_SYS_FROM_STRING_BORROW
Eric Snow6b4be192017-05-22 21:36:03 -07002941#undef SET_SYS_FROM_STRING_INT_RESULT
Eric Snow6b4be192017-05-22 21:36:03 -07002942
Victor Stinnerab672812019-01-23 15:04:40 +01002943
2944/* Set up a preliminary stderr printer until we have enough
2945 infrastructure for the io module in place.
2946
2947 Use UTF-8/surrogateescape and ignore EAGAIN errors. */
Victor Stinner331a6a52019-05-27 16:39:22 +02002948PyStatus
Victor Stinnerab672812019-01-23 15:04:40 +01002949_PySys_SetPreliminaryStderr(PyObject *sysdict)
2950{
2951 PyObject *pstderr = PyFile_NewStdPrinter(fileno(stderr));
2952 if (pstderr == NULL) {
2953 goto error;
2954 }
2955 if (_PyDict_SetItemId(sysdict, &PyId_stderr, pstderr) < 0) {
2956 goto error;
2957 }
2958 if (PyDict_SetItemString(sysdict, "__stderr__", pstderr) < 0) {
2959 goto error;
2960 }
2961 Py_DECREF(pstderr);
Victor Stinner331a6a52019-05-27 16:39:22 +02002962 return _PyStatus_OK();
Victor Stinnerab672812019-01-23 15:04:40 +01002963
2964error:
2965 Py_XDECREF(pstderr);
Victor Stinner331a6a52019-05-27 16:39:22 +02002966 return _PyStatus_ERR("can't set preliminary stderr");
Victor Stinnerab672812019-01-23 15:04:40 +01002967}
2968
2969
2970/* Create sys module without all attributes: _PySys_InitMain() should be called
2971 later to add remaining attributes. */
Victor Stinner331a6a52019-05-27 16:39:22 +02002972PyStatus
Victor Stinner0fd2c302019-06-04 03:15:09 +02002973_PySys_Create(_PyRuntimeState *runtime, PyInterpreterState *interp,
2974 PyObject **sysmod_p)
Victor Stinnerab672812019-01-23 15:04:40 +01002975{
2976 PyObject *modules = PyDict_New();
2977 if (modules == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002978 return _PyStatus_ERR("can't make modules dictionary");
Victor Stinnerab672812019-01-23 15:04:40 +01002979 }
2980 interp->modules = modules;
2981
2982 PyObject *sysmod = _PyModule_CreateInitialized(&sysmodule, PYTHON_API_VERSION);
2983 if (sysmod == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002984 return _PyStatus_ERR("failed to create a module object");
Victor Stinnerab672812019-01-23 15:04:40 +01002985 }
2986
2987 PyObject *sysdict = PyModule_GetDict(sysmod);
2988 if (sysdict == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002989 return _PyStatus_ERR("can't initialize sys dict");
Victor Stinnerab672812019-01-23 15:04:40 +01002990 }
2991 Py_INCREF(sysdict);
2992 interp->sysdict = sysdict;
2993
2994 if (PyDict_SetItemString(sysdict, "modules", interp->modules) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002995 return _PyStatus_ERR("can't initialize sys module");
Victor Stinnerab672812019-01-23 15:04:40 +01002996 }
2997
Victor Stinner331a6a52019-05-27 16:39:22 +02002998 PyStatus status = _PySys_SetPreliminaryStderr(sysdict);
2999 if (_PyStatus_EXCEPTION(status)) {
3000 return status;
Victor Stinnerab672812019-01-23 15:04:40 +01003001 }
3002
Victor Stinner0fd2c302019-06-04 03:15:09 +02003003 status = _PySys_InitCore(runtime, interp, sysdict);
Victor Stinner331a6a52019-05-27 16:39:22 +02003004 if (_PyStatus_EXCEPTION(status)) {
3005 return status;
Victor Stinnerab672812019-01-23 15:04:40 +01003006 }
3007
3008 _PyImport_FixupBuiltin(sysmod, "sys", interp->modules);
3009
3010 *sysmod_p = sysmod;
Victor Stinner331a6a52019-05-27 16:39:22 +02003011 return _PyStatus_OK();
Victor Stinnerab672812019-01-23 15:04:40 +01003012}
3013
3014
Guido van Rossum65bf9f21997-04-29 18:33:38 +00003015static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00003016makepathobject(const wchar_t *path, wchar_t delim)
Guido van Rossum5b3138b1990-11-18 17:41:40 +00003017{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003018 int i, n;
3019 const wchar_t *p;
3020 PyObject *v, *w;
Tim Peters216b78b2006-01-06 02:40:53 +00003021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003022 n = 1;
3023 p = path;
3024 while ((p = wcschr(p, delim)) != NULL) {
3025 n++;
3026 p++;
3027 }
3028 v = PyList_New(n);
3029 if (v == NULL)
3030 return NULL;
3031 for (i = 0; ; i++) {
3032 p = wcschr(path, delim);
3033 if (p == NULL)
3034 p = path + wcslen(path); /* End of string */
3035 w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
3036 if (w == NULL) {
3037 Py_DECREF(v);
3038 return NULL;
3039 }
Zackery Spytz99d56b52018-12-08 07:16:55 -07003040 PyList_SET_ITEM(v, i, w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003041 if (*p == '\0')
3042 break;
3043 path = p+1;
3044 }
3045 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003046}
3047
3048void
Martin v. Löwis790465f2008-04-05 20:41:37 +00003049PySys_SetPath(const wchar_t *path)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003050{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003051 PyObject *v;
3052 if ((v = makepathobject(path, DELIM)) == NULL)
3053 Py_FatalError("can't create sys.path");
Victor Stinnerbd303c12013-11-07 23:07:29 +01003054 if (_PySys_SetObjectId(&PyId_path, v) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003055 Py_FatalError("can't assign sys.path");
3056 Py_DECREF(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00003057}
3058
Guido van Rossum65bf9f21997-04-29 18:33:38 +00003059static PyObject *
Victor Stinner74f65682019-03-15 15:08:05 +01003060make_sys_argv(int argc, wchar_t * const * argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00003061{
Victor Stinner74f65682019-03-15 15:08:05 +01003062 PyObject *list = PyList_New(argc);
3063 if (list == NULL) {
3064 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003065 }
Victor Stinner74f65682019-03-15 15:08:05 +01003066
3067 for (Py_ssize_t i = 0; i < argc; i++) {
3068 PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
3069 if (v == NULL) {
3070 Py_DECREF(list);
3071 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003072 }
Victor Stinner74f65682019-03-15 15:08:05 +01003073 PyList_SET_ITEM(list, i, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003074 }
Victor Stinner74f65682019-03-15 15:08:05 +01003075 return list;
Guido van Rossum3f5da241990-12-20 15:06:42 +00003076}
3077
Victor Stinner11a247d2017-12-13 21:05:57 +01003078void
3079PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
Victor Stinnerd5dda982017-12-13 17:31:16 +01003080{
Victor Stinner74f65682019-03-15 15:08:05 +01003081 if (argc < 1 || argv == NULL) {
3082 /* Ensure at least one (empty) argument is seen */
3083 wchar_t* empty_argv[1] = {L""};
3084 argv = empty_argv;
3085 argc = 1;
3086 }
3087
3088 PyObject *av = make_sys_argv(argc, argv);
Victor Stinnerd5dda982017-12-13 17:31:16 +01003089 if (av == NULL) {
Victor Stinner11a247d2017-12-13 21:05:57 +01003090 Py_FatalError("no mem for sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01003091 }
3092 if (PySys_SetObject("argv", av) != 0) {
3093 Py_DECREF(av);
Victor Stinner11a247d2017-12-13 21:05:57 +01003094 Py_FatalError("can't assign sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01003095 }
3096 Py_DECREF(av);
3097
3098 if (updatepath) {
3099 /* If argv[0] is not '-c' nor '-m', prepend argv[0] to sys.path.
3100 If argv[0] is a symlink, use the real path. */
Victor Stinner331a6a52019-05-27 16:39:22 +02003101 const PyWideStringList argv_list = {.length = argc, .items = argv};
Victor Stinnerdcf61712019-03-19 16:09:27 +01003102 PyObject *path0 = NULL;
3103 if (_PyPathConfig_ComputeSysPath0(&argv_list, &path0)) {
3104 if (path0 == NULL) {
3105 Py_FatalError("can't compute path0 from argv");
Victor Stinner11a247d2017-12-13 21:05:57 +01003106 }
Victor Stinnerdcf61712019-03-19 16:09:27 +01003107
3108 PyObject *sys_path = _PySys_GetObjectId(&PyId_path);
3109 if (sys_path != NULL) {
3110 if (PyList_Insert(sys_path, 0, path0) < 0) {
3111 Py_DECREF(path0);
3112 Py_FatalError("can't prepend path0 to sys.path");
3113 }
3114 }
3115 Py_DECREF(path0);
Victor Stinner11a247d2017-12-13 21:05:57 +01003116 }
Victor Stinnerd5dda982017-12-13 17:31:16 +01003117 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003118}
Guido van Rossuma890e681998-05-12 14:59:24 +00003119
Antoine Pitrouf978fac2010-05-21 17:25:34 +00003120void
3121PySys_SetArgv(int argc, wchar_t **argv)
3122{
Christian Heimesad73a9c2013-08-10 16:36:18 +02003123 PySys_SetArgvEx(argc, argv, Py_IsolatedFlag == 0);
Antoine Pitrouf978fac2010-05-21 17:25:34 +00003124}
3125
Victor Stinner14284c22010-04-23 12:02:30 +00003126/* Reimplementation of PyFile_WriteString() no calling indirectly
3127 PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
3128
3129static int
Victor Stinner79766632010-08-16 17:36:42 +00003130sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
Victor Stinner14284c22010-04-23 12:02:30 +00003131{
Victor Stinnerc3ccaae2016-08-20 01:24:22 +02003132 PyObject *writer = NULL, *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003133 int err;
Victor Stinner14284c22010-04-23 12:02:30 +00003134
Victor Stinnerecccc4f2010-06-08 20:46:00 +00003135 if (file == NULL)
3136 return -1;
3137
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003138 writer = _PyObject_GetAttrId(file, &PyId_write);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003139 if (writer == NULL)
3140 goto error;
Victor Stinner14284c22010-04-23 12:02:30 +00003141
Victor Stinner7bfb42d2016-12-05 17:04:32 +01003142 result = PyObject_CallFunctionObjArgs(writer, unicode, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003143 if (result == NULL) {
3144 goto error;
3145 } else {
3146 err = 0;
3147 goto finally;
3148 }
Victor Stinner14284c22010-04-23 12:02:30 +00003149
3150error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003151 err = -1;
Victor Stinner14284c22010-04-23 12:02:30 +00003152finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003153 Py_XDECREF(writer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003154 Py_XDECREF(result);
3155 return err;
Victor Stinner14284c22010-04-23 12:02:30 +00003156}
3157
Victor Stinner79766632010-08-16 17:36:42 +00003158static int
3159sys_pyfile_write(const char *text, PyObject *file)
3160{
3161 PyObject *unicode = NULL;
3162 int err;
3163
3164 if (file == NULL)
3165 return -1;
3166
3167 unicode = PyUnicode_FromString(text);
3168 if (unicode == NULL)
3169 return -1;
3170
3171 err = sys_pyfile_write_unicode(unicode, file);
3172 Py_DECREF(unicode);
3173 return err;
3174}
Guido van Rossuma890e681998-05-12 14:59:24 +00003175
3176/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
3177 Adapted from code submitted by Just van Rossum.
3178
3179 PySys_WriteStdout(format, ...)
3180 PySys_WriteStderr(format, ...)
3181
3182 The first function writes to sys.stdout; the second to sys.stderr. When
3183 there is a problem, they write to the real (C level) stdout or stderr;
Guido van Rossum8442af31998-10-12 18:22:10 +00003184 no exceptions are raised.
Guido van Rossuma890e681998-05-12 14:59:24 +00003185
Victor Stinner14284c22010-04-23 12:02:30 +00003186 PyErr_CheckSignals() is not called to avoid the execution of the Python
Victor Stinner79766632010-08-16 17:36:42 +00003187 signal handlers: they may raise a new exception whereas sys_write()
3188 ignores all exceptions.
Victor Stinner14284c22010-04-23 12:02:30 +00003189
Guido van Rossuma890e681998-05-12 14:59:24 +00003190 Both take a printf-style format string as their first argument followed
3191 by a variable length argument list determined by the format string.
3192
3193 *** WARNING ***
3194
3195 The format should limit the total size of the formatted output string to
3196 1000 bytes. In particular, this means that no unrestricted "%s" formats
3197 should occur; these should be limited using "%.<N>s where <N> is a
3198 decimal number calculated so that <N> plus the maximum size of other
3199 formatted text does not exceed 1000 bytes. Also watch out for "%f",
3200 which can print hundreds of digits for very large numbers.
3201
3202 */
3203
3204static void
Victor Stinner09054372013-11-06 22:41:44 +01003205sys_write(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Guido van Rossuma890e681998-05-12 14:59:24 +00003206{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003207 PyObject *file;
3208 PyObject *error_type, *error_value, *error_traceback;
3209 char buffer[1001];
3210 int written;
Guido van Rossuma890e681998-05-12 14:59:24 +00003211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003212 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01003213 file = _PySys_GetObjectId(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003214 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
3215 if (sys_pyfile_write(buffer, file) != 0) {
3216 PyErr_Clear();
3217 fputs(buffer, fp);
3218 }
3219 if (written < 0 || (size_t)written >= sizeof(buffer)) {
3220 const char *truncated = "... truncated";
Victor Stinner79766632010-08-16 17:36:42 +00003221 if (sys_pyfile_write(truncated, file) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003222 fputs(truncated, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003223 }
3224 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossuma890e681998-05-12 14:59:24 +00003225}
3226
3227void
Guido van Rossuma890e681998-05-12 14:59:24 +00003228PySys_WriteStdout(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00003229{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003230 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00003231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003232 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003233 sys_write(&PyId_stdout, stdout, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003234 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00003235}
3236
3237void
Guido van Rossuma890e681998-05-12 14:59:24 +00003238PySys_WriteStderr(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00003239{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003240 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00003241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003242 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003243 sys_write(&PyId_stderr, stderr, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00003244 va_end(va);
3245}
3246
3247static void
Victor Stinner09054372013-11-06 22:41:44 +01003248sys_format(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Victor Stinner79766632010-08-16 17:36:42 +00003249{
3250 PyObject *file, *message;
3251 PyObject *error_type, *error_value, *error_traceback;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02003252 const char *utf8;
Victor Stinner79766632010-08-16 17:36:42 +00003253
3254 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01003255 file = _PySys_GetObjectId(key);
Victor Stinner79766632010-08-16 17:36:42 +00003256 message = PyUnicode_FromFormatV(format, va);
3257 if (message != NULL) {
3258 if (sys_pyfile_write_unicode(message, file) != 0) {
3259 PyErr_Clear();
Serhiy Storchaka06515832016-11-20 09:13:07 +02003260 utf8 = PyUnicode_AsUTF8(message);
Victor Stinner79766632010-08-16 17:36:42 +00003261 if (utf8 != NULL)
3262 fputs(utf8, fp);
3263 }
3264 Py_DECREF(message);
3265 }
3266 PyErr_Restore(error_type, error_value, error_traceback);
3267}
3268
3269void
3270PySys_FormatStdout(const char *format, ...)
3271{
3272 va_list va;
3273
3274 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003275 sys_format(&PyId_stdout, stdout, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00003276 va_end(va);
3277}
3278
3279void
3280PySys_FormatStderr(const char *format, ...)
3281{
3282 va_list va;
3283
3284 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003285 sys_format(&PyId_stderr, stderr, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003286 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00003287}