blob: 97bff94d8b4196fc3447072ddb24e28fa06fead6 [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 }
Eric Snow396e0a82019-05-31 21:16:47 -0600123 PyInterpreterState *is = ts->interp;
124 _PyRuntimeState *runtime = is->runtime;
125 return runtime->audit_hook_head
Steve Dowerb82e17e2019-05-23 08:45:22 -0700126 || (is && is->audit_hooks)
127 || PyDTrace_AUDIT_ENABLED();
128}
129
130int
131PySys_Audit(const char *event, const char *argFormat, ...)
132{
133 PyObject *eventName = NULL;
134 PyObject *eventArgs = NULL;
135 PyObject *hooks = NULL;
136 PyObject *hook = NULL;
137 int res = -1;
138
139 /* N format is inappropriate, because you do not know
140 whether the reference is consumed by the call.
141 Assert rather than exception for perf reasons */
142 assert(!argFormat || !strchr(argFormat, 'N'));
143
144 /* Early exit when no hooks are registered */
145 if (!should_audit()) {
146 return 0;
147 }
148
149 _Py_AuditHookEntry *e = _PyRuntime.audit_hook_head;
150 PyThreadState *ts = _PyThreadState_GET();
151 PyInterpreterState *is = ts ? ts->interp : NULL;
152 int dtrace = PyDTrace_AUDIT_ENABLED();
153
154 PyObject *exc_type, *exc_value, *exc_tb;
155 if (ts) {
156 PyErr_Fetch(&exc_type, &exc_value, &exc_tb);
157 }
158
159 /* Initialize event args now */
160 if (argFormat && argFormat[0]) {
161 va_list args;
162 va_start(args, argFormat);
163 eventArgs = Py_VaBuildValue(argFormat, args);
164 if (eventArgs && !PyTuple_Check(eventArgs)) {
165 PyObject *argTuple = PyTuple_Pack(1, eventArgs);
166 Py_DECREF(eventArgs);
167 eventArgs = argTuple;
168 }
169 } else {
170 eventArgs = PyTuple_New(0);
171 }
172 if (!eventArgs) {
173 goto exit;
174 }
175
176 /* Call global hooks */
177 for (; e; e = e->next) {
178 if (e->hookCFunction(event, eventArgs, e->userData) < 0) {
179 goto exit;
180 }
181 }
182
183 /* Dtrace USDT point */
184 if (dtrace) {
185 PyDTrace_AUDIT(event, (void *)eventArgs);
186 }
187
188 /* Call interpreter hooks */
189 if (is && is->audit_hooks) {
190 eventName = PyUnicode_FromString(event);
191 if (!eventName) {
192 goto exit;
193 }
194
195 hooks = PyObject_GetIter(is->audit_hooks);
196 if (!hooks) {
197 goto exit;
198 }
199
200 /* Disallow tracing in hooks unless explicitly enabled */
201 ts->tracing++;
202 ts->use_tracing = 0;
203 while ((hook = PyIter_Next(hooks)) != NULL) {
204 PyObject *o;
205 int canTrace = -1;
206 o = PyObject_GetAttrString(hook, "__cantrace__");
207 if (o) {
208 canTrace = PyObject_IsTrue(o);
209 Py_DECREF(o);
210 } else if (PyErr_Occurred() &&
211 PyErr_ExceptionMatches(PyExc_AttributeError)) {
212 PyErr_Clear();
213 canTrace = 0;
214 }
215 if (canTrace < 0) {
216 break;
217 }
218 if (canTrace) {
219 ts->use_tracing = (ts->c_tracefunc || ts->c_profilefunc);
220 ts->tracing--;
221 }
222 o = PyObject_CallFunctionObjArgs(hook, eventName,
223 eventArgs, NULL);
224 if (canTrace) {
225 ts->tracing++;
226 ts->use_tracing = 0;
227 }
228 if (!o) {
229 break;
230 }
231 Py_DECREF(o);
232 Py_CLEAR(hook);
233 }
234 ts->use_tracing = (ts->c_tracefunc || ts->c_profilefunc);
235 ts->tracing--;
236 if (PyErr_Occurred()) {
237 goto exit;
238 }
239 }
240
241 res = 0;
242
243exit:
244 Py_XDECREF(hook);
245 Py_XDECREF(hooks);
246 Py_XDECREF(eventName);
247 Py_XDECREF(eventArgs);
248
249 if (ts) {
250 if (!res) {
251 PyErr_Restore(exc_type, exc_value, exc_tb);
252 } else {
253 assert(PyErr_Occurred());
254 Py_XDECREF(exc_type);
255 Py_XDECREF(exc_value);
256 Py_XDECREF(exc_tb);
257 }
258 }
259
260 return res;
261}
262
263/* We expose this function primarily for our own cleanup during
264 * finalization. In general, it should not need to be called,
265 * and as such it is not defined in any header files.
266 */
267void _PySys_ClearAuditHooks(void) {
268 /* Must be finalizing to clear hooks */
269 _PyRuntimeState *runtime = &_PyRuntime;
270 PyThreadState *ts = _PyRuntimeState_GetThreadState(runtime);
271 assert(!ts || _Py_CURRENTLY_FINALIZING(runtime, ts));
272 if (!ts || !_Py_CURRENTLY_FINALIZING(runtime, ts))
273 return;
274
275 if (Py_VerboseFlag) {
276 PySys_WriteStderr("# clear sys.audit hooks\n");
277 }
278
279 /* Hooks can abort later hooks for this event, but cannot
280 abort the clear operation itself. */
281 PySys_Audit("cpython._PySys_ClearAuditHooks", NULL);
282 PyErr_Clear();
283
Eric Snow396e0a82019-05-31 21:16:47 -0600284 _Py_AuditHookEntry *e = runtime->audit_hook_head, *n;
285 runtime->audit_hook_head = NULL;
Steve Dowerb82e17e2019-05-23 08:45:22 -0700286 while (e) {
287 n = e->next;
288 PyMem_RawFree(e);
289 e = n;
290 }
291}
292
293int
294PySys_AddAuditHook(Py_AuditHookFunction hook, void *userData)
295{
Eric Snow396e0a82019-05-31 21:16:47 -0600296 _PyRuntimeState *runtime = &_PyRuntime;
Steve Dowerb82e17e2019-05-23 08:45:22 -0700297 /* Invoke existing audit hooks to allow them an opportunity to abort. */
298 /* Cannot invoke hooks until we are initialized */
299 if (Py_IsInitialized()) {
300 if (PySys_Audit("sys.addaudithook", NULL) < 0) {
301 if (PyErr_ExceptionMatches(PyExc_Exception)) {
302 /* We do not report errors derived from Exception */
303 PyErr_Clear();
304 return 0;
305 }
306 return -1;
307 }
308 }
309
Eric Snow396e0a82019-05-31 21:16:47 -0600310 _Py_AuditHookEntry *e = runtime->audit_hook_head;
Steve Dowerb82e17e2019-05-23 08:45:22 -0700311 if (!e) {
312 e = (_Py_AuditHookEntry*)PyMem_RawMalloc(sizeof(_Py_AuditHookEntry));
Eric Snow396e0a82019-05-31 21:16:47 -0600313 runtime->audit_hook_head = e;
Steve Dowerb82e17e2019-05-23 08:45:22 -0700314 } else {
315 while (e->next)
316 e = e->next;
317 e = e->next = (_Py_AuditHookEntry*)PyMem_RawMalloc(
318 sizeof(_Py_AuditHookEntry));
319 }
320
321 if (!e) {
322 if (Py_IsInitialized())
323 PyErr_NoMemory();
324 return -1;
325 }
326
327 e->next = NULL;
328 e->hookCFunction = (Py_AuditHookFunction)hook;
329 e->userData = userData;
330
331 return 0;
332}
333
334/*[clinic input]
335sys.addaudithook
336
337 hook: object
338
339Adds a new audit hook callback.
340[clinic start generated code]*/
341
342static PyObject *
343sys_addaudithook_impl(PyObject *module, PyObject *hook)
344/*[clinic end generated code: output=4f9c17aaeb02f44e input=0f3e191217a45e34]*/
345{
346 /* Invoke existing audit hooks to allow them an opportunity to abort. */
347 if (PySys_Audit("sys.addaudithook", NULL) < 0) {
348 if (PyErr_ExceptionMatches(PyExc_Exception)) {
349 /* We do not report errors derived from Exception */
350 PyErr_Clear();
351 Py_RETURN_NONE;
352 }
353 return NULL;
354 }
355
356 PyInterpreterState *is = _PyInterpreterState_Get();
357
358 if (is->audit_hooks == NULL) {
359 is->audit_hooks = PyList_New(0);
360 if (is->audit_hooks == NULL) {
361 return NULL;
362 }
363 }
364
365 if (PyList_Append(is->audit_hooks, hook) < 0) {
366 return NULL;
367 }
368
369 Py_RETURN_NONE;
370}
371
372PyDoc_STRVAR(audit_doc,
373"audit(event, *args)\n\
374\n\
375Passes the event to any audit hooks that are attached.");
376
377static PyObject *
378sys_audit(PyObject *self, PyObject *const *args, Py_ssize_t argc)
379{
380 if (argc == 0) {
381 PyErr_SetString(PyExc_TypeError, "audit() missing 1 required positional argument: 'event'");
382 return NULL;
383 }
384
385 if (!should_audit()) {
386 Py_RETURN_NONE;
387 }
388
389 PyObject *auditEvent = args[0];
390 if (!auditEvent) {
391 PyErr_SetString(PyExc_TypeError, "expected str for argument 'event'");
392 return NULL;
393 }
394 if (!PyUnicode_Check(auditEvent)) {
395 PyErr_Format(PyExc_TypeError, "expected str for argument 'event', not %.200s",
396 Py_TYPE(auditEvent)->tp_name);
397 return NULL;
398 }
399 const char *event = PyUnicode_AsUTF8(auditEvent);
400 if (!event) {
401 return NULL;
402 }
403
404 PyObject *auditArgs = _PyTuple_FromArray(args + 1, argc - 1);
405 if (!auditArgs) {
406 return NULL;
407 }
408
409 int res = PySys_Audit(event, "O", auditArgs);
410 Py_DECREF(auditArgs);
411
412 if (res < 0) {
413 return NULL;
414 }
415
416 Py_RETURN_NONE;
417}
418
419
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400420static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +0200421sys_breakpointhook(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *keywords)
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400422{
423 assert(!PyErr_Occurred());
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300424 char *envar = Py_GETENV("PYTHONBREAKPOINT");
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400425
426 if (envar == NULL || strlen(envar) == 0) {
427 envar = "pdb.set_trace";
428 }
429 else if (!strcmp(envar, "0")) {
430 /* The breakpoint is explicitly no-op'd. */
431 Py_RETURN_NONE;
432 }
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300433 /* According to POSIX the string returned by getenv() might be invalidated
434 * or the string content might be overwritten by a subsequent call to
435 * getenv(). Since importing a module can performs the getenv() calls,
436 * we need to save a copy of envar. */
437 envar = _PyMem_RawStrdup(envar);
438 if (envar == NULL) {
439 PyErr_NoMemory();
440 return NULL;
441 }
Serhiy Storchaka4ae06c52017-12-12 13:55:04 +0200442 const char *last_dot = strrchr(envar, '.');
443 const char *attrname = NULL;
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400444 PyObject *modulepath = NULL;
445
446 if (last_dot == NULL) {
447 /* The breakpoint is a built-in, e.g. PYTHONBREAKPOINT=int */
448 modulepath = PyUnicode_FromString("builtins");
449 attrname = envar;
450 }
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200451 else if (last_dot != envar) {
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400452 /* Split on the last dot; */
453 modulepath = PyUnicode_FromStringAndSize(envar, last_dot - envar);
454 attrname = last_dot + 1;
455 }
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200456 else {
457 goto warn;
458 }
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400459 if (modulepath == NULL) {
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300460 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400461 return NULL;
462 }
463
Anthony Sottiledce345c2018-11-01 10:25:05 -0700464 PyObject *module = PyImport_Import(modulepath);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400465 Py_DECREF(modulepath);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400466
467 if (module == NULL) {
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200468 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
469 goto warn;
470 }
471 PyMem_RawFree(envar);
472 return NULL;
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400473 }
474
475 PyObject *hook = PyObject_GetAttrString(module, attrname);
476 Py_DECREF(module);
477
478 if (hook == NULL) {
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200479 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
480 goto warn;
481 }
482 PyMem_RawFree(envar);
483 return NULL;
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400484 }
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300485 PyMem_RawFree(envar);
Jeroen Demeyeraacc77f2019-05-29 20:31:52 +0200486 PyObject *retval = _PyObject_Vectorcall(hook, args, nargs, keywords);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400487 Py_DECREF(hook);
488 return retval;
489
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200490 warn:
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400491 /* If any of the imports went wrong, then warn and ignore. */
492 PyErr_Clear();
493 int status = PyErr_WarnFormat(
494 PyExc_RuntimeWarning, 0,
495 "Ignoring unimportable $PYTHONBREAKPOINT: \"%s\"", envar);
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300496 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400497 if (status < 0) {
498 /* Printing the warning raised an exception. */
499 return NULL;
500 }
501 /* The warning was (probably) issued. */
502 Py_RETURN_NONE;
503}
504
505PyDoc_STRVAR(breakpointhook_doc,
506"breakpointhook(*args, **kws)\n"
507"\n"
508"This hook function is called by built-in breakpoint().\n"
509);
510
Victor Stinner13d49ee2010-12-04 17:24:33 +0000511/* Write repr(o) to sys.stdout using sys.stdout.encoding and 'backslashreplace'
512 error handler. If sys.stdout has a buffer attribute, use
513 sys.stdout.buffer.write(encoded), otherwise redecode the string and use
514 sys.stdout.write(redecoded).
515
516 Helper function for sys_displayhook(). */
517static int
518sys_displayhook_unencodable(PyObject *outf, PyObject *o)
519{
520 PyObject *stdout_encoding = NULL;
521 PyObject *encoded, *escaped_str, *repr_str, *buffer, *result;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200522 const char *stdout_encoding_str;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000523 int ret;
524
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200525 stdout_encoding = _PyObject_GetAttrId(outf, &PyId_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000526 if (stdout_encoding == NULL)
527 goto error;
Serhiy Storchaka06515832016-11-20 09:13:07 +0200528 stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000529 if (stdout_encoding_str == NULL)
530 goto error;
531
532 repr_str = PyObject_Repr(o);
533 if (repr_str == NULL)
534 goto error;
535 encoded = PyUnicode_AsEncodedString(repr_str,
536 stdout_encoding_str,
537 "backslashreplace");
538 Py_DECREF(repr_str);
539 if (encoded == NULL)
540 goto error;
541
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200542 buffer = _PyObject_GetAttrId(outf, &PyId_buffer);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000543 if (buffer) {
Victor Stinner7e425412016-12-09 00:36:19 +0100544 result = _PyObject_CallMethodIdObjArgs(buffer, &PyId_write, encoded, NULL);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000545 Py_DECREF(buffer);
546 Py_DECREF(encoded);
547 if (result == NULL)
548 goto error;
549 Py_DECREF(result);
550 }
551 else {
552 PyErr_Clear();
553 escaped_str = PyUnicode_FromEncodedObject(encoded,
554 stdout_encoding_str,
555 "strict");
556 Py_DECREF(encoded);
557 if (PyFile_WriteObject(escaped_str, outf, Py_PRINT_RAW) != 0) {
558 Py_DECREF(escaped_str);
559 goto error;
560 }
561 Py_DECREF(escaped_str);
562 }
563 ret = 0;
564 goto finally;
565
566error:
567 ret = -1;
568finally:
569 Py_XDECREF(stdout_encoding);
570 return ret;
571}
572
Tal Einatede0b6f2018-12-31 17:12:08 +0200573/*[clinic input]
574sys.displayhook
575
576 object as o: object
577 /
578
579Print an object to sys.stdout and also save it in builtins._
580[clinic start generated code]*/
581
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000582static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200583sys_displayhook(PyObject *module, PyObject *o)
584/*[clinic end generated code: output=347477d006df92ed input=08ba730166d7ef72]*/
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000585{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 PyObject *outf;
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100587 PyObject *builtins;
588 static PyObject *newline = NULL;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000589 int err;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000590
Eric Snow3f9eee62017-09-15 16:35:20 -0600591 builtins = _PyImport_GetModuleId(&PyId_builtins);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 if (builtins == NULL) {
Stefan Krah027b09c2019-03-25 21:50:58 +0100593 if (!PyErr_Occurred()) {
594 PyErr_SetString(PyExc_RuntimeError, "lost builtins module");
595 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 return NULL;
597 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600598 Py_DECREF(builtins);
Moshe Zadka03897ea2001-07-23 13:32:43 +0000599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000600 /* Print value except if None */
601 /* After printing, also assign to '_' */
602 /* Before, set '_' to None to avoid recursion */
603 if (o == Py_None) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200604 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000605 }
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200606 if (_PyObject_SetAttrId(builtins, &PyId__, Py_None) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 return NULL;
Victor Stinnerbd303c12013-11-07 23:07:29 +0100608 outf = _PySys_GetObjectId(&PyId_stdout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 if (outf == NULL || outf == Py_None) {
610 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
611 return NULL;
612 }
Victor Stinner13d49ee2010-12-04 17:24:33 +0000613 if (PyFile_WriteObject(o, outf, 0) != 0) {
614 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
615 /* repr(o) is not encodable to sys.stdout.encoding with
616 * sys.stdout.errors error handler (which is probably 'strict') */
617 PyErr_Clear();
618 err = sys_displayhook_unencodable(outf, o);
619 if (err)
620 return NULL;
621 }
622 else {
623 return NULL;
624 }
625 }
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100626 if (newline == NULL) {
627 newline = PyUnicode_FromString("\n");
628 if (newline == NULL)
629 return NULL;
630 }
631 if (PyFile_WriteObject(newline, outf, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 return NULL;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200633 if (_PyObject_SetAttrId(builtins, &PyId__, o) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200635 Py_RETURN_NONE;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000636}
637
Tal Einatede0b6f2018-12-31 17:12:08 +0200638
639/*[clinic input]
640sys.excepthook
641
642 exctype: object
643 value: object
644 traceback: object
645 /
646
647Handle an exception by displaying it with a traceback on sys.stderr.
648[clinic start generated code]*/
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000649
650static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200651sys_excepthook_impl(PyObject *module, PyObject *exctype, PyObject *value,
652 PyObject *traceback)
653/*[clinic end generated code: output=18d99fdda21b6b5e input=ecf606fa826f19d9]*/
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000654{
Tal Einatede0b6f2018-12-31 17:12:08 +0200655 PyErr_Display(exctype, value, traceback);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200656 Py_RETURN_NONE;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000657}
658
Tal Einatede0b6f2018-12-31 17:12:08 +0200659
660/*[clinic input]
661sys.exc_info
662
663Return current exception information: (type, value, traceback).
664
665Return information about the most recent exception caught by an except
666clause in the current stack frame or in an older stack frame.
667[clinic start generated code]*/
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000668
669static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200670sys_exc_info_impl(PyObject *module)
671/*[clinic end generated code: output=3afd0940cf3a4d30 input=b5c5bf077788a3e5]*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000672{
Victor Stinner50b48572018-11-01 01:51:40 +0100673 _PyErr_StackItem *err_info = _PyErr_GetTopmostException(_PyThreadState_GET());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 return Py_BuildValue(
675 "(OOO)",
Mark Shannonae3087c2017-10-22 22:41:51 +0100676 err_info->exc_type != NULL ? err_info->exc_type : Py_None,
677 err_info->exc_value != NULL ? err_info->exc_value : Py_None,
678 err_info->exc_traceback != NULL ?
679 err_info->exc_traceback : Py_None);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000680}
681
Tal Einatede0b6f2018-12-31 17:12:08 +0200682
683/*[clinic input]
Victor Stinneref9d9b62019-05-22 11:28:22 +0200684sys.unraisablehook
685
686 unraisable: object
687 /
688
689Handle an unraisable exception.
690
691The unraisable argument has the following attributes:
692
693* exc_type: Exception type.
Victor Stinner71c52e32019-05-27 08:57:14 +0200694* exc_value: Exception value, can be None.
695* exc_traceback: Exception traceback, can be None.
696* err_msg: Error message, can be None.
697* object: Object causing the exception, can be None.
Victor Stinneref9d9b62019-05-22 11:28:22 +0200698[clinic start generated code]*/
699
700static PyObject *
701sys_unraisablehook(PyObject *module, PyObject *unraisable)
Victor Stinner71c52e32019-05-27 08:57:14 +0200702/*[clinic end generated code: output=bb92838b32abaa14 input=ec3af148294af8d3]*/
Victor Stinneref9d9b62019-05-22 11:28:22 +0200703{
704 return _PyErr_WriteUnraisableDefaultHook(unraisable);
705}
706
707
708/*[clinic input]
Tal Einatede0b6f2018-12-31 17:12:08 +0200709sys.exit
710
711 status: object = NULL
712 /
713
714Exit the interpreter by raising SystemExit(status).
715
716If the status is omitted or None, it defaults to zero (i.e., success).
717If the status is an integer, it will be used as the system exit status.
718If it is another kind of object, it will be printed and the system
719exit status will be one (i.e., failure).
720[clinic start generated code]*/
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000721
722static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200723sys_exit_impl(PyObject *module, PyObject *status)
724/*[clinic end generated code: output=13870986c1ab2ec0 input=a737351f86685e9c]*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000725{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 /* Raise SystemExit so callers may catch it or clean up. */
Tal Einatede0b6f2018-12-31 17:12:08 +0200727 PyErr_SetObject(PyExc_SystemExit, status);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000728 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000729}
730
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000731
Martin v. Löwis107b7da2001-11-09 20:59:39 +0000732
Tal Einatede0b6f2018-12-31 17:12:08 +0200733/*[clinic input]
734sys.getdefaultencoding
735
736Return the current default encoding used by the Unicode implementation.
737[clinic start generated code]*/
738
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000739static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200740sys_getdefaultencoding_impl(PyObject *module)
741/*[clinic end generated code: output=256d19dfcc0711e6 input=d416856ddbef6909]*/
Fred Drake8b4d01d2000-05-09 19:57:01 +0000742{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 return PyUnicode_FromString(PyUnicode_GetDefaultEncoding());
Fred Drake8b4d01d2000-05-09 19:57:01 +0000744}
745
Tal Einatede0b6f2018-12-31 17:12:08 +0200746/*[clinic input]
747sys.getfilesystemencoding
748
749Return the encoding used to convert Unicode filenames to OS filenames.
750[clinic start generated code]*/
Fred Drake8b4d01d2000-05-09 19:57:01 +0000751
752static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200753sys_getfilesystemencoding_impl(PyObject *module)
754/*[clinic end generated code: output=1dc4bdbe9be44aa7 input=8475f8649b8c7d8c]*/
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000755{
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200756 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Victor Stinner331a6a52019-05-27 16:39:22 +0200757 const PyConfig *config = &interp->config;
Victor Stinner709d23d2019-05-02 14:56:30 -0400758 return PyUnicode_FromWideChar(config->filesystem_encoding, -1);
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000759}
760
Tal Einatede0b6f2018-12-31 17:12:08 +0200761/*[clinic input]
762sys.getfilesystemencodeerrors
763
764Return the error mode used Unicode to OS filename conversion.
765[clinic start generated code]*/
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000766
Martin v. Löwis04dc25c2008-10-03 16:09:28 +0000767static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200768sys_getfilesystemencodeerrors_impl(PyObject *module)
769/*[clinic end generated code: output=ba77b36bbf7c96f5 input=22a1e8365566f1e5]*/
Steve Dowercc16be82016-09-08 10:35:16 -0700770{
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200771 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Victor Stinner331a6a52019-05-27 16:39:22 +0200772 const PyConfig *config = &interp->config;
Victor Stinner709d23d2019-05-02 14:56:30 -0400773 return PyUnicode_FromWideChar(config->filesystem_errors, -1);
Steve Dowercc16be82016-09-08 10:35:16 -0700774}
775
Tal Einatede0b6f2018-12-31 17:12:08 +0200776/*[clinic input]
777sys.intern
778
779 string as s: unicode
780 /
781
782``Intern'' the given string.
783
784This enters the string in the (global) table of interned strings whose
785purpose is to speed up dictionary lookups. Return the string itself or
786the previously interned string object with the same value.
787[clinic start generated code]*/
Steve Dowercc16be82016-09-08 10:35:16 -0700788
789static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200790sys_intern_impl(PyObject *module, PyObject *s)
791/*[clinic end generated code: output=be680c24f5c9e5d6 input=849483c006924e2f]*/
Georg Brandl66a796e2006-12-19 20:50:34 +0000792{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 if (PyUnicode_CheckExact(s)) {
794 Py_INCREF(s);
795 PyUnicode_InternInPlace(&s);
796 return s;
797 }
798 else {
799 PyErr_Format(PyExc_TypeError,
Tal Einatede0b6f2018-12-31 17:12:08 +0200800 "can't intern %.400s", s->ob_type->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000801 return NULL;
802 }
Georg Brandl66a796e2006-12-19 20:50:34 +0000803}
804
Georg Brandl66a796e2006-12-19 20:50:34 +0000805
Fred Drake5755ce62001-06-27 19:19:46 +0000806/*
807 * Cached interned string objects used for calling the profile and
808 * trace functions. Initialized by trace_init().
809 */
Nick Coghlan5a851672017-09-08 10:14:16 +1000810static PyObject *whatstrings[8] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
Fred Drake5755ce62001-06-27 19:19:46 +0000811
812static int
813trace_init(void)
814{
Nick Coghlan5a851672017-09-08 10:14:16 +1000815 static const char * const whatnames[8] = {
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200816 "call", "exception", "line", "return",
Nick Coghlan5a851672017-09-08 10:14:16 +1000817 "c_call", "c_exception", "c_return",
818 "opcode"
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200819 };
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 PyObject *name;
821 int i;
Nick Coghlan5a851672017-09-08 10:14:16 +1000822 for (i = 0; i < 8; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 if (whatstrings[i] == NULL) {
824 name = PyUnicode_InternFromString(whatnames[i]);
825 if (name == NULL)
826 return -1;
827 whatstrings[i] = name;
828 }
829 }
830 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000831}
832
833
834static PyObject *
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100835call_trampoline(PyObject* callback,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 PyFrameObject *frame, int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000837{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 PyObject *result;
Victor Stinner78da82b2016-08-20 01:22:57 +0200839 PyObject *stack[3];
Fred Drake5755ce62001-06-27 19:19:46 +0000840
Victor Stinner78da82b2016-08-20 01:22:57 +0200841 if (PyFrame_FastToLocalsWithError(frame) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000842 return NULL;
Victor Stinner78da82b2016-08-20 01:22:57 +0200843 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100844
Victor Stinner78da82b2016-08-20 01:22:57 +0200845 stack[0] = (PyObject *)frame;
846 stack[1] = whatstrings[what];
847 stack[2] = (arg != NULL) ? arg : Py_None;
Fred Drake5755ce62001-06-27 19:19:46 +0000848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 /* call the Python-level function */
Victor Stinner559bb6a2016-08-22 22:48:54 +0200850 result = _PyObject_FastCall(callback, stack, 3);
Fred Drake5755ce62001-06-27 19:19:46 +0000851
Victor Stinner78da82b2016-08-20 01:22:57 +0200852 PyFrame_LocalsToFast(frame, 1);
853 if (result == NULL) {
854 PyTraceBack_Here(frame);
855 }
856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000857 return result;
Fred Drake5755ce62001-06-27 19:19:46 +0000858}
859
860static int
861profile_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000863{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 if (arg == NULL)
867 arg = Py_None;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100868 result = call_trampoline(self, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 if (result == NULL) {
870 PyEval_SetProfile(NULL, NULL);
871 return -1;
872 }
873 Py_DECREF(result);
874 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000875}
876
877static int
878trace_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000880{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 PyObject *callback;
882 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 if (what == PyTrace_CALL)
885 callback = self;
886 else
887 callback = frame->f_trace;
888 if (callback == NULL)
889 return 0;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100890 result = call_trampoline(callback, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 if (result == NULL) {
892 PyEval_SetTrace(NULL, NULL);
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200893 Py_CLEAR(frame->f_trace);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 return -1;
895 }
896 if (result != Py_None) {
Serhiy Storchakaec397562016-04-06 09:50:03 +0300897 Py_XSETREF(frame->f_trace, result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 }
899 else {
900 Py_DECREF(result);
901 }
902 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000903}
Fred Draked0838392001-06-16 21:02:31 +0000904
Fred Drake8b4d01d2000-05-09 19:57:01 +0000905static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000906sys_settrace(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000907{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 if (trace_init() == -1)
909 return NULL;
910 if (args == Py_None)
911 PyEval_SetTrace(NULL, NULL);
912 else
913 PyEval_SetTrace(trace_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200914 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000915}
916
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000917PyDoc_STRVAR(settrace_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000918"settrace(function)\n\
919\n\
920Set the global debug tracing function. It will be called on each\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000921function call. See the debugger chapter in the library manual."
922);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000923
Tal Einatede0b6f2018-12-31 17:12:08 +0200924/*[clinic input]
925sys.gettrace
926
927Return the global debug tracing function set with sys.settrace.
928
929See the debugger chapter in the library manual.
930[clinic start generated code]*/
931
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000932static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200933sys_gettrace_impl(PyObject *module)
934/*[clinic end generated code: output=e97e3a4d8c971b6e input=373b51bb2147f4d8]*/
Christian Heimes9bd667a2008-01-20 15:14:11 +0000935{
Victor Stinner50b48572018-11-01 01:51:40 +0100936 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 PyObject *temp = tstate->c_traceobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 if (temp == NULL)
940 temp = Py_None;
941 Py_INCREF(temp);
942 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000943}
944
Christian Heimes9bd667a2008-01-20 15:14:11 +0000945static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000946sys_setprofile(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000947{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 if (trace_init() == -1)
949 return NULL;
950 if (args == Py_None)
951 PyEval_SetProfile(NULL, NULL);
952 else
953 PyEval_SetProfile(profile_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200954 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000955}
956
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000957PyDoc_STRVAR(setprofile_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000958"setprofile(function)\n\
959\n\
960Set the profiling function. It will be called on each function call\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000961and return. See the profiler chapter in the library manual."
962);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000963
Tal Einatede0b6f2018-12-31 17:12:08 +0200964/*[clinic input]
965sys.getprofile
966
967Return the profiling function set with sys.setprofile.
968
969See the profiler chapter in the library manual.
970[clinic start generated code]*/
971
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000972static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200973sys_getprofile_impl(PyObject *module)
974/*[clinic end generated code: output=579b96b373448188 input=1b3209d89a32965d]*/
Christian Heimes9bd667a2008-01-20 15:14:11 +0000975{
Victor Stinner50b48572018-11-01 01:51:40 +0100976 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 PyObject *temp = tstate->c_profileobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 if (temp == NULL)
980 temp = Py_None;
981 Py_INCREF(temp);
982 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000983}
984
Tal Einatede0b6f2018-12-31 17:12:08 +0200985/*[clinic input]
986sys.setcheckinterval
987
988 n: int
989 /
990
991Set the async event check interval to n instructions.
992
993This tells the Python interpreter to check for asynchronous events
994every n instructions.
995
996This also affects how often thread switches occur.
997[clinic start generated code]*/
Christian Heimes9bd667a2008-01-20 15:14:11 +0000998
999static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001000sys_setcheckinterval_impl(PyObject *module, int n)
1001/*[clinic end generated code: output=3f686cef07e6e178 input=7a35b17bf22a6227]*/
Guido van Rossuma0d7a231995-01-09 17:46:13 +00001002{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1004 "sys.getcheckinterval() and sys.setcheckinterval() "
1005 "are deprecated. Use sys.setswitchinterval() "
1006 "instead.", 1) < 0)
1007 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +02001008
Victor Stinnercaba55b2018-08-03 15:33:52 +02001009 PyInterpreterState *interp = _PyInterpreterState_Get();
Tal Einatede0b6f2018-12-31 17:12:08 +02001010 interp->check_interval = n;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001011 Py_RETURN_NONE;
Guido van Rossuma0d7a231995-01-09 17:46:13 +00001012}
1013
Tal Einatede0b6f2018-12-31 17:12:08 +02001014/*[clinic input]
1015sys.getcheckinterval
1016
1017Return the current check interval; see sys.setcheckinterval().
1018[clinic start generated code]*/
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001019
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001020static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001021sys_getcheckinterval_impl(PyObject *module)
1022/*[clinic end generated code: output=1b5060bf2b23a47c input=4b6589cbcca1db4e]*/
Tim Peterse5e065b2003-07-06 18:36:54 +00001023{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1025 "sys.getcheckinterval() and sys.setcheckinterval() "
1026 "are deprecated. Use sys.getswitchinterval() "
1027 "instead.", 1) < 0)
1028 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +02001029 PyInterpreterState *interp = _PyInterpreterState_Get();
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001030 return PyLong_FromLong(interp->check_interval);
Tim Peterse5e065b2003-07-06 18:36:54 +00001031}
1032
Tal Einatede0b6f2018-12-31 17:12:08 +02001033/*[clinic input]
1034sys.setswitchinterval
1035
1036 interval: double
1037 /
1038
1039Set the ideal thread switching delay inside the Python interpreter.
1040
1041The actual frequency of switching threads can be lower if the
1042interpreter executes long sequences of uninterruptible code
1043(this is implementation-specific and workload-dependent).
1044
1045The parameter must represent the desired switching delay in seconds
1046A typical value is 0.005 (5 milliseconds).
1047[clinic start generated code]*/
Tim Peterse5e065b2003-07-06 18:36:54 +00001048
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001049static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001050sys_setswitchinterval_impl(PyObject *module, double interval)
1051/*[clinic end generated code: output=65a19629e5153983 input=561b477134df91d9]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001052{
Tal Einatede0b6f2018-12-31 17:12:08 +02001053 if (interval <= 0.0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 PyErr_SetString(PyExc_ValueError,
1055 "switch interval must be strictly positive");
1056 return NULL;
1057 }
Tal Einatede0b6f2018-12-31 17:12:08 +02001058 _PyEval_SetSwitchInterval((unsigned long) (1e6 * interval));
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001059 Py_RETURN_NONE;
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001060}
1061
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001062
Tal Einatede0b6f2018-12-31 17:12:08 +02001063/*[clinic input]
1064sys.getswitchinterval -> double
1065
1066Return the current thread switch interval; see sys.setswitchinterval().
1067[clinic start generated code]*/
1068
1069static double
1070sys_getswitchinterval_impl(PyObject *module)
1071/*[clinic end generated code: output=a38c277c85b5096d input=bdf9d39c0ebbbb6f]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001072{
Tal Einatede0b6f2018-12-31 17:12:08 +02001073 return 1e-6 * _PyEval_GetSwitchInterval();
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001074}
1075
Tal Einatede0b6f2018-12-31 17:12:08 +02001076/*[clinic input]
1077sys.setrecursionlimit
1078
1079 limit as new_limit: int
1080 /
1081
1082Set the maximum depth of the Python interpreter stack to n.
1083
1084This limit prevents infinite recursion from causing an overflow of the C
1085stack and crashing Python. The highest possible limit is platform-
1086dependent.
1087[clinic start generated code]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001088
Tim Peterse5e065b2003-07-06 18:36:54 +00001089static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001090sys_setrecursionlimit_impl(PyObject *module, int new_limit)
1091/*[clinic end generated code: output=35e1c64754800ace input=b0f7a23393924af3]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001092{
Tal Einatede0b6f2018-12-31 17:12:08 +02001093 int mark;
Victor Stinner50856d52015-10-13 00:11:21 +02001094 PyThreadState *tstate;
1095
Victor Stinner50856d52015-10-13 00:11:21 +02001096 if (new_limit < 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 PyErr_SetString(PyExc_ValueError,
Victor Stinner50856d52015-10-13 00:11:21 +02001098 "recursion limit must be greater or equal than 1");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099 return NULL;
1100 }
Victor Stinner50856d52015-10-13 00:11:21 +02001101
1102 /* Issue #25274: When the recursion depth hits the recursion limit in
1103 _Py_CheckRecursiveCall(), the overflowed flag of the thread state is
1104 set to 1 and a RecursionError is raised. The overflowed flag is reset
1105 to 0 when the recursion depth goes below the low-water mark: see
1106 Py_LeaveRecursiveCall().
1107
1108 Reject too low new limit if the current recursion depth is higher than
1109 the new low-water mark. Otherwise it may not be possible anymore to
1110 reset the overflowed flag to 0. */
1111 mark = _Py_RecursionLimitLowerWaterMark(new_limit);
Victor Stinner50b48572018-11-01 01:51:40 +01001112 tstate = _PyThreadState_GET();
Victor Stinner50856d52015-10-13 00:11:21 +02001113 if (tstate->recursion_depth >= mark) {
1114 PyErr_Format(PyExc_RecursionError,
1115 "cannot set the recursion limit to %i at "
1116 "the recursion depth %i: the limit is too low",
1117 new_limit, tstate->recursion_depth);
1118 return NULL;
1119 }
1120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001121 Py_SetRecursionLimit(new_limit);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001122 Py_RETURN_NONE;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001123}
1124
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001125/*[clinic input]
1126sys.set_coroutine_origin_tracking_depth
1127
1128 depth: int
1129
1130Enable or disable origin tracking for coroutine objects in this thread.
1131
Tal Einatede0b6f2018-12-31 17:12:08 +02001132Coroutine objects will track 'depth' frames of traceback information
1133about where they came from, available in their cr_origin attribute.
1134
1135Set a depth of 0 to disable.
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001136[clinic start generated code]*/
1137
1138static PyObject *
1139sys_set_coroutine_origin_tracking_depth_impl(PyObject *module, int depth)
Tal Einatede0b6f2018-12-31 17:12:08 +02001140/*[clinic end generated code: output=0a2123c1cc6759c5 input=a1d0a05f89d2c426]*/
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001141{
1142 if (depth < 0) {
1143 PyErr_SetString(PyExc_ValueError, "depth must be >= 0");
1144 return NULL;
1145 }
1146 _PyEval_SetCoroutineOriginTrackingDepth(depth);
1147 Py_RETURN_NONE;
1148}
1149
1150/*[clinic input]
1151sys.get_coroutine_origin_tracking_depth -> int
1152
1153Check status of origin tracking for coroutine objects in this thread.
1154[clinic start generated code]*/
1155
1156static int
1157sys_get_coroutine_origin_tracking_depth_impl(PyObject *module)
1158/*[clinic end generated code: output=3699f7be95a3afb8 input=335266a71205b61a]*/
1159{
1160 return _PyEval_GetCoroutineOriginTrackingDepth();
1161}
1162
Yury Selivanoveb636452016-09-08 22:01:51 -07001163static PyTypeObject AsyncGenHooksType;
1164
1165PyDoc_STRVAR(asyncgen_hooks_doc,
1166"asyncgen_hooks\n\
1167\n\
1168A struct sequence providing information about asynhronous\n\
1169generators hooks. The attributes are read only.");
1170
1171static PyStructSequence_Field asyncgen_hooks_fields[] = {
1172 {"firstiter", "Hook to intercept first iteration"},
1173 {"finalizer", "Hook to intercept finalization"},
1174 {0}
1175};
1176
1177static PyStructSequence_Desc asyncgen_hooks_desc = {
1178 "asyncgen_hooks", /* name */
1179 asyncgen_hooks_doc, /* doc */
1180 asyncgen_hooks_fields , /* fields */
1181 2
1182};
1183
Yury Selivanoveb636452016-09-08 22:01:51 -07001184static PyObject *
1185sys_set_asyncgen_hooks(PyObject *self, PyObject *args, PyObject *kw)
1186{
1187 static char *keywords[] = {"firstiter", "finalizer", NULL};
1188 PyObject *firstiter = NULL;
1189 PyObject *finalizer = NULL;
1190
1191 if (!PyArg_ParseTupleAndKeywords(
1192 args, kw, "|OO", keywords,
1193 &firstiter, &finalizer)) {
1194 return NULL;
1195 }
1196
1197 if (finalizer && finalizer != Py_None) {
1198 if (!PyCallable_Check(finalizer)) {
1199 PyErr_Format(PyExc_TypeError,
1200 "callable finalizer expected, got %.50s",
1201 Py_TYPE(finalizer)->tp_name);
1202 return NULL;
1203 }
1204 _PyEval_SetAsyncGenFinalizer(finalizer);
1205 }
1206 else if (finalizer == Py_None) {
1207 _PyEval_SetAsyncGenFinalizer(NULL);
1208 }
1209
1210 if (firstiter && firstiter != Py_None) {
1211 if (!PyCallable_Check(firstiter)) {
1212 PyErr_Format(PyExc_TypeError,
1213 "callable firstiter expected, got %.50s",
1214 Py_TYPE(firstiter)->tp_name);
1215 return NULL;
1216 }
1217 _PyEval_SetAsyncGenFirstiter(firstiter);
1218 }
1219 else if (firstiter == Py_None) {
1220 _PyEval_SetAsyncGenFirstiter(NULL);
1221 }
1222
1223 Py_RETURN_NONE;
1224}
1225
1226PyDoc_STRVAR(set_asyncgen_hooks_doc,
Tal Einatede0b6f2018-12-31 17:12:08 +02001227"set_asyncgen_hooks(* [, firstiter] [, finalizer])\n\
Yury Selivanoveb636452016-09-08 22:01:51 -07001228\n\
1229Set a finalizer for async generators objects."
1230);
1231
Tal Einatede0b6f2018-12-31 17:12:08 +02001232/*[clinic input]
1233sys.get_asyncgen_hooks
1234
1235Return the installed asynchronous generators hooks.
1236
1237This returns a namedtuple of the form (firstiter, finalizer).
1238[clinic start generated code]*/
1239
Yury Selivanoveb636452016-09-08 22:01:51 -07001240static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001241sys_get_asyncgen_hooks_impl(PyObject *module)
1242/*[clinic end generated code: output=53a253707146f6cf input=3676b9ea62b14625]*/
Yury Selivanoveb636452016-09-08 22:01:51 -07001243{
1244 PyObject *res;
1245 PyObject *firstiter = _PyEval_GetAsyncGenFirstiter();
1246 PyObject *finalizer = _PyEval_GetAsyncGenFinalizer();
1247
1248 res = PyStructSequence_New(&AsyncGenHooksType);
1249 if (res == NULL) {
1250 return NULL;
1251 }
1252
1253 if (firstiter == NULL) {
1254 firstiter = Py_None;
1255 }
1256
1257 if (finalizer == NULL) {
1258 finalizer = Py_None;
1259 }
1260
1261 Py_INCREF(firstiter);
1262 PyStructSequence_SET_ITEM(res, 0, firstiter);
1263
1264 Py_INCREF(finalizer);
1265 PyStructSequence_SET_ITEM(res, 1, finalizer);
1266
1267 return res;
1268}
1269
Yury Selivanoveb636452016-09-08 22:01:51 -07001270
Mark Dickinsondc787d22010-05-23 13:33:13 +00001271static PyTypeObject Hash_InfoType;
1272
1273PyDoc_STRVAR(hash_info_doc,
1274"hash_info\n\
1275\n\
1276A struct sequence providing parameters used for computing\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +01001277hashes. The attributes are read only.");
Mark Dickinsondc787d22010-05-23 13:33:13 +00001278
1279static PyStructSequence_Field hash_info_fields[] = {
1280 {"width", "width of the type used for hashing, in bits"},
1281 {"modulus", "prime number giving the modulus on which the hash "
1282 "function is based"},
1283 {"inf", "value to be used for hash of a positive infinity"},
1284 {"nan", "value to be used for hash of a nan"},
1285 {"imag", "multiplier used for the imaginary part of a complex number"},
Christian Heimes985ecdc2013-11-20 11:46:18 +01001286 {"algorithm", "name of the algorithm for hashing of str, bytes and "
1287 "memoryviews"},
1288 {"hash_bits", "internal output size of hash algorithm"},
1289 {"seed_bits", "seed size of hash algorithm"},
1290 {"cutoff", "small string optimization cutoff"},
Mark Dickinsondc787d22010-05-23 13:33:13 +00001291 {NULL, NULL}
1292};
1293
1294static PyStructSequence_Desc hash_info_desc = {
1295 "sys.hash_info",
1296 hash_info_doc,
1297 hash_info_fields,
Christian Heimes985ecdc2013-11-20 11:46:18 +01001298 9,
Mark Dickinsondc787d22010-05-23 13:33:13 +00001299};
1300
Matthias Klosed885e952010-07-06 10:53:30 +00001301static PyObject *
Mark Dickinsondc787d22010-05-23 13:33:13 +00001302get_hash_info(void)
1303{
1304 PyObject *hash_info;
1305 int field = 0;
Christian Heimes985ecdc2013-11-20 11:46:18 +01001306 PyHash_FuncDef *hashfunc;
Mark Dickinsondc787d22010-05-23 13:33:13 +00001307 hash_info = PyStructSequence_New(&Hash_InfoType);
1308 if (hash_info == NULL)
1309 return NULL;
Christian Heimes985ecdc2013-11-20 11:46:18 +01001310 hashfunc = PyHash_GetFuncDef();
Mark Dickinsondc787d22010-05-23 13:33:13 +00001311 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001312 PyLong_FromLong(8*sizeof(Py_hash_t)));
Mark Dickinsondc787d22010-05-23 13:33:13 +00001313 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8035bc52010-10-23 16:20:50 +00001314 PyLong_FromSsize_t(_PyHASH_MODULUS));
Mark Dickinsondc787d22010-05-23 13:33:13 +00001315 PyStructSequence_SET_ITEM(hash_info, field++,
1316 PyLong_FromLong(_PyHASH_INF));
1317 PyStructSequence_SET_ITEM(hash_info, field++,
1318 PyLong_FromLong(_PyHASH_NAN));
1319 PyStructSequence_SET_ITEM(hash_info, field++,
1320 PyLong_FromLong(_PyHASH_IMAG));
Christian Heimes985ecdc2013-11-20 11:46:18 +01001321 PyStructSequence_SET_ITEM(hash_info, field++,
1322 PyUnicode_FromString(hashfunc->name));
1323 PyStructSequence_SET_ITEM(hash_info, field++,
1324 PyLong_FromLong(hashfunc->hash_bits));
1325 PyStructSequence_SET_ITEM(hash_info, field++,
1326 PyLong_FromLong(hashfunc->seed_bits));
1327 PyStructSequence_SET_ITEM(hash_info, field++,
1328 PyLong_FromLong(Py_HASH_CUTOFF));
Mark Dickinsondc787d22010-05-23 13:33:13 +00001329 if (PyErr_Occurred()) {
1330 Py_CLEAR(hash_info);
1331 return NULL;
1332 }
1333 return hash_info;
1334}
Tal Einatede0b6f2018-12-31 17:12:08 +02001335/*[clinic input]
1336sys.getrecursionlimit
Mark Dickinsondc787d22010-05-23 13:33:13 +00001337
Tal Einatede0b6f2018-12-31 17:12:08 +02001338Return the current value of the recursion limit.
Mark Dickinsondc787d22010-05-23 13:33:13 +00001339
Tal Einatede0b6f2018-12-31 17:12:08 +02001340The recursion limit is the maximum depth of the Python interpreter
1341stack. This limit prevents infinite recursion from causing an overflow
1342of the C stack and crashing Python.
1343[clinic start generated code]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001344
1345static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001346sys_getrecursionlimit_impl(PyObject *module)
1347/*[clinic end generated code: output=d571fb6b4549ef2e input=1c6129fd2efaeea8]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001348{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001349 return PyLong_FromLong(Py_GetRecursionLimit());
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001350}
1351
Mark Hammond8696ebc2002-10-08 02:44:31 +00001352#ifdef MS_WINDOWS
Mark Hammond8696ebc2002-10-08 02:44:31 +00001353
Eric Smithf7bb5782010-01-27 00:44:57 +00001354static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};
1355
1356static PyStructSequence_Field windows_version_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001357 {"major", "Major version number"},
1358 {"minor", "Minor version number"},
1359 {"build", "Build number"},
1360 {"platform", "Operating system platform"},
1361 {"service_pack", "Latest Service Pack installed on the system"},
1362 {"service_pack_major", "Service Pack major version number"},
1363 {"service_pack_minor", "Service Pack minor version number"},
1364 {"suite_mask", "Bit mask identifying available product suites"},
1365 {"product_type", "System product type"},
Steve Dower74f4af72016-09-17 17:27:48 -07001366 {"platform_version", "Diagnostic version number"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001367 {0}
Eric Smithf7bb5782010-01-27 00:44:57 +00001368};
1369
1370static PyStructSequence_Desc windows_version_desc = {
Tal Einatede0b6f2018-12-31 17:12:08 +02001371 "sys.getwindowsversion", /* name */
1372 sys_getwindowsversion__doc__, /* doc */
1373 windows_version_fields, /* fields */
1374 5 /* For backward compatibility,
1375 only the first 5 items are accessible
1376 via indexing, the rest are name only */
Eric Smithf7bb5782010-01-27 00:44:57 +00001377};
1378
Steve Dower3e96f322015-03-02 08:01:10 -08001379/* Disable deprecation warnings about GetVersionEx as the result is
1380 being passed straight through to the caller, who is responsible for
1381 using it correctly. */
1382#pragma warning(push)
1383#pragma warning(disable:4996)
1384
Tal Einatede0b6f2018-12-31 17:12:08 +02001385/*[clinic input]
1386sys.getwindowsversion
1387
1388Return info about the running version of Windows as a named tuple.
1389
1390The members are named: major, minor, build, platform, service_pack,
1391service_pack_major, service_pack_minor, suite_mask, product_type and
1392platform_version. For backward compatibility, only the first 5 items
1393are available by indexing. All elements are numbers, except
1394service_pack and platform_type which are strings, and platform_version
1395which is a 3-tuple. Platform is always 2. Product_type may be 1 for a
1396workstation, 2 for a domain controller, 3 for a server.
1397Platform_version is a 3-tuple containing a version number that is
1398intended for identifying the OS rather than feature detection.
1399[clinic start generated code]*/
1400
Mark Hammond8696ebc2002-10-08 02:44:31 +00001401static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001402sys_getwindowsversion_impl(PyObject *module)
1403/*[clinic end generated code: output=1ec063280b932857 input=73a228a328fee63a]*/
Mark Hammond8696ebc2002-10-08 02:44:31 +00001404{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001405 PyObject *version;
1406 int pos = 0;
Minmin Gong8ebc6452019-02-02 20:26:55 -08001407 OSVERSIONINFOEXW ver;
Steve Dower74f4af72016-09-17 17:27:48 -07001408 DWORD realMajor, realMinor, realBuild;
1409 HANDLE hKernel32;
1410 wchar_t kernel32_path[MAX_PATH];
1411 LPVOID verblock;
1412 DWORD verblock_size;
1413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 ver.dwOSVersionInfoSize = sizeof(ver);
Minmin Gong8ebc6452019-02-02 20:26:55 -08001415 if (!GetVersionExW((OSVERSIONINFOW*) &ver))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001416 return PyErr_SetFromWindowsErr(0);
Eric Smithf7bb5782010-01-27 00:44:57 +00001417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 version = PyStructSequence_New(&WindowsVersionType);
1419 if (version == NULL)
1420 return NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +00001421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion));
1423 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion));
1424 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber));
1425 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId));
Minmin Gong8ebc6452019-02-02 20:26:55 -08001426 PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromWideChar(ver.szCSDVersion, -1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001427 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor));
1428 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor));
1429 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask));
1430 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType));
Eric Smithf7bb5782010-01-27 00:44:57 +00001431
Steve Dower74f4af72016-09-17 17:27:48 -07001432 realMajor = ver.dwMajorVersion;
1433 realMinor = ver.dwMinorVersion;
1434 realBuild = ver.dwBuildNumber;
1435
1436 // GetVersion will lie if we are running in a compatibility mode.
1437 // We need to read the version info from a system file resource
1438 // to accurately identify the OS version. If we fail for any reason,
1439 // just return whatever GetVersion said.
Tony Roberts4860f012019-02-02 18:16:42 +01001440 Py_BEGIN_ALLOW_THREADS
Steve Dower74f4af72016-09-17 17:27:48 -07001441 hKernel32 = GetModuleHandleW(L"kernel32.dll");
Tony Roberts4860f012019-02-02 18:16:42 +01001442 Py_END_ALLOW_THREADS
Steve Dower74f4af72016-09-17 17:27:48 -07001443 if (hKernel32 && GetModuleFileNameW(hKernel32, kernel32_path, MAX_PATH) &&
1444 (verblock_size = GetFileVersionInfoSizeW(kernel32_path, NULL)) &&
1445 (verblock = PyMem_RawMalloc(verblock_size))) {
1446 VS_FIXEDFILEINFO *ffi;
1447 UINT ffi_len;
1448
1449 if (GetFileVersionInfoW(kernel32_path, 0, verblock_size, verblock) &&
1450 VerQueryValueW(verblock, L"", (LPVOID)&ffi, &ffi_len)) {
1451 realMajor = HIWORD(ffi->dwProductVersionMS);
1452 realMinor = LOWORD(ffi->dwProductVersionMS);
1453 realBuild = HIWORD(ffi->dwProductVersionLS);
1454 }
1455 PyMem_RawFree(verblock);
1456 }
Segev Finer48fb7662017-06-04 20:52:27 +03001457 PyStructSequence_SET_ITEM(version, pos++, Py_BuildValue("(kkk)",
1458 realMajor,
1459 realMinor,
1460 realBuild
Steve Dower74f4af72016-09-17 17:27:48 -07001461 ));
1462
Serhiy Storchaka48d761e2013-12-17 15:11:24 +02001463 if (PyErr_Occurred()) {
1464 Py_DECREF(version);
1465 return NULL;
1466 }
Steve Dower74f4af72016-09-17 17:27:48 -07001467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 return version;
Mark Hammond8696ebc2002-10-08 02:44:31 +00001469}
1470
Steve Dower3e96f322015-03-02 08:01:10 -08001471#pragma warning(pop)
1472
Tal Einatede0b6f2018-12-31 17:12:08 +02001473/*[clinic input]
1474sys._enablelegacywindowsfsencoding
1475
1476Changes the default filesystem encoding to mbcs:replace.
1477
1478This is done for consistency with earlier versions of Python. See PEP
1479529 for more information.
1480
1481This is equivalent to defining the PYTHONLEGACYWINDOWSFSENCODING
1482environment variable before launching Python.
1483[clinic start generated code]*/
Steve Dowercc16be82016-09-08 10:35:16 -07001484
1485static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001486sys__enablelegacywindowsfsencoding_impl(PyObject *module)
1487/*[clinic end generated code: output=f5c3855b45e24fe9 input=2bfa931a20704492]*/
Steve Dowercc16be82016-09-08 10:35:16 -07001488{
Victor Stinner709d23d2019-05-02 14:56:30 -04001489 if (_PyUnicode_EnableLegacyWindowsFSEncoding() < 0) {
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001490 return NULL;
1491 }
Steve Dowercc16be82016-09-08 10:35:16 -07001492 Py_RETURN_NONE;
1493}
1494
Mark Hammond8696ebc2002-10-08 02:44:31 +00001495#endif /* MS_WINDOWS */
1496
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001497#ifdef HAVE_DLOPEN
Tal Einatede0b6f2018-12-31 17:12:08 +02001498
1499/*[clinic input]
1500sys.setdlopenflags
1501
1502 flags as new_val: int
1503 /
1504
1505Set the flags used by the interpreter for dlopen calls.
1506
1507This is used, for example, when the interpreter loads extension
1508modules. Among other things, this will enable a lazy resolving of
1509symbols when importing a module, if called as sys.setdlopenflags(0).
1510To share symbols across extension modules, call as
1511sys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag
1512modules can be found in the os module (RTLD_xxx constants, e.g.
1513os.RTLD_LAZY).
1514[clinic start generated code]*/
1515
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001516static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001517sys_setdlopenflags_impl(PyObject *module, int new_val)
1518/*[clinic end generated code: output=ec918b7fe0a37281 input=4c838211e857a77f]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001519{
Victor Stinnercaba55b2018-08-03 15:33:52 +02001520 PyInterpreterState *interp = _PyInterpreterState_Get();
1521 interp->dlopenflags = new_val;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001522 Py_RETURN_NONE;
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001523}
1524
Tal Einatede0b6f2018-12-31 17:12:08 +02001525
1526/*[clinic input]
1527sys.getdlopenflags
1528
1529Return the current value of the flags that are used for dlopen calls.
1530
1531The flag constants are defined in the os module.
1532[clinic start generated code]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001533
1534static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001535sys_getdlopenflags_impl(PyObject *module)
1536/*[clinic end generated code: output=e92cd1bc5005da6e input=dc4ea0899c53b4b6]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001537{
Victor Stinnercaba55b2018-08-03 15:33:52 +02001538 PyInterpreterState *interp = _PyInterpreterState_Get();
1539 return PyLong_FromLong(interp->dlopenflags);
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001540}
1541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001542#endif /* HAVE_DLOPEN */
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001543
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001544#ifdef USE_MALLOPT
1545/* Link with -lmalloc (or -lmpc) on an SGI */
1546#include <malloc.h>
1547
Tal Einatede0b6f2018-12-31 17:12:08 +02001548/*[clinic input]
1549sys.mdebug
1550
1551 flag: int
1552 /
1553[clinic start generated code]*/
1554
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001555static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001556sys_mdebug_impl(PyObject *module, int flag)
1557/*[clinic end generated code: output=5431d545847c3637 input=151d150ae1636f8a]*/
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001558{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 int flag;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 mallopt(M_DEBUG, flag);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001561 Py_RETURN_NONE;
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001562}
1563#endif /* USE_MALLOPT */
1564
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001565size_t
1566_PySys_GetSizeOf(PyObject *o)
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001567{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001568 PyObject *res = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001569 PyObject *method;
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001570 Py_ssize_t size;
Benjamin Petersona5758c02009-05-09 18:15:04 +00001571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 /* Make sure the type is initialized. float gets initialized late */
1573 if (PyType_Ready(Py_TYPE(o)) < 0)
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001574 return (size_t)-1;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001575
Benjamin Petersonce798522012-01-22 11:24:29 -05001576 method = _PyObject_LookupSpecial(o, &PyId___sizeof__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001577 if (method == NULL) {
1578 if (!PyErr_Occurred())
1579 PyErr_Format(PyExc_TypeError,
1580 "Type %.100s doesn't define __sizeof__",
1581 Py_TYPE(o)->tp_name);
1582 }
1583 else {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001584 res = _PyObject_CallNoArg(method);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 Py_DECREF(method);
1586 }
1587
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001588 if (res == NULL)
1589 return (size_t)-1;
1590
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001591 size = PyLong_AsSsize_t(res);
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001592 Py_DECREF(res);
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001593 if (size == -1 && PyErr_Occurred())
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001594 return (size_t)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001596 if (size < 0) {
1597 PyErr_SetString(PyExc_ValueError, "__sizeof__() should return >= 0");
1598 return (size_t)-1;
1599 }
1600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 /* add gc_head size */
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001602 if (PyObject_IS_GC(o))
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001603 return ((size_t)size) + sizeof(PyGC_Head);
1604 return (size_t)size;
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001605}
1606
1607static PyObject *
1608sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
1609{
1610 static char *kwlist[] = {"object", "default", 0};
1611 size_t size;
1612 PyObject *o, *dflt = NULL;
1613
1614 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
1615 kwlist, &o, &dflt))
1616 return NULL;
1617
1618 size = _PySys_GetSizeOf(o);
1619
1620 if (size == (size_t)-1 && PyErr_Occurred()) {
1621 /* Has a default value been given */
1622 if (dflt != NULL && PyErr_ExceptionMatches(PyExc_TypeError)) {
1623 PyErr_Clear();
1624 Py_INCREF(dflt);
1625 return dflt;
1626 }
1627 else
1628 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001629 }
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001630
1631 return PyLong_FromSize_t(size);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001632}
1633
1634PyDoc_STRVAR(getsizeof_doc,
Tal Einatede0b6f2018-12-31 17:12:08 +02001635"getsizeof(object [, default]) -> int\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001636\n\
1637Return the size of object in bytes.");
1638
Tal Einatede0b6f2018-12-31 17:12:08 +02001639/*[clinic input]
1640sys.getrefcount -> Py_ssize_t
1641
1642 object: object
1643 /
1644
1645Return the reference count of object.
1646
1647The count returned is generally one higher than you might expect,
1648because it includes the (temporary) reference as an argument to
1649getrefcount().
1650[clinic start generated code]*/
1651
1652static Py_ssize_t
1653sys_getrefcount_impl(PyObject *module, PyObject *object)
1654/*[clinic end generated code: output=5fd477f2264b85b2 input=bf474efd50a21535]*/
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001655{
Tal Einatede0b6f2018-12-31 17:12:08 +02001656 return object->ob_refcnt;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001657}
1658
Tim Peters4be93d02002-07-07 19:59:50 +00001659#ifdef Py_REF_DEBUG
Tal Einatede0b6f2018-12-31 17:12:08 +02001660/*[clinic input]
1661sys.gettotalrefcount -> Py_ssize_t
1662[clinic start generated code]*/
1663
1664static Py_ssize_t
1665sys_gettotalrefcount_impl(PyObject *module)
1666/*[clinic end generated code: output=4103886cf17c25bc input=53b744faa5d2e4f6]*/
Mark Hammond440d8982000-06-20 08:12:48 +00001667{
Tal Einatede0b6f2018-12-31 17:12:08 +02001668 return _Py_GetRefTotal();
Mark Hammond440d8982000-06-20 08:12:48 +00001669}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001670#endif /* Py_REF_DEBUG */
Mark Hammond440d8982000-06-20 08:12:48 +00001671
Tal Einatede0b6f2018-12-31 17:12:08 +02001672/*[clinic input]
1673sys.getallocatedblocks -> Py_ssize_t
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001674
Tal Einatede0b6f2018-12-31 17:12:08 +02001675Return the number of memory blocks currently allocated.
1676[clinic start generated code]*/
1677
1678static Py_ssize_t
1679sys_getallocatedblocks_impl(PyObject *module)
1680/*[clinic end generated code: output=f0c4e873f0b6dcf7 input=dab13ee346a0673e]*/
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001681{
Tal Einatede0b6f2018-12-31 17:12:08 +02001682 return _Py_GetAllocatedBlocks();
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001683}
1684
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001685#ifdef COUNT_ALLOCS
Tal Einatede0b6f2018-12-31 17:12:08 +02001686/*[clinic input]
1687sys.getcounts
1688[clinic start generated code]*/
1689
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001690static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001691sys_getcounts_impl(PyObject *module)
1692/*[clinic end generated code: output=20df00bc164f43cb input=ad2ec7bda5424953]*/
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001693{
Pablo Galindo49c75a82018-10-28 15:02:17 +00001694 extern PyObject *_Py_get_counts(void);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001695
Pablo Galindo49c75a82018-10-28 15:02:17 +00001696 return _Py_get_counts();
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001697}
1698#endif
1699
Tal Einatede0b6f2018-12-31 17:12:08 +02001700/*[clinic input]
1701sys._getframe
1702
1703 depth: int = 0
1704 /
1705
1706Return a frame object from the call stack.
1707
1708If optional integer depth is given, return the frame object that many
1709calls below the top of the stack. If that is deeper than the call
1710stack, ValueError is raised. The default for depth is zero, returning
1711the frame at the top of the call stack.
1712
1713This function should be used for internal and specialized purposes
1714only.
1715[clinic start generated code]*/
Barry Warsawb6a54d22000-12-06 21:47:46 +00001716
1717static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001718sys__getframe_impl(PyObject *module, int depth)
1719/*[clinic end generated code: output=d438776c04d59804 input=c1be8a6464b11ee5]*/
Barry Warsawb6a54d22000-12-06 21:47:46 +00001720{
Victor Stinner50b48572018-11-01 01:51:40 +01001721 PyFrameObject *f = _PyThreadState_GET()->frame;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001722
Steve Dowerb82e17e2019-05-23 08:45:22 -07001723 if (PySys_Audit("sys._getframe", "O", f) < 0) {
1724 return NULL;
1725 }
1726
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001727 while (depth > 0 && f != NULL) {
1728 f = f->f_back;
1729 --depth;
1730 }
1731 if (f == NULL) {
1732 PyErr_SetString(PyExc_ValueError,
1733 "call stack is not deep enough");
1734 return NULL;
1735 }
1736 Py_INCREF(f);
1737 return (PyObject*)f;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001738}
1739
Tal Einatede0b6f2018-12-31 17:12:08 +02001740/*[clinic input]
1741sys._current_frames
1742
1743Return a dict mapping each thread's thread id to its current stack frame.
1744
1745This function should be used for specialized purposes only.
1746[clinic start generated code]*/
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001747
1748static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001749sys__current_frames_impl(PyObject *module)
1750/*[clinic end generated code: output=d2a41ac0a0a3809a input=2a9049c5f5033691]*/
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001751{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001752 return _PyThread_CurrentFrames();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001753}
1754
Tal Einatede0b6f2018-12-31 17:12:08 +02001755/*[clinic input]
1756sys.call_tracing
1757
1758 func: object
1759 args as funcargs: object(subclass_of='&PyTuple_Type')
1760 /
1761
1762Call func(*args), while tracing is enabled.
1763
1764The tracing state is saved, and restored afterwards. This is intended
1765to be called from a debugger from a checkpoint, to recursively debug
1766some other code.
1767[clinic start generated code]*/
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001768
1769static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001770sys_call_tracing_impl(PyObject *module, PyObject *func, PyObject *funcargs)
1771/*[clinic end generated code: output=7e4999853cd4e5a6 input=5102e8b11049f92f]*/
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001772{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001773 return _PyEval_CallTracing(func, funcargs);
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001774}
1775
Tal Einatede0b6f2018-12-31 17:12:08 +02001776/*[clinic input]
1777sys.callstats
1778
1779Return a tuple of function call statistics.
1780
1781A tuple is returned only if CALL_PROFILE was defined when Python was
1782built. Otherwise, this returns None.
1783
1784When enabled, this function returns detailed, implementation-specific
1785details about the number of function calls executed. The return value
1786is a 11-tuple where the entries in the tuple are counts of:
17870. all function calls
17881. calls to PyFunction_Type objects
17892. PyFunction calls that do not create an argument tuple
17903. PyFunction calls that do not create an argument tuple
1791 and bypass PyEval_EvalCodeEx()
17924. PyMethod calls
17935. PyMethod calls on bound methods
17946. PyType calls
17957. PyCFunction calls
17968. generator calls
17979. All other calls
179810. Number of stack pops performed by call_function()
1799[clinic start generated code]*/
Barry Warsawb6a54d22000-12-06 21:47:46 +00001800
Victor Stinner048afd92016-11-28 11:59:04 +01001801static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001802sys_callstats_impl(PyObject *module)
1803/*[clinic end generated code: output=edc4a74957fa8def input=d447d8d224d5d175]*/
Victor Stinner048afd92016-11-28 11:59:04 +01001804{
1805 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1806 "sys.callstats() has been deprecated in Python 3.7 "
1807 "and will be removed in the future", 1) < 0) {
1808 return NULL;
1809 }
1810
1811 Py_RETURN_NONE;
1812}
1813
1814
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001815#ifdef __cplusplus
1816extern "C" {
1817#endif
1818
Tal Einatede0b6f2018-12-31 17:12:08 +02001819/*[clinic input]
1820sys._debugmallocstats
1821
1822Print summary info to stderr about the state of pymalloc's structures.
1823
1824In Py_DEBUG mode, also perform some expensive internal consistency
1825checks.
1826[clinic start generated code]*/
1827
David Malcolm49526f42012-06-22 14:55:41 -04001828static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001829sys__debugmallocstats_impl(PyObject *module)
1830/*[clinic end generated code: output=ec3565f8c7cee46a input=33c0c9c416f98424]*/
David Malcolm49526f42012-06-22 14:55:41 -04001831{
1832#ifdef WITH_PYMALLOC
Victor Stinner6bf992a2017-12-06 17:26:10 +01001833 if (_PyObject_DebugMallocStats(stderr)) {
Victor Stinner34be807c2016-03-14 12:04:26 +01001834 fputc('\n', stderr);
1835 }
David Malcolm49526f42012-06-22 14:55:41 -04001836#endif
1837 _PyObject_DebugTypeStats(stderr);
1838
1839 Py_RETURN_NONE;
1840}
David Malcolm49526f42012-06-22 14:55:41 -04001841
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001842#ifdef Py_TRACE_REFS
Guido van Rossumded690f1996-05-24 20:48:31 +00001843/* Defined in objects.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001844extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001845#endif
Guido van Rossumded690f1996-05-24 20:48:31 +00001846
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001847#ifdef DYNAMIC_EXECUTION_PROFILE
1848/* Defined in ceval.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001849extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001850#endif
1851
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001852#ifdef __cplusplus
1853}
1854#endif
1855
Tal Einatede0b6f2018-12-31 17:12:08 +02001856
1857/*[clinic input]
1858sys._clear_type_cache
1859
1860Clear the internal type lookup cache.
1861[clinic start generated code]*/
1862
Christian Heimes15ebc882008-02-04 18:48:49 +00001863static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001864sys__clear_type_cache_impl(PyObject *module)
1865/*[clinic end generated code: output=20e48ca54a6f6971 input=127f3e04a8d9b555]*/
Christian Heimes15ebc882008-02-04 18:48:49 +00001866{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001867 PyType_ClearCache();
1868 Py_RETURN_NONE;
Christian Heimes15ebc882008-02-04 18:48:49 +00001869}
1870
Tal Einatede0b6f2018-12-31 17:12:08 +02001871/*[clinic input]
1872sys.is_finalizing
1873
1874Return True if Python is exiting.
1875[clinic start generated code]*/
1876
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001877static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001878sys_is_finalizing_impl(PyObject *module)
1879/*[clinic end generated code: output=735b5ff7962ab281 input=f0df747a039948a5]*/
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001880{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001881 return PyBool_FromLong(_Py_IsFinalizing());
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001882}
1883
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001884#ifdef ANDROID_API_LEVEL
Tal Einatede0b6f2018-12-31 17:12:08 +02001885/*[clinic input]
1886sys.getandroidapilevel
1887
1888Return the build time API version of Android as an integer.
1889[clinic start generated code]*/
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001890
1891static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001892sys_getandroidapilevel_impl(PyObject *module)
1893/*[clinic end generated code: output=214abf183a1c70c1 input=3e6d6c9fcdd24ac6]*/
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001894{
1895 return PyLong_FromLong(ANDROID_API_LEVEL);
1896}
1897#endif /* ANDROID_API_LEVEL */
1898
1899
Steve Dowerb82e17e2019-05-23 08:45:22 -07001900
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001901static PyMethodDef sys_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001902 /* Might as well keep this in alphabetic order */
Steve Dowerb82e17e2019-05-23 08:45:22 -07001903 SYS_ADDAUDITHOOK_METHODDEF
1904 {"audit", (PyCFunction)(void(*)(void))sys_audit, METH_FASTCALL, audit_doc },
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001905 {"breakpointhook", (PyCFunction)(void(*)(void))sys_breakpointhook,
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04001906 METH_FASTCALL | METH_KEYWORDS, breakpointhook_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001907 SYS_CALLSTATS_METHODDEF
1908 SYS__CLEAR_TYPE_CACHE_METHODDEF
1909 SYS__CURRENT_FRAMES_METHODDEF
1910 SYS_DISPLAYHOOK_METHODDEF
1911 SYS_EXC_INFO_METHODDEF
1912 SYS_EXCEPTHOOK_METHODDEF
1913 SYS_EXIT_METHODDEF
1914 SYS_GETDEFAULTENCODING_METHODDEF
1915 SYS_GETDLOPENFLAGS_METHODDEF
1916 SYS_GETALLOCATEDBLOCKS_METHODDEF
1917 SYS_GETCOUNTS_METHODDEF
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001918#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001919 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001920#endif
Tal Einatede0b6f2018-12-31 17:12:08 +02001921 SYS_GETFILESYSTEMENCODING_METHODDEF
1922 SYS_GETFILESYSTEMENCODEERRORS_METHODDEF
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001923#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001924 {"getobjects", _Py_GetObjects, METH_VARARGS},
Tim Peters4be93d02002-07-07 19:59:50 +00001925#endif
Tal Einatede0b6f2018-12-31 17:12:08 +02001926 SYS_GETTOTALREFCOUNT_METHODDEF
1927 SYS_GETREFCOUNT_METHODDEF
1928 SYS_GETRECURSIONLIMIT_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001929 {"getsizeof", (PyCFunction)(void(*)(void))sys_getsizeof,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001930 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001931 SYS__GETFRAME_METHODDEF
1932 SYS_GETWINDOWSVERSION_METHODDEF
1933 SYS__ENABLELEGACYWINDOWSFSENCODING_METHODDEF
1934 SYS_INTERN_METHODDEF
1935 SYS_IS_FINALIZING_METHODDEF
1936 SYS_MDEBUG_METHODDEF
1937 SYS_SETCHECKINTERVAL_METHODDEF
1938 SYS_GETCHECKINTERVAL_METHODDEF
1939 SYS_SETSWITCHINTERVAL_METHODDEF
1940 SYS_GETSWITCHINTERVAL_METHODDEF
1941 SYS_SETDLOPENFLAGS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001942 {"setprofile", sys_setprofile, METH_O, setprofile_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001943 SYS_GETPROFILE_METHODDEF
1944 SYS_SETRECURSIONLIMIT_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 {"settrace", sys_settrace, METH_O, settrace_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001946 SYS_GETTRACE_METHODDEF
1947 SYS_CALL_TRACING_METHODDEF
1948 SYS__DEBUGMALLOCSTATS_METHODDEF
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001949 SYS_SET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
1950 SYS_GET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001951 {"set_asyncgen_hooks", (PyCFunction)(void(*)(void))sys_set_asyncgen_hooks,
Yury Selivanoveb636452016-09-08 22:01:51 -07001952 METH_VARARGS | METH_KEYWORDS, set_asyncgen_hooks_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001953 SYS_GET_ASYNCGEN_HOOKS_METHODDEF
1954 SYS_GETANDROIDAPILEVEL_METHODDEF
Victor Stinneref9d9b62019-05-22 11:28:22 +02001955 SYS_UNRAISABLEHOOK_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001956 {NULL, NULL} /* sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +00001957};
1958
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001959static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001960list_builtin_module_names(void)
Guido van Rossum34679b71993-01-26 13:33:44 +00001961{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001962 PyObject *list = PyList_New(0);
1963 int i;
1964 if (list == NULL)
1965 return NULL;
1966 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1967 PyObject *name = PyUnicode_FromString(
1968 PyImport_Inittab[i].name);
1969 if (name == NULL)
1970 break;
1971 PyList_Append(list, name);
1972 Py_DECREF(name);
1973 }
1974 if (PyList_Sort(list) != 0) {
1975 Py_DECREF(list);
1976 list = NULL;
1977 }
1978 if (list) {
1979 PyObject *v = PyList_AsTuple(list);
1980 Py_DECREF(list);
1981 list = v;
1982 }
1983 return list;
Guido van Rossum34679b71993-01-26 13:33:44 +00001984}
1985
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001986/* Pre-initialization support for sys.warnoptions and sys._xoptions
1987 *
1988 * Modern internal code paths:
1989 * These APIs get called after _Py_InitializeCore and get to use the
1990 * regular CPython list, dict, and unicode APIs.
1991 *
1992 * Legacy embedding code paths:
1993 * The multi-phase initialization API isn't public yet, so embedding
1994 * apps still need to be able configure sys.warnoptions and sys._xoptions
1995 * before they call Py_Initialize. To support this, we stash copies of
1996 * the supplied wchar * sequences in linked lists, and then migrate the
1997 * contents of those lists to the sys module in _PyInitializeCore.
1998 *
1999 */
2000
2001struct _preinit_entry {
2002 wchar_t *value;
2003 struct _preinit_entry *next;
2004};
2005
2006typedef struct _preinit_entry *_Py_PreInitEntry;
2007
2008static _Py_PreInitEntry _preinit_warnoptions = NULL;
2009static _Py_PreInitEntry _preinit_xoptions = NULL;
2010
2011static _Py_PreInitEntry
2012_alloc_preinit_entry(const wchar_t *value)
2013{
2014 /* To get this to work, we have to initialize the runtime implicitly */
2015 _PyRuntime_Initialize();
2016
2017 /* Force default allocator, so we can ensure that it also gets used to
2018 * destroy the linked list in _clear_preinit_entries.
2019 */
2020 PyMemAllocatorEx old_alloc;
2021 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2022
2023 _Py_PreInitEntry node = PyMem_RawCalloc(1, sizeof(*node));
2024 if (node != NULL) {
2025 node->value = _PyMem_RawWcsdup(value);
2026 if (node->value == NULL) {
2027 PyMem_RawFree(node);
2028 node = NULL;
2029 };
2030 };
2031
2032 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2033 return node;
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002034}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002035
2036static int
2037_append_preinit_entry(_Py_PreInitEntry *optionlist, const wchar_t *value)
2038{
2039 _Py_PreInitEntry new_entry = _alloc_preinit_entry(value);
2040 if (new_entry == NULL) {
2041 return -1;
2042 }
2043 /* We maintain the linked list in this order so it's easy to play back
2044 * the add commands in the same order later on in _Py_InitializeCore
2045 */
2046 _Py_PreInitEntry last_entry = *optionlist;
2047 if (last_entry == NULL) {
2048 *optionlist = new_entry;
2049 } else {
2050 while (last_entry->next != NULL) {
2051 last_entry = last_entry->next;
2052 }
2053 last_entry->next = new_entry;
2054 }
2055 return 0;
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002056}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002057
2058static void
2059_clear_preinit_entries(_Py_PreInitEntry *optionlist)
2060{
2061 _Py_PreInitEntry current = *optionlist;
2062 *optionlist = NULL;
2063 /* Deallocate the nodes and their contents using the default allocator */
2064 PyMemAllocatorEx old_alloc;
2065 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2066 while (current != NULL) {
2067 _Py_PreInitEntry next = current->next;
2068 PyMem_RawFree(current->value);
2069 PyMem_RawFree(current);
2070 current = next;
2071 }
2072 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002073}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002074
2075static void
2076_clear_all_preinit_options(void)
2077{
2078 _clear_preinit_entries(&_preinit_warnoptions);
2079 _clear_preinit_entries(&_preinit_xoptions);
2080}
2081
2082static int
2083_PySys_ReadPreInitOptions(void)
2084{
2085 /* Rerun the add commands with the actual sys module available */
Victor Stinner50b48572018-11-01 01:51:40 +01002086 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002087 if (tstate == NULL) {
2088 /* Still don't have a thread state, so something is wrong! */
2089 return -1;
2090 }
2091 _Py_PreInitEntry entry = _preinit_warnoptions;
2092 while (entry != NULL) {
2093 PySys_AddWarnOption(entry->value);
2094 entry = entry->next;
2095 }
2096 entry = _preinit_xoptions;
2097 while (entry != NULL) {
2098 PySys_AddXOption(entry->value);
2099 entry = entry->next;
2100 }
2101
2102 _clear_all_preinit_options();
2103 return 0;
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002104}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002105
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002106static PyObject *
2107get_warnoptions(void)
2108{
Eric Snowdae02762017-09-14 00:35:58 -07002109 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002110 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002111 /* PEP432 TODO: we can reach this if warnoptions is NULL in the main
2112 * interpreter config. When that happens, we need to properly set
2113 * the `warnoptions` reference in the main interpreter config as well.
2114 *
2115 * For Python 3.7, we shouldn't be able to get here due to the
2116 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
2117 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
2118 * call optional for embedding applications, thus making this
2119 * reachable again.
2120 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002121 warnoptions = PyList_New(0);
2122 if (warnoptions == NULL)
2123 return NULL;
Eric Snowdae02762017-09-14 00:35:58 -07002124 if (_PySys_SetObjectId(&PyId_warnoptions, warnoptions)) {
2125 Py_DECREF(warnoptions);
2126 return NULL;
2127 }
2128 Py_DECREF(warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002129 }
2130 return warnoptions;
2131}
Guido van Rossum23fff912000-12-15 22:02:05 +00002132
2133void
2134PySys_ResetWarnOptions(void)
2135{
Victor Stinner50b48572018-11-01 01:51:40 +01002136 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002137 if (tstate == NULL) {
2138 _clear_preinit_entries(&_preinit_warnoptions);
2139 return;
2140 }
2141
Eric Snowdae02762017-09-14 00:35:58 -07002142 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002143 if (warnoptions == NULL || !PyList_Check(warnoptions))
2144 return;
2145 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
Guido van Rossum23fff912000-12-15 22:02:05 +00002146}
2147
Victor Stinnere1b29952018-10-30 14:31:42 +01002148static int
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002149_PySys_AddWarnOptionWithError(PyObject *option)
Guido van Rossum23fff912000-12-15 22:02:05 +00002150{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002151 PyObject *warnoptions = get_warnoptions();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002152 if (warnoptions == NULL) {
2153 return -1;
2154 }
2155 if (PyList_Append(warnoptions, option)) {
2156 return -1;
2157 }
2158 return 0;
2159}
2160
2161void
2162PySys_AddWarnOptionUnicode(PyObject *option)
2163{
Victor Stinnere1b29952018-10-30 14:31:42 +01002164 if (_PySys_AddWarnOptionWithError(option) < 0) {
2165 /* No return value, therefore clear error state if possible */
2166 if (_PyThreadState_UncheckedGet()) {
2167 PyErr_Clear();
2168 }
2169 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00002170}
2171
2172void
2173PySys_AddWarnOption(const wchar_t *s)
2174{
Victor Stinner50b48572018-11-01 01:51:40 +01002175 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002176 if (tstate == NULL) {
2177 _append_preinit_entry(&_preinit_warnoptions, s);
2178 return;
2179 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00002180 PyObject *unicode;
2181 unicode = PyUnicode_FromWideChar(s, -1);
2182 if (unicode == NULL)
2183 return;
2184 PySys_AddWarnOptionUnicode(unicode);
2185 Py_DECREF(unicode);
Guido van Rossum23fff912000-12-15 22:02:05 +00002186}
2187
Christian Heimes33fe8092008-04-13 13:53:33 +00002188int
2189PySys_HasWarnOptions(void)
2190{
Eric Snowdae02762017-09-14 00:35:58 -07002191 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Serhiy Storchakadffccc62018-12-10 13:50:22 +02002192 return (warnoptions != NULL && PyList_Check(warnoptions)
2193 && PyList_GET_SIZE(warnoptions) > 0);
Christian Heimes33fe8092008-04-13 13:53:33 +00002194}
2195
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002196static PyObject *
2197get_xoptions(void)
2198{
Eric Snowdae02762017-09-14 00:35:58 -07002199 PyObject *xoptions = _PySys_GetObjectId(&PyId__xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002200 if (xoptions == NULL || !PyDict_Check(xoptions)) {
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002201 /* PEP432 TODO: we can reach this if xoptions is NULL in the main
2202 * interpreter config. When that happens, we need to properly set
2203 * the `xoptions` reference in the main interpreter config as well.
2204 *
2205 * For Python 3.7, we shouldn't be able to get here due to the
2206 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
2207 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
2208 * call optional for embedding applications, thus making this
2209 * reachable again.
2210 */
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002211 xoptions = PyDict_New();
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002212 if (xoptions == NULL)
2213 return NULL;
Eric Snowdae02762017-09-14 00:35:58 -07002214 if (_PySys_SetObjectId(&PyId__xoptions, xoptions)) {
2215 Py_DECREF(xoptions);
2216 return NULL;
2217 }
2218 Py_DECREF(xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002219 }
2220 return xoptions;
2221}
2222
Victor Stinnere1b29952018-10-30 14:31:42 +01002223static int
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002224_PySys_AddXOptionWithError(const wchar_t *s)
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002225{
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002226 PyObject *name = NULL, *value = NULL;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002227
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002228 PyObject *opts = get_xoptions();
2229 if (opts == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002230 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002231 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002232
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002233 const wchar_t *name_end = wcschr(s, L'=');
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002234 if (!name_end) {
2235 name = PyUnicode_FromWideChar(s, -1);
2236 value = Py_True;
2237 Py_INCREF(value);
2238 }
2239 else {
2240 name = PyUnicode_FromWideChar(s, name_end - s);
2241 value = PyUnicode_FromWideChar(name_end + 1, -1);
2242 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002243 if (name == NULL || value == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002244 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002245 }
2246 if (PyDict_SetItem(opts, name, value) < 0) {
2247 goto error;
2248 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002249 Py_DECREF(name);
2250 Py_DECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002251 return 0;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002252
2253error:
2254 Py_XDECREF(name);
2255 Py_XDECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002256 return -1;
2257}
2258
2259void
2260PySys_AddXOption(const wchar_t *s)
2261{
Victor Stinner50b48572018-11-01 01:51:40 +01002262 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002263 if (tstate == NULL) {
2264 _append_preinit_entry(&_preinit_xoptions, s);
2265 return;
2266 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002267 if (_PySys_AddXOptionWithError(s) < 0) {
2268 /* No return value, therefore clear error state if possible */
2269 if (_PyThreadState_UncheckedGet()) {
2270 PyErr_Clear();
2271 }
Victor Stinner0cae6092016-11-11 01:43:56 +01002272 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002273}
2274
2275PyObject *
2276PySys_GetXOptions(void)
2277{
2278 return get_xoptions();
2279}
2280
Guido van Rossum40552d01998-08-06 03:34:39 +00002281/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
2282 Two literals concatenated works just fine. If you have a K&R compiler
2283 or other abomination that however *does* understand longer strings,
2284 get rid of the !!! comment in the middle and the quotes that surround it. */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002285PyDoc_VAR(sys_doc) =
2286PyDoc_STR(
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002287"This module provides access to some objects used or maintained by the\n\
2288interpreter and to functions that interact strongly with the interpreter.\n\
2289\n\
2290Dynamic objects:\n\
2291\n\
2292argv -- command line arguments; argv[0] is the script pathname if known\n\
2293path -- module search path; path[0] is the script directory, else ''\n\
2294modules -- dictionary of loaded modules\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002295\n\
2296displayhook -- called to show results in an interactive session\n\
2297excepthook -- called to handle any uncaught exception other than SystemExit\n\
2298 To customize printing in an interactive session or to install a custom\n\
2299 top-level exception handler, assign other functions to replace these.\n\
2300\n\
Benjamin Peterson06157a42008-07-15 00:28:36 +00002301stdin -- standard input file object; used by input()\n\
Georg Brandl88fc6642007-02-09 21:28:07 +00002302stdout -- standard output file object; used by print()\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002303stderr -- standard error object; used for error messages\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002304 By assigning other file objects (or objects that behave like files)\n\
2305 to these, it is possible to redirect all of the interpreter's I/O.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002306\n\
2307last_type -- type of last uncaught exception\n\
2308last_value -- value of last uncaught exception\n\
2309last_traceback -- traceback of last uncaught exception\n\
2310 These three are only available in an interactive session after a\n\
2311 traceback has been printed.\n\
Guido van Rossuma71b5f41999-01-14 19:07:00 +00002312"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002313)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002314/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002315PyDoc_STR(
Guido van Rossuma71b5f41999-01-14 19:07:00 +00002316"\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002317Static objects:\n\
2318\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002319builtin_module_names -- tuple of module names built into this interpreter\n\
2320copyright -- copyright notice pertaining to this interpreter\n\
2321exec_prefix -- prefix used to find the machine-specific Python library\n\
Petri Lehtinen4b0eab62012-02-02 21:23:15 +02002322executable -- absolute path of the executable binary of the Python interpreter\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002323float_info -- a struct sequence with information about the float implementation.\n\
2324float_repr_style -- string indicating the style of repr() output for floats\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +01002325hash_info -- a struct sequence with information about the hash algorithm.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002326hexversion -- version information encoded as a single integer\n\
Barry Warsaw409da152012-06-03 16:18:47 -04002327implementation -- Python implementation information.\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00002328int_info -- a struct sequence with information about the int implementation.\n\
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00002329maxsize -- the largest supported length of containers.\n\
Serhiy Storchakad3faf432015-01-18 11:28:37 +02002330maxunicode -- the value of the largest Unicode code point\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002331platform -- platform identifier\n\
2332prefix -- prefix used to find the Python library\n\
2333thread_info -- a struct sequence with information about the thread implementation.\n\
Fred Drake801c08d2000-04-13 15:29:10 +00002334version -- the version of this interpreter as a string\n\
Eric Smith0e5b5622009-02-06 01:32:42 +00002335version_info -- version information as a named tuple\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002336"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002337)
Steve Dowercc16be82016-09-08 10:35:16 -07002338#ifdef MS_COREDLL
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002339/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002340PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002341"dllhandle -- [Windows only] integer handle of the Python DLL\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002342winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002343"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002344)
Steve Dowercc16be82016-09-08 10:35:16 -07002345#endif /* MS_COREDLL */
2346#ifdef MS_WINDOWS
2347/* concatenating string here */
2348PyDoc_STR(
oldkaa0735f2018-02-02 16:52:55 +08002349"_enablelegacywindowsfsencoding -- [Windows only]\n\
Steve Dowercc16be82016-09-08 10:35:16 -07002350"
2351)
2352#endif
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002353PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002354"__stdin__ -- the original stdin; don't touch!\n\
2355__stdout__ -- the original stdout; don't touch!\n\
2356__stderr__ -- the original stderr; don't touch!\n\
2357__displayhook__ -- the original displayhook; don't touch!\n\
2358__excepthook__ -- the original excepthook; don't touch!\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002359\n\
2360Functions:\n\
2361\n\
Georg Brandl1a3284e2007-12-02 09:40:06 +00002362displayhook() -- print an object to the screen, and save it in builtins._\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002363excepthook() -- print an exception and its traceback to sys.stderr\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002364exc_info() -- return thread-safe information about the current exception\n\
2365exit() -- exit the interpreter by raising SystemExit\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002366getdlopenflags() -- returns flags to be used for dlopen() calls\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002367getprofile() -- get the global profiling function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002368getrefcount() -- return the reference count for an object (plus one :-)\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002369getrecursionlimit() -- return the max recursion depth for the interpreter\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002370getsizeof() -- return the size of an object in bytes\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002371gettrace() -- get the global debug tracing function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002372setcheckinterval() -- control how often the interpreter checks for events\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002373setdlopenflags() -- set the flags to be used for dlopen() calls\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002374setprofile() -- set the global profiling function\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002375setrecursionlimit() -- set the max recursion depth for the interpreter\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002376settrace() -- set the global debug tracing function\n\
Fred Drakeccede592000-08-14 20:59:57 +00002377"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002378)
Fred Drakeccede592000-08-14 20:59:57 +00002379/* end of sys_doc */ ;
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002380
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002381
2382PyDoc_STRVAR(flags__doc__,
2383"sys.flags\n\
2384\n\
2385Flags provided through command line arguments or environment vars.");
2386
2387static PyTypeObject FlagsType;
2388
2389static PyStructSequence_Field flags_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002390 {"debug", "-d"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002391 {"inspect", "-i"},
2392 {"interactive", "-i"},
2393 {"optimize", "-O or -OO"},
2394 {"dont_write_bytecode", "-B"},
2395 {"no_user_site", "-s"},
2396 {"no_site", "-S"},
2397 {"ignore_environment", "-E"},
2398 {"verbose", "-v"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002399 /* {"unbuffered", "-u"}, */
2400 /* {"skip_first", "-x"}, */
Georg Brandl8aa7e992010-12-28 18:30:18 +00002401 {"bytes_warning", "-b"},
2402 {"quiet", "-q"},
Georg Brandl09a7c722012-02-20 21:31:46 +01002403 {"hash_randomization", "-R"},
Christian Heimesad73a9c2013-08-10 16:36:18 +02002404 {"isolated", "-I"},
Victor Stinner5e3806f2017-11-30 11:40:24 +01002405 {"dev_mode", "-X dev"},
Victor Stinner91106cd2017-12-13 12:29:09 +01002406 {"utf8_mode", "-X utf8"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002407 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002408};
2409
2410static PyStructSequence_Desc flags_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002411 "sys.flags", /* name */
2412 flags__doc__, /* doc */
2413 flags_fields, /* fields */
Victor Stinner91106cd2017-12-13 12:29:09 +01002414 15
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002415};
2416
2417static PyObject*
Eric Snow396e0a82019-05-31 21:16:47 -06002418make_flags(PyInterpreterState *interp)
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002419{
Eric Snow396e0a82019-05-31 21:16:47 -06002420 _PyRuntimeState *runtime = interp->runtime;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002421 int pos = 0;
2422 PyObject *seq;
Victor Stinner331a6a52019-05-27 16:39:22 +02002423 const PyPreConfig *preconfig = &runtime->preconfig;
2424 const PyConfig *config = &interp->config;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002426 seq = PyStructSequence_New(&FlagsType);
2427 if (seq == NULL)
2428 return NULL;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002429
2430#define SetFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002431 PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002432
Victor Stinnerfbca9082018-08-30 00:50:45 +02002433 SetFlag(config->parser_debug);
2434 SetFlag(config->inspect);
2435 SetFlag(config->interactive);
2436 SetFlag(config->optimization_level);
2437 SetFlag(!config->write_bytecode);
2438 SetFlag(!config->user_site_directory);
2439 SetFlag(!config->site_import);
Victor Stinner20004952019-03-26 02:31:11 +01002440 SetFlag(!config->use_environment);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002441 SetFlag(config->verbose);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002442 /* SetFlag(saw_unbuffered_flag); */
2443 /* SetFlag(skipfirstline); */
Victor Stinnerfbca9082018-08-30 00:50:45 +02002444 SetFlag(config->bytes_warning);
2445 SetFlag(config->quiet);
2446 SetFlag(config->use_hash_seed == 0 || config->hash_seed != 0);
Victor Stinner20004952019-03-26 02:31:11 +01002447 SetFlag(config->isolated);
2448 PyStructSequence_SET_ITEM(seq, pos++, PyBool_FromLong(config->dev_mode));
2449 SetFlag(preconfig->utf8_mode);
Victor Stinner91106cd2017-12-13 12:29:09 +01002450#undef SetFlag
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002452 if (PyErr_Occurred()) {
Serhiy Storchaka87a854d2013-12-17 14:59:42 +02002453 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002454 return NULL;
2455 }
2456 return seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002457}
2458
Eric Smith0e5b5622009-02-06 01:32:42 +00002459PyDoc_STRVAR(version_info__doc__,
2460"sys.version_info\n\
2461\n\
2462Version information as a named tuple.");
2463
2464static PyTypeObject VersionInfoType;
2465
2466static PyStructSequence_Field version_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002467 {"major", "Major release number"},
2468 {"minor", "Minor release number"},
2469 {"micro", "Patch release number"},
Ned Deilyda4887a2016-11-04 17:03:34 -04002470 {"releaselevel", "'alpha', 'beta', 'candidate', or 'final'"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002471 {"serial", "Serial release number"},
2472 {0}
Eric Smith0e5b5622009-02-06 01:32:42 +00002473};
2474
2475static PyStructSequence_Desc version_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002476 "sys.version_info", /* name */
2477 version_info__doc__, /* doc */
2478 version_info_fields, /* fields */
2479 5
Eric Smith0e5b5622009-02-06 01:32:42 +00002480};
2481
2482static PyObject *
2483make_version_info(void)
2484{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002485 PyObject *version_info;
2486 char *s;
2487 int pos = 0;
Eric Smith0e5b5622009-02-06 01:32:42 +00002488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002489 version_info = PyStructSequence_New(&VersionInfoType);
2490 if (version_info == NULL) {
2491 return NULL;
2492 }
Eric Smith0e5b5622009-02-06 01:32:42 +00002493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002494 /*
2495 * These release level checks are mutually exclusive and cover
2496 * the field, so don't get too fancy with the pre-processor!
2497 */
Eric Smith0e5b5622009-02-06 01:32:42 +00002498#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002499 s = "alpha";
Eric Smith0e5b5622009-02-06 01:32:42 +00002500#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002501 s = "beta";
Eric Smith0e5b5622009-02-06 01:32:42 +00002502#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002503 s = "candidate";
Eric Smith0e5b5622009-02-06 01:32:42 +00002504#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002505 s = "final";
Eric Smith0e5b5622009-02-06 01:32:42 +00002506#endif
2507
2508#define SetIntItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002509 PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002510#define SetStrItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002511 PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002513 SetIntItem(PY_MAJOR_VERSION);
2514 SetIntItem(PY_MINOR_VERSION);
2515 SetIntItem(PY_MICRO_VERSION);
2516 SetStrItem(s);
2517 SetIntItem(PY_RELEASE_SERIAL);
Eric Smith0e5b5622009-02-06 01:32:42 +00002518#undef SetIntItem
2519#undef SetStrItem
2520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002521 if (PyErr_Occurred()) {
2522 Py_CLEAR(version_info);
2523 return NULL;
2524 }
2525 return version_info;
Eric Smith0e5b5622009-02-06 01:32:42 +00002526}
2527
Brett Cannon3adc7b72012-07-09 14:22:12 -04002528/* sys.implementation values */
2529#define NAME "cpython"
2530const char *_PySys_ImplName = NAME;
Victor Stinnercf01b682015-11-05 11:21:38 +01002531#define MAJOR Py_STRINGIFY(PY_MAJOR_VERSION)
2532#define MINOR Py_STRINGIFY(PY_MINOR_VERSION)
Ned Deily529ea5d2014-06-30 23:31:14 -07002533#define TAG NAME "-" MAJOR MINOR
Brett Cannon3adc7b72012-07-09 14:22:12 -04002534const char *_PySys_ImplCacheTag = TAG;
2535#undef NAME
Brett Cannon3adc7b72012-07-09 14:22:12 -04002536#undef MAJOR
2537#undef MINOR
2538#undef TAG
2539
Barry Warsaw409da152012-06-03 16:18:47 -04002540static PyObject *
2541make_impl_info(PyObject *version_info)
2542{
2543 int res;
2544 PyObject *impl_info, *value, *ns;
2545
2546 impl_info = PyDict_New();
2547 if (impl_info == NULL)
2548 return NULL;
2549
2550 /* populate the dict */
2551
Brett Cannon3adc7b72012-07-09 14:22:12 -04002552 value = PyUnicode_FromString(_PySys_ImplName);
Barry Warsaw409da152012-06-03 16:18:47 -04002553 if (value == NULL)
2554 goto error;
2555 res = PyDict_SetItemString(impl_info, "name", value);
2556 Py_DECREF(value);
2557 if (res < 0)
2558 goto error;
2559
Brett Cannon3adc7b72012-07-09 14:22:12 -04002560 value = PyUnicode_FromString(_PySys_ImplCacheTag);
Barry Warsaw409da152012-06-03 16:18:47 -04002561 if (value == NULL)
2562 goto error;
2563 res = PyDict_SetItemString(impl_info, "cache_tag", value);
2564 Py_DECREF(value);
2565 if (res < 0)
2566 goto error;
Barry Warsaw409da152012-06-03 16:18:47 -04002567
2568 res = PyDict_SetItemString(impl_info, "version", version_info);
2569 if (res < 0)
2570 goto error;
2571
2572 value = PyLong_FromLong(PY_VERSION_HEX);
2573 if (value == NULL)
2574 goto error;
2575 res = PyDict_SetItemString(impl_info, "hexversion", value);
2576 Py_DECREF(value);
2577 if (res < 0)
2578 goto error;
2579
doko@ubuntu.com55532312016-06-14 08:55:19 +02002580#ifdef MULTIARCH
2581 value = PyUnicode_FromString(MULTIARCH);
2582 if (value == NULL)
2583 goto error;
2584 res = PyDict_SetItemString(impl_info, "_multiarch", value);
2585 Py_DECREF(value);
2586 if (res < 0)
2587 goto error;
2588#endif
2589
Barry Warsaw409da152012-06-03 16:18:47 -04002590 /* dict ready */
2591
2592 ns = _PyNamespace_New(impl_info);
2593 Py_DECREF(impl_info);
2594 return ns;
2595
2596error:
2597 Py_CLEAR(impl_info);
2598 return NULL;
2599}
2600
Martin v. Löwis1a214512008-06-11 05:26:20 +00002601static struct PyModuleDef sysmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002602 PyModuleDef_HEAD_INIT,
2603 "sys",
2604 sys_doc,
2605 -1, /* multiple "initialization" just copies the module dict. */
2606 sys_methods,
2607 NULL,
2608 NULL,
2609 NULL,
2610 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002611};
2612
Eric Snow6b4be192017-05-22 21:36:03 -07002613/* Updating the sys namespace, returning NULL pointer on error */
Victor Stinner8fea2522013-10-27 17:15:42 +01002614#define SET_SYS_FROM_STRING_BORROW(key, value) \
Victor Stinner58049602013-07-22 22:40:00 +02002615 do { \
Victor Stinner58049602013-07-22 22:40:00 +02002616 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002617 if (v == NULL) { \
2618 goto err_occurred; \
2619 } \
Victor Stinner58049602013-07-22 22:40:00 +02002620 res = PyDict_SetItemString(sysdict, key, v); \
2621 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002622 goto err_occurred; \
Victor Stinner8fea2522013-10-27 17:15:42 +01002623 } \
2624 } while (0)
2625#define SET_SYS_FROM_STRING(key, value) \
2626 do { \
Victor Stinner8fea2522013-10-27 17:15:42 +01002627 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002628 if (v == NULL) { \
2629 goto err_occurred; \
2630 } \
Victor Stinner8fea2522013-10-27 17:15:42 +01002631 res = PyDict_SetItemString(sysdict, key, v); \
2632 Py_DECREF(v); \
2633 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002634 goto err_occurred; \
Victor Stinner58049602013-07-22 22:40:00 +02002635 } \
2636 } while (0)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002637
Victor Stinner331a6a52019-05-27 16:39:22 +02002638static PyStatus
Eric Snow396e0a82019-05-31 21:16:47 -06002639_PySys_InitCore(PyInterpreterState *interp, PyObject *sysdict)
Eric Snow6b4be192017-05-22 21:36:03 -07002640{
Victor Stinnerab672812019-01-23 15:04:40 +01002641 PyObject *version_info;
Eric Snow6b4be192017-05-22 21:36:03 -07002642 int res;
2643
Nick Coghland6009512014-11-20 21:39:37 +10002644 /* stdin/stdout/stderr are set in pylifecycle.c */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002645
Victor Stinner8fea2522013-10-27 17:15:42 +01002646 SET_SYS_FROM_STRING_BORROW("__displayhook__",
2647 PyDict_GetItemString(sysdict, "displayhook"));
2648 SET_SYS_FROM_STRING_BORROW("__excepthook__",
2649 PyDict_GetItemString(sysdict, "excepthook"));
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04002650 SET_SYS_FROM_STRING_BORROW(
2651 "__breakpointhook__",
2652 PyDict_GetItemString(sysdict, "breakpointhook"));
Victor Stinneref9d9b62019-05-22 11:28:22 +02002653 SET_SYS_FROM_STRING_BORROW("__unraisablehook__",
2654 PyDict_GetItemString(sysdict, "unraisablehook"));
2655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002656 SET_SYS_FROM_STRING("version",
2657 PyUnicode_FromString(Py_GetVersion()));
2658 SET_SYS_FROM_STRING("hexversion",
2659 PyLong_FromLong(PY_VERSION_HEX));
Ned Deily5c4b0d02017-03-04 00:19:55 -05002660 SET_SYS_FROM_STRING("_git",
2661 Py_BuildValue("(szz)", "CPython", _Py_gitidentifier(),
2662 _Py_gitversion()));
INADA Naoki6b42eb12017-06-29 15:31:38 +09002663 SET_SYS_FROM_STRING("_framework", PyUnicode_FromString(_PYTHONFRAMEWORK));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002664 SET_SYS_FROM_STRING("api_version",
2665 PyLong_FromLong(PYTHON_API_VERSION));
2666 SET_SYS_FROM_STRING("copyright",
2667 PyUnicode_FromString(Py_GetCopyright()));
2668 SET_SYS_FROM_STRING("platform",
2669 PyUnicode_FromString(Py_GetPlatform()));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002670 SET_SYS_FROM_STRING("maxsize",
2671 PyLong_FromSsize_t(PY_SSIZE_T_MAX));
2672 SET_SYS_FROM_STRING("float_info",
2673 PyFloat_GetInfo());
2674 SET_SYS_FROM_STRING("int_info",
2675 PyLong_GetInfo());
Mark Dickinsondc787d22010-05-23 13:33:13 +00002676 /* initialize hash_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002677 if (Hash_InfoType.tp_name == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002678 if (PyStructSequence_InitType2(&Hash_InfoType, &hash_info_desc) < 0) {
2679 goto type_init_failed;
2680 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002681 }
Mark Dickinsondc787d22010-05-23 13:33:13 +00002682 SET_SYS_FROM_STRING("hash_info",
2683 get_hash_info());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002684 SET_SYS_FROM_STRING("maxunicode",
Ezio Melotti48a2f8f2011-09-29 00:18:19 +03002685 PyLong_FromLong(0x10FFFF));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002686 SET_SYS_FROM_STRING("builtin_module_names",
2687 list_builtin_module_names());
Christian Heimes743e0cd2012-10-17 23:52:17 +02002688#if PY_BIG_ENDIAN
2689 SET_SYS_FROM_STRING("byteorder",
2690 PyUnicode_FromString("big"));
2691#else
2692 SET_SYS_FROM_STRING("byteorder",
2693 PyUnicode_FromString("little"));
2694#endif
Fred Drake099325e2000-08-14 15:47:03 +00002695
Guido van Rossum8b9ea871996-08-23 18:14:47 +00002696#ifdef MS_COREDLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002697 SET_SYS_FROM_STRING("dllhandle",
2698 PyLong_FromVoidPtr(PyWin_DLLhModule));
2699 SET_SYS_FROM_STRING("winver",
2700 PyUnicode_FromString(PyWin_DLLVersionString));
Guido van Rossumc606fe11996-04-09 02:37:57 +00002701#endif
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00002702#ifdef ABIFLAGS
2703 SET_SYS_FROM_STRING("abiflags",
2704 PyUnicode_FromString(ABIFLAGS));
2705#endif
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002707 /* version_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002708 if (VersionInfoType.tp_name == NULL) {
2709 if (PyStructSequence_InitType2(&VersionInfoType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002710 &version_info_desc) < 0) {
2711 goto type_init_failed;
2712 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002713 }
Barry Warsaw409da152012-06-03 16:18:47 -04002714 version_info = make_version_info();
2715 SET_SYS_FROM_STRING("version_info", version_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002716 /* prevent user from creating new instances */
2717 VersionInfoType.tp_init = NULL;
2718 VersionInfoType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002719 res = PyDict_DelItemString(VersionInfoType.tp_dict, "__new__");
2720 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
2721 PyErr_Clear();
Eric Smith0e5b5622009-02-06 01:32:42 +00002722
Barry Warsaw409da152012-06-03 16:18:47 -04002723 /* implementation */
2724 SET_SYS_FROM_STRING("implementation", make_impl_info(version_info));
2725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002726 /* flags */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002727 if (FlagsType.tp_name == 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002728 if (PyStructSequence_InitType2(&FlagsType, &flags_desc) < 0) {
2729 goto type_init_failed;
2730 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002731 }
Victor Stinner43125222019-04-24 18:23:53 +02002732 /* Set flags to their default values (updated by _PySys_InitMain()) */
Eric Snow396e0a82019-05-31 21:16:47 -06002733 SET_SYS_FROM_STRING("flags", make_flags(interp));
Eric Smithf7bb5782010-01-27 00:44:57 +00002734
2735#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002736 /* getwindowsversion */
2737 if (WindowsVersionType.tp_name == 0)
Victor Stinner1c8f0592013-07-22 22:24:54 +02002738 if (PyStructSequence_InitType2(&WindowsVersionType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002739 &windows_version_desc) < 0) {
2740 goto type_init_failed;
2741 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002742 /* prevent user from creating new instances */
2743 WindowsVersionType.tp_init = NULL;
2744 WindowsVersionType.tp_new = NULL;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002745 assert(!PyErr_Occurred());
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002746 res = PyDict_DelItemString(WindowsVersionType.tp_dict, "__new__");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002747 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError)) {
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002748 PyErr_Clear();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002749 }
Eric Smithf7bb5782010-01-27 00:44:57 +00002750#endif
2751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002752 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002753#ifndef PY_NO_SHORT_FLOAT_REPR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002754 SET_SYS_FROM_STRING("float_repr_style",
2755 PyUnicode_FromString("short"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002756#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002757 SET_SYS_FROM_STRING("float_repr_style",
2758 PyUnicode_FromString("legacy"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002759#endif
2760
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002761 SET_SYS_FROM_STRING("thread_info", PyThread_GetInfo());
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002762
Yury Selivanoveb636452016-09-08 22:01:51 -07002763 /* initialize asyncgen_hooks */
2764 if (AsyncGenHooksType.tp_name == NULL) {
2765 if (PyStructSequence_InitType2(
2766 &AsyncGenHooksType, &asyncgen_hooks_desc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002767 goto type_init_failed;
Yury Selivanoveb636452016-09-08 22:01:51 -07002768 }
2769 }
2770
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002771 if (PyErr_Occurred()) {
2772 goto err_occurred;
2773 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002774 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002775
2776type_init_failed:
Victor Stinner331a6a52019-05-27 16:39:22 +02002777 return _PyStatus_ERR("failed to initialize a type");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002778
2779err_occurred:
Victor Stinner331a6a52019-05-27 16:39:22 +02002780 return _PyStatus_ERR("can't initialize sys module");
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002781}
2782
Eric Snow6b4be192017-05-22 21:36:03 -07002783#undef SET_SYS_FROM_STRING
Eric Snow6b4be192017-05-22 21:36:03 -07002784
2785/* Updating the sys namespace, returning integer error codes */
Eric Snow6b4be192017-05-22 21:36:03 -07002786#define SET_SYS_FROM_STRING_INT_RESULT(key, value) \
2787 do { \
2788 PyObject *v = (value); \
2789 if (v == NULL) \
2790 return -1; \
2791 res = PyDict_SetItemString(sysdict, key, v); \
2792 Py_DECREF(v); \
2793 if (res < 0) { \
2794 return res; \
2795 } \
2796 } while (0)
2797
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002798
2799static int
2800sys_add_xoption(PyObject *opts, const wchar_t *s)
2801{
2802 PyObject *name, *value;
2803
2804 const wchar_t *name_end = wcschr(s, L'=');
2805 if (!name_end) {
2806 name = PyUnicode_FromWideChar(s, -1);
2807 value = Py_True;
2808 Py_INCREF(value);
2809 }
2810 else {
2811 name = PyUnicode_FromWideChar(s, name_end - s);
2812 value = PyUnicode_FromWideChar(name_end + 1, -1);
2813 }
2814 if (name == NULL || value == NULL) {
2815 goto error;
2816 }
2817 if (PyDict_SetItem(opts, name, value) < 0) {
2818 goto error;
2819 }
2820 Py_DECREF(name);
2821 Py_DECREF(value);
2822 return 0;
2823
2824error:
2825 Py_XDECREF(name);
2826 Py_XDECREF(value);
2827 return -1;
2828}
2829
2830
2831static PyObject*
Victor Stinner331a6a52019-05-27 16:39:22 +02002832sys_create_xoptions_dict(const PyConfig *config)
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002833{
2834 Py_ssize_t nxoption = config->xoptions.length;
2835 wchar_t * const * xoptions = config->xoptions.items;
2836 PyObject *dict = PyDict_New();
2837 if (dict == NULL) {
2838 return NULL;
2839 }
2840
2841 for (Py_ssize_t i=0; i < nxoption; i++) {
2842 const wchar_t *option = xoptions[i];
2843 if (sys_add_xoption(dict, option) < 0) {
2844 Py_DECREF(dict);
2845 return NULL;
2846 }
2847 }
2848
2849 return dict;
2850}
2851
2852
Eric Snow6b4be192017-05-22 21:36:03 -07002853int
Eric Snow396e0a82019-05-31 21:16:47 -06002854_PySys_InitMain(PyInterpreterState *interp)
Eric Snow6b4be192017-05-22 21:36:03 -07002855{
Victor Stinnerab672812019-01-23 15:04:40 +01002856 PyObject *sysdict = interp->sysdict;
Victor Stinner331a6a52019-05-27 16:39:22 +02002857 const PyConfig *config = &interp->config;
Eric Snow6b4be192017-05-22 21:36:03 -07002858 int res;
2859
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002860#define COPY_LIST(KEY, VALUE) \
Victor Stinner37cd9822018-11-16 11:55:35 +01002861 do { \
Victor Stinner331a6a52019-05-27 16:39:22 +02002862 PyObject *list = _PyWideStringList_AsList(&(VALUE)); \
Victor Stinner37cd9822018-11-16 11:55:35 +01002863 if (list == NULL) { \
2864 return -1; \
2865 } \
2866 SET_SYS_FROM_STRING_BORROW(KEY, list); \
2867 Py_DECREF(list); \
2868 } while (0)
2869
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002870#define SET_SYS_FROM_WSTR(KEY, VALUE) \
2871 do { \
2872 PyObject *str = PyUnicode_FromWideChar(VALUE, -1); \
2873 if (str == NULL) { \
2874 return -1; \
2875 } \
2876 SET_SYS_FROM_STRING_BORROW(KEY, str); \
2877 Py_DECREF(str); \
2878 } while (0)
Victor Stinner37cd9822018-11-16 11:55:35 +01002879
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002880 COPY_LIST("path", config->module_search_paths);
2881
2882 SET_SYS_FROM_WSTR("executable", config->executable);
2883 SET_SYS_FROM_WSTR("prefix", config->prefix);
2884 SET_SYS_FROM_WSTR("base_prefix", config->base_prefix);
2885 SET_SYS_FROM_WSTR("exec_prefix", config->exec_prefix);
2886 SET_SYS_FROM_WSTR("base_exec_prefix", config->base_exec_prefix);
Victor Stinner41264f12017-12-15 02:05:29 +01002887
Carl Meyerb193fa92018-06-15 22:40:56 -06002888 if (config->pycache_prefix != NULL) {
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002889 SET_SYS_FROM_WSTR("pycache_prefix", config->pycache_prefix);
Carl Meyerb193fa92018-06-15 22:40:56 -06002890 } else {
2891 PyDict_SetItemString(sysdict, "pycache_prefix", Py_None);
2892 }
2893
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002894 COPY_LIST("argv", config->argv);
2895 COPY_LIST("warnoptions", config->warnoptions);
2896
2897 PyObject *xoptions = sys_create_xoptions_dict(config);
2898 if (xoptions == NULL) {
2899 return -1;
Victor Stinner41264f12017-12-15 02:05:29 +01002900 }
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002901 SET_SYS_FROM_STRING_BORROW("_xoptions", xoptions);
Pablo Galindo34ef64f2019-03-27 12:43:47 +00002902 Py_DECREF(xoptions);
Victor Stinner41264f12017-12-15 02:05:29 +01002903
Victor Stinner37cd9822018-11-16 11:55:35 +01002904#undef COPY_LIST
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002905#undef SET_SYS_FROM_WSTR
Victor Stinner37cd9822018-11-16 11:55:35 +01002906
Eric Snow6b4be192017-05-22 21:36:03 -07002907 /* Set flags to their final values */
Eric Snow396e0a82019-05-31 21:16:47 -06002908 SET_SYS_FROM_STRING_INT_RESULT("flags", make_flags(interp));
Eric Snow6b4be192017-05-22 21:36:03 -07002909 /* prevent user from creating new instances */
2910 FlagsType.tp_init = NULL;
2911 FlagsType.tp_new = NULL;
2912 res = PyDict_DelItemString(FlagsType.tp_dict, "__new__");
2913 if (res < 0) {
2914 if (!PyErr_ExceptionMatches(PyExc_KeyError)) {
2915 return res;
2916 }
2917 PyErr_Clear();
2918 }
2919
2920 SET_SYS_FROM_STRING_INT_RESULT("dont_write_bytecode",
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002921 PyBool_FromLong(!config->write_bytecode));
Eric Snow6b4be192017-05-22 21:36:03 -07002922
Eric Snowdae02762017-09-14 00:35:58 -07002923 if (get_warnoptions() == NULL)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002924 return -1;
Victor Stinner865de272017-06-08 13:27:47 +02002925
Eric Snowdae02762017-09-14 00:35:58 -07002926 if (get_xoptions() == NULL)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002927 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002928
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002929 /* Transfer any sys.warnoptions and sys._xoptions set directly
2930 * by an embedding application from the linked list to the module. */
2931 if (_PySys_ReadPreInitOptions() != 0)
2932 return -1;
2933
Eric Snow6b4be192017-05-22 21:36:03 -07002934 if (PyErr_Occurred())
2935 return -1;
2936 return 0;
Victor Stinner41264f12017-12-15 02:05:29 +01002937
2938err_occurred:
2939 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002940}
2941
Victor Stinner41264f12017-12-15 02:05:29 +01002942#undef SET_SYS_FROM_STRING_BORROW
Eric Snow6b4be192017-05-22 21:36:03 -07002943#undef SET_SYS_FROM_STRING_INT_RESULT
Eric Snow6b4be192017-05-22 21:36:03 -07002944
Victor Stinnerab672812019-01-23 15:04:40 +01002945
2946/* Set up a preliminary stderr printer until we have enough
2947 infrastructure for the io module in place.
2948
2949 Use UTF-8/surrogateescape and ignore EAGAIN errors. */
Victor Stinner331a6a52019-05-27 16:39:22 +02002950PyStatus
Victor Stinnerab672812019-01-23 15:04:40 +01002951_PySys_SetPreliminaryStderr(PyObject *sysdict)
2952{
2953 PyObject *pstderr = PyFile_NewStdPrinter(fileno(stderr));
2954 if (pstderr == NULL) {
2955 goto error;
2956 }
2957 if (_PyDict_SetItemId(sysdict, &PyId_stderr, pstderr) < 0) {
2958 goto error;
2959 }
2960 if (PyDict_SetItemString(sysdict, "__stderr__", pstderr) < 0) {
2961 goto error;
2962 }
2963 Py_DECREF(pstderr);
Victor Stinner331a6a52019-05-27 16:39:22 +02002964 return _PyStatus_OK();
Victor Stinnerab672812019-01-23 15:04:40 +01002965
2966error:
2967 Py_XDECREF(pstderr);
Victor Stinner331a6a52019-05-27 16:39:22 +02002968 return _PyStatus_ERR("can't set preliminary stderr");
Victor Stinnerab672812019-01-23 15:04:40 +01002969}
2970
2971
2972/* Create sys module without all attributes: _PySys_InitMain() should be called
2973 later to add remaining attributes. */
Victor Stinner331a6a52019-05-27 16:39:22 +02002974PyStatus
Eric Snow396e0a82019-05-31 21:16:47 -06002975_PySys_Create(PyInterpreterState *interp, PyObject **sysmod_p)
Victor Stinnerab672812019-01-23 15:04:40 +01002976{
2977 PyObject *modules = PyDict_New();
2978 if (modules == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002979 return _PyStatus_ERR("can't make modules dictionary");
Victor Stinnerab672812019-01-23 15:04:40 +01002980 }
2981 interp->modules = modules;
2982
2983 PyObject *sysmod = _PyModule_CreateInitialized(&sysmodule, PYTHON_API_VERSION);
2984 if (sysmod == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002985 return _PyStatus_ERR("failed to create a module object");
Victor Stinnerab672812019-01-23 15:04:40 +01002986 }
2987
2988 PyObject *sysdict = PyModule_GetDict(sysmod);
2989 if (sysdict == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002990 return _PyStatus_ERR("can't initialize sys dict");
Victor Stinnerab672812019-01-23 15:04:40 +01002991 }
2992 Py_INCREF(sysdict);
2993 interp->sysdict = sysdict;
2994
2995 if (PyDict_SetItemString(sysdict, "modules", interp->modules) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002996 return _PyStatus_ERR("can't initialize sys module");
Victor Stinnerab672812019-01-23 15:04:40 +01002997 }
2998
Victor Stinner331a6a52019-05-27 16:39:22 +02002999 PyStatus status = _PySys_SetPreliminaryStderr(sysdict);
3000 if (_PyStatus_EXCEPTION(status)) {
3001 return status;
Victor Stinnerab672812019-01-23 15:04:40 +01003002 }
3003
Eric Snow396e0a82019-05-31 21:16:47 -06003004 status = _PySys_InitCore(interp, sysdict);
Victor Stinner331a6a52019-05-27 16:39:22 +02003005 if (_PyStatus_EXCEPTION(status)) {
3006 return status;
Victor Stinnerab672812019-01-23 15:04:40 +01003007 }
3008
3009 _PyImport_FixupBuiltin(sysmod, "sys", interp->modules);
3010
3011 *sysmod_p = sysmod;
Victor Stinner331a6a52019-05-27 16:39:22 +02003012 return _PyStatus_OK();
Victor Stinnerab672812019-01-23 15:04:40 +01003013}
3014
3015
Guido van Rossum65bf9f21997-04-29 18:33:38 +00003016static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00003017makepathobject(const wchar_t *path, wchar_t delim)
Guido van Rossum5b3138b1990-11-18 17:41:40 +00003018{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003019 int i, n;
3020 const wchar_t *p;
3021 PyObject *v, *w;
Tim Peters216b78b2006-01-06 02:40:53 +00003022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003023 n = 1;
3024 p = path;
3025 while ((p = wcschr(p, delim)) != NULL) {
3026 n++;
3027 p++;
3028 }
3029 v = PyList_New(n);
3030 if (v == NULL)
3031 return NULL;
3032 for (i = 0; ; i++) {
3033 p = wcschr(path, delim);
3034 if (p == NULL)
3035 p = path + wcslen(path); /* End of string */
3036 w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
3037 if (w == NULL) {
3038 Py_DECREF(v);
3039 return NULL;
3040 }
Zackery Spytz99d56b52018-12-08 07:16:55 -07003041 PyList_SET_ITEM(v, i, w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003042 if (*p == '\0')
3043 break;
3044 path = p+1;
3045 }
3046 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003047}
3048
3049void
Martin v. Löwis790465f2008-04-05 20:41:37 +00003050PySys_SetPath(const wchar_t *path)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003051{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003052 PyObject *v;
3053 if ((v = makepathobject(path, DELIM)) == NULL)
3054 Py_FatalError("can't create sys.path");
Victor Stinnerbd303c12013-11-07 23:07:29 +01003055 if (_PySys_SetObjectId(&PyId_path, v) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003056 Py_FatalError("can't assign sys.path");
3057 Py_DECREF(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00003058}
3059
Guido van Rossum65bf9f21997-04-29 18:33:38 +00003060static PyObject *
Victor Stinner74f65682019-03-15 15:08:05 +01003061make_sys_argv(int argc, wchar_t * const * argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00003062{
Victor Stinner74f65682019-03-15 15:08:05 +01003063 PyObject *list = PyList_New(argc);
3064 if (list == NULL) {
3065 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003066 }
Victor Stinner74f65682019-03-15 15:08:05 +01003067
3068 for (Py_ssize_t i = 0; i < argc; i++) {
3069 PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
3070 if (v == NULL) {
3071 Py_DECREF(list);
3072 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003073 }
Victor Stinner74f65682019-03-15 15:08:05 +01003074 PyList_SET_ITEM(list, i, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003075 }
Victor Stinner74f65682019-03-15 15:08:05 +01003076 return list;
Guido van Rossum3f5da241990-12-20 15:06:42 +00003077}
3078
Victor Stinner11a247d2017-12-13 21:05:57 +01003079void
3080PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
Victor Stinnerd5dda982017-12-13 17:31:16 +01003081{
Victor Stinner74f65682019-03-15 15:08:05 +01003082 if (argc < 1 || argv == NULL) {
3083 /* Ensure at least one (empty) argument is seen */
3084 wchar_t* empty_argv[1] = {L""};
3085 argv = empty_argv;
3086 argc = 1;
3087 }
3088
3089 PyObject *av = make_sys_argv(argc, argv);
Victor Stinnerd5dda982017-12-13 17:31:16 +01003090 if (av == NULL) {
Victor Stinner11a247d2017-12-13 21:05:57 +01003091 Py_FatalError("no mem for sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01003092 }
3093 if (PySys_SetObject("argv", av) != 0) {
3094 Py_DECREF(av);
Victor Stinner11a247d2017-12-13 21:05:57 +01003095 Py_FatalError("can't assign sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01003096 }
3097 Py_DECREF(av);
3098
3099 if (updatepath) {
3100 /* If argv[0] is not '-c' nor '-m', prepend argv[0] to sys.path.
3101 If argv[0] is a symlink, use the real path. */
Victor Stinner331a6a52019-05-27 16:39:22 +02003102 const PyWideStringList argv_list = {.length = argc, .items = argv};
Victor Stinnerdcf61712019-03-19 16:09:27 +01003103 PyObject *path0 = NULL;
3104 if (_PyPathConfig_ComputeSysPath0(&argv_list, &path0)) {
3105 if (path0 == NULL) {
3106 Py_FatalError("can't compute path0 from argv");
Victor Stinner11a247d2017-12-13 21:05:57 +01003107 }
Victor Stinnerdcf61712019-03-19 16:09:27 +01003108
3109 PyObject *sys_path = _PySys_GetObjectId(&PyId_path);
3110 if (sys_path != NULL) {
3111 if (PyList_Insert(sys_path, 0, path0) < 0) {
3112 Py_DECREF(path0);
3113 Py_FatalError("can't prepend path0 to sys.path");
3114 }
3115 }
3116 Py_DECREF(path0);
Victor Stinner11a247d2017-12-13 21:05:57 +01003117 }
Victor Stinnerd5dda982017-12-13 17:31:16 +01003118 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003119}
Guido van Rossuma890e681998-05-12 14:59:24 +00003120
Antoine Pitrouf978fac2010-05-21 17:25:34 +00003121void
3122PySys_SetArgv(int argc, wchar_t **argv)
3123{
Christian Heimesad73a9c2013-08-10 16:36:18 +02003124 PySys_SetArgvEx(argc, argv, Py_IsolatedFlag == 0);
Antoine Pitrouf978fac2010-05-21 17:25:34 +00003125}
3126
Victor Stinner14284c22010-04-23 12:02:30 +00003127/* Reimplementation of PyFile_WriteString() no calling indirectly
3128 PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
3129
3130static int
Victor Stinner79766632010-08-16 17:36:42 +00003131sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
Victor Stinner14284c22010-04-23 12:02:30 +00003132{
Victor Stinnerc3ccaae2016-08-20 01:24:22 +02003133 PyObject *writer = NULL, *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003134 int err;
Victor Stinner14284c22010-04-23 12:02:30 +00003135
Victor Stinnerecccc4f2010-06-08 20:46:00 +00003136 if (file == NULL)
3137 return -1;
3138
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003139 writer = _PyObject_GetAttrId(file, &PyId_write);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003140 if (writer == NULL)
3141 goto error;
Victor Stinner14284c22010-04-23 12:02:30 +00003142
Victor Stinner7bfb42d2016-12-05 17:04:32 +01003143 result = PyObject_CallFunctionObjArgs(writer, unicode, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003144 if (result == NULL) {
3145 goto error;
3146 } else {
3147 err = 0;
3148 goto finally;
3149 }
Victor Stinner14284c22010-04-23 12:02:30 +00003150
3151error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003152 err = -1;
Victor Stinner14284c22010-04-23 12:02:30 +00003153finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003154 Py_XDECREF(writer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003155 Py_XDECREF(result);
3156 return err;
Victor Stinner14284c22010-04-23 12:02:30 +00003157}
3158
Victor Stinner79766632010-08-16 17:36:42 +00003159static int
3160sys_pyfile_write(const char *text, PyObject *file)
3161{
3162 PyObject *unicode = NULL;
3163 int err;
3164
3165 if (file == NULL)
3166 return -1;
3167
3168 unicode = PyUnicode_FromString(text);
3169 if (unicode == NULL)
3170 return -1;
3171
3172 err = sys_pyfile_write_unicode(unicode, file);
3173 Py_DECREF(unicode);
3174 return err;
3175}
Guido van Rossuma890e681998-05-12 14:59:24 +00003176
3177/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
3178 Adapted from code submitted by Just van Rossum.
3179
3180 PySys_WriteStdout(format, ...)
3181 PySys_WriteStderr(format, ...)
3182
3183 The first function writes to sys.stdout; the second to sys.stderr. When
3184 there is a problem, they write to the real (C level) stdout or stderr;
Guido van Rossum8442af31998-10-12 18:22:10 +00003185 no exceptions are raised.
Guido van Rossuma890e681998-05-12 14:59:24 +00003186
Victor Stinner14284c22010-04-23 12:02:30 +00003187 PyErr_CheckSignals() is not called to avoid the execution of the Python
Victor Stinner79766632010-08-16 17:36:42 +00003188 signal handlers: they may raise a new exception whereas sys_write()
3189 ignores all exceptions.
Victor Stinner14284c22010-04-23 12:02:30 +00003190
Guido van Rossuma890e681998-05-12 14:59:24 +00003191 Both take a printf-style format string as their first argument followed
3192 by a variable length argument list determined by the format string.
3193
3194 *** WARNING ***
3195
3196 The format should limit the total size of the formatted output string to
3197 1000 bytes. In particular, this means that no unrestricted "%s" formats
3198 should occur; these should be limited using "%.<N>s where <N> is a
3199 decimal number calculated so that <N> plus the maximum size of other
3200 formatted text does not exceed 1000 bytes. Also watch out for "%f",
3201 which can print hundreds of digits for very large numbers.
3202
3203 */
3204
3205static void
Victor Stinner09054372013-11-06 22:41:44 +01003206sys_write(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Guido van Rossuma890e681998-05-12 14:59:24 +00003207{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003208 PyObject *file;
3209 PyObject *error_type, *error_value, *error_traceback;
3210 char buffer[1001];
3211 int written;
Guido van Rossuma890e681998-05-12 14:59:24 +00003212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003213 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01003214 file = _PySys_GetObjectId(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003215 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
3216 if (sys_pyfile_write(buffer, file) != 0) {
3217 PyErr_Clear();
3218 fputs(buffer, fp);
3219 }
3220 if (written < 0 || (size_t)written >= sizeof(buffer)) {
3221 const char *truncated = "... truncated";
Victor Stinner79766632010-08-16 17:36:42 +00003222 if (sys_pyfile_write(truncated, file) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003223 fputs(truncated, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003224 }
3225 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossuma890e681998-05-12 14:59:24 +00003226}
3227
3228void
Guido van Rossuma890e681998-05-12 14:59:24 +00003229PySys_WriteStdout(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00003230{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003231 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00003232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003233 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003234 sys_write(&PyId_stdout, stdout, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003235 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00003236}
3237
3238void
Guido van Rossuma890e681998-05-12 14:59:24 +00003239PySys_WriteStderr(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00003240{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003241 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00003242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003243 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003244 sys_write(&PyId_stderr, stderr, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00003245 va_end(va);
3246}
3247
3248static void
Victor Stinner09054372013-11-06 22:41:44 +01003249sys_format(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Victor Stinner79766632010-08-16 17:36:42 +00003250{
3251 PyObject *file, *message;
3252 PyObject *error_type, *error_value, *error_traceback;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02003253 const char *utf8;
Victor Stinner79766632010-08-16 17:36:42 +00003254
3255 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01003256 file = _PySys_GetObjectId(key);
Victor Stinner79766632010-08-16 17:36:42 +00003257 message = PyUnicode_FromFormatV(format, va);
3258 if (message != NULL) {
3259 if (sys_pyfile_write_unicode(message, file) != 0) {
3260 PyErr_Clear();
Serhiy Storchaka06515832016-11-20 09:13:07 +02003261 utf8 = PyUnicode_AsUTF8(message);
Victor Stinner79766632010-08-16 17:36:42 +00003262 if (utf8 != NULL)
3263 fputs(utf8, fp);
3264 }
3265 Py_DECREF(message);
3266 }
3267 PyErr_Restore(error_type, error_value, error_traceback);
3268}
3269
3270void
3271PySys_FormatStdout(const char *format, ...)
3272{
3273 va_list va;
3274
3275 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003276 sys_format(&PyId_stdout, stdout, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00003277 va_end(va);
3278}
3279
3280void
3281PySys_FormatStderr(const char *format, ...)
3282{
3283 va_list va;
3284
3285 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003286 sys_format(&PyId_stderr, stderr, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003287 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00003288}