blob: 9f866a2a3d2fa09ab6d906d2ba061d4bb6db81d6 [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 Stinner838f2642019-06-13 22:41:23 +020020#include "pycore_ceval.h"
Victor Stinner331a6a52019-05-27 16:39:22 +020021#include "pycore_initconfig.h"
Victor Stinner838f2642019-06-13 22:41:23 +020022#include "pycore_pathconfig.h"
23#include "pycore_pyerrors.h"
Victor Stinner621cebe2018-11-12 16:53:38 +010024#include "pycore_pylifecycle.h"
25#include "pycore_pymem.h"
Victor Stinner621cebe2018-11-12 16:53:38 +010026#include "pycore_pystate.h"
Steve Dowerb82e17e2019-05-23 08:45:22 -070027#include "pycore_tupleobject.h"
Victor Stinnerd5c355c2011-04-30 14:53:09 +020028#include "pythread.h"
Steve Dowerb82e17e2019-05-23 08:45:22 -070029#include "pydtrace.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000030
Guido van Rossume2437a11992-03-23 18:20:18 +000031#include "osdefs.h"
Stefan Krah1845d142016-04-25 21:38:53 +020032#include <locale.h>
Guido van Rossum3f5da241990-12-20 15:06:42 +000033
Mark Hammond8696ebc2002-10-08 02:44:31 +000034#ifdef MS_WINDOWS
35#define WIN32_LEAN_AND_MEAN
Amaury Forgeot d'Arc06cfe952007-11-10 13:55:44 +000036#include <windows.h>
Mark Hammond8696ebc2002-10-08 02:44:31 +000037#endif /* MS_WINDOWS */
38
Guido van Rossum9b38a141996-09-11 23:12:24 +000039#ifdef MS_COREDLL
Guido van Rossumc606fe11996-04-09 02:37:57 +000040extern void *PyWin_DLLhModule;
Guido van Rossum6c1e5f21997-09-29 23:34:23 +000041/* A string loaded from the DLL at startup: */
42extern const char *PyWin_DLLVersionString;
Guido van Rossumc606fe11996-04-09 02:37:57 +000043#endif
44
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -080045/*[clinic input]
46module sys
47[clinic start generated code]*/
48/*[clinic end generated code: output=da39a3ee5e6b4b0d input=3726b388feee8cea]*/
49
50#include "clinic/sysmodule.c.h"
51
Victor Stinnerbd303c12013-11-07 23:07:29 +010052_Py_IDENTIFIER(_);
53_Py_IDENTIFIER(__sizeof__);
Eric Snowdae02762017-09-14 00:35:58 -070054_Py_IDENTIFIER(_xoptions);
Victor Stinnerbd303c12013-11-07 23:07:29 +010055_Py_IDENTIFIER(buffer);
56_Py_IDENTIFIER(builtins);
57_Py_IDENTIFIER(encoding);
58_Py_IDENTIFIER(path);
59_Py_IDENTIFIER(stdout);
60_Py_IDENTIFIER(stderr);
Eric Snowdae02762017-09-14 00:35:58 -070061_Py_IDENTIFIER(warnoptions);
Victor Stinnerbd303c12013-11-07 23:07:29 +010062_Py_IDENTIFIER(write);
63
Victor Stinner838f2642019-06-13 22:41:23 +020064static PyObject *
65sys_get_object_id(PyThreadState *tstate, _Py_Identifier *key)
Victor Stinnerd67bd452013-11-06 22:36:40 +010066{
Victor Stinner838f2642019-06-13 22:41:23 +020067 PyObject *sd = tstate->interp->sysdict;
Victor Stinnercaba55b2018-08-03 15:33:52 +020068 if (sd == NULL) {
Victor Stinnerd67bd452013-11-06 22:36:40 +010069 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +020070 }
Victor Stinnerd67bd452013-11-06 22:36:40 +010071 return _PyDict_GetItemId(sd, key);
72}
73
74PyObject *
Victor Stinner838f2642019-06-13 22:41:23 +020075_PySys_GetObjectId(_Py_Identifier *key)
76{
77 PyThreadState *tstate = _PyThreadState_GET();
78 return sys_get_object_id(tstate, key);
79}
80
81PyObject *
Neal Norwitzf3081322007-08-25 00:32:45 +000082PySys_GetObject(const char *name)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000083{
Victor Stinner838f2642019-06-13 22:41:23 +020084 PyThreadState *tstate = _PyThreadState_GET();
85 PyObject *sd = tstate->interp->sysdict;
Victor Stinnercaba55b2018-08-03 15:33:52 +020086 if (sd == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000087 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +020088 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000089 return PyDict_GetItemString(sd, name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000090}
91
Victor Stinner838f2642019-06-13 22:41:23 +020092static int
93sys_set_object_id(PyThreadState *tstate, _Py_Identifier *key, PyObject *v)
Victor Stinnerd67bd452013-11-06 22:36:40 +010094{
Victor Stinner838f2642019-06-13 22:41:23 +020095 PyObject *sd = tstate->interp->sysdict;
Victor Stinnerd67bd452013-11-06 22:36:40 +010096 if (v == NULL) {
Victor Stinnercaba55b2018-08-03 15:33:52 +020097 if (_PyDict_GetItemId(sd, key) == NULL) {
Victor Stinnerd67bd452013-11-06 22:36:40 +010098 return 0;
Victor Stinnercaba55b2018-08-03 15:33:52 +020099 }
100 else {
Victor Stinnerd67bd452013-11-06 22:36:40 +0100101 return _PyDict_DelItemId(sd, key);
Victor Stinnercaba55b2018-08-03 15:33:52 +0200102 }
Victor Stinnerd67bd452013-11-06 22:36:40 +0100103 }
Victor Stinnercaba55b2018-08-03 15:33:52 +0200104 else {
Victor Stinnerd67bd452013-11-06 22:36:40 +0100105 return _PyDict_SetItemId(sd, key, v);
Victor Stinnercaba55b2018-08-03 15:33:52 +0200106 }
Victor Stinnerd67bd452013-11-06 22:36:40 +0100107}
108
109int
Victor Stinner838f2642019-06-13 22:41:23 +0200110_PySys_SetObjectId(_Py_Identifier *key, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000111{
Victor Stinner838f2642019-06-13 22:41:23 +0200112 PyThreadState *tstate = _PyThreadState_GET();
113 return sys_set_object_id(tstate, key, v);
114}
115
116static int
117sys_set_object(PyThreadState *tstate, const char *name, PyObject *v)
118{
119 PyObject *sd = tstate->interp->sysdict;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000120 if (v == NULL) {
Victor Stinnercaba55b2018-08-03 15:33:52 +0200121 if (PyDict_GetItemString(sd, name) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000122 return 0;
Victor Stinnercaba55b2018-08-03 15:33:52 +0200123 }
124 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000125 return PyDict_DelItemString(sd, name);
Victor Stinnercaba55b2018-08-03 15:33:52 +0200126 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000127 }
Victor Stinnercaba55b2018-08-03 15:33:52 +0200128 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000129 return PyDict_SetItemString(sd, name, v);
Victor Stinnercaba55b2018-08-03 15:33:52 +0200130 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000131}
132
Victor Stinner838f2642019-06-13 22:41:23 +0200133int
134PySys_SetObject(const char *name, PyObject *v)
Steve Dowerb82e17e2019-05-23 08:45:22 -0700135{
Victor Stinner838f2642019-06-13 22:41:23 +0200136 PyThreadState *tstate = _PyThreadState_GET();
137 return sys_set_object(tstate, name, v);
138}
139
140static int
141should_audit(PyThreadState *ts)
142{
Steve Dowerb82e17e2019-05-23 08:45:22 -0700143 if (!ts) {
144 return 0;
145 }
Victor Stinner0fd2c302019-06-04 03:15:09 +0200146 PyInterpreterState *is = ts ? ts->interp : NULL;
147 return _PyRuntime.audit_hook_head
Steve Dowerb82e17e2019-05-23 08:45:22 -0700148 || (is && is->audit_hooks)
149 || PyDTrace_AUDIT_ENABLED();
150}
151
152int
153PySys_Audit(const char *event, const char *argFormat, ...)
154{
155 PyObject *eventName = NULL;
156 PyObject *eventArgs = NULL;
157 PyObject *hooks = NULL;
158 PyObject *hook = NULL;
159 int res = -1;
Victor Stinner838f2642019-06-13 22:41:23 +0200160 PyThreadState *ts = _PyThreadState_GET();
Steve Dowerb82e17e2019-05-23 08:45:22 -0700161
162 /* N format is inappropriate, because you do not know
163 whether the reference is consumed by the call.
164 Assert rather than exception for perf reasons */
165 assert(!argFormat || !strchr(argFormat, 'N'));
166
167 /* Early exit when no hooks are registered */
Victor Stinner838f2642019-06-13 22:41:23 +0200168 if (!should_audit(ts)) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700169 return 0;
170 }
171
172 _Py_AuditHookEntry *e = _PyRuntime.audit_hook_head;
Steve Dowerb82e17e2019-05-23 08:45:22 -0700173 int dtrace = PyDTrace_AUDIT_ENABLED();
174
175 PyObject *exc_type, *exc_value, *exc_tb;
176 if (ts) {
Victor Stinner838f2642019-06-13 22:41:23 +0200177 _PyErr_Fetch(ts, &exc_type, &exc_value, &exc_tb);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700178 }
179
180 /* Initialize event args now */
181 if (argFormat && argFormat[0]) {
182 va_list args;
183 va_start(args, argFormat);
Steve Dowerb8cbe742019-12-09 11:05:39 -0800184 eventArgs = _Py_VaBuildValue_SizeT(argFormat, args);
Zackery Spytz08286d52019-06-21 09:31:59 -0600185 va_end(args);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700186 if (eventArgs && !PyTuple_Check(eventArgs)) {
187 PyObject *argTuple = PyTuple_Pack(1, eventArgs);
188 Py_DECREF(eventArgs);
189 eventArgs = argTuple;
190 }
191 } else {
192 eventArgs = PyTuple_New(0);
193 }
194 if (!eventArgs) {
195 goto exit;
196 }
197
198 /* Call global hooks */
199 for (; e; e = e->next) {
200 if (e->hookCFunction(event, eventArgs, e->userData) < 0) {
201 goto exit;
202 }
203 }
204
205 /* Dtrace USDT point */
206 if (dtrace) {
207 PyDTrace_AUDIT(event, (void *)eventArgs);
208 }
209
210 /* Call interpreter hooks */
Victor Stinner838f2642019-06-13 22:41:23 +0200211 PyInterpreterState *is = ts ? ts->interp : NULL;
Steve Dowerb82e17e2019-05-23 08:45:22 -0700212 if (is && is->audit_hooks) {
213 eventName = PyUnicode_FromString(event);
214 if (!eventName) {
215 goto exit;
216 }
217
218 hooks = PyObject_GetIter(is->audit_hooks);
219 if (!hooks) {
220 goto exit;
221 }
222
223 /* Disallow tracing in hooks unless explicitly enabled */
224 ts->tracing++;
225 ts->use_tracing = 0;
226 while ((hook = PyIter_Next(hooks)) != NULL) {
Serhiy Storchaka41c57b32019-09-01 12:03:39 +0300227 _Py_IDENTIFIER(__cantrace__);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700228 PyObject *o;
Serhiy Storchaka41c57b32019-09-01 12:03:39 +0300229 int canTrace = _PyObject_LookupAttrId(hook, &PyId___cantrace__, &o);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700230 if (o) {
231 canTrace = PyObject_IsTrue(o);
232 Py_DECREF(o);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700233 }
234 if (canTrace < 0) {
235 break;
236 }
237 if (canTrace) {
238 ts->use_tracing = (ts->c_tracefunc || ts->c_profilefunc);
239 ts->tracing--;
240 }
241 o = PyObject_CallFunctionObjArgs(hook, eventName,
242 eventArgs, NULL);
243 if (canTrace) {
244 ts->tracing++;
245 ts->use_tracing = 0;
246 }
247 if (!o) {
248 break;
249 }
250 Py_DECREF(o);
251 Py_CLEAR(hook);
252 }
253 ts->use_tracing = (ts->c_tracefunc || ts->c_profilefunc);
254 ts->tracing--;
Victor Stinner838f2642019-06-13 22:41:23 +0200255 if (_PyErr_Occurred(ts)) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700256 goto exit;
257 }
258 }
259
260 res = 0;
261
262exit:
263 Py_XDECREF(hook);
264 Py_XDECREF(hooks);
265 Py_XDECREF(eventName);
266 Py_XDECREF(eventArgs);
267
268 if (ts) {
269 if (!res) {
Victor Stinner838f2642019-06-13 22:41:23 +0200270 _PyErr_Restore(ts, exc_type, exc_value, exc_tb);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700271 } else {
Victor Stinner838f2642019-06-13 22:41:23 +0200272 assert(_PyErr_Occurred(ts));
Steve Dowerb82e17e2019-05-23 08:45:22 -0700273 Py_XDECREF(exc_type);
274 Py_XDECREF(exc_value);
275 Py_XDECREF(exc_tb);
276 }
277 }
278
279 return res;
280}
281
282/* We expose this function primarily for our own cleanup during
283 * finalization. In general, it should not need to be called,
284 * and as such it is not defined in any header files.
285 */
Victor Stinner838f2642019-06-13 22:41:23 +0200286void
287_PySys_ClearAuditHooks(void)
288{
Steve Dowerb82e17e2019-05-23 08:45:22 -0700289 /* Must be finalizing to clear hooks */
290 _PyRuntimeState *runtime = &_PyRuntime;
291 PyThreadState *ts = _PyRuntimeState_GetThreadState(runtime);
292 assert(!ts || _Py_CURRENTLY_FINALIZING(runtime, ts));
Victor Stinner838f2642019-06-13 22:41:23 +0200293 if (!ts || !_Py_CURRENTLY_FINALIZING(runtime, ts)) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700294 return;
Victor Stinner838f2642019-06-13 22:41:23 +0200295 }
Steve Dowerb82e17e2019-05-23 08:45:22 -0700296
Victor Stinner838f2642019-06-13 22:41:23 +0200297 const PyConfig *config = &ts->interp->config;
298 if (config->verbose) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700299 PySys_WriteStderr("# clear sys.audit hooks\n");
300 }
301
302 /* Hooks can abort later hooks for this event, but cannot
303 abort the clear operation itself. */
304 PySys_Audit("cpython._PySys_ClearAuditHooks", NULL);
Victor Stinner838f2642019-06-13 22:41:23 +0200305 _PyErr_Clear(ts);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700306
Victor Stinner0fd2c302019-06-04 03:15:09 +0200307 _Py_AuditHookEntry *e = _PyRuntime.audit_hook_head, *n;
308 _PyRuntime.audit_hook_head = NULL;
Steve Dowerb82e17e2019-05-23 08:45:22 -0700309 while (e) {
310 n = e->next;
311 PyMem_RawFree(e);
312 e = n;
313 }
314}
315
316int
317PySys_AddAuditHook(Py_AuditHookFunction hook, void *userData)
318{
Victor Stinner838f2642019-06-13 22:41:23 +0200319 _PyRuntimeState *runtime = &_PyRuntime;
320 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
321
Steve Dowerb82e17e2019-05-23 08:45:22 -0700322 /* Invoke existing audit hooks to allow them an opportunity to abort. */
323 /* Cannot invoke hooks until we are initialized */
Victor Stinner838f2642019-06-13 22:41:23 +0200324 if (runtime->initialized) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700325 if (PySys_Audit("sys.addaudithook", NULL) < 0) {
Steve Dowerbea33f52019-11-28 08:46:11 -0800326 if (_PyErr_ExceptionMatches(tstate, PyExc_RuntimeError)) {
327 /* We do not report errors derived from RuntimeError */
Victor Stinner838f2642019-06-13 22:41:23 +0200328 _PyErr_Clear(tstate);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700329 return 0;
330 }
331 return -1;
332 }
333 }
334
Victor Stinner0fd2c302019-06-04 03:15:09 +0200335 _Py_AuditHookEntry *e = _PyRuntime.audit_hook_head;
Steve Dowerb82e17e2019-05-23 08:45:22 -0700336 if (!e) {
337 e = (_Py_AuditHookEntry*)PyMem_RawMalloc(sizeof(_Py_AuditHookEntry));
Victor Stinner0fd2c302019-06-04 03:15:09 +0200338 _PyRuntime.audit_hook_head = e;
Steve Dowerb82e17e2019-05-23 08:45:22 -0700339 } else {
Victor Stinner838f2642019-06-13 22:41:23 +0200340 while (e->next) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700341 e = e->next;
Victor Stinner838f2642019-06-13 22:41:23 +0200342 }
Steve Dowerb82e17e2019-05-23 08:45:22 -0700343 e = e->next = (_Py_AuditHookEntry*)PyMem_RawMalloc(
344 sizeof(_Py_AuditHookEntry));
345 }
346
347 if (!e) {
Victor Stinner838f2642019-06-13 22:41:23 +0200348 if (runtime->initialized) {
349 _PyErr_NoMemory(tstate);
350 }
Steve Dowerb82e17e2019-05-23 08:45:22 -0700351 return -1;
352 }
353
354 e->next = NULL;
355 e->hookCFunction = (Py_AuditHookFunction)hook;
356 e->userData = userData;
357
358 return 0;
359}
360
361/*[clinic input]
362sys.addaudithook
363
364 hook: object
365
366Adds a new audit hook callback.
367[clinic start generated code]*/
368
369static PyObject *
370sys_addaudithook_impl(PyObject *module, PyObject *hook)
371/*[clinic end generated code: output=4f9c17aaeb02f44e input=0f3e191217a45e34]*/
372{
Victor Stinner838f2642019-06-13 22:41:23 +0200373 PyThreadState *tstate = _PyThreadState_GET();
374
Steve Dowerb82e17e2019-05-23 08:45:22 -0700375 /* Invoke existing audit hooks to allow them an opportunity to abort. */
376 if (PySys_Audit("sys.addaudithook", NULL) < 0) {
Victor Stinner838f2642019-06-13 22:41:23 +0200377 if (_PyErr_ExceptionMatches(tstate, PyExc_Exception)) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700378 /* We do not report errors derived from Exception */
Victor Stinner838f2642019-06-13 22:41:23 +0200379 _PyErr_Clear(tstate);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700380 Py_RETURN_NONE;
381 }
382 return NULL;
383 }
384
Victor Stinner838f2642019-06-13 22:41:23 +0200385 PyInterpreterState *is = tstate->interp;
Steve Dowerb82e17e2019-05-23 08:45:22 -0700386
387 if (is->audit_hooks == NULL) {
388 is->audit_hooks = PyList_New(0);
389 if (is->audit_hooks == NULL) {
390 return NULL;
391 }
392 }
393
394 if (PyList_Append(is->audit_hooks, hook) < 0) {
395 return NULL;
396 }
397
398 Py_RETURN_NONE;
399}
400
401PyDoc_STRVAR(audit_doc,
402"audit(event, *args)\n\
403\n\
404Passes the event to any audit hooks that are attached.");
405
406static PyObject *
407sys_audit(PyObject *self, PyObject *const *args, Py_ssize_t argc)
408{
Victor Stinner838f2642019-06-13 22:41:23 +0200409 PyThreadState *tstate = _PyThreadState_GET();
410
Steve Dowerb82e17e2019-05-23 08:45:22 -0700411 if (argc == 0) {
Victor Stinner838f2642019-06-13 22:41:23 +0200412 _PyErr_SetString(tstate, PyExc_TypeError,
413 "audit() missing 1 required positional argument: "
414 "'event'");
Steve Dowerb82e17e2019-05-23 08:45:22 -0700415 return NULL;
416 }
417
Victor Stinner838f2642019-06-13 22:41:23 +0200418 if (!should_audit(tstate)) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700419 Py_RETURN_NONE;
420 }
421
422 PyObject *auditEvent = args[0];
423 if (!auditEvent) {
Victor Stinner838f2642019-06-13 22:41:23 +0200424 _PyErr_SetString(tstate, PyExc_TypeError,
425 "expected str for argument 'event'");
Steve Dowerb82e17e2019-05-23 08:45:22 -0700426 return NULL;
427 }
428 if (!PyUnicode_Check(auditEvent)) {
Victor Stinner838f2642019-06-13 22:41:23 +0200429 _PyErr_Format(tstate, PyExc_TypeError,
430 "expected str for argument 'event', not %.200s",
431 Py_TYPE(auditEvent)->tp_name);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700432 return NULL;
433 }
434 const char *event = PyUnicode_AsUTF8(auditEvent);
435 if (!event) {
436 return NULL;
437 }
438
439 PyObject *auditArgs = _PyTuple_FromArray(args + 1, argc - 1);
440 if (!auditArgs) {
441 return NULL;
442 }
443
444 int res = PySys_Audit(event, "O", auditArgs);
445 Py_DECREF(auditArgs);
446
447 if (res < 0) {
448 return NULL;
449 }
450
451 Py_RETURN_NONE;
452}
453
454
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400455static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +0200456sys_breakpointhook(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *keywords)
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400457{
Victor Stinner838f2642019-06-13 22:41:23 +0200458 PyThreadState *tstate = _PyThreadState_GET();
459 assert(!_PyErr_Occurred(tstate));
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300460 char *envar = Py_GETENV("PYTHONBREAKPOINT");
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400461
462 if (envar == NULL || strlen(envar) == 0) {
463 envar = "pdb.set_trace";
464 }
465 else if (!strcmp(envar, "0")) {
466 /* The breakpoint is explicitly no-op'd. */
467 Py_RETURN_NONE;
468 }
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300469 /* According to POSIX the string returned by getenv() might be invalidated
470 * or the string content might be overwritten by a subsequent call to
471 * getenv(). Since importing a module can performs the getenv() calls,
472 * we need to save a copy of envar. */
473 envar = _PyMem_RawStrdup(envar);
474 if (envar == NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +0200475 _PyErr_NoMemory(tstate);
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300476 return NULL;
477 }
Serhiy Storchaka4ae06c52017-12-12 13:55:04 +0200478 const char *last_dot = strrchr(envar, '.');
479 const char *attrname = NULL;
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400480 PyObject *modulepath = NULL;
481
482 if (last_dot == NULL) {
483 /* The breakpoint is a built-in, e.g. PYTHONBREAKPOINT=int */
484 modulepath = PyUnicode_FromString("builtins");
485 attrname = envar;
486 }
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200487 else if (last_dot != envar) {
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400488 /* Split on the last dot; */
489 modulepath = PyUnicode_FromStringAndSize(envar, last_dot - envar);
490 attrname = last_dot + 1;
491 }
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200492 else {
493 goto warn;
494 }
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400495 if (modulepath == NULL) {
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300496 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400497 return NULL;
498 }
499
Anthony Sottiledce345c2018-11-01 10:25:05 -0700500 PyObject *module = PyImport_Import(modulepath);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400501 Py_DECREF(modulepath);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400502
503 if (module == NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +0200504 if (_PyErr_ExceptionMatches(tstate, PyExc_ImportError)) {
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200505 goto warn;
506 }
507 PyMem_RawFree(envar);
508 return NULL;
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400509 }
510
511 PyObject *hook = PyObject_GetAttrString(module, attrname);
512 Py_DECREF(module);
513
514 if (hook == NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +0200515 if (_PyErr_ExceptionMatches(tstate, PyExc_AttributeError)) {
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200516 goto warn;
517 }
518 PyMem_RawFree(envar);
519 return NULL;
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400520 }
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300521 PyMem_RawFree(envar);
Jeroen Demeyeraacc77f2019-05-29 20:31:52 +0200522 PyObject *retval = _PyObject_Vectorcall(hook, args, nargs, keywords);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400523 Py_DECREF(hook);
524 return retval;
525
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200526 warn:
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400527 /* If any of the imports went wrong, then warn and ignore. */
Victor Stinner838f2642019-06-13 22:41:23 +0200528 _PyErr_Clear(tstate);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400529 int status = PyErr_WarnFormat(
530 PyExc_RuntimeWarning, 0,
531 "Ignoring unimportable $PYTHONBREAKPOINT: \"%s\"", envar);
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300532 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400533 if (status < 0) {
534 /* Printing the warning raised an exception. */
535 return NULL;
536 }
537 /* The warning was (probably) issued. */
538 Py_RETURN_NONE;
539}
540
541PyDoc_STRVAR(breakpointhook_doc,
542"breakpointhook(*args, **kws)\n"
543"\n"
544"This hook function is called by built-in breakpoint().\n"
545);
546
Victor Stinner13d49ee2010-12-04 17:24:33 +0000547/* Write repr(o) to sys.stdout using sys.stdout.encoding and 'backslashreplace'
548 error handler. If sys.stdout has a buffer attribute, use
549 sys.stdout.buffer.write(encoded), otherwise redecode the string and use
550 sys.stdout.write(redecoded).
551
552 Helper function for sys_displayhook(). */
553static int
Victor Stinner838f2642019-06-13 22:41:23 +0200554sys_displayhook_unencodable(PyThreadState *tstate, PyObject *outf, PyObject *o)
Victor Stinner13d49ee2010-12-04 17:24:33 +0000555{
556 PyObject *stdout_encoding = NULL;
557 PyObject *encoded, *escaped_str, *repr_str, *buffer, *result;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200558 const char *stdout_encoding_str;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000559 int ret;
560
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200561 stdout_encoding = _PyObject_GetAttrId(outf, &PyId_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000562 if (stdout_encoding == NULL)
563 goto error;
Serhiy Storchaka06515832016-11-20 09:13:07 +0200564 stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000565 if (stdout_encoding_str == NULL)
566 goto error;
567
568 repr_str = PyObject_Repr(o);
569 if (repr_str == NULL)
570 goto error;
571 encoded = PyUnicode_AsEncodedString(repr_str,
572 stdout_encoding_str,
573 "backslashreplace");
574 Py_DECREF(repr_str);
575 if (encoded == NULL)
576 goto error;
577
Serhiy Storchaka41c57b32019-09-01 12:03:39 +0300578 if (_PyObject_LookupAttrId(outf, &PyId_buffer, &buffer) < 0) {
579 Py_DECREF(encoded);
580 goto error;
581 }
Victor Stinner13d49ee2010-12-04 17:24:33 +0000582 if (buffer) {
Jeroen Demeyer59ad1102019-07-11 10:59:05 +0200583 result = _PyObject_CallMethodIdOneArg(buffer, &PyId_write, encoded);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000584 Py_DECREF(buffer);
585 Py_DECREF(encoded);
586 if (result == NULL)
587 goto error;
588 Py_DECREF(result);
589 }
590 else {
Victor Stinner13d49ee2010-12-04 17:24:33 +0000591 escaped_str = PyUnicode_FromEncodedObject(encoded,
592 stdout_encoding_str,
593 "strict");
594 Py_DECREF(encoded);
595 if (PyFile_WriteObject(escaped_str, outf, Py_PRINT_RAW) != 0) {
596 Py_DECREF(escaped_str);
597 goto error;
598 }
599 Py_DECREF(escaped_str);
600 }
601 ret = 0;
602 goto finally;
603
604error:
605 ret = -1;
606finally:
607 Py_XDECREF(stdout_encoding);
608 return ret;
609}
610
Tal Einatede0b6f2018-12-31 17:12:08 +0200611/*[clinic input]
612sys.displayhook
613
614 object as o: object
615 /
616
617Print an object to sys.stdout and also save it in builtins._
618[clinic start generated code]*/
619
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000620static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200621sys_displayhook(PyObject *module, PyObject *o)
622/*[clinic end generated code: output=347477d006df92ed input=08ba730166d7ef72]*/
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000623{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624 PyObject *outf;
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100625 PyObject *builtins;
626 static PyObject *newline = NULL;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000627 int err;
Victor Stinner838f2642019-06-13 22:41:23 +0200628 PyThreadState *tstate = _PyThreadState_GET();
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000629
Eric Snow3f9eee62017-09-15 16:35:20 -0600630 builtins = _PyImport_GetModuleId(&PyId_builtins);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 if (builtins == NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +0200632 if (!_PyErr_Occurred(tstate)) {
633 _PyErr_SetString(tstate, PyExc_RuntimeError,
634 "lost builtins module");
Stefan Krah027b09c2019-03-25 21:50:58 +0100635 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 return NULL;
637 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600638 Py_DECREF(builtins);
Moshe Zadka03897ea2001-07-23 13:32:43 +0000639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 /* Print value except if None */
641 /* After printing, also assign to '_' */
642 /* Before, set '_' to None to avoid recursion */
643 if (o == Py_None) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200644 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 }
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200646 if (_PyObject_SetAttrId(builtins, &PyId__, Py_None) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 return NULL;
Victor Stinner838f2642019-06-13 22:41:23 +0200648 outf = sys_get_object_id(tstate, &PyId_stdout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 if (outf == NULL || outf == Py_None) {
Victor Stinner838f2642019-06-13 22:41:23 +0200650 _PyErr_SetString(tstate, PyExc_RuntimeError, "lost sys.stdout");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 return NULL;
652 }
Victor Stinner13d49ee2010-12-04 17:24:33 +0000653 if (PyFile_WriteObject(o, outf, 0) != 0) {
Victor Stinner838f2642019-06-13 22:41:23 +0200654 if (_PyErr_ExceptionMatches(tstate, PyExc_UnicodeEncodeError)) {
Victor Stinner13d49ee2010-12-04 17:24:33 +0000655 /* repr(o) is not encodable to sys.stdout.encoding with
656 * sys.stdout.errors error handler (which is probably 'strict') */
Victor Stinner838f2642019-06-13 22:41:23 +0200657 _PyErr_Clear(tstate);
658 err = sys_displayhook_unencodable(tstate, outf, o);
659 if (err) {
Victor Stinner13d49ee2010-12-04 17:24:33 +0000660 return NULL;
Victor Stinner838f2642019-06-13 22:41:23 +0200661 }
Victor Stinner13d49ee2010-12-04 17:24:33 +0000662 }
663 else {
664 return NULL;
665 }
666 }
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100667 if (newline == NULL) {
668 newline = PyUnicode_FromString("\n");
669 if (newline == NULL)
670 return NULL;
671 }
672 if (PyFile_WriteObject(newline, outf, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000673 return NULL;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200674 if (_PyObject_SetAttrId(builtins, &PyId__, o) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200676 Py_RETURN_NONE;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000677}
678
Tal Einatede0b6f2018-12-31 17:12:08 +0200679
680/*[clinic input]
681sys.excepthook
682
683 exctype: object
684 value: object
685 traceback: object
686 /
687
688Handle an exception by displaying it with a traceback on sys.stderr.
689[clinic start generated code]*/
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000690
691static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200692sys_excepthook_impl(PyObject *module, PyObject *exctype, PyObject *value,
693 PyObject *traceback)
694/*[clinic end generated code: output=18d99fdda21b6b5e input=ecf606fa826f19d9]*/
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000695{
Tal Einatede0b6f2018-12-31 17:12:08 +0200696 PyErr_Display(exctype, value, traceback);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200697 Py_RETURN_NONE;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000698}
699
Tal Einatede0b6f2018-12-31 17:12:08 +0200700
701/*[clinic input]
702sys.exc_info
703
704Return current exception information: (type, value, traceback).
705
706Return information about the most recent exception caught by an except
707clause in the current stack frame or in an older stack frame.
708[clinic start generated code]*/
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000709
710static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200711sys_exc_info_impl(PyObject *module)
712/*[clinic end generated code: output=3afd0940cf3a4d30 input=b5c5bf077788a3e5]*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000713{
Victor Stinner50b48572018-11-01 01:51:40 +0100714 _PyErr_StackItem *err_info = _PyErr_GetTopmostException(_PyThreadState_GET());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 return Py_BuildValue(
716 "(OOO)",
Mark Shannonae3087c2017-10-22 22:41:51 +0100717 err_info->exc_type != NULL ? err_info->exc_type : Py_None,
718 err_info->exc_value != NULL ? err_info->exc_value : Py_None,
719 err_info->exc_traceback != NULL ?
720 err_info->exc_traceback : Py_None);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000721}
722
Tal Einatede0b6f2018-12-31 17:12:08 +0200723
724/*[clinic input]
Victor Stinneref9d9b62019-05-22 11:28:22 +0200725sys.unraisablehook
726
727 unraisable: object
728 /
729
730Handle an unraisable exception.
731
732The unraisable argument has the following attributes:
733
734* exc_type: Exception type.
Victor Stinner71c52e32019-05-27 08:57:14 +0200735* exc_value: Exception value, can be None.
736* exc_traceback: Exception traceback, can be None.
737* err_msg: Error message, can be None.
738* object: Object causing the exception, can be None.
Victor Stinneref9d9b62019-05-22 11:28:22 +0200739[clinic start generated code]*/
740
741static PyObject *
742sys_unraisablehook(PyObject *module, PyObject *unraisable)
Victor Stinner71c52e32019-05-27 08:57:14 +0200743/*[clinic end generated code: output=bb92838b32abaa14 input=ec3af148294af8d3]*/
Victor Stinneref9d9b62019-05-22 11:28:22 +0200744{
745 return _PyErr_WriteUnraisableDefaultHook(unraisable);
746}
747
748
749/*[clinic input]
Tal Einatede0b6f2018-12-31 17:12:08 +0200750sys.exit
751
Serhiy Storchaka279f4462019-09-14 12:24:05 +0300752 status: object = None
Tal Einatede0b6f2018-12-31 17:12:08 +0200753 /
754
755Exit the interpreter by raising SystemExit(status).
756
757If the status is omitted or None, it defaults to zero (i.e., success).
758If the status is an integer, it will be used as the system exit status.
759If it is another kind of object, it will be printed and the system
760exit status will be one (i.e., failure).
761[clinic start generated code]*/
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000762
763static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200764sys_exit_impl(PyObject *module, PyObject *status)
Serhiy Storchaka279f4462019-09-14 12:24:05 +0300765/*[clinic end generated code: output=13870986c1ab2ec0 input=b86ca9497baa94f2]*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000766{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000767 /* Raise SystemExit so callers may catch it or clean up. */
Victor Stinner838f2642019-06-13 22:41:23 +0200768 PyThreadState *tstate = _PyThreadState_GET();
769 _PyErr_SetObject(tstate, PyExc_SystemExit, status);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000770 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000771}
772
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000773
Martin v. Löwis107b7da2001-11-09 20:59:39 +0000774
Tal Einatede0b6f2018-12-31 17:12:08 +0200775/*[clinic input]
776sys.getdefaultencoding
777
778Return the current default encoding used by the Unicode implementation.
779[clinic start generated code]*/
780
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000781static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200782sys_getdefaultencoding_impl(PyObject *module)
783/*[clinic end generated code: output=256d19dfcc0711e6 input=d416856ddbef6909]*/
Fred Drake8b4d01d2000-05-09 19:57:01 +0000784{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 return PyUnicode_FromString(PyUnicode_GetDefaultEncoding());
Fred Drake8b4d01d2000-05-09 19:57:01 +0000786}
787
Tal Einatede0b6f2018-12-31 17:12:08 +0200788/*[clinic input]
789sys.getfilesystemencoding
790
791Return the encoding used to convert Unicode filenames to OS filenames.
792[clinic start generated code]*/
Fred Drake8b4d01d2000-05-09 19:57:01 +0000793
794static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200795sys_getfilesystemencoding_impl(PyObject *module)
796/*[clinic end generated code: output=1dc4bdbe9be44aa7 input=8475f8649b8c7d8c]*/
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000797{
Victor Stinner838f2642019-06-13 22:41:23 +0200798 PyThreadState *tstate = _PyThreadState_GET();
799 const PyConfig *config = &tstate->interp->config;
Victor Stinner709d23d2019-05-02 14:56:30 -0400800 return PyUnicode_FromWideChar(config->filesystem_encoding, -1);
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000801}
802
Tal Einatede0b6f2018-12-31 17:12:08 +0200803/*[clinic input]
804sys.getfilesystemencodeerrors
805
806Return the error mode used Unicode to OS filename conversion.
807[clinic start generated code]*/
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000808
Martin v. Löwis04dc25c2008-10-03 16:09:28 +0000809static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200810sys_getfilesystemencodeerrors_impl(PyObject *module)
811/*[clinic end generated code: output=ba77b36bbf7c96f5 input=22a1e8365566f1e5]*/
Steve Dowercc16be82016-09-08 10:35:16 -0700812{
Victor Stinner838f2642019-06-13 22:41:23 +0200813 PyThreadState *tstate = _PyThreadState_GET();
814 const PyConfig *config = &tstate->interp->config;
Victor Stinner709d23d2019-05-02 14:56:30 -0400815 return PyUnicode_FromWideChar(config->filesystem_errors, -1);
Steve Dowercc16be82016-09-08 10:35:16 -0700816}
817
Tal Einatede0b6f2018-12-31 17:12:08 +0200818/*[clinic input]
819sys.intern
820
821 string as s: unicode
822 /
823
824``Intern'' the given string.
825
826This enters the string in the (global) table of interned strings whose
827purpose is to speed up dictionary lookups. Return the string itself or
828the previously interned string object with the same value.
829[clinic start generated code]*/
Steve Dowercc16be82016-09-08 10:35:16 -0700830
831static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200832sys_intern_impl(PyObject *module, PyObject *s)
833/*[clinic end generated code: output=be680c24f5c9e5d6 input=849483c006924e2f]*/
Georg Brandl66a796e2006-12-19 20:50:34 +0000834{
Victor Stinner838f2642019-06-13 22:41:23 +0200835 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 if (PyUnicode_CheckExact(s)) {
837 Py_INCREF(s);
838 PyUnicode_InternInPlace(&s);
839 return s;
840 }
841 else {
Victor Stinner838f2642019-06-13 22:41:23 +0200842 _PyErr_Format(tstate, PyExc_TypeError,
843 "can't intern %.400s", s->ob_type->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 return NULL;
845 }
Georg Brandl66a796e2006-12-19 20:50:34 +0000846}
847
Georg Brandl66a796e2006-12-19 20:50:34 +0000848
Fred Drake5755ce62001-06-27 19:19:46 +0000849/*
850 * Cached interned string objects used for calling the profile and
851 * trace functions. Initialized by trace_init().
852 */
Nick Coghlan5a851672017-09-08 10:14:16 +1000853static PyObject *whatstrings[8] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
Fred Drake5755ce62001-06-27 19:19:46 +0000854
855static int
856trace_init(void)
857{
Nick Coghlan5a851672017-09-08 10:14:16 +1000858 static const char * const whatnames[8] = {
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200859 "call", "exception", "line", "return",
Nick Coghlan5a851672017-09-08 10:14:16 +1000860 "c_call", "c_exception", "c_return",
861 "opcode"
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200862 };
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000863 PyObject *name;
864 int i;
Nick Coghlan5a851672017-09-08 10:14:16 +1000865 for (i = 0; i < 8; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 if (whatstrings[i] == NULL) {
867 name = PyUnicode_InternFromString(whatnames[i]);
868 if (name == NULL)
869 return -1;
870 whatstrings[i] = name;
871 }
872 }
873 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000874}
875
876
877static PyObject *
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100878call_trampoline(PyObject* callback,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 PyFrameObject *frame, int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000880{
Victor Stinner78da82b2016-08-20 01:22:57 +0200881 if (PyFrame_FastToLocalsWithError(frame) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 return NULL;
Victor Stinner78da82b2016-08-20 01:22:57 +0200883 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100884
Victor Stinner838f2642019-06-13 22:41:23 +0200885 PyObject *stack[3];
Victor Stinner78da82b2016-08-20 01:22:57 +0200886 stack[0] = (PyObject *)frame;
887 stack[1] = whatstrings[what];
888 stack[2] = (arg != NULL) ? arg : Py_None;
Fred Drake5755ce62001-06-27 19:19:46 +0000889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 /* call the Python-level function */
Victor Stinner838f2642019-06-13 22:41:23 +0200891 PyObject *result = _PyObject_FastCall(callback, stack, 3);
Fred Drake5755ce62001-06-27 19:19:46 +0000892
Victor Stinner78da82b2016-08-20 01:22:57 +0200893 PyFrame_LocalsToFast(frame, 1);
894 if (result == NULL) {
895 PyTraceBack_Here(frame);
896 }
897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 return result;
Fred Drake5755ce62001-06-27 19:19:46 +0000899}
900
901static int
902profile_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000904{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 if (arg == NULL)
908 arg = Py_None;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100909 result = call_trampoline(self, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 if (result == NULL) {
911 PyEval_SetProfile(NULL, NULL);
912 return -1;
913 }
914 Py_DECREF(result);
915 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000916}
917
918static int
919trace_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000921{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 PyObject *callback;
923 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 if (what == PyTrace_CALL)
926 callback = self;
927 else
928 callback = frame->f_trace;
929 if (callback == NULL)
930 return 0;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100931 result = call_trampoline(callback, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 if (result == NULL) {
933 PyEval_SetTrace(NULL, NULL);
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200934 Py_CLEAR(frame->f_trace);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 return -1;
936 }
937 if (result != Py_None) {
Serhiy Storchakaec397562016-04-06 09:50:03 +0300938 Py_XSETREF(frame->f_trace, result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 }
940 else {
941 Py_DECREF(result);
942 }
943 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000944}
Fred Draked0838392001-06-16 21:02:31 +0000945
Fred Drake8b4d01d2000-05-09 19:57:01 +0000946static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000947sys_settrace(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000948{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 if (trace_init() == -1)
950 return NULL;
951 if (args == Py_None)
952 PyEval_SetTrace(NULL, NULL);
953 else
954 PyEval_SetTrace(trace_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200955 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000956}
957
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000958PyDoc_STRVAR(settrace_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000959"settrace(function)\n\
960\n\
961Set the global debug tracing function. It will be called on each\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000962function call. See the debugger chapter in the library manual."
963);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000964
Tal Einatede0b6f2018-12-31 17:12:08 +0200965/*[clinic input]
966sys.gettrace
967
968Return the global debug tracing function set with sys.settrace.
969
970See the debugger chapter in the library manual.
971[clinic start generated code]*/
972
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000973static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200974sys_gettrace_impl(PyObject *module)
975/*[clinic end generated code: output=e97e3a4d8c971b6e input=373b51bb2147f4d8]*/
Christian Heimes9bd667a2008-01-20 15:14:11 +0000976{
Victor Stinner50b48572018-11-01 01:51:40 +0100977 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 PyObject *temp = tstate->c_traceobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 if (temp == NULL)
981 temp = Py_None;
982 Py_INCREF(temp);
983 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000984}
985
Christian Heimes9bd667a2008-01-20 15:14:11 +0000986static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000987sys_setprofile(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000988{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 if (trace_init() == -1)
990 return NULL;
991 if (args == Py_None)
992 PyEval_SetProfile(NULL, NULL);
993 else
994 PyEval_SetProfile(profile_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200995 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000996}
997
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000998PyDoc_STRVAR(setprofile_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000999"setprofile(function)\n\
1000\n\
1001Set the profiling function. It will be called on each function call\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001002and return. See the profiler chapter in the library manual."
1003);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001004
Tal Einatede0b6f2018-12-31 17:12:08 +02001005/*[clinic input]
1006sys.getprofile
1007
1008Return the profiling function set with sys.setprofile.
1009
1010See the profiler chapter in the library manual.
1011[clinic start generated code]*/
1012
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001013static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001014sys_getprofile_impl(PyObject *module)
1015/*[clinic end generated code: output=579b96b373448188 input=1b3209d89a32965d]*/
Christian Heimes9bd667a2008-01-20 15:14:11 +00001016{
Victor Stinner50b48572018-11-01 01:51:40 +01001017 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 PyObject *temp = tstate->c_profileobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +00001019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 if (temp == NULL)
1021 temp = Py_None;
1022 Py_INCREF(temp);
1023 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +00001024}
1025
Tim Peterse5e065b2003-07-06 18:36:54 +00001026
Tal Einatede0b6f2018-12-31 17:12:08 +02001027/*[clinic input]
1028sys.setswitchinterval
1029
1030 interval: double
1031 /
1032
1033Set the ideal thread switching delay inside the Python interpreter.
1034
1035The actual frequency of switching threads can be lower if the
1036interpreter executes long sequences of uninterruptible code
1037(this is implementation-specific and workload-dependent).
1038
1039The parameter must represent the desired switching delay in seconds
1040A typical value is 0.005 (5 milliseconds).
1041[clinic start generated code]*/
Tim Peterse5e065b2003-07-06 18:36:54 +00001042
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001043static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001044sys_setswitchinterval_impl(PyObject *module, double interval)
1045/*[clinic end generated code: output=65a19629e5153983 input=561b477134df91d9]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001046{
Victor Stinner838f2642019-06-13 22:41:23 +02001047 PyThreadState *tstate = _PyThreadState_GET();
Tal Einatede0b6f2018-12-31 17:12:08 +02001048 if (interval <= 0.0) {
Victor Stinner838f2642019-06-13 22:41:23 +02001049 _PyErr_SetString(tstate, PyExc_ValueError,
1050 "switch interval must be strictly positive");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 return NULL;
1052 }
Tal Einatede0b6f2018-12-31 17:12:08 +02001053 _PyEval_SetSwitchInterval((unsigned long) (1e6 * interval));
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001054 Py_RETURN_NONE;
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001055}
1056
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001057
Tal Einatede0b6f2018-12-31 17:12:08 +02001058/*[clinic input]
1059sys.getswitchinterval -> double
1060
1061Return the current thread switch interval; see sys.setswitchinterval().
1062[clinic start generated code]*/
1063
1064static double
1065sys_getswitchinterval_impl(PyObject *module)
1066/*[clinic end generated code: output=a38c277c85b5096d input=bdf9d39c0ebbbb6f]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001067{
Tal Einatede0b6f2018-12-31 17:12:08 +02001068 return 1e-6 * _PyEval_GetSwitchInterval();
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001069}
1070
Tal Einatede0b6f2018-12-31 17:12:08 +02001071/*[clinic input]
1072sys.setrecursionlimit
1073
1074 limit as new_limit: int
1075 /
1076
1077Set the maximum depth of the Python interpreter stack to n.
1078
1079This limit prevents infinite recursion from causing an overflow of the C
1080stack and crashing Python. The highest possible limit is platform-
1081dependent.
1082[clinic start generated code]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001083
Tim Peterse5e065b2003-07-06 18:36:54 +00001084static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001085sys_setrecursionlimit_impl(PyObject *module, int new_limit)
1086/*[clinic end generated code: output=35e1c64754800ace input=b0f7a23393924af3]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001087{
Tal Einatede0b6f2018-12-31 17:12:08 +02001088 int mark;
Victor Stinner838f2642019-06-13 22:41:23 +02001089 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner50856d52015-10-13 00:11:21 +02001090
Victor Stinner50856d52015-10-13 00:11:21 +02001091 if (new_limit < 1) {
Victor Stinner838f2642019-06-13 22:41:23 +02001092 _PyErr_SetString(tstate, PyExc_ValueError,
1093 "recursion limit must be greater or equal than 1");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 return NULL;
1095 }
Victor Stinner50856d52015-10-13 00:11:21 +02001096
1097 /* Issue #25274: When the recursion depth hits the recursion limit in
1098 _Py_CheckRecursiveCall(), the overflowed flag of the thread state is
1099 set to 1 and a RecursionError is raised. The overflowed flag is reset
1100 to 0 when the recursion depth goes below the low-water mark: see
1101 Py_LeaveRecursiveCall().
1102
1103 Reject too low new limit if the current recursion depth is higher than
1104 the new low-water mark. Otherwise it may not be possible anymore to
1105 reset the overflowed flag to 0. */
1106 mark = _Py_RecursionLimitLowerWaterMark(new_limit);
Victor Stinner50856d52015-10-13 00:11:21 +02001107 if (tstate->recursion_depth >= mark) {
Victor Stinner838f2642019-06-13 22:41:23 +02001108 _PyErr_Format(tstate, PyExc_RecursionError,
1109 "cannot set the recursion limit to %i at "
1110 "the recursion depth %i: the limit is too low",
1111 new_limit, tstate->recursion_depth);
Victor Stinner50856d52015-10-13 00:11:21 +02001112 return NULL;
1113 }
1114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 Py_SetRecursionLimit(new_limit);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001116 Py_RETURN_NONE;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001117}
1118
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001119/*[clinic input]
1120sys.set_coroutine_origin_tracking_depth
1121
1122 depth: int
1123
1124Enable or disable origin tracking for coroutine objects in this thread.
1125
Tal Einatede0b6f2018-12-31 17:12:08 +02001126Coroutine objects will track 'depth' frames of traceback information
1127about where they came from, available in their cr_origin attribute.
1128
1129Set a depth of 0 to disable.
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001130[clinic start generated code]*/
1131
1132static PyObject *
1133sys_set_coroutine_origin_tracking_depth_impl(PyObject *module, int depth)
Tal Einatede0b6f2018-12-31 17:12:08 +02001134/*[clinic end generated code: output=0a2123c1cc6759c5 input=a1d0a05f89d2c426]*/
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001135{
Victor Stinner838f2642019-06-13 22:41:23 +02001136 PyThreadState *tstate = _PyThreadState_GET();
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001137 if (depth < 0) {
Victor Stinner838f2642019-06-13 22:41:23 +02001138 _PyErr_SetString(tstate, PyExc_ValueError, "depth must be >= 0");
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001139 return NULL;
1140 }
Victor Stinner838f2642019-06-13 22:41:23 +02001141 _PyEval_SetCoroutineOriginTrackingDepth(tstate, depth);
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001142 Py_RETURN_NONE;
1143}
1144
1145/*[clinic input]
1146sys.get_coroutine_origin_tracking_depth -> int
1147
1148Check status of origin tracking for coroutine objects in this thread.
1149[clinic start generated code]*/
1150
1151static int
1152sys_get_coroutine_origin_tracking_depth_impl(PyObject *module)
1153/*[clinic end generated code: output=3699f7be95a3afb8 input=335266a71205b61a]*/
1154{
1155 return _PyEval_GetCoroutineOriginTrackingDepth();
1156}
1157
Yury Selivanoveb636452016-09-08 22:01:51 -07001158static PyTypeObject AsyncGenHooksType;
1159
1160PyDoc_STRVAR(asyncgen_hooks_doc,
1161"asyncgen_hooks\n\
1162\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07001163A named tuple providing information about asynchronous\n\
Yury Selivanoveb636452016-09-08 22:01:51 -07001164generators hooks. The attributes are read only.");
1165
1166static PyStructSequence_Field asyncgen_hooks_fields[] = {
1167 {"firstiter", "Hook to intercept first iteration"},
1168 {"finalizer", "Hook to intercept finalization"},
1169 {0}
1170};
1171
1172static PyStructSequence_Desc asyncgen_hooks_desc = {
1173 "asyncgen_hooks", /* name */
1174 asyncgen_hooks_doc, /* doc */
1175 asyncgen_hooks_fields , /* fields */
1176 2
1177};
1178
Yury Selivanoveb636452016-09-08 22:01:51 -07001179static PyObject *
1180sys_set_asyncgen_hooks(PyObject *self, PyObject *args, PyObject *kw)
1181{
1182 static char *keywords[] = {"firstiter", "finalizer", NULL};
1183 PyObject *firstiter = NULL;
1184 PyObject *finalizer = NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02001185 PyThreadState *tstate = _PyThreadState_GET();
Yury Selivanoveb636452016-09-08 22:01:51 -07001186
1187 if (!PyArg_ParseTupleAndKeywords(
1188 args, kw, "|OO", keywords,
1189 &firstiter, &finalizer)) {
1190 return NULL;
1191 }
1192
1193 if (finalizer && finalizer != Py_None) {
1194 if (!PyCallable_Check(finalizer)) {
Victor Stinner838f2642019-06-13 22:41:23 +02001195 _PyErr_Format(tstate, PyExc_TypeError,
1196 "callable finalizer expected, got %.50s",
1197 Py_TYPE(finalizer)->tp_name);
Yury Selivanoveb636452016-09-08 22:01:51 -07001198 return NULL;
1199 }
1200 _PyEval_SetAsyncGenFinalizer(finalizer);
1201 }
1202 else if (finalizer == Py_None) {
1203 _PyEval_SetAsyncGenFinalizer(NULL);
1204 }
1205
1206 if (firstiter && firstiter != Py_None) {
1207 if (!PyCallable_Check(firstiter)) {
Victor Stinner838f2642019-06-13 22:41:23 +02001208 _PyErr_Format(tstate, PyExc_TypeError,
1209 "callable firstiter expected, got %.50s",
1210 Py_TYPE(firstiter)->tp_name);
Yury Selivanoveb636452016-09-08 22:01:51 -07001211 return NULL;
1212 }
1213 _PyEval_SetAsyncGenFirstiter(firstiter);
1214 }
1215 else if (firstiter == Py_None) {
1216 _PyEval_SetAsyncGenFirstiter(NULL);
1217 }
1218
1219 Py_RETURN_NONE;
1220}
1221
1222PyDoc_STRVAR(set_asyncgen_hooks_doc,
Tal Einatede0b6f2018-12-31 17:12:08 +02001223"set_asyncgen_hooks(* [, firstiter] [, finalizer])\n\
Yury Selivanoveb636452016-09-08 22:01:51 -07001224\n\
1225Set a finalizer for async generators objects."
1226);
1227
Tal Einatede0b6f2018-12-31 17:12:08 +02001228/*[clinic input]
1229sys.get_asyncgen_hooks
1230
1231Return the installed asynchronous generators hooks.
1232
1233This returns a namedtuple of the form (firstiter, finalizer).
1234[clinic start generated code]*/
1235
Yury Selivanoveb636452016-09-08 22:01:51 -07001236static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001237sys_get_asyncgen_hooks_impl(PyObject *module)
1238/*[clinic end generated code: output=53a253707146f6cf input=3676b9ea62b14625]*/
Yury Selivanoveb636452016-09-08 22:01:51 -07001239{
1240 PyObject *res;
1241 PyObject *firstiter = _PyEval_GetAsyncGenFirstiter();
1242 PyObject *finalizer = _PyEval_GetAsyncGenFinalizer();
1243
1244 res = PyStructSequence_New(&AsyncGenHooksType);
1245 if (res == NULL) {
1246 return NULL;
1247 }
1248
1249 if (firstiter == NULL) {
1250 firstiter = Py_None;
1251 }
1252
1253 if (finalizer == NULL) {
1254 finalizer = Py_None;
1255 }
1256
1257 Py_INCREF(firstiter);
1258 PyStructSequence_SET_ITEM(res, 0, firstiter);
1259
1260 Py_INCREF(finalizer);
1261 PyStructSequence_SET_ITEM(res, 1, finalizer);
1262
1263 return res;
1264}
1265
Yury Selivanoveb636452016-09-08 22:01:51 -07001266
Mark Dickinsondc787d22010-05-23 13:33:13 +00001267static PyTypeObject Hash_InfoType;
1268
1269PyDoc_STRVAR(hash_info_doc,
1270"hash_info\n\
1271\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07001272A named tuple providing parameters used for computing\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +01001273hashes. The attributes are read only.");
Mark Dickinsondc787d22010-05-23 13:33:13 +00001274
1275static PyStructSequence_Field hash_info_fields[] = {
1276 {"width", "width of the type used for hashing, in bits"},
1277 {"modulus", "prime number giving the modulus on which the hash "
1278 "function is based"},
1279 {"inf", "value to be used for hash of a positive infinity"},
1280 {"nan", "value to be used for hash of a nan"},
1281 {"imag", "multiplier used for the imaginary part of a complex number"},
Christian Heimes985ecdc2013-11-20 11:46:18 +01001282 {"algorithm", "name of the algorithm for hashing of str, bytes and "
1283 "memoryviews"},
1284 {"hash_bits", "internal output size of hash algorithm"},
1285 {"seed_bits", "seed size of hash algorithm"},
1286 {"cutoff", "small string optimization cutoff"},
Mark Dickinsondc787d22010-05-23 13:33:13 +00001287 {NULL, NULL}
1288};
1289
1290static PyStructSequence_Desc hash_info_desc = {
1291 "sys.hash_info",
1292 hash_info_doc,
1293 hash_info_fields,
Christian Heimes985ecdc2013-11-20 11:46:18 +01001294 9,
Mark Dickinsondc787d22010-05-23 13:33:13 +00001295};
1296
Matthias Klosed885e952010-07-06 10:53:30 +00001297static PyObject *
Victor Stinner838f2642019-06-13 22:41:23 +02001298get_hash_info(PyThreadState *tstate)
Mark Dickinsondc787d22010-05-23 13:33:13 +00001299{
1300 PyObject *hash_info;
1301 int field = 0;
Christian Heimes985ecdc2013-11-20 11:46:18 +01001302 PyHash_FuncDef *hashfunc;
Mark Dickinsondc787d22010-05-23 13:33:13 +00001303 hash_info = PyStructSequence_New(&Hash_InfoType);
1304 if (hash_info == NULL)
1305 return NULL;
Christian Heimes985ecdc2013-11-20 11:46:18 +01001306 hashfunc = PyHash_GetFuncDef();
Mark Dickinsondc787d22010-05-23 13:33:13 +00001307 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001308 PyLong_FromLong(8*sizeof(Py_hash_t)));
Mark Dickinsondc787d22010-05-23 13:33:13 +00001309 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8035bc52010-10-23 16:20:50 +00001310 PyLong_FromSsize_t(_PyHASH_MODULUS));
Mark Dickinsondc787d22010-05-23 13:33:13 +00001311 PyStructSequence_SET_ITEM(hash_info, field++,
1312 PyLong_FromLong(_PyHASH_INF));
1313 PyStructSequence_SET_ITEM(hash_info, field++,
1314 PyLong_FromLong(_PyHASH_NAN));
1315 PyStructSequence_SET_ITEM(hash_info, field++,
1316 PyLong_FromLong(_PyHASH_IMAG));
Christian Heimes985ecdc2013-11-20 11:46:18 +01001317 PyStructSequence_SET_ITEM(hash_info, field++,
1318 PyUnicode_FromString(hashfunc->name));
1319 PyStructSequence_SET_ITEM(hash_info, field++,
1320 PyLong_FromLong(hashfunc->hash_bits));
1321 PyStructSequence_SET_ITEM(hash_info, field++,
1322 PyLong_FromLong(hashfunc->seed_bits));
1323 PyStructSequence_SET_ITEM(hash_info, field++,
1324 PyLong_FromLong(Py_HASH_CUTOFF));
Victor Stinner838f2642019-06-13 22:41:23 +02001325 if (_PyErr_Occurred(tstate)) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00001326 Py_CLEAR(hash_info);
1327 return NULL;
1328 }
1329 return hash_info;
1330}
Tal Einatede0b6f2018-12-31 17:12:08 +02001331/*[clinic input]
1332sys.getrecursionlimit
Mark Dickinsondc787d22010-05-23 13:33:13 +00001333
Tal Einatede0b6f2018-12-31 17:12:08 +02001334Return the current value of the recursion limit.
Mark Dickinsondc787d22010-05-23 13:33:13 +00001335
Tal Einatede0b6f2018-12-31 17:12:08 +02001336The recursion limit is the maximum depth of the Python interpreter
1337stack. This limit prevents infinite recursion from causing an overflow
1338of the C stack and crashing Python.
1339[clinic start generated code]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001340
1341static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001342sys_getrecursionlimit_impl(PyObject *module)
1343/*[clinic end generated code: output=d571fb6b4549ef2e input=1c6129fd2efaeea8]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001344{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001345 return PyLong_FromLong(Py_GetRecursionLimit());
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001346}
1347
Mark Hammond8696ebc2002-10-08 02:44:31 +00001348#ifdef MS_WINDOWS
Mark Hammond8696ebc2002-10-08 02:44:31 +00001349
Eric Smithf7bb5782010-01-27 00:44:57 +00001350static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};
1351
1352static PyStructSequence_Field windows_version_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 {"major", "Major version number"},
1354 {"minor", "Minor version number"},
1355 {"build", "Build number"},
1356 {"platform", "Operating system platform"},
1357 {"service_pack", "Latest Service Pack installed on the system"},
1358 {"service_pack_major", "Service Pack major version number"},
1359 {"service_pack_minor", "Service Pack minor version number"},
1360 {"suite_mask", "Bit mask identifying available product suites"},
1361 {"product_type", "System product type"},
Steve Dower74f4af72016-09-17 17:27:48 -07001362 {"platform_version", "Diagnostic version number"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001363 {0}
Eric Smithf7bb5782010-01-27 00:44:57 +00001364};
1365
1366static PyStructSequence_Desc windows_version_desc = {
Tal Einatede0b6f2018-12-31 17:12:08 +02001367 "sys.getwindowsversion", /* name */
1368 sys_getwindowsversion__doc__, /* doc */
1369 windows_version_fields, /* fields */
1370 5 /* For backward compatibility,
1371 only the first 5 items are accessible
1372 via indexing, the rest are name only */
Eric Smithf7bb5782010-01-27 00:44:57 +00001373};
1374
Steve Dower3e96f322015-03-02 08:01:10 -08001375/* Disable deprecation warnings about GetVersionEx as the result is
1376 being passed straight through to the caller, who is responsible for
1377 using it correctly. */
1378#pragma warning(push)
1379#pragma warning(disable:4996)
1380
Tal Einatede0b6f2018-12-31 17:12:08 +02001381/*[clinic input]
1382sys.getwindowsversion
1383
1384Return info about the running version of Windows as a named tuple.
1385
1386The members are named: major, minor, build, platform, service_pack,
1387service_pack_major, service_pack_minor, suite_mask, product_type and
1388platform_version. For backward compatibility, only the first 5 items
1389are available by indexing. All elements are numbers, except
1390service_pack and platform_type which are strings, and platform_version
1391which is a 3-tuple. Platform is always 2. Product_type may be 1 for a
1392workstation, 2 for a domain controller, 3 for a server.
1393Platform_version is a 3-tuple containing a version number that is
1394intended for identifying the OS rather than feature detection.
1395[clinic start generated code]*/
1396
Mark Hammond8696ebc2002-10-08 02:44:31 +00001397static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001398sys_getwindowsversion_impl(PyObject *module)
1399/*[clinic end generated code: output=1ec063280b932857 input=73a228a328fee63a]*/
Mark Hammond8696ebc2002-10-08 02:44:31 +00001400{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001401 PyObject *version;
1402 int pos = 0;
Minmin Gong8ebc6452019-02-02 20:26:55 -08001403 OSVERSIONINFOEXW ver;
Steve Dower74f4af72016-09-17 17:27:48 -07001404 DWORD realMajor, realMinor, realBuild;
1405 HANDLE hKernel32;
1406 wchar_t kernel32_path[MAX_PATH];
1407 LPVOID verblock;
1408 DWORD verblock_size;
Victor Stinner838f2642019-06-13 22:41:23 +02001409 PyThreadState *tstate = _PyThreadState_GET();
Steve Dower74f4af72016-09-17 17:27:48 -07001410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001411 ver.dwOSVersionInfoSize = sizeof(ver);
Minmin Gong8ebc6452019-02-02 20:26:55 -08001412 if (!GetVersionExW((OSVERSIONINFOW*) &ver))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001413 return PyErr_SetFromWindowsErr(0);
Eric Smithf7bb5782010-01-27 00:44:57 +00001414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 version = PyStructSequence_New(&WindowsVersionType);
1416 if (version == NULL)
1417 return NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +00001418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001419 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion));
1420 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion));
1421 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber));
1422 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId));
Minmin Gong8ebc6452019-02-02 20:26:55 -08001423 PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromWideChar(ver.szCSDVersion, -1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001424 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor));
1425 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor));
1426 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask));
1427 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType));
Eric Smithf7bb5782010-01-27 00:44:57 +00001428
Steve Dower74f4af72016-09-17 17:27:48 -07001429 realMajor = ver.dwMajorVersion;
1430 realMinor = ver.dwMinorVersion;
1431 realBuild = ver.dwBuildNumber;
1432
1433 // GetVersion will lie if we are running in a compatibility mode.
1434 // We need to read the version info from a system file resource
1435 // to accurately identify the OS version. If we fail for any reason,
1436 // just return whatever GetVersion said.
Tony Roberts4860f012019-02-02 18:16:42 +01001437 Py_BEGIN_ALLOW_THREADS
Steve Dower74f4af72016-09-17 17:27:48 -07001438 hKernel32 = GetModuleHandleW(L"kernel32.dll");
Tony Roberts4860f012019-02-02 18:16:42 +01001439 Py_END_ALLOW_THREADS
Steve Dower74f4af72016-09-17 17:27:48 -07001440 if (hKernel32 && GetModuleFileNameW(hKernel32, kernel32_path, MAX_PATH) &&
1441 (verblock_size = GetFileVersionInfoSizeW(kernel32_path, NULL)) &&
1442 (verblock = PyMem_RawMalloc(verblock_size))) {
1443 VS_FIXEDFILEINFO *ffi;
1444 UINT ffi_len;
1445
1446 if (GetFileVersionInfoW(kernel32_path, 0, verblock_size, verblock) &&
1447 VerQueryValueW(verblock, L"", (LPVOID)&ffi, &ffi_len)) {
1448 realMajor = HIWORD(ffi->dwProductVersionMS);
1449 realMinor = LOWORD(ffi->dwProductVersionMS);
1450 realBuild = HIWORD(ffi->dwProductVersionLS);
1451 }
1452 PyMem_RawFree(verblock);
1453 }
Segev Finer48fb7662017-06-04 20:52:27 +03001454 PyStructSequence_SET_ITEM(version, pos++, Py_BuildValue("(kkk)",
1455 realMajor,
1456 realMinor,
1457 realBuild
Steve Dower74f4af72016-09-17 17:27:48 -07001458 ));
1459
Victor Stinner838f2642019-06-13 22:41:23 +02001460 if (_PyErr_Occurred(tstate)) {
Serhiy Storchaka48d761e2013-12-17 15:11:24 +02001461 Py_DECREF(version);
1462 return NULL;
1463 }
Steve Dower74f4af72016-09-17 17:27:48 -07001464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001465 return version;
Mark Hammond8696ebc2002-10-08 02:44:31 +00001466}
1467
Steve Dower3e96f322015-03-02 08:01:10 -08001468#pragma warning(pop)
1469
Tal Einatede0b6f2018-12-31 17:12:08 +02001470/*[clinic input]
1471sys._enablelegacywindowsfsencoding
1472
1473Changes the default filesystem encoding to mbcs:replace.
1474
1475This is done for consistency with earlier versions of Python. See PEP
1476529 for more information.
1477
1478This is equivalent to defining the PYTHONLEGACYWINDOWSFSENCODING
1479environment variable before launching Python.
1480[clinic start generated code]*/
Steve Dowercc16be82016-09-08 10:35:16 -07001481
1482static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001483sys__enablelegacywindowsfsencoding_impl(PyObject *module)
1484/*[clinic end generated code: output=f5c3855b45e24fe9 input=2bfa931a20704492]*/
Steve Dowercc16be82016-09-08 10:35:16 -07001485{
Victor Stinner709d23d2019-05-02 14:56:30 -04001486 if (_PyUnicode_EnableLegacyWindowsFSEncoding() < 0) {
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001487 return NULL;
1488 }
Steve Dowercc16be82016-09-08 10:35:16 -07001489 Py_RETURN_NONE;
1490}
1491
Mark Hammond8696ebc2002-10-08 02:44:31 +00001492#endif /* MS_WINDOWS */
1493
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001494#ifdef HAVE_DLOPEN
Tal Einatede0b6f2018-12-31 17:12:08 +02001495
1496/*[clinic input]
1497sys.setdlopenflags
1498
1499 flags as new_val: int
1500 /
1501
1502Set the flags used by the interpreter for dlopen calls.
1503
1504This is used, for example, when the interpreter loads extension
1505modules. Among other things, this will enable a lazy resolving of
1506symbols when importing a module, if called as sys.setdlopenflags(0).
1507To share symbols across extension modules, call as
1508sys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag
1509modules can be found in the os module (RTLD_xxx constants, e.g.
1510os.RTLD_LAZY).
1511[clinic start generated code]*/
1512
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001513static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001514sys_setdlopenflags_impl(PyObject *module, int new_val)
1515/*[clinic end generated code: output=ec918b7fe0a37281 input=4c838211e857a77f]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001516{
Victor Stinner838f2642019-06-13 22:41:23 +02001517 PyThreadState *tstate = _PyThreadState_GET();
1518 tstate->interp->dlopenflags = new_val;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001519 Py_RETURN_NONE;
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001520}
1521
Tal Einatede0b6f2018-12-31 17:12:08 +02001522
1523/*[clinic input]
1524sys.getdlopenflags
1525
1526Return the current value of the flags that are used for dlopen calls.
1527
1528The flag constants are defined in the os module.
1529[clinic start generated code]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001530
1531static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001532sys_getdlopenflags_impl(PyObject *module)
1533/*[clinic end generated code: output=e92cd1bc5005da6e input=dc4ea0899c53b4b6]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001534{
Victor Stinner838f2642019-06-13 22:41:23 +02001535 PyThreadState *tstate = _PyThreadState_GET();
1536 return PyLong_FromLong(tstate->interp->dlopenflags);
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001537}
1538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001539#endif /* HAVE_DLOPEN */
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001540
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001541#ifdef USE_MALLOPT
1542/* Link with -lmalloc (or -lmpc) on an SGI */
1543#include <malloc.h>
1544
Tal Einatede0b6f2018-12-31 17:12:08 +02001545/*[clinic input]
1546sys.mdebug
1547
1548 flag: int
1549 /
1550[clinic start generated code]*/
1551
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001552static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001553sys_mdebug_impl(PyObject *module, int flag)
1554/*[clinic end generated code: output=5431d545847c3637 input=151d150ae1636f8a]*/
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001555{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001556 int flag;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001557 mallopt(M_DEBUG, flag);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001558 Py_RETURN_NONE;
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001559}
1560#endif /* USE_MALLOPT */
1561
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001562size_t
1563_PySys_GetSizeOf(PyObject *o)
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001564{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565 PyObject *res = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001566 PyObject *method;
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001567 Py_ssize_t size;
Victor Stinner838f2642019-06-13 22:41:23 +02001568 PyThreadState *tstate = _PyThreadState_GET();
Benjamin Petersona5758c02009-05-09 18:15:04 +00001569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 /* Make sure the type is initialized. float gets initialized late */
Victor Stinner838f2642019-06-13 22:41:23 +02001571 if (PyType_Ready(Py_TYPE(o)) < 0) {
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001572 return (size_t)-1;
Victor Stinner838f2642019-06-13 22:41:23 +02001573 }
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001574
Benjamin Petersonce798522012-01-22 11:24:29 -05001575 method = _PyObject_LookupSpecial(o, &PyId___sizeof__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 if (method == NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +02001577 if (!_PyErr_Occurred(tstate)) {
1578 _PyErr_Format(tstate, PyExc_TypeError,
1579 "Type %.100s doesn't define __sizeof__",
1580 Py_TYPE(o)->tp_name);
1581 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001582 }
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);
Victor Stinner838f2642019-06-13 22:41:23 +02001593 if (size == -1 && _PyErr_Occurred(tstate))
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) {
Victor Stinner838f2642019-06-13 22:41:23 +02001597 _PyErr_SetString(tstate, PyExc_ValueError,
1598 "__sizeof__() should return >= 0");
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001599 return (size_t)-1;
1600 }
1601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001602 /* add gc_head size */
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001603 if (PyObject_IS_GC(o))
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001604 return ((size_t)size) + sizeof(PyGC_Head);
1605 return (size_t)size;
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001606}
1607
1608static PyObject *
1609sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
1610{
1611 static char *kwlist[] = {"object", "default", 0};
1612 size_t size;
1613 PyObject *o, *dflt = NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02001614 PyThreadState *tstate = _PyThreadState_GET();
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001615
1616 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
Victor Stinner838f2642019-06-13 22:41:23 +02001617 kwlist, &o, &dflt)) {
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001618 return NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02001619 }
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001620
1621 size = _PySys_GetSizeOf(o);
1622
Victor Stinner838f2642019-06-13 22:41:23 +02001623 if (size == (size_t)-1 && _PyErr_Occurred(tstate)) {
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001624 /* Has a default value been given */
Victor Stinner838f2642019-06-13 22:41:23 +02001625 if (dflt != NULL && _PyErr_ExceptionMatches(tstate, PyExc_TypeError)) {
1626 _PyErr_Clear(tstate);
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001627 Py_INCREF(dflt);
1628 return dflt;
1629 }
1630 else
1631 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001632 }
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001633
1634 return PyLong_FromSize_t(size);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001635}
1636
1637PyDoc_STRVAR(getsizeof_doc,
Tal Einatede0b6f2018-12-31 17:12:08 +02001638"getsizeof(object [, default]) -> int\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001639\n\
1640Return the size of object in bytes.");
1641
Tal Einatede0b6f2018-12-31 17:12:08 +02001642/*[clinic input]
1643sys.getrefcount -> Py_ssize_t
1644
1645 object: object
1646 /
1647
1648Return the reference count of object.
1649
1650The count returned is generally one higher than you might expect,
1651because it includes the (temporary) reference as an argument to
1652getrefcount().
1653[clinic start generated code]*/
1654
1655static Py_ssize_t
1656sys_getrefcount_impl(PyObject *module, PyObject *object)
1657/*[clinic end generated code: output=5fd477f2264b85b2 input=bf474efd50a21535]*/
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001658{
Tal Einatede0b6f2018-12-31 17:12:08 +02001659 return object->ob_refcnt;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001660}
1661
Tim Peters4be93d02002-07-07 19:59:50 +00001662#ifdef Py_REF_DEBUG
Tal Einatede0b6f2018-12-31 17:12:08 +02001663/*[clinic input]
1664sys.gettotalrefcount -> Py_ssize_t
1665[clinic start generated code]*/
1666
1667static Py_ssize_t
1668sys_gettotalrefcount_impl(PyObject *module)
1669/*[clinic end generated code: output=4103886cf17c25bc input=53b744faa5d2e4f6]*/
Mark Hammond440d8982000-06-20 08:12:48 +00001670{
Tal Einatede0b6f2018-12-31 17:12:08 +02001671 return _Py_GetRefTotal();
Mark Hammond440d8982000-06-20 08:12:48 +00001672}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001673#endif /* Py_REF_DEBUG */
Mark Hammond440d8982000-06-20 08:12:48 +00001674
Tal Einatede0b6f2018-12-31 17:12:08 +02001675/*[clinic input]
1676sys.getallocatedblocks -> Py_ssize_t
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001677
Tal Einatede0b6f2018-12-31 17:12:08 +02001678Return the number of memory blocks currently allocated.
1679[clinic start generated code]*/
1680
1681static Py_ssize_t
1682sys_getallocatedblocks_impl(PyObject *module)
1683/*[clinic end generated code: output=f0c4e873f0b6dcf7 input=dab13ee346a0673e]*/
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001684{
Tal Einatede0b6f2018-12-31 17:12:08 +02001685 return _Py_GetAllocatedBlocks();
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001686}
1687
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001688#ifdef COUNT_ALLOCS
Tal Einatede0b6f2018-12-31 17:12:08 +02001689/*[clinic input]
1690sys.getcounts
1691[clinic start generated code]*/
1692
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001693static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001694sys_getcounts_impl(PyObject *module)
1695/*[clinic end generated code: output=20df00bc164f43cb input=ad2ec7bda5424953]*/
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001696{
Pablo Galindo49c75a82018-10-28 15:02:17 +00001697 extern PyObject *_Py_get_counts(void);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001698
Pablo Galindo49c75a82018-10-28 15:02:17 +00001699 return _Py_get_counts();
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001700}
1701#endif
1702
Tal Einatede0b6f2018-12-31 17:12:08 +02001703/*[clinic input]
1704sys._getframe
1705
1706 depth: int = 0
1707 /
1708
1709Return a frame object from the call stack.
1710
1711If optional integer depth is given, return the frame object that many
1712calls below the top of the stack. If that is deeper than the call
1713stack, ValueError is raised. The default for depth is zero, returning
1714the frame at the top of the call stack.
1715
1716This function should be used for internal and specialized purposes
1717only.
1718[clinic start generated code]*/
Barry Warsawb6a54d22000-12-06 21:47:46 +00001719
1720static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001721sys__getframe_impl(PyObject *module, int depth)
1722/*[clinic end generated code: output=d438776c04d59804 input=c1be8a6464b11ee5]*/
Barry Warsawb6a54d22000-12-06 21:47:46 +00001723{
Victor Stinner838f2642019-06-13 22:41:23 +02001724 PyThreadState *tstate = _PyThreadState_GET();
1725 PyFrameObject *f = tstate->frame;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001726
Steve Dowerb82e17e2019-05-23 08:45:22 -07001727 if (PySys_Audit("sys._getframe", "O", f) < 0) {
1728 return NULL;
1729 }
1730
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001731 while (depth > 0 && f != NULL) {
1732 f = f->f_back;
1733 --depth;
1734 }
1735 if (f == NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +02001736 _PyErr_SetString(tstate, PyExc_ValueError,
1737 "call stack is not deep enough");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001738 return NULL;
1739 }
1740 Py_INCREF(f);
1741 return (PyObject*)f;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001742}
1743
Tal Einatede0b6f2018-12-31 17:12:08 +02001744/*[clinic input]
1745sys._current_frames
1746
1747Return a dict mapping each thread's thread id to its current stack frame.
1748
1749This function should be used for specialized purposes only.
1750[clinic start generated code]*/
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001751
1752static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001753sys__current_frames_impl(PyObject *module)
1754/*[clinic end generated code: output=d2a41ac0a0a3809a input=2a9049c5f5033691]*/
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001755{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001756 return _PyThread_CurrentFrames();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001757}
1758
Tal Einatede0b6f2018-12-31 17:12:08 +02001759/*[clinic input]
1760sys.call_tracing
1761
1762 func: object
1763 args as funcargs: object(subclass_of='&PyTuple_Type')
1764 /
1765
1766Call func(*args), while tracing is enabled.
1767
1768The tracing state is saved, and restored afterwards. This is intended
1769to be called from a debugger from a checkpoint, to recursively debug
1770some other code.
1771[clinic start generated code]*/
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001772
1773static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001774sys_call_tracing_impl(PyObject *module, PyObject *func, PyObject *funcargs)
1775/*[clinic end generated code: output=7e4999853cd4e5a6 input=5102e8b11049f92f]*/
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001776{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001777 return _PyEval_CallTracing(func, funcargs);
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001778}
1779
Victor Stinner048afd92016-11-28 11:59:04 +01001780
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001781#ifdef __cplusplus
1782extern "C" {
1783#endif
1784
Tal Einatede0b6f2018-12-31 17:12:08 +02001785/*[clinic input]
1786sys._debugmallocstats
1787
1788Print summary info to stderr about the state of pymalloc's structures.
1789
1790In Py_DEBUG mode, also perform some expensive internal consistency
1791checks.
1792[clinic start generated code]*/
1793
David Malcolm49526f42012-06-22 14:55:41 -04001794static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001795sys__debugmallocstats_impl(PyObject *module)
1796/*[clinic end generated code: output=ec3565f8c7cee46a input=33c0c9c416f98424]*/
David Malcolm49526f42012-06-22 14:55:41 -04001797{
1798#ifdef WITH_PYMALLOC
Victor Stinner6bf992a2017-12-06 17:26:10 +01001799 if (_PyObject_DebugMallocStats(stderr)) {
Victor Stinner34be8072016-03-14 12:04:26 +01001800 fputc('\n', stderr);
1801 }
David Malcolm49526f42012-06-22 14:55:41 -04001802#endif
1803 _PyObject_DebugTypeStats(stderr);
1804
1805 Py_RETURN_NONE;
1806}
David Malcolm49526f42012-06-22 14:55:41 -04001807
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001808#ifdef Py_TRACE_REFS
Guido van Rossumded690f1996-05-24 20:48:31 +00001809/* Defined in objects.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001810extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001811#endif
Guido van Rossumded690f1996-05-24 20:48:31 +00001812
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001813#ifdef DYNAMIC_EXECUTION_PROFILE
1814/* Defined in ceval.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001815extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001816#endif
1817
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001818#ifdef __cplusplus
1819}
1820#endif
1821
Tal Einatede0b6f2018-12-31 17:12:08 +02001822
1823/*[clinic input]
1824sys._clear_type_cache
1825
1826Clear the internal type lookup cache.
1827[clinic start generated code]*/
1828
Christian Heimes15ebc882008-02-04 18:48:49 +00001829static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001830sys__clear_type_cache_impl(PyObject *module)
1831/*[clinic end generated code: output=20e48ca54a6f6971 input=127f3e04a8d9b555]*/
Christian Heimes15ebc882008-02-04 18:48:49 +00001832{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001833 PyType_ClearCache();
1834 Py_RETURN_NONE;
Christian Heimes15ebc882008-02-04 18:48:49 +00001835}
1836
Tal Einatede0b6f2018-12-31 17:12:08 +02001837/*[clinic input]
1838sys.is_finalizing
1839
1840Return True if Python is exiting.
1841[clinic start generated code]*/
1842
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001843static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001844sys_is_finalizing_impl(PyObject *module)
1845/*[clinic end generated code: output=735b5ff7962ab281 input=f0df747a039948a5]*/
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001846{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001847 return PyBool_FromLong(_Py_IsFinalizing());
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001848}
1849
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001850#ifdef ANDROID_API_LEVEL
Tal Einatede0b6f2018-12-31 17:12:08 +02001851/*[clinic input]
1852sys.getandroidapilevel
1853
1854Return the build time API version of Android as an integer.
1855[clinic start generated code]*/
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001856
1857static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001858sys_getandroidapilevel_impl(PyObject *module)
1859/*[clinic end generated code: output=214abf183a1c70c1 input=3e6d6c9fcdd24ac6]*/
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001860{
1861 return PyLong_FromLong(ANDROID_API_LEVEL);
1862}
1863#endif /* ANDROID_API_LEVEL */
1864
1865
Steve Dowerb82e17e2019-05-23 08:45:22 -07001866
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001867static PyMethodDef sys_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001868 /* Might as well keep this in alphabetic order */
Steve Dowerb82e17e2019-05-23 08:45:22 -07001869 SYS_ADDAUDITHOOK_METHODDEF
1870 {"audit", (PyCFunction)(void(*)(void))sys_audit, METH_FASTCALL, audit_doc },
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001871 {"breakpointhook", (PyCFunction)(void(*)(void))sys_breakpointhook,
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04001872 METH_FASTCALL | METH_KEYWORDS, breakpointhook_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001873 SYS__CLEAR_TYPE_CACHE_METHODDEF
1874 SYS__CURRENT_FRAMES_METHODDEF
1875 SYS_DISPLAYHOOK_METHODDEF
1876 SYS_EXC_INFO_METHODDEF
1877 SYS_EXCEPTHOOK_METHODDEF
1878 SYS_EXIT_METHODDEF
1879 SYS_GETDEFAULTENCODING_METHODDEF
1880 SYS_GETDLOPENFLAGS_METHODDEF
1881 SYS_GETALLOCATEDBLOCKS_METHODDEF
1882 SYS_GETCOUNTS_METHODDEF
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001883#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001884 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001885#endif
Tal Einatede0b6f2018-12-31 17:12:08 +02001886 SYS_GETFILESYSTEMENCODING_METHODDEF
1887 SYS_GETFILESYSTEMENCODEERRORS_METHODDEF
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001888#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001889 {"getobjects", _Py_GetObjects, METH_VARARGS},
Tim Peters4be93d02002-07-07 19:59:50 +00001890#endif
Tal Einatede0b6f2018-12-31 17:12:08 +02001891 SYS_GETTOTALREFCOUNT_METHODDEF
1892 SYS_GETREFCOUNT_METHODDEF
1893 SYS_GETRECURSIONLIMIT_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001894 {"getsizeof", (PyCFunction)(void(*)(void))sys_getsizeof,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001896 SYS__GETFRAME_METHODDEF
1897 SYS_GETWINDOWSVERSION_METHODDEF
1898 SYS__ENABLELEGACYWINDOWSFSENCODING_METHODDEF
1899 SYS_INTERN_METHODDEF
1900 SYS_IS_FINALIZING_METHODDEF
1901 SYS_MDEBUG_METHODDEF
Tal Einatede0b6f2018-12-31 17:12:08 +02001902 SYS_SETSWITCHINTERVAL_METHODDEF
1903 SYS_GETSWITCHINTERVAL_METHODDEF
1904 SYS_SETDLOPENFLAGS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 {"setprofile", sys_setprofile, METH_O, setprofile_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001906 SYS_GETPROFILE_METHODDEF
1907 SYS_SETRECURSIONLIMIT_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001908 {"settrace", sys_settrace, METH_O, settrace_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001909 SYS_GETTRACE_METHODDEF
1910 SYS_CALL_TRACING_METHODDEF
1911 SYS__DEBUGMALLOCSTATS_METHODDEF
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001912 SYS_SET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
1913 SYS_GET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001914 {"set_asyncgen_hooks", (PyCFunction)(void(*)(void))sys_set_asyncgen_hooks,
Yury Selivanoveb636452016-09-08 22:01:51 -07001915 METH_VARARGS | METH_KEYWORDS, set_asyncgen_hooks_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001916 SYS_GET_ASYNCGEN_HOOKS_METHODDEF
1917 SYS_GETANDROIDAPILEVEL_METHODDEF
Victor Stinneref9d9b62019-05-22 11:28:22 +02001918 SYS_UNRAISABLEHOOK_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001919 {NULL, NULL} /* sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +00001920};
1921
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001922static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001923list_builtin_module_names(void)
Guido van Rossum34679b71993-01-26 13:33:44 +00001924{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001925 PyObject *list = PyList_New(0);
1926 int i;
1927 if (list == NULL)
1928 return NULL;
1929 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1930 PyObject *name = PyUnicode_FromString(
1931 PyImport_Inittab[i].name);
1932 if (name == NULL)
1933 break;
1934 PyList_Append(list, name);
1935 Py_DECREF(name);
1936 }
1937 if (PyList_Sort(list) != 0) {
1938 Py_DECREF(list);
1939 list = NULL;
1940 }
1941 if (list) {
1942 PyObject *v = PyList_AsTuple(list);
1943 Py_DECREF(list);
1944 list = v;
1945 }
1946 return list;
Guido van Rossum34679b71993-01-26 13:33:44 +00001947}
1948
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001949/* Pre-initialization support for sys.warnoptions and sys._xoptions
1950 *
1951 * Modern internal code paths:
1952 * These APIs get called after _Py_InitializeCore and get to use the
1953 * regular CPython list, dict, and unicode APIs.
1954 *
1955 * Legacy embedding code paths:
1956 * The multi-phase initialization API isn't public yet, so embedding
1957 * apps still need to be able configure sys.warnoptions and sys._xoptions
1958 * before they call Py_Initialize. To support this, we stash copies of
1959 * the supplied wchar * sequences in linked lists, and then migrate the
1960 * contents of those lists to the sys module in _PyInitializeCore.
1961 *
1962 */
1963
1964struct _preinit_entry {
1965 wchar_t *value;
1966 struct _preinit_entry *next;
1967};
1968
1969typedef struct _preinit_entry *_Py_PreInitEntry;
1970
1971static _Py_PreInitEntry _preinit_warnoptions = NULL;
1972static _Py_PreInitEntry _preinit_xoptions = NULL;
1973
1974static _Py_PreInitEntry
1975_alloc_preinit_entry(const wchar_t *value)
1976{
1977 /* To get this to work, we have to initialize the runtime implicitly */
1978 _PyRuntime_Initialize();
1979
1980 /* Force default allocator, so we can ensure that it also gets used to
1981 * destroy the linked list in _clear_preinit_entries.
1982 */
1983 PyMemAllocatorEx old_alloc;
1984 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1985
1986 _Py_PreInitEntry node = PyMem_RawCalloc(1, sizeof(*node));
1987 if (node != NULL) {
1988 node->value = _PyMem_RawWcsdup(value);
1989 if (node->value == NULL) {
1990 PyMem_RawFree(node);
1991 node = NULL;
1992 };
1993 };
1994
1995 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1996 return node;
Zackery Spytz1a2252e2019-05-06 10:56:51 -06001997}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001998
1999static int
2000_append_preinit_entry(_Py_PreInitEntry *optionlist, const wchar_t *value)
2001{
2002 _Py_PreInitEntry new_entry = _alloc_preinit_entry(value);
2003 if (new_entry == NULL) {
2004 return -1;
2005 }
2006 /* We maintain the linked list in this order so it's easy to play back
2007 * the add commands in the same order later on in _Py_InitializeCore
2008 */
2009 _Py_PreInitEntry last_entry = *optionlist;
2010 if (last_entry == NULL) {
2011 *optionlist = new_entry;
2012 } else {
2013 while (last_entry->next != NULL) {
2014 last_entry = last_entry->next;
2015 }
2016 last_entry->next = new_entry;
2017 }
2018 return 0;
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002019}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002020
2021static void
2022_clear_preinit_entries(_Py_PreInitEntry *optionlist)
2023{
2024 _Py_PreInitEntry current = *optionlist;
2025 *optionlist = NULL;
2026 /* Deallocate the nodes and their contents using the default allocator */
2027 PyMemAllocatorEx old_alloc;
2028 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2029 while (current != NULL) {
2030 _Py_PreInitEntry next = current->next;
2031 PyMem_RawFree(current->value);
2032 PyMem_RawFree(current);
2033 current = next;
2034 }
2035 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002036}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002037
Victor Stinner120b7072019-08-23 18:03:08 +01002038
2039PyStatus
Victor Stinnerfb4ae152019-09-30 01:40:17 +02002040_PySys_ReadPreinitWarnOptions(PyWideStringList *options)
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002041{
Victor Stinner120b7072019-08-23 18:03:08 +01002042 PyStatus status;
2043 _Py_PreInitEntry entry;
2044
2045 for (entry = _preinit_warnoptions; entry != NULL; entry = entry->next) {
Victor Stinnerfb4ae152019-09-30 01:40:17 +02002046 status = PyWideStringList_Append(options, entry->value);
Victor Stinner120b7072019-08-23 18:03:08 +01002047 if (_PyStatus_EXCEPTION(status)) {
2048 return status;
2049 }
2050 }
2051
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002052 _clear_preinit_entries(&_preinit_warnoptions);
Victor Stinner120b7072019-08-23 18:03:08 +01002053 return _PyStatus_OK();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002054}
2055
Victor Stinner120b7072019-08-23 18:03:08 +01002056
2057PyStatus
2058_PySys_ReadPreinitXOptions(PyConfig *config)
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002059{
Victor Stinner120b7072019-08-23 18:03:08 +01002060 PyStatus status;
2061 _Py_PreInitEntry entry;
2062
2063 for (entry = _preinit_xoptions; entry != NULL; entry = entry->next) {
2064 status = PyWideStringList_Append(&config->xoptions, entry->value);
2065 if (_PyStatus_EXCEPTION(status)) {
2066 return status;
2067 }
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002068 }
2069
Victor Stinner120b7072019-08-23 18:03:08 +01002070 _clear_preinit_entries(&_preinit_xoptions);
2071 return _PyStatus_OK();
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002072}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002073
Victor Stinner120b7072019-08-23 18:03:08 +01002074
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002075static PyObject *
Victor Stinner838f2642019-06-13 22:41:23 +02002076get_warnoptions(PyThreadState *tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002077{
Victor Stinner838f2642019-06-13 22:41:23 +02002078 PyObject *warnoptions = sys_get_object_id(tstate, &PyId_warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002079 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002080 /* PEP432 TODO: we can reach this if warnoptions is NULL in the main
2081 * interpreter config. When that happens, we need to properly set
2082 * the `warnoptions` reference in the main interpreter config as well.
2083 *
2084 * For Python 3.7, we shouldn't be able to get here due to the
2085 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
2086 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
2087 * call optional for embedding applications, thus making this
2088 * reachable again.
2089 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002090 warnoptions = PyList_New(0);
Victor Stinner838f2642019-06-13 22:41:23 +02002091 if (warnoptions == NULL) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002092 return NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02002093 }
2094 if (sys_set_object_id(tstate, &PyId_warnoptions, warnoptions)) {
Eric Snowdae02762017-09-14 00:35:58 -07002095 Py_DECREF(warnoptions);
2096 return NULL;
2097 }
2098 Py_DECREF(warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002099 }
2100 return warnoptions;
2101}
Guido van Rossum23fff912000-12-15 22:02:05 +00002102
2103void
2104PySys_ResetWarnOptions(void)
2105{
Victor Stinner50b48572018-11-01 01:51:40 +01002106 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002107 if (tstate == NULL) {
2108 _clear_preinit_entries(&_preinit_warnoptions);
2109 return;
2110 }
2111
Victor Stinner838f2642019-06-13 22:41:23 +02002112 PyObject *warnoptions = sys_get_object_id(tstate, &PyId_warnoptions);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002113 if (warnoptions == NULL || !PyList_Check(warnoptions))
2114 return;
2115 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
Guido van Rossum23fff912000-12-15 22:02:05 +00002116}
2117
Victor Stinnere1b29952018-10-30 14:31:42 +01002118static int
Victor Stinner838f2642019-06-13 22:41:23 +02002119_PySys_AddWarnOptionWithError(PyThreadState *tstate, PyObject *option)
Guido van Rossum23fff912000-12-15 22:02:05 +00002120{
Victor Stinner838f2642019-06-13 22:41:23 +02002121 PyObject *warnoptions = get_warnoptions(tstate);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002122 if (warnoptions == NULL) {
2123 return -1;
2124 }
2125 if (PyList_Append(warnoptions, option)) {
2126 return -1;
2127 }
2128 return 0;
2129}
2130
2131void
2132PySys_AddWarnOptionUnicode(PyObject *option)
2133{
Victor Stinner838f2642019-06-13 22:41:23 +02002134 PyThreadState *tstate = _PyThreadState_GET();
2135 if (_PySys_AddWarnOptionWithError(tstate, option) < 0) {
Victor Stinnere1b29952018-10-30 14:31:42 +01002136 /* No return value, therefore clear error state if possible */
Victor Stinner838f2642019-06-13 22:41:23 +02002137 if (tstate) {
2138 _PyErr_Clear(tstate);
Victor Stinnere1b29952018-10-30 14:31:42 +01002139 }
2140 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00002141}
2142
2143void
2144PySys_AddWarnOption(const wchar_t *s)
2145{
Victor Stinner50b48572018-11-01 01:51:40 +01002146 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002147 if (tstate == NULL) {
2148 _append_preinit_entry(&_preinit_warnoptions, s);
2149 return;
2150 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00002151 PyObject *unicode;
2152 unicode = PyUnicode_FromWideChar(s, -1);
2153 if (unicode == NULL)
2154 return;
2155 PySys_AddWarnOptionUnicode(unicode);
2156 Py_DECREF(unicode);
Guido van Rossum23fff912000-12-15 22:02:05 +00002157}
2158
Christian Heimes33fe8092008-04-13 13:53:33 +00002159int
2160PySys_HasWarnOptions(void)
2161{
Victor Stinner838f2642019-06-13 22:41:23 +02002162 PyThreadState *tstate = _PyThreadState_GET();
2163 PyObject *warnoptions = sys_get_object_id(tstate, &PyId_warnoptions);
Serhiy Storchakadffccc62018-12-10 13:50:22 +02002164 return (warnoptions != NULL && PyList_Check(warnoptions)
2165 && PyList_GET_SIZE(warnoptions) > 0);
Christian Heimes33fe8092008-04-13 13:53:33 +00002166}
2167
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002168static PyObject *
Victor Stinner838f2642019-06-13 22:41:23 +02002169get_xoptions(PyThreadState *tstate)
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002170{
Victor Stinner838f2642019-06-13 22:41:23 +02002171 PyObject *xoptions = sys_get_object_id(tstate, &PyId__xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002172 if (xoptions == NULL || !PyDict_Check(xoptions)) {
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002173 /* PEP432 TODO: we can reach this if xoptions is NULL in the main
2174 * interpreter config. When that happens, we need to properly set
2175 * the `xoptions` reference in the main interpreter config as well.
2176 *
2177 * For Python 3.7, we shouldn't be able to get here due to the
2178 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
2179 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
2180 * call optional for embedding applications, thus making this
2181 * reachable again.
2182 */
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002183 xoptions = PyDict_New();
Victor Stinner838f2642019-06-13 22:41:23 +02002184 if (xoptions == NULL) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002185 return NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02002186 }
2187 if (sys_set_object_id(tstate, &PyId__xoptions, xoptions)) {
Eric Snowdae02762017-09-14 00:35:58 -07002188 Py_DECREF(xoptions);
2189 return NULL;
2190 }
2191 Py_DECREF(xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002192 }
2193 return xoptions;
2194}
2195
Victor Stinnere1b29952018-10-30 14:31:42 +01002196static int
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002197_PySys_AddXOptionWithError(const wchar_t *s)
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002198{
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002199 PyObject *name = NULL, *value = NULL;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002200
Victor Stinner838f2642019-06-13 22:41:23 +02002201 PyThreadState *tstate = _PyThreadState_GET();
2202 PyObject *opts = get_xoptions(tstate);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002203 if (opts == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002204 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002205 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002206
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002207 const wchar_t *name_end = wcschr(s, L'=');
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002208 if (!name_end) {
2209 name = PyUnicode_FromWideChar(s, -1);
2210 value = Py_True;
2211 Py_INCREF(value);
2212 }
2213 else {
2214 name = PyUnicode_FromWideChar(s, name_end - s);
2215 value = PyUnicode_FromWideChar(name_end + 1, -1);
2216 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002217 if (name == NULL || value == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002218 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002219 }
2220 if (PyDict_SetItem(opts, name, value) < 0) {
2221 goto error;
2222 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002223 Py_DECREF(name);
2224 Py_DECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002225 return 0;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002226
2227error:
2228 Py_XDECREF(name);
2229 Py_XDECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002230 return -1;
2231}
2232
2233void
2234PySys_AddXOption(const wchar_t *s)
2235{
Victor Stinner50b48572018-11-01 01:51:40 +01002236 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002237 if (tstate == NULL) {
2238 _append_preinit_entry(&_preinit_xoptions, s);
2239 return;
2240 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002241 if (_PySys_AddXOptionWithError(s) < 0) {
2242 /* No return value, therefore clear error state if possible */
Victor Stinner120b7072019-08-23 18:03:08 +01002243 _PyErr_Clear(tstate);
Victor Stinner0cae6092016-11-11 01:43:56 +01002244 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002245}
2246
2247PyObject *
2248PySys_GetXOptions(void)
2249{
Victor Stinner838f2642019-06-13 22:41:23 +02002250 PyThreadState *tstate = _PyThreadState_GET();
2251 return get_xoptions(tstate);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002252}
2253
Guido van Rossum40552d01998-08-06 03:34:39 +00002254/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
2255 Two literals concatenated works just fine. If you have a K&R compiler
2256 or other abomination that however *does* understand longer strings,
2257 get rid of the !!! comment in the middle and the quotes that surround it. */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002258PyDoc_VAR(sys_doc) =
2259PyDoc_STR(
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002260"This module provides access to some objects used or maintained by the\n\
2261interpreter and to functions that interact strongly with the interpreter.\n\
2262\n\
2263Dynamic objects:\n\
2264\n\
2265argv -- command line arguments; argv[0] is the script pathname if known\n\
2266path -- module search path; path[0] is the script directory, else ''\n\
2267modules -- dictionary of loaded modules\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002268\n\
2269displayhook -- called to show results in an interactive session\n\
2270excepthook -- called to handle any uncaught exception other than SystemExit\n\
2271 To customize printing in an interactive session or to install a custom\n\
2272 top-level exception handler, assign other functions to replace these.\n\
2273\n\
Benjamin Peterson06157a42008-07-15 00:28:36 +00002274stdin -- standard input file object; used by input()\n\
Georg Brandl88fc6642007-02-09 21:28:07 +00002275stdout -- standard output file object; used by print()\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002276stderr -- standard error object; used for error messages\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002277 By assigning other file objects (or objects that behave like files)\n\
2278 to these, it is possible to redirect all of the interpreter's I/O.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002279\n\
2280last_type -- type of last uncaught exception\n\
2281last_value -- value of last uncaught exception\n\
2282last_traceback -- traceback of last uncaught exception\n\
2283 These three are only available in an interactive session after a\n\
2284 traceback has been printed.\n\
Guido van Rossuma71b5f41999-01-14 19:07:00 +00002285"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002286)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002287/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002288PyDoc_STR(
Guido van Rossuma71b5f41999-01-14 19:07:00 +00002289"\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002290Static objects:\n\
2291\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002292builtin_module_names -- tuple of module names built into this interpreter\n\
2293copyright -- copyright notice pertaining to this interpreter\n\
2294exec_prefix -- prefix used to find the machine-specific Python library\n\
Petri Lehtinen4b0eab62012-02-02 21:23:15 +02002295executable -- absolute path of the executable binary of the Python interpreter\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07002296float_info -- a named tuple with information about the float implementation.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002297float_repr_style -- string indicating the style of repr() output for floats\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07002298hash_info -- a named tuple with information about the hash algorithm.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002299hexversion -- version information encoded as a single integer\n\
Barry Warsaw409da152012-06-03 16:18:47 -04002300implementation -- Python implementation information.\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07002301int_info -- a named tuple with information about the int implementation.\n\
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00002302maxsize -- the largest supported length of containers.\n\
Serhiy Storchakad3faf432015-01-18 11:28:37 +02002303maxunicode -- the value of the largest Unicode code point\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002304platform -- platform identifier\n\
2305prefix -- prefix used to find the Python library\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07002306thread_info -- a named tuple with information about the thread implementation.\n\
Fred Drake801c08d2000-04-13 15:29:10 +00002307version -- the version of this interpreter as a string\n\
Eric Smith0e5b5622009-02-06 01:32:42 +00002308version_info -- version information as a named tuple\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002309"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002310)
Steve Dowercc16be82016-09-08 10:35:16 -07002311#ifdef MS_COREDLL
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002312/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002313PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002314"dllhandle -- [Windows only] integer handle of the Python DLL\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002315winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002316"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002317)
Steve Dowercc16be82016-09-08 10:35:16 -07002318#endif /* MS_COREDLL */
2319#ifdef MS_WINDOWS
2320/* concatenating string here */
2321PyDoc_STR(
oldkaa0735f2018-02-02 16:52:55 +08002322"_enablelegacywindowsfsencoding -- [Windows only]\n\
Steve Dowercc16be82016-09-08 10:35:16 -07002323"
2324)
2325#endif
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002326PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002327"__stdin__ -- the original stdin; don't touch!\n\
2328__stdout__ -- the original stdout; don't touch!\n\
2329__stderr__ -- the original stderr; don't touch!\n\
2330__displayhook__ -- the original displayhook; don't touch!\n\
2331__excepthook__ -- the original excepthook; don't touch!\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002332\n\
2333Functions:\n\
2334\n\
Georg Brandl1a3284e2007-12-02 09:40:06 +00002335displayhook() -- print an object to the screen, and save it in builtins._\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002336excepthook() -- print an exception and its traceback to sys.stderr\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002337exc_info() -- return thread-safe information about the current exception\n\
2338exit() -- exit the interpreter by raising SystemExit\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002339getdlopenflags() -- returns flags to be used for dlopen() calls\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002340getprofile() -- get the global profiling function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002341getrefcount() -- return the reference count for an object (plus one :-)\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002342getrecursionlimit() -- return the max recursion depth for the interpreter\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002343getsizeof() -- return the size of an object in bytes\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002344gettrace() -- get the global debug tracing function\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002345setdlopenflags() -- set the flags to be used for dlopen() calls\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002346setprofile() -- set the global profiling function\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002347setrecursionlimit() -- set the max recursion depth for the interpreter\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002348settrace() -- set the global debug tracing function\n\
Fred Drakeccede592000-08-14 20:59:57 +00002349"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002350)
Fred Drakeccede592000-08-14 20:59:57 +00002351/* end of sys_doc */ ;
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002352
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002353
2354PyDoc_STRVAR(flags__doc__,
2355"sys.flags\n\
2356\n\
2357Flags provided through command line arguments or environment vars.");
2358
2359static PyTypeObject FlagsType;
2360
2361static PyStructSequence_Field flags_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002362 {"debug", "-d"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 {"inspect", "-i"},
2364 {"interactive", "-i"},
2365 {"optimize", "-O or -OO"},
2366 {"dont_write_bytecode", "-B"},
2367 {"no_user_site", "-s"},
2368 {"no_site", "-S"},
2369 {"ignore_environment", "-E"},
2370 {"verbose", "-v"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002371 /* {"unbuffered", "-u"}, */
2372 /* {"skip_first", "-x"}, */
Georg Brandl8aa7e992010-12-28 18:30:18 +00002373 {"bytes_warning", "-b"},
2374 {"quiet", "-q"},
Georg Brandl09a7c722012-02-20 21:31:46 +01002375 {"hash_randomization", "-R"},
Christian Heimesad73a9c2013-08-10 16:36:18 +02002376 {"isolated", "-I"},
Victor Stinner5e3806f2017-11-30 11:40:24 +01002377 {"dev_mode", "-X dev"},
Victor Stinner91106cd2017-12-13 12:29:09 +01002378 {"utf8_mode", "-X utf8"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002380};
2381
2382static PyStructSequence_Desc flags_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002383 "sys.flags", /* name */
2384 flags__doc__, /* doc */
2385 flags_fields, /* fields */
Victor Stinner91106cd2017-12-13 12:29:09 +01002386 15
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002387};
2388
2389static PyObject*
Victor Stinner01b1cc12019-11-20 02:27:56 +01002390make_flags(PyThreadState *tstate)
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002391{
Victor Stinner01b1cc12019-11-20 02:27:56 +01002392 PyInterpreterState *interp = tstate->interp;
2393 const PyPreConfig *preconfig = &interp->runtime->preconfig;
2394 const PyConfig *config = &interp->config;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002395
Victor Stinner01b1cc12019-11-20 02:27:56 +01002396 PyObject *seq = PyStructSequence_New(&FlagsType);
2397 if (seq == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002398 return NULL;
Victor Stinner01b1cc12019-11-20 02:27:56 +01002399 }
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002400
Victor Stinner01b1cc12019-11-20 02:27:56 +01002401 int pos = 0;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002402#define SetFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002403 PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002404
Victor Stinnerfbca9082018-08-30 00:50:45 +02002405 SetFlag(config->parser_debug);
2406 SetFlag(config->inspect);
2407 SetFlag(config->interactive);
2408 SetFlag(config->optimization_level);
2409 SetFlag(!config->write_bytecode);
2410 SetFlag(!config->user_site_directory);
2411 SetFlag(!config->site_import);
Victor Stinner20004952019-03-26 02:31:11 +01002412 SetFlag(!config->use_environment);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002413 SetFlag(config->verbose);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002414 /* SetFlag(saw_unbuffered_flag); */
2415 /* SetFlag(skipfirstline); */
Victor Stinnerfbca9082018-08-30 00:50:45 +02002416 SetFlag(config->bytes_warning);
2417 SetFlag(config->quiet);
2418 SetFlag(config->use_hash_seed == 0 || config->hash_seed != 0);
Victor Stinner20004952019-03-26 02:31:11 +01002419 SetFlag(config->isolated);
2420 PyStructSequence_SET_ITEM(seq, pos++, PyBool_FromLong(config->dev_mode));
2421 SetFlag(preconfig->utf8_mode);
Victor Stinner91106cd2017-12-13 12:29:09 +01002422#undef SetFlag
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002423
Victor Stinner838f2642019-06-13 22:41:23 +02002424 if (_PyErr_Occurred(tstate)) {
Serhiy Storchaka87a854d2013-12-17 14:59:42 +02002425 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002426 return NULL;
2427 }
2428 return seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002429}
2430
Eric Smith0e5b5622009-02-06 01:32:42 +00002431PyDoc_STRVAR(version_info__doc__,
2432"sys.version_info\n\
2433\n\
2434Version information as a named tuple.");
2435
2436static PyTypeObject VersionInfoType;
2437
2438static PyStructSequence_Field version_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002439 {"major", "Major release number"},
2440 {"minor", "Minor release number"},
2441 {"micro", "Patch release number"},
Ned Deilyda4887a2016-11-04 17:03:34 -04002442 {"releaselevel", "'alpha', 'beta', 'candidate', or 'final'"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002443 {"serial", "Serial release number"},
2444 {0}
Eric Smith0e5b5622009-02-06 01:32:42 +00002445};
2446
2447static PyStructSequence_Desc version_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002448 "sys.version_info", /* name */
2449 version_info__doc__, /* doc */
2450 version_info_fields, /* fields */
2451 5
Eric Smith0e5b5622009-02-06 01:32:42 +00002452};
2453
2454static PyObject *
Victor Stinner838f2642019-06-13 22:41:23 +02002455make_version_info(PyThreadState *tstate)
Eric Smith0e5b5622009-02-06 01:32:42 +00002456{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002457 PyObject *version_info;
2458 char *s;
2459 int pos = 0;
Eric Smith0e5b5622009-02-06 01:32:42 +00002460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002461 version_info = PyStructSequence_New(&VersionInfoType);
2462 if (version_info == NULL) {
2463 return NULL;
2464 }
Eric Smith0e5b5622009-02-06 01:32:42 +00002465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002466 /*
2467 * These release level checks are mutually exclusive and cover
2468 * the field, so don't get too fancy with the pre-processor!
2469 */
Eric Smith0e5b5622009-02-06 01:32:42 +00002470#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002471 s = "alpha";
Eric Smith0e5b5622009-02-06 01:32:42 +00002472#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002473 s = "beta";
Eric Smith0e5b5622009-02-06 01:32:42 +00002474#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002475 s = "candidate";
Eric Smith0e5b5622009-02-06 01:32:42 +00002476#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002477 s = "final";
Eric Smith0e5b5622009-02-06 01:32:42 +00002478#endif
2479
2480#define SetIntItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002481 PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002482#define SetStrItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002483 PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002485 SetIntItem(PY_MAJOR_VERSION);
2486 SetIntItem(PY_MINOR_VERSION);
2487 SetIntItem(PY_MICRO_VERSION);
2488 SetStrItem(s);
2489 SetIntItem(PY_RELEASE_SERIAL);
Eric Smith0e5b5622009-02-06 01:32:42 +00002490#undef SetIntItem
2491#undef SetStrItem
2492
Victor Stinner838f2642019-06-13 22:41:23 +02002493 if (_PyErr_Occurred(tstate)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002494 Py_CLEAR(version_info);
2495 return NULL;
2496 }
2497 return version_info;
Eric Smith0e5b5622009-02-06 01:32:42 +00002498}
2499
Brett Cannon3adc7b72012-07-09 14:22:12 -04002500/* sys.implementation values */
2501#define NAME "cpython"
2502const char *_PySys_ImplName = NAME;
Victor Stinnercf01b682015-11-05 11:21:38 +01002503#define MAJOR Py_STRINGIFY(PY_MAJOR_VERSION)
2504#define MINOR Py_STRINGIFY(PY_MINOR_VERSION)
Ned Deily529ea5d2014-06-30 23:31:14 -07002505#define TAG NAME "-" MAJOR MINOR
Brett Cannon3adc7b72012-07-09 14:22:12 -04002506const char *_PySys_ImplCacheTag = TAG;
2507#undef NAME
Brett Cannon3adc7b72012-07-09 14:22:12 -04002508#undef MAJOR
2509#undef MINOR
2510#undef TAG
2511
Barry Warsaw409da152012-06-03 16:18:47 -04002512static PyObject *
2513make_impl_info(PyObject *version_info)
2514{
2515 int res;
2516 PyObject *impl_info, *value, *ns;
2517
2518 impl_info = PyDict_New();
2519 if (impl_info == NULL)
2520 return NULL;
2521
2522 /* populate the dict */
2523
Brett Cannon3adc7b72012-07-09 14:22:12 -04002524 value = PyUnicode_FromString(_PySys_ImplName);
Barry Warsaw409da152012-06-03 16:18:47 -04002525 if (value == NULL)
2526 goto error;
2527 res = PyDict_SetItemString(impl_info, "name", value);
2528 Py_DECREF(value);
2529 if (res < 0)
2530 goto error;
2531
Brett Cannon3adc7b72012-07-09 14:22:12 -04002532 value = PyUnicode_FromString(_PySys_ImplCacheTag);
Barry Warsaw409da152012-06-03 16:18:47 -04002533 if (value == NULL)
2534 goto error;
2535 res = PyDict_SetItemString(impl_info, "cache_tag", value);
2536 Py_DECREF(value);
2537 if (res < 0)
2538 goto error;
Barry Warsaw409da152012-06-03 16:18:47 -04002539
2540 res = PyDict_SetItemString(impl_info, "version", version_info);
2541 if (res < 0)
2542 goto error;
2543
2544 value = PyLong_FromLong(PY_VERSION_HEX);
2545 if (value == NULL)
2546 goto error;
2547 res = PyDict_SetItemString(impl_info, "hexversion", value);
2548 Py_DECREF(value);
2549 if (res < 0)
2550 goto error;
2551
doko@ubuntu.com55532312016-06-14 08:55:19 +02002552#ifdef MULTIARCH
2553 value = PyUnicode_FromString(MULTIARCH);
2554 if (value == NULL)
2555 goto error;
2556 res = PyDict_SetItemString(impl_info, "_multiarch", value);
2557 Py_DECREF(value);
2558 if (res < 0)
2559 goto error;
2560#endif
2561
Barry Warsaw409da152012-06-03 16:18:47 -04002562 /* dict ready */
2563
2564 ns = _PyNamespace_New(impl_info);
2565 Py_DECREF(impl_info);
2566 return ns;
2567
2568error:
2569 Py_CLEAR(impl_info);
2570 return NULL;
2571}
2572
Martin v. Löwis1a214512008-06-11 05:26:20 +00002573static struct PyModuleDef sysmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002574 PyModuleDef_HEAD_INIT,
2575 "sys",
2576 sys_doc,
2577 -1, /* multiple "initialization" just copies the module dict. */
2578 sys_methods,
2579 NULL,
2580 NULL,
2581 NULL,
2582 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002583};
2584
Eric Snow6b4be192017-05-22 21:36:03 -07002585/* Updating the sys namespace, returning NULL pointer on error */
Victor Stinner8fea2522013-10-27 17:15:42 +01002586#define SET_SYS_FROM_STRING_BORROW(key, value) \
Victor Stinner58049602013-07-22 22:40:00 +02002587 do { \
Victor Stinner58049602013-07-22 22:40:00 +02002588 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002589 if (v == NULL) { \
2590 goto err_occurred; \
2591 } \
Victor Stinner58049602013-07-22 22:40:00 +02002592 res = PyDict_SetItemString(sysdict, key, v); \
2593 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002594 goto err_occurred; \
Victor Stinner8fea2522013-10-27 17:15:42 +01002595 } \
2596 } while (0)
2597#define SET_SYS_FROM_STRING(key, value) \
2598 do { \
Victor Stinner8fea2522013-10-27 17:15:42 +01002599 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002600 if (v == NULL) { \
2601 goto err_occurred; \
2602 } \
Victor Stinner8fea2522013-10-27 17:15:42 +01002603 res = PyDict_SetItemString(sysdict, key, v); \
2604 Py_DECREF(v); \
2605 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002606 goto err_occurred; \
Victor Stinner58049602013-07-22 22:40:00 +02002607 } \
2608 } while (0)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002609
Victor Stinner331a6a52019-05-27 16:39:22 +02002610static PyStatus
Victor Stinner01b1cc12019-11-20 02:27:56 +01002611_PySys_InitCore(PyThreadState *tstate, PyObject *sysdict)
Eric Snow6b4be192017-05-22 21:36:03 -07002612{
Victor Stinnerab672812019-01-23 15:04:40 +01002613 PyObject *version_info;
Eric Snow6b4be192017-05-22 21:36:03 -07002614 int res;
2615
Nick Coghland6009512014-11-20 21:39:37 +10002616 /* stdin/stdout/stderr are set in pylifecycle.c */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002617
Victor Stinner8fea2522013-10-27 17:15:42 +01002618 SET_SYS_FROM_STRING_BORROW("__displayhook__",
2619 PyDict_GetItemString(sysdict, "displayhook"));
2620 SET_SYS_FROM_STRING_BORROW("__excepthook__",
2621 PyDict_GetItemString(sysdict, "excepthook"));
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04002622 SET_SYS_FROM_STRING_BORROW(
2623 "__breakpointhook__",
2624 PyDict_GetItemString(sysdict, "breakpointhook"));
Victor Stinneref9d9b62019-05-22 11:28:22 +02002625 SET_SYS_FROM_STRING_BORROW("__unraisablehook__",
2626 PyDict_GetItemString(sysdict, "unraisablehook"));
2627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002628 SET_SYS_FROM_STRING("version",
2629 PyUnicode_FromString(Py_GetVersion()));
2630 SET_SYS_FROM_STRING("hexversion",
2631 PyLong_FromLong(PY_VERSION_HEX));
Ned Deily5c4b0d02017-03-04 00:19:55 -05002632 SET_SYS_FROM_STRING("_git",
2633 Py_BuildValue("(szz)", "CPython", _Py_gitidentifier(),
2634 _Py_gitversion()));
INADA Naoki6b42eb12017-06-29 15:31:38 +09002635 SET_SYS_FROM_STRING("_framework", PyUnicode_FromString(_PYTHONFRAMEWORK));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002636 SET_SYS_FROM_STRING("api_version",
2637 PyLong_FromLong(PYTHON_API_VERSION));
2638 SET_SYS_FROM_STRING("copyright",
2639 PyUnicode_FromString(Py_GetCopyright()));
2640 SET_SYS_FROM_STRING("platform",
2641 PyUnicode_FromString(Py_GetPlatform()));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002642 SET_SYS_FROM_STRING("maxsize",
2643 PyLong_FromSsize_t(PY_SSIZE_T_MAX));
2644 SET_SYS_FROM_STRING("float_info",
2645 PyFloat_GetInfo());
2646 SET_SYS_FROM_STRING("int_info",
2647 PyLong_GetInfo());
Mark Dickinsondc787d22010-05-23 13:33:13 +00002648 /* initialize hash_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002649 if (Hash_InfoType.tp_name == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002650 if (PyStructSequence_InitType2(&Hash_InfoType, &hash_info_desc) < 0) {
2651 goto type_init_failed;
2652 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002653 }
Mark Dickinsondc787d22010-05-23 13:33:13 +00002654 SET_SYS_FROM_STRING("hash_info",
Victor Stinner838f2642019-06-13 22:41:23 +02002655 get_hash_info(tstate));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002656 SET_SYS_FROM_STRING("maxunicode",
Ezio Melotti48a2f8f2011-09-29 00:18:19 +03002657 PyLong_FromLong(0x10FFFF));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002658 SET_SYS_FROM_STRING("builtin_module_names",
2659 list_builtin_module_names());
Christian Heimes743e0cd2012-10-17 23:52:17 +02002660#if PY_BIG_ENDIAN
2661 SET_SYS_FROM_STRING("byteorder",
2662 PyUnicode_FromString("big"));
2663#else
2664 SET_SYS_FROM_STRING("byteorder",
2665 PyUnicode_FromString("little"));
2666#endif
Fred Drake099325e2000-08-14 15:47:03 +00002667
Guido van Rossum8b9ea871996-08-23 18:14:47 +00002668#ifdef MS_COREDLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002669 SET_SYS_FROM_STRING("dllhandle",
2670 PyLong_FromVoidPtr(PyWin_DLLhModule));
2671 SET_SYS_FROM_STRING("winver",
2672 PyUnicode_FromString(PyWin_DLLVersionString));
Guido van Rossumc606fe11996-04-09 02:37:57 +00002673#endif
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00002674#ifdef ABIFLAGS
2675 SET_SYS_FROM_STRING("abiflags",
2676 PyUnicode_FromString(ABIFLAGS));
2677#endif
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002679 /* version_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002680 if (VersionInfoType.tp_name == NULL) {
2681 if (PyStructSequence_InitType2(&VersionInfoType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002682 &version_info_desc) < 0) {
2683 goto type_init_failed;
2684 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002685 }
Victor Stinner838f2642019-06-13 22:41:23 +02002686 version_info = make_version_info(tstate);
Barry Warsaw409da152012-06-03 16:18:47 -04002687 SET_SYS_FROM_STRING("version_info", version_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002688 /* prevent user from creating new instances */
2689 VersionInfoType.tp_init = NULL;
2690 VersionInfoType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002691 res = PyDict_DelItemString(VersionInfoType.tp_dict, "__new__");
Victor Stinner838f2642019-06-13 22:41:23 +02002692 if (res < 0 && _PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
2693 _PyErr_Clear(tstate);
2694 }
Eric Smith0e5b5622009-02-06 01:32:42 +00002695
Barry Warsaw409da152012-06-03 16:18:47 -04002696 /* implementation */
2697 SET_SYS_FROM_STRING("implementation", make_impl_info(version_info));
2698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002699 /* flags */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002700 if (FlagsType.tp_name == 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002701 if (PyStructSequence_InitType2(&FlagsType, &flags_desc) < 0) {
2702 goto type_init_failed;
2703 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002704 }
Victor Stinner43125222019-04-24 18:23:53 +02002705 /* Set flags to their default values (updated by _PySys_InitMain()) */
Victor Stinner01b1cc12019-11-20 02:27:56 +01002706 SET_SYS_FROM_STRING("flags", make_flags(tstate));
Eric Smithf7bb5782010-01-27 00:44:57 +00002707
2708#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002709 /* getwindowsversion */
2710 if (WindowsVersionType.tp_name == 0)
Victor Stinner1c8f0592013-07-22 22:24:54 +02002711 if (PyStructSequence_InitType2(&WindowsVersionType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002712 &windows_version_desc) < 0) {
2713 goto type_init_failed;
2714 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002715 /* prevent user from creating new instances */
2716 WindowsVersionType.tp_init = NULL;
2717 WindowsVersionType.tp_new = NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02002718 assert(!_PyErr_Occurred(tstate));
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002719 res = PyDict_DelItemString(WindowsVersionType.tp_dict, "__new__");
Victor Stinner838f2642019-06-13 22:41:23 +02002720 if (res < 0 && _PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
2721 _PyErr_Clear(tstate);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002722 }
Eric Smithf7bb5782010-01-27 00:44:57 +00002723#endif
2724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002725 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002726#ifndef PY_NO_SHORT_FLOAT_REPR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002727 SET_SYS_FROM_STRING("float_repr_style",
2728 PyUnicode_FromString("short"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002729#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002730 SET_SYS_FROM_STRING("float_repr_style",
2731 PyUnicode_FromString("legacy"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002732#endif
2733
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002734 SET_SYS_FROM_STRING("thread_info", PyThread_GetInfo());
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002735
Yury Selivanoveb636452016-09-08 22:01:51 -07002736 /* initialize asyncgen_hooks */
2737 if (AsyncGenHooksType.tp_name == NULL) {
2738 if (PyStructSequence_InitType2(
2739 &AsyncGenHooksType, &asyncgen_hooks_desc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002740 goto type_init_failed;
Yury Selivanoveb636452016-09-08 22:01:51 -07002741 }
2742 }
2743
Victor Stinner838f2642019-06-13 22:41:23 +02002744 if (_PyErr_Occurred(tstate)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002745 goto err_occurred;
2746 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002747 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002748
2749type_init_failed:
Victor Stinner331a6a52019-05-27 16:39:22 +02002750 return _PyStatus_ERR("failed to initialize a type");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002751
2752err_occurred:
Victor Stinner331a6a52019-05-27 16:39:22 +02002753 return _PyStatus_ERR("can't initialize sys module");
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002754}
2755
Eric Snow6b4be192017-05-22 21:36:03 -07002756#undef SET_SYS_FROM_STRING
Eric Snow6b4be192017-05-22 21:36:03 -07002757
2758/* Updating the sys namespace, returning integer error codes */
Eric Snow6b4be192017-05-22 21:36:03 -07002759#define SET_SYS_FROM_STRING_INT_RESULT(key, value) \
2760 do { \
2761 PyObject *v = (value); \
2762 if (v == NULL) \
2763 return -1; \
2764 res = PyDict_SetItemString(sysdict, key, v); \
2765 Py_DECREF(v); \
2766 if (res < 0) { \
2767 return res; \
2768 } \
2769 } while (0)
2770
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002771
2772static int
2773sys_add_xoption(PyObject *opts, const wchar_t *s)
2774{
2775 PyObject *name, *value;
2776
2777 const wchar_t *name_end = wcschr(s, L'=');
2778 if (!name_end) {
2779 name = PyUnicode_FromWideChar(s, -1);
2780 value = Py_True;
2781 Py_INCREF(value);
2782 }
2783 else {
2784 name = PyUnicode_FromWideChar(s, name_end - s);
2785 value = PyUnicode_FromWideChar(name_end + 1, -1);
2786 }
2787 if (name == NULL || value == NULL) {
2788 goto error;
2789 }
2790 if (PyDict_SetItem(opts, name, value) < 0) {
2791 goto error;
2792 }
2793 Py_DECREF(name);
2794 Py_DECREF(value);
2795 return 0;
2796
2797error:
2798 Py_XDECREF(name);
2799 Py_XDECREF(value);
2800 return -1;
2801}
2802
2803
2804static PyObject*
Victor Stinner331a6a52019-05-27 16:39:22 +02002805sys_create_xoptions_dict(const PyConfig *config)
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002806{
2807 Py_ssize_t nxoption = config->xoptions.length;
2808 wchar_t * const * xoptions = config->xoptions.items;
2809 PyObject *dict = PyDict_New();
2810 if (dict == NULL) {
2811 return NULL;
2812 }
2813
2814 for (Py_ssize_t i=0; i < nxoption; i++) {
2815 const wchar_t *option = xoptions[i];
2816 if (sys_add_xoption(dict, option) < 0) {
2817 Py_DECREF(dict);
2818 return NULL;
2819 }
2820 }
2821
2822 return dict;
2823}
2824
2825
Eric Snow6b4be192017-05-22 21:36:03 -07002826int
Victor Stinner01b1cc12019-11-20 02:27:56 +01002827_PySys_InitMain(PyThreadState *tstate)
Eric Snow6b4be192017-05-22 21:36:03 -07002828{
Victor Stinner838f2642019-06-13 22:41:23 +02002829 PyObject *sysdict = tstate->interp->sysdict;
2830 const PyConfig *config = &tstate->interp->config;
Eric Snow6b4be192017-05-22 21:36:03 -07002831 int res;
2832
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002833#define COPY_LIST(KEY, VALUE) \
Victor Stinner37cd9822018-11-16 11:55:35 +01002834 do { \
Victor Stinner331a6a52019-05-27 16:39:22 +02002835 PyObject *list = _PyWideStringList_AsList(&(VALUE)); \
Victor Stinner37cd9822018-11-16 11:55:35 +01002836 if (list == NULL) { \
2837 return -1; \
2838 } \
2839 SET_SYS_FROM_STRING_BORROW(KEY, list); \
2840 Py_DECREF(list); \
2841 } while (0)
2842
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002843#define SET_SYS_FROM_WSTR(KEY, VALUE) \
2844 do { \
2845 PyObject *str = PyUnicode_FromWideChar(VALUE, -1); \
2846 if (str == NULL) { \
2847 return -1; \
2848 } \
2849 SET_SYS_FROM_STRING_BORROW(KEY, str); \
2850 Py_DECREF(str); \
2851 } while (0)
Victor Stinner37cd9822018-11-16 11:55:35 +01002852
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002853 COPY_LIST("path", config->module_search_paths);
2854
2855 SET_SYS_FROM_WSTR("executable", config->executable);
Steve Dower9048c492019-06-29 10:34:11 -07002856 SET_SYS_FROM_WSTR("_base_executable", config->base_executable);
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002857 SET_SYS_FROM_WSTR("prefix", config->prefix);
2858 SET_SYS_FROM_WSTR("base_prefix", config->base_prefix);
2859 SET_SYS_FROM_WSTR("exec_prefix", config->exec_prefix);
2860 SET_SYS_FROM_WSTR("base_exec_prefix", config->base_exec_prefix);
Victor Stinner41264f12017-12-15 02:05:29 +01002861
Carl Meyerb193fa92018-06-15 22:40:56 -06002862 if (config->pycache_prefix != NULL) {
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002863 SET_SYS_FROM_WSTR("pycache_prefix", config->pycache_prefix);
Carl Meyerb193fa92018-06-15 22:40:56 -06002864 } else {
2865 PyDict_SetItemString(sysdict, "pycache_prefix", Py_None);
2866 }
2867
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002868 COPY_LIST("argv", config->argv);
2869 COPY_LIST("warnoptions", config->warnoptions);
2870
2871 PyObject *xoptions = sys_create_xoptions_dict(config);
2872 if (xoptions == NULL) {
2873 return -1;
Victor Stinner41264f12017-12-15 02:05:29 +01002874 }
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002875 SET_SYS_FROM_STRING_BORROW("_xoptions", xoptions);
Pablo Galindo34ef64f2019-03-27 12:43:47 +00002876 Py_DECREF(xoptions);
Victor Stinner41264f12017-12-15 02:05:29 +01002877
Victor Stinner37cd9822018-11-16 11:55:35 +01002878#undef COPY_LIST
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002879#undef SET_SYS_FROM_WSTR
Victor Stinner37cd9822018-11-16 11:55:35 +01002880
Eric Snow6b4be192017-05-22 21:36:03 -07002881 /* Set flags to their final values */
Victor Stinner01b1cc12019-11-20 02:27:56 +01002882 SET_SYS_FROM_STRING_INT_RESULT("flags", make_flags(tstate));
Eric Snow6b4be192017-05-22 21:36:03 -07002883 /* prevent user from creating new instances */
2884 FlagsType.tp_init = NULL;
2885 FlagsType.tp_new = NULL;
2886 res = PyDict_DelItemString(FlagsType.tp_dict, "__new__");
2887 if (res < 0) {
Victor Stinner838f2642019-06-13 22:41:23 +02002888 if (!_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
Eric Snow6b4be192017-05-22 21:36:03 -07002889 return res;
2890 }
Victor Stinner838f2642019-06-13 22:41:23 +02002891 _PyErr_Clear(tstate);
Eric Snow6b4be192017-05-22 21:36:03 -07002892 }
2893
2894 SET_SYS_FROM_STRING_INT_RESULT("dont_write_bytecode",
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002895 PyBool_FromLong(!config->write_bytecode));
Eric Snow6b4be192017-05-22 21:36:03 -07002896
Victor Stinner838f2642019-06-13 22:41:23 +02002897 if (get_warnoptions(tstate) == NULL) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002898 return -1;
Victor Stinner838f2642019-06-13 22:41:23 +02002899 }
Victor Stinner865de272017-06-08 13:27:47 +02002900
Victor Stinner838f2642019-06-13 22:41:23 +02002901 if (get_xoptions(tstate) == NULL)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002902 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002903
Victor Stinner838f2642019-06-13 22:41:23 +02002904 if (_PyErr_Occurred(tstate)) {
2905 goto err_occurred;
2906 }
2907
Eric Snow6b4be192017-05-22 21:36:03 -07002908 return 0;
Victor Stinner41264f12017-12-15 02:05:29 +01002909
2910err_occurred:
2911 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002912}
2913
Victor Stinner41264f12017-12-15 02:05:29 +01002914#undef SET_SYS_FROM_STRING_BORROW
Eric Snow6b4be192017-05-22 21:36:03 -07002915#undef SET_SYS_FROM_STRING_INT_RESULT
Eric Snow6b4be192017-05-22 21:36:03 -07002916
Victor Stinnerab672812019-01-23 15:04:40 +01002917
2918/* Set up a preliminary stderr printer until we have enough
2919 infrastructure for the io module in place.
2920
2921 Use UTF-8/surrogateescape and ignore EAGAIN errors. */
Victor Stinner81fe5bd2019-12-06 02:43:30 +01002922static PyStatus
Victor Stinnerab672812019-01-23 15:04:40 +01002923_PySys_SetPreliminaryStderr(PyObject *sysdict)
2924{
2925 PyObject *pstderr = PyFile_NewStdPrinter(fileno(stderr));
2926 if (pstderr == NULL) {
2927 goto error;
2928 }
2929 if (_PyDict_SetItemId(sysdict, &PyId_stderr, pstderr) < 0) {
2930 goto error;
2931 }
2932 if (PyDict_SetItemString(sysdict, "__stderr__", pstderr) < 0) {
2933 goto error;
2934 }
2935 Py_DECREF(pstderr);
Victor Stinner331a6a52019-05-27 16:39:22 +02002936 return _PyStatus_OK();
Victor Stinnerab672812019-01-23 15:04:40 +01002937
2938error:
2939 Py_XDECREF(pstderr);
Victor Stinner331a6a52019-05-27 16:39:22 +02002940 return _PyStatus_ERR("can't set preliminary stderr");
Victor Stinnerab672812019-01-23 15:04:40 +01002941}
2942
2943
2944/* Create sys module without all attributes: _PySys_InitMain() should be called
2945 later to add remaining attributes. */
Victor Stinner331a6a52019-05-27 16:39:22 +02002946PyStatus
Victor Stinner01b1cc12019-11-20 02:27:56 +01002947_PySys_Create(PyThreadState *tstate, PyObject **sysmod_p)
Victor Stinnerab672812019-01-23 15:04:40 +01002948{
Victor Stinner81fe5bd2019-12-06 02:43:30 +01002949 assert(!_PyErr_Occurred(tstate));
2950
Victor Stinnerb45d2592019-06-20 00:05:23 +02002951 PyInterpreterState *interp = tstate->interp;
Victor Stinner838f2642019-06-13 22:41:23 +02002952
Victor Stinnerab672812019-01-23 15:04:40 +01002953 PyObject *modules = PyDict_New();
2954 if (modules == NULL) {
Victor Stinner81fe5bd2019-12-06 02:43:30 +01002955 goto error;
Victor Stinnerab672812019-01-23 15:04:40 +01002956 }
2957 interp->modules = modules;
2958
2959 PyObject *sysmod = _PyModule_CreateInitialized(&sysmodule, PYTHON_API_VERSION);
2960 if (sysmod == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002961 return _PyStatus_ERR("failed to create a module object");
Victor Stinnerab672812019-01-23 15:04:40 +01002962 }
2963
2964 PyObject *sysdict = PyModule_GetDict(sysmod);
2965 if (sysdict == NULL) {
Victor Stinner81fe5bd2019-12-06 02:43:30 +01002966 goto error;
Victor Stinnerab672812019-01-23 15:04:40 +01002967 }
2968 Py_INCREF(sysdict);
2969 interp->sysdict = sysdict;
2970
2971 if (PyDict_SetItemString(sysdict, "modules", interp->modules) < 0) {
Victor Stinner81fe5bd2019-12-06 02:43:30 +01002972 goto error;
Victor Stinnerab672812019-01-23 15:04:40 +01002973 }
2974
Victor Stinner331a6a52019-05-27 16:39:22 +02002975 PyStatus status = _PySys_SetPreliminaryStderr(sysdict);
2976 if (_PyStatus_EXCEPTION(status)) {
2977 return status;
Victor Stinnerab672812019-01-23 15:04:40 +01002978 }
2979
Victor Stinner01b1cc12019-11-20 02:27:56 +01002980 status = _PySys_InitCore(tstate, sysdict);
Victor Stinner331a6a52019-05-27 16:39:22 +02002981 if (_PyStatus_EXCEPTION(status)) {
2982 return status;
Victor Stinnerab672812019-01-23 15:04:40 +01002983 }
2984
Victor Stinner81fe5bd2019-12-06 02:43:30 +01002985 if (_PyImport_FixupBuiltin(sysmod, "sys", interp->modules) < 0) {
2986 goto error;
2987 }
2988
2989 assert(!_PyErr_Occurred(tstate));
Victor Stinnerab672812019-01-23 15:04:40 +01002990
2991 *sysmod_p = sysmod;
Victor Stinner331a6a52019-05-27 16:39:22 +02002992 return _PyStatus_OK();
Victor Stinner81fe5bd2019-12-06 02:43:30 +01002993
2994error:
2995 return _PyStatus_ERR("can't initialize sys module");
Victor Stinnerab672812019-01-23 15:04:40 +01002996}
2997
2998
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002999static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00003000makepathobject(const wchar_t *path, wchar_t delim)
Guido van Rossum5b3138b1990-11-18 17:41:40 +00003001{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003002 int i, n;
3003 const wchar_t *p;
3004 PyObject *v, *w;
Tim Peters216b78b2006-01-06 02:40:53 +00003005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003006 n = 1;
3007 p = path;
3008 while ((p = wcschr(p, delim)) != NULL) {
3009 n++;
3010 p++;
3011 }
3012 v = PyList_New(n);
3013 if (v == NULL)
3014 return NULL;
3015 for (i = 0; ; i++) {
3016 p = wcschr(path, delim);
3017 if (p == NULL)
3018 p = path + wcslen(path); /* End of string */
3019 w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
3020 if (w == NULL) {
3021 Py_DECREF(v);
3022 return NULL;
3023 }
Zackery Spytz99d56b52018-12-08 07:16:55 -07003024 PyList_SET_ITEM(v, i, w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003025 if (*p == '\0')
3026 break;
3027 path = p+1;
3028 }
3029 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003030}
3031
3032void
Martin v. Löwis790465f2008-04-05 20:41:37 +00003033PySys_SetPath(const wchar_t *path)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003034{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003035 PyObject *v;
3036 if ((v = makepathobject(path, DELIM)) == NULL)
3037 Py_FatalError("can't create sys.path");
Victor Stinner838f2642019-06-13 22:41:23 +02003038 PyThreadState *tstate = _PyThreadState_GET();
3039 if (sys_set_object_id(tstate, &PyId_path, v) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003040 Py_FatalError("can't assign sys.path");
Victor Stinner838f2642019-06-13 22:41:23 +02003041 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003042 Py_DECREF(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00003043}
3044
Guido van Rossum65bf9f21997-04-29 18:33:38 +00003045static PyObject *
Victor Stinner74f65682019-03-15 15:08:05 +01003046make_sys_argv(int argc, wchar_t * const * argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00003047{
Victor Stinner74f65682019-03-15 15:08:05 +01003048 PyObject *list = PyList_New(argc);
3049 if (list == NULL) {
3050 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003051 }
Victor Stinner74f65682019-03-15 15:08:05 +01003052
3053 for (Py_ssize_t i = 0; i < argc; i++) {
3054 PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
3055 if (v == NULL) {
3056 Py_DECREF(list);
3057 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003058 }
Victor Stinner74f65682019-03-15 15:08:05 +01003059 PyList_SET_ITEM(list, i, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003060 }
Victor Stinner74f65682019-03-15 15:08:05 +01003061 return list;
Guido van Rossum3f5da241990-12-20 15:06:42 +00003062}
3063
Victor Stinner11a247d2017-12-13 21:05:57 +01003064void
3065PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
Victor Stinnerd5dda982017-12-13 17:31:16 +01003066{
Victor Stinnerc4868252019-08-23 11:04:16 +01003067 wchar_t* empty_argv[1] = {L""};
Victor Stinner838f2642019-06-13 22:41:23 +02003068 PyThreadState *tstate = _PyThreadState_GET();
3069
Victor Stinner74f65682019-03-15 15:08:05 +01003070 if (argc < 1 || argv == NULL) {
3071 /* Ensure at least one (empty) argument is seen */
Victor Stinner74f65682019-03-15 15:08:05 +01003072 argv = empty_argv;
3073 argc = 1;
3074 }
3075
3076 PyObject *av = make_sys_argv(argc, argv);
Victor Stinnerd5dda982017-12-13 17:31:16 +01003077 if (av == NULL) {
Victor Stinner11a247d2017-12-13 21:05:57 +01003078 Py_FatalError("no mem for sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01003079 }
Victor Stinner838f2642019-06-13 22:41:23 +02003080 if (sys_set_object(tstate, "argv", av) != 0) {
Victor Stinnerd5dda982017-12-13 17:31:16 +01003081 Py_DECREF(av);
Victor Stinner11a247d2017-12-13 21:05:57 +01003082 Py_FatalError("can't assign sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01003083 }
3084 Py_DECREF(av);
3085
3086 if (updatepath) {
3087 /* If argv[0] is not '-c' nor '-m', prepend argv[0] to sys.path.
3088 If argv[0] is a symlink, use the real path. */
Victor Stinner331a6a52019-05-27 16:39:22 +02003089 const PyWideStringList argv_list = {.length = argc, .items = argv};
Victor Stinnerdcf61712019-03-19 16:09:27 +01003090 PyObject *path0 = NULL;
3091 if (_PyPathConfig_ComputeSysPath0(&argv_list, &path0)) {
3092 if (path0 == NULL) {
3093 Py_FatalError("can't compute path0 from argv");
Victor Stinner11a247d2017-12-13 21:05:57 +01003094 }
Victor Stinnerdcf61712019-03-19 16:09:27 +01003095
Victor Stinner838f2642019-06-13 22:41:23 +02003096 PyObject *sys_path = sys_get_object_id(tstate, &PyId_path);
Victor Stinnerdcf61712019-03-19 16:09:27 +01003097 if (sys_path != NULL) {
3098 if (PyList_Insert(sys_path, 0, path0) < 0) {
3099 Py_DECREF(path0);
3100 Py_FatalError("can't prepend path0 to sys.path");
3101 }
3102 }
3103 Py_DECREF(path0);
Victor Stinner11a247d2017-12-13 21:05:57 +01003104 }
Victor Stinnerd5dda982017-12-13 17:31:16 +01003105 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003106}
Guido van Rossuma890e681998-05-12 14:59:24 +00003107
Antoine Pitrouf978fac2010-05-21 17:25:34 +00003108void
3109PySys_SetArgv(int argc, wchar_t **argv)
3110{
Christian Heimesad73a9c2013-08-10 16:36:18 +02003111 PySys_SetArgvEx(argc, argv, Py_IsolatedFlag == 0);
Antoine Pitrouf978fac2010-05-21 17:25:34 +00003112}
3113
Victor Stinner14284c22010-04-23 12:02:30 +00003114/* Reimplementation of PyFile_WriteString() no calling indirectly
3115 PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
3116
3117static int
Victor Stinner79766632010-08-16 17:36:42 +00003118sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
Victor Stinner14284c22010-04-23 12:02:30 +00003119{
Victor Stinnerecccc4f2010-06-08 20:46:00 +00003120 if (file == NULL)
3121 return -1;
Jeroen Demeyerb1263d52019-06-28 11:49:00 +02003122 assert(unicode != NULL);
Jeroen Demeyer59ad1102019-07-11 10:59:05 +02003123 PyObject *result = _PyObject_CallMethodIdOneArg(file, &PyId_write, unicode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003124 if (result == NULL) {
Jeroen Demeyerb1263d52019-06-28 11:49:00 +02003125 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003126 }
Jeroen Demeyerb1263d52019-06-28 11:49:00 +02003127 Py_DECREF(result);
3128 return 0;
Victor Stinner14284c22010-04-23 12:02:30 +00003129}
3130
Victor Stinner79766632010-08-16 17:36:42 +00003131static int
3132sys_pyfile_write(const char *text, PyObject *file)
3133{
3134 PyObject *unicode = NULL;
3135 int err;
3136
3137 if (file == NULL)
3138 return -1;
3139
3140 unicode = PyUnicode_FromString(text);
3141 if (unicode == NULL)
3142 return -1;
3143
3144 err = sys_pyfile_write_unicode(unicode, file);
3145 Py_DECREF(unicode);
3146 return err;
3147}
Guido van Rossuma890e681998-05-12 14:59:24 +00003148
3149/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
3150 Adapted from code submitted by Just van Rossum.
3151
3152 PySys_WriteStdout(format, ...)
3153 PySys_WriteStderr(format, ...)
3154
3155 The first function writes to sys.stdout; the second to sys.stderr. When
3156 there is a problem, they write to the real (C level) stdout or stderr;
Guido van Rossum8442af31998-10-12 18:22:10 +00003157 no exceptions are raised.
Guido van Rossuma890e681998-05-12 14:59:24 +00003158
Victor Stinner14284c22010-04-23 12:02:30 +00003159 PyErr_CheckSignals() is not called to avoid the execution of the Python
Victor Stinner79766632010-08-16 17:36:42 +00003160 signal handlers: they may raise a new exception whereas sys_write()
3161 ignores all exceptions.
Victor Stinner14284c22010-04-23 12:02:30 +00003162
Guido van Rossuma890e681998-05-12 14:59:24 +00003163 Both take a printf-style format string as their first argument followed
3164 by a variable length argument list determined by the format string.
3165
3166 *** WARNING ***
3167
3168 The format should limit the total size of the formatted output string to
3169 1000 bytes. In particular, this means that no unrestricted "%s" formats
3170 should occur; these should be limited using "%.<N>s where <N> is a
3171 decimal number calculated so that <N> plus the maximum size of other
3172 formatted text does not exceed 1000 bytes. Also watch out for "%f",
3173 which can print hundreds of digits for very large numbers.
3174
3175 */
3176
3177static void
Victor Stinner09054372013-11-06 22:41:44 +01003178sys_write(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Guido van Rossuma890e681998-05-12 14:59:24 +00003179{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003180 PyObject *file;
3181 PyObject *error_type, *error_value, *error_traceback;
3182 char buffer[1001];
3183 int written;
Victor Stinner838f2642019-06-13 22:41:23 +02003184 PyThreadState *tstate = _PyThreadState_GET();
Guido van Rossuma890e681998-05-12 14:59:24 +00003185
Victor Stinner838f2642019-06-13 22:41:23 +02003186 _PyErr_Fetch(tstate, &error_type, &error_value, &error_traceback);
3187 file = sys_get_object_id(tstate, key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003188 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
3189 if (sys_pyfile_write(buffer, file) != 0) {
Victor Stinner838f2642019-06-13 22:41:23 +02003190 _PyErr_Clear(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003191 fputs(buffer, fp);
3192 }
3193 if (written < 0 || (size_t)written >= sizeof(buffer)) {
3194 const char *truncated = "... truncated";
Victor Stinner79766632010-08-16 17:36:42 +00003195 if (sys_pyfile_write(truncated, file) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003196 fputs(truncated, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003197 }
Victor Stinner838f2642019-06-13 22:41:23 +02003198 _PyErr_Restore(tstate, error_type, error_value, error_traceback);
Guido van Rossuma890e681998-05-12 14:59:24 +00003199}
3200
3201void
Guido van Rossuma890e681998-05-12 14:59:24 +00003202PySys_WriteStdout(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00003203{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003204 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00003205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003206 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003207 sys_write(&PyId_stdout, stdout, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003208 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00003209}
3210
3211void
Guido van Rossuma890e681998-05-12 14:59:24 +00003212PySys_WriteStderr(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00003213{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003214 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00003215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003216 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003217 sys_write(&PyId_stderr, stderr, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00003218 va_end(va);
3219}
3220
3221static void
Victor Stinner09054372013-11-06 22:41:44 +01003222sys_format(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Victor Stinner79766632010-08-16 17:36:42 +00003223{
3224 PyObject *file, *message;
3225 PyObject *error_type, *error_value, *error_traceback;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02003226 const char *utf8;
Victor Stinner838f2642019-06-13 22:41:23 +02003227 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner79766632010-08-16 17:36:42 +00003228
Victor Stinner838f2642019-06-13 22:41:23 +02003229 _PyErr_Fetch(tstate, &error_type, &error_value, &error_traceback);
3230 file = sys_get_object_id(tstate, key);
Victor Stinner79766632010-08-16 17:36:42 +00003231 message = PyUnicode_FromFormatV(format, va);
3232 if (message != NULL) {
3233 if (sys_pyfile_write_unicode(message, file) != 0) {
Victor Stinner838f2642019-06-13 22:41:23 +02003234 _PyErr_Clear(tstate);
Serhiy Storchaka06515832016-11-20 09:13:07 +02003235 utf8 = PyUnicode_AsUTF8(message);
Victor Stinner79766632010-08-16 17:36:42 +00003236 if (utf8 != NULL)
3237 fputs(utf8, fp);
3238 }
3239 Py_DECREF(message);
3240 }
Victor Stinner838f2642019-06-13 22:41:23 +02003241 _PyErr_Restore(tstate, error_type, error_value, error_traceback);
Victor Stinner79766632010-08-16 17:36:42 +00003242}
3243
3244void
3245PySys_FormatStdout(const char *format, ...)
3246{
3247 va_list va;
3248
3249 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003250 sys_format(&PyId_stdout, stdout, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00003251 va_end(va);
3252}
3253
3254void
3255PySys_FormatStderr(const char *format, ...)
3256{
3257 va_list va;
3258
3259 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003260 sys_format(&PyId_stderr, stderr, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003261 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00003262}