blob: c877fd76ace8bf11be75bfc0abc4df66dc4a3ace [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) {
Andy Lestere6be9b52020-02-11 20:28:35 -0600207 PyDTrace_AUDIT(event, (void *)eventArgs);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700208 }
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);
Victor Stinner7b3c2522020-03-07 00:24:23 +0100292 PyThreadState *finalizing = _PyRuntimeState_GetFinalizing(runtime);
293 assert(!ts || finalizing == ts);
294 if (!ts || finalizing != ts) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700295 return;
Victor Stinner838f2642019-06-13 22:41:23 +0200296 }
Steve Dowerb82e17e2019-05-23 08:45:22 -0700297
Victor Stinner838f2642019-06-13 22:41:23 +0200298 const PyConfig *config = &ts->interp->config;
299 if (config->verbose) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700300 PySys_WriteStderr("# clear sys.audit hooks\n");
301 }
302
303 /* Hooks can abort later hooks for this event, but cannot
304 abort the clear operation itself. */
305 PySys_Audit("cpython._PySys_ClearAuditHooks", NULL);
Victor Stinner838f2642019-06-13 22:41:23 +0200306 _PyErr_Clear(ts);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700307
Victor Stinner0fd2c302019-06-04 03:15:09 +0200308 _Py_AuditHookEntry *e = _PyRuntime.audit_hook_head, *n;
309 _PyRuntime.audit_hook_head = NULL;
Steve Dowerb82e17e2019-05-23 08:45:22 -0700310 while (e) {
311 n = e->next;
312 PyMem_RawFree(e);
313 e = n;
314 }
315}
316
317int
318PySys_AddAuditHook(Py_AuditHookFunction hook, void *userData)
319{
Victor Stinner838f2642019-06-13 22:41:23 +0200320 _PyRuntimeState *runtime = &_PyRuntime;
321 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
322
Steve Dowerb82e17e2019-05-23 08:45:22 -0700323 /* Invoke existing audit hooks to allow them an opportunity to abort. */
324 /* Cannot invoke hooks until we are initialized */
Victor Stinner838f2642019-06-13 22:41:23 +0200325 if (runtime->initialized) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700326 if (PySys_Audit("sys.addaudithook", NULL) < 0) {
Steve Dowerbea33f52019-11-28 08:46:11 -0800327 if (_PyErr_ExceptionMatches(tstate, PyExc_RuntimeError)) {
328 /* We do not report errors derived from RuntimeError */
Victor Stinner838f2642019-06-13 22:41:23 +0200329 _PyErr_Clear(tstate);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700330 return 0;
331 }
332 return -1;
333 }
334 }
335
Victor Stinner0fd2c302019-06-04 03:15:09 +0200336 _Py_AuditHookEntry *e = _PyRuntime.audit_hook_head;
Steve Dowerb82e17e2019-05-23 08:45:22 -0700337 if (!e) {
338 e = (_Py_AuditHookEntry*)PyMem_RawMalloc(sizeof(_Py_AuditHookEntry));
Victor Stinner0fd2c302019-06-04 03:15:09 +0200339 _PyRuntime.audit_hook_head = e;
Steve Dowerb82e17e2019-05-23 08:45:22 -0700340 } else {
Victor Stinner838f2642019-06-13 22:41:23 +0200341 while (e->next) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700342 e = e->next;
Victor Stinner838f2642019-06-13 22:41:23 +0200343 }
Steve Dowerb82e17e2019-05-23 08:45:22 -0700344 e = e->next = (_Py_AuditHookEntry*)PyMem_RawMalloc(
345 sizeof(_Py_AuditHookEntry));
346 }
347
348 if (!e) {
Victor Stinner838f2642019-06-13 22:41:23 +0200349 if (runtime->initialized) {
350 _PyErr_NoMemory(tstate);
351 }
Steve Dowerb82e17e2019-05-23 08:45:22 -0700352 return -1;
353 }
354
355 e->next = NULL;
356 e->hookCFunction = (Py_AuditHookFunction)hook;
357 e->userData = userData;
358
359 return 0;
360}
361
362/*[clinic input]
363sys.addaudithook
364
365 hook: object
366
367Adds a new audit hook callback.
368[clinic start generated code]*/
369
370static PyObject *
371sys_addaudithook_impl(PyObject *module, PyObject *hook)
372/*[clinic end generated code: output=4f9c17aaeb02f44e input=0f3e191217a45e34]*/
373{
Victor Stinner838f2642019-06-13 22:41:23 +0200374 PyThreadState *tstate = _PyThreadState_GET();
375
Steve Dowerb82e17e2019-05-23 08:45:22 -0700376 /* Invoke existing audit hooks to allow them an opportunity to abort. */
377 if (PySys_Audit("sys.addaudithook", NULL) < 0) {
Victor Stinner838f2642019-06-13 22:41:23 +0200378 if (_PyErr_ExceptionMatches(tstate, PyExc_Exception)) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700379 /* We do not report errors derived from Exception */
Victor Stinner838f2642019-06-13 22:41:23 +0200380 _PyErr_Clear(tstate);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700381 Py_RETURN_NONE;
382 }
383 return NULL;
384 }
385
Victor Stinner838f2642019-06-13 22:41:23 +0200386 PyInterpreterState *is = tstate->interp;
Steve Dowerb82e17e2019-05-23 08:45:22 -0700387
388 if (is->audit_hooks == NULL) {
389 is->audit_hooks = PyList_New(0);
390 if (is->audit_hooks == NULL) {
391 return NULL;
392 }
393 }
394
395 if (PyList_Append(is->audit_hooks, hook) < 0) {
396 return NULL;
397 }
398
399 Py_RETURN_NONE;
400}
401
402PyDoc_STRVAR(audit_doc,
403"audit(event, *args)\n\
404\n\
405Passes the event to any audit hooks that are attached.");
406
407static PyObject *
408sys_audit(PyObject *self, PyObject *const *args, Py_ssize_t argc)
409{
Victor Stinner838f2642019-06-13 22:41:23 +0200410 PyThreadState *tstate = _PyThreadState_GET();
411
Steve Dowerb82e17e2019-05-23 08:45:22 -0700412 if (argc == 0) {
Victor Stinner838f2642019-06-13 22:41:23 +0200413 _PyErr_SetString(tstate, PyExc_TypeError,
414 "audit() missing 1 required positional argument: "
415 "'event'");
Steve Dowerb82e17e2019-05-23 08:45:22 -0700416 return NULL;
417 }
418
Victor Stinner838f2642019-06-13 22:41:23 +0200419 if (!should_audit(tstate)) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700420 Py_RETURN_NONE;
421 }
422
423 PyObject *auditEvent = args[0];
424 if (!auditEvent) {
Victor Stinner838f2642019-06-13 22:41:23 +0200425 _PyErr_SetString(tstate, PyExc_TypeError,
426 "expected str for argument 'event'");
Steve Dowerb82e17e2019-05-23 08:45:22 -0700427 return NULL;
428 }
429 if (!PyUnicode_Check(auditEvent)) {
Victor Stinner838f2642019-06-13 22:41:23 +0200430 _PyErr_Format(tstate, PyExc_TypeError,
431 "expected str for argument 'event', not %.200s",
432 Py_TYPE(auditEvent)->tp_name);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700433 return NULL;
434 }
435 const char *event = PyUnicode_AsUTF8(auditEvent);
436 if (!event) {
437 return NULL;
438 }
439
440 PyObject *auditArgs = _PyTuple_FromArray(args + 1, argc - 1);
441 if (!auditArgs) {
442 return NULL;
443 }
444
445 int res = PySys_Audit(event, "O", auditArgs);
446 Py_DECREF(auditArgs);
447
448 if (res < 0) {
449 return NULL;
450 }
451
452 Py_RETURN_NONE;
453}
454
455
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400456static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +0200457sys_breakpointhook(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *keywords)
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400458{
Victor Stinner838f2642019-06-13 22:41:23 +0200459 PyThreadState *tstate = _PyThreadState_GET();
460 assert(!_PyErr_Occurred(tstate));
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300461 char *envar = Py_GETENV("PYTHONBREAKPOINT");
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400462
463 if (envar == NULL || strlen(envar) == 0) {
464 envar = "pdb.set_trace";
465 }
466 else if (!strcmp(envar, "0")) {
467 /* The breakpoint is explicitly no-op'd. */
468 Py_RETURN_NONE;
469 }
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300470 /* According to POSIX the string returned by getenv() might be invalidated
471 * or the string content might be overwritten by a subsequent call to
472 * getenv(). Since importing a module can performs the getenv() calls,
473 * we need to save a copy of envar. */
474 envar = _PyMem_RawStrdup(envar);
475 if (envar == NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +0200476 _PyErr_NoMemory(tstate);
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300477 return NULL;
478 }
Serhiy Storchaka4ae06c52017-12-12 13:55:04 +0200479 const char *last_dot = strrchr(envar, '.');
480 const char *attrname = NULL;
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400481 PyObject *modulepath = NULL;
482
483 if (last_dot == NULL) {
484 /* The breakpoint is a built-in, e.g. PYTHONBREAKPOINT=int */
485 modulepath = PyUnicode_FromString("builtins");
486 attrname = envar;
487 }
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200488 else if (last_dot != envar) {
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400489 /* Split on the last dot; */
490 modulepath = PyUnicode_FromStringAndSize(envar, last_dot - envar);
491 attrname = last_dot + 1;
492 }
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200493 else {
494 goto warn;
495 }
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400496 if (modulepath == NULL) {
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300497 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400498 return NULL;
499 }
500
Anthony Sottiledce345c2018-11-01 10:25:05 -0700501 PyObject *module = PyImport_Import(modulepath);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400502 Py_DECREF(modulepath);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400503
504 if (module == NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +0200505 if (_PyErr_ExceptionMatches(tstate, PyExc_ImportError)) {
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200506 goto warn;
507 }
508 PyMem_RawFree(envar);
509 return NULL;
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400510 }
511
512 PyObject *hook = PyObject_GetAttrString(module, attrname);
513 Py_DECREF(module);
514
515 if (hook == NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +0200516 if (_PyErr_ExceptionMatches(tstate, PyExc_AttributeError)) {
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200517 goto warn;
518 }
519 PyMem_RawFree(envar);
520 return NULL;
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400521 }
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300522 PyMem_RawFree(envar);
Petr Viktorinffd97532020-02-11 17:46:57 +0100523 PyObject *retval = PyObject_Vectorcall(hook, args, nargs, keywords);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400524 Py_DECREF(hook);
525 return retval;
526
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200527 warn:
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400528 /* If any of the imports went wrong, then warn and ignore. */
Victor Stinner838f2642019-06-13 22:41:23 +0200529 _PyErr_Clear(tstate);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400530 int status = PyErr_WarnFormat(
531 PyExc_RuntimeWarning, 0,
532 "Ignoring unimportable $PYTHONBREAKPOINT: \"%s\"", envar);
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300533 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400534 if (status < 0) {
535 /* Printing the warning raised an exception. */
536 return NULL;
537 }
538 /* The warning was (probably) issued. */
539 Py_RETURN_NONE;
540}
541
542PyDoc_STRVAR(breakpointhook_doc,
543"breakpointhook(*args, **kws)\n"
544"\n"
545"This hook function is called by built-in breakpoint().\n"
546);
547
Victor Stinner13d49ee2010-12-04 17:24:33 +0000548/* Write repr(o) to sys.stdout using sys.stdout.encoding and 'backslashreplace'
549 error handler. If sys.stdout has a buffer attribute, use
550 sys.stdout.buffer.write(encoded), otherwise redecode the string and use
551 sys.stdout.write(redecoded).
552
553 Helper function for sys_displayhook(). */
554static int
Andy Lesterda4d6562020-03-05 22:34:36 -0600555sys_displayhook_unencodable(PyObject *outf, PyObject *o)
Victor Stinner13d49ee2010-12-04 17:24:33 +0000556{
557 PyObject *stdout_encoding = NULL;
558 PyObject *encoded, *escaped_str, *repr_str, *buffer, *result;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200559 const char *stdout_encoding_str;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000560 int ret;
561
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200562 stdout_encoding = _PyObject_GetAttrId(outf, &PyId_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000563 if (stdout_encoding == NULL)
564 goto error;
Serhiy Storchaka06515832016-11-20 09:13:07 +0200565 stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000566 if (stdout_encoding_str == NULL)
567 goto error;
568
569 repr_str = PyObject_Repr(o);
570 if (repr_str == NULL)
571 goto error;
572 encoded = PyUnicode_AsEncodedString(repr_str,
573 stdout_encoding_str,
574 "backslashreplace");
575 Py_DECREF(repr_str);
576 if (encoded == NULL)
577 goto error;
578
Serhiy Storchaka41c57b32019-09-01 12:03:39 +0300579 if (_PyObject_LookupAttrId(outf, &PyId_buffer, &buffer) < 0) {
580 Py_DECREF(encoded);
581 goto error;
582 }
Victor Stinner13d49ee2010-12-04 17:24:33 +0000583 if (buffer) {
Jeroen Demeyer59ad1102019-07-11 10:59:05 +0200584 result = _PyObject_CallMethodIdOneArg(buffer, &PyId_write, encoded);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000585 Py_DECREF(buffer);
586 Py_DECREF(encoded);
587 if (result == NULL)
588 goto error;
589 Py_DECREF(result);
590 }
591 else {
Victor Stinner13d49ee2010-12-04 17:24:33 +0000592 escaped_str = PyUnicode_FromEncodedObject(encoded,
593 stdout_encoding_str,
594 "strict");
595 Py_DECREF(encoded);
596 if (PyFile_WriteObject(escaped_str, outf, Py_PRINT_RAW) != 0) {
597 Py_DECREF(escaped_str);
598 goto error;
599 }
600 Py_DECREF(escaped_str);
601 }
602 ret = 0;
603 goto finally;
604
605error:
606 ret = -1;
607finally:
608 Py_XDECREF(stdout_encoding);
609 return ret;
610}
611
Tal Einatede0b6f2018-12-31 17:12:08 +0200612/*[clinic input]
613sys.displayhook
614
615 object as o: object
616 /
617
618Print an object to sys.stdout and also save it in builtins._
619[clinic start generated code]*/
620
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000621static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200622sys_displayhook(PyObject *module, PyObject *o)
623/*[clinic end generated code: output=347477d006df92ed input=08ba730166d7ef72]*/
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000624{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 PyObject *outf;
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100626 PyObject *builtins;
627 static PyObject *newline = NULL;
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)) {
Andy Lesterda4d6562020-03-05 22:34:36 -0600655 int err;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000656 /* repr(o) is not encodable to sys.stdout.encoding with
657 * sys.stdout.errors error handler (which is probably 'strict') */
Victor Stinner838f2642019-06-13 22:41:23 +0200658 _PyErr_Clear(tstate);
Andy Lesterda4d6562020-03-05 22:34:36 -0600659 err = sys_displayhook_unencodable(outf, o);
Victor Stinner838f2642019-06-13 22:41:23 +0200660 if (err) {
Victor Stinner13d49ee2010-12-04 17:24:33 +0000661 return NULL;
Victor Stinner838f2642019-06-13 22:41:23 +0200662 }
Victor Stinner13d49ee2010-12-04 17:24:33 +0000663 }
664 else {
665 return NULL;
666 }
667 }
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100668 if (newline == NULL) {
669 newline = PyUnicode_FromString("\n");
670 if (newline == NULL)
671 return NULL;
672 }
673 if (PyFile_WriteObject(newline, outf, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 return NULL;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200675 if (_PyObject_SetAttrId(builtins, &PyId__, o) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200677 Py_RETURN_NONE;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000678}
679
Tal Einatede0b6f2018-12-31 17:12:08 +0200680
681/*[clinic input]
682sys.excepthook
683
684 exctype: object
685 value: object
686 traceback: object
687 /
688
689Handle an exception by displaying it with a traceback on sys.stderr.
690[clinic start generated code]*/
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000691
692static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200693sys_excepthook_impl(PyObject *module, PyObject *exctype, PyObject *value,
694 PyObject *traceback)
695/*[clinic end generated code: output=18d99fdda21b6b5e input=ecf606fa826f19d9]*/
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000696{
Tal Einatede0b6f2018-12-31 17:12:08 +0200697 PyErr_Display(exctype, value, traceback);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200698 Py_RETURN_NONE;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000699}
700
Tal Einatede0b6f2018-12-31 17:12:08 +0200701
702/*[clinic input]
703sys.exc_info
704
705Return current exception information: (type, value, traceback).
706
707Return information about the most recent exception caught by an except
708clause in the current stack frame or in an older stack frame.
709[clinic start generated code]*/
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000710
711static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200712sys_exc_info_impl(PyObject *module)
713/*[clinic end generated code: output=3afd0940cf3a4d30 input=b5c5bf077788a3e5]*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000714{
Victor Stinner50b48572018-11-01 01:51:40 +0100715 _PyErr_StackItem *err_info = _PyErr_GetTopmostException(_PyThreadState_GET());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000716 return Py_BuildValue(
717 "(OOO)",
Mark Shannonae3087c2017-10-22 22:41:51 +0100718 err_info->exc_type != NULL ? err_info->exc_type : Py_None,
719 err_info->exc_value != NULL ? err_info->exc_value : Py_None,
720 err_info->exc_traceback != NULL ?
721 err_info->exc_traceback : Py_None);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000722}
723
Tal Einatede0b6f2018-12-31 17:12:08 +0200724
725/*[clinic input]
Victor Stinneref9d9b62019-05-22 11:28:22 +0200726sys.unraisablehook
727
728 unraisable: object
729 /
730
731Handle an unraisable exception.
732
733The unraisable argument has the following attributes:
734
735* exc_type: Exception type.
Victor Stinner71c52e32019-05-27 08:57:14 +0200736* exc_value: Exception value, can be None.
737* exc_traceback: Exception traceback, can be None.
738* err_msg: Error message, can be None.
739* object: Object causing the exception, can be None.
Victor Stinneref9d9b62019-05-22 11:28:22 +0200740[clinic start generated code]*/
741
742static PyObject *
743sys_unraisablehook(PyObject *module, PyObject *unraisable)
Victor Stinner71c52e32019-05-27 08:57:14 +0200744/*[clinic end generated code: output=bb92838b32abaa14 input=ec3af148294af8d3]*/
Victor Stinneref9d9b62019-05-22 11:28:22 +0200745{
746 return _PyErr_WriteUnraisableDefaultHook(unraisable);
747}
748
749
750/*[clinic input]
Tal Einatede0b6f2018-12-31 17:12:08 +0200751sys.exit
752
Serhiy Storchaka279f4462019-09-14 12:24:05 +0300753 status: object = None
Tal Einatede0b6f2018-12-31 17:12:08 +0200754 /
755
756Exit the interpreter by raising SystemExit(status).
757
758If the status is omitted or None, it defaults to zero (i.e., success).
759If the status is an integer, it will be used as the system exit status.
760If it is another kind of object, it will be printed and the system
761exit status will be one (i.e., failure).
762[clinic start generated code]*/
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000763
764static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200765sys_exit_impl(PyObject *module, PyObject *status)
Serhiy Storchaka279f4462019-09-14 12:24:05 +0300766/*[clinic end generated code: output=13870986c1ab2ec0 input=b86ca9497baa94f2]*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000767{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 /* Raise SystemExit so callers may catch it or clean up. */
Victor Stinner838f2642019-06-13 22:41:23 +0200769 PyThreadState *tstate = _PyThreadState_GET();
770 _PyErr_SetObject(tstate, PyExc_SystemExit, status);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000771 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000772}
773
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000774
Martin v. Löwis107b7da2001-11-09 20:59:39 +0000775
Tal Einatede0b6f2018-12-31 17:12:08 +0200776/*[clinic input]
777sys.getdefaultencoding
778
779Return the current default encoding used by the Unicode implementation.
780[clinic start generated code]*/
781
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000782static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200783sys_getdefaultencoding_impl(PyObject *module)
784/*[clinic end generated code: output=256d19dfcc0711e6 input=d416856ddbef6909]*/
Fred Drake8b4d01d2000-05-09 19:57:01 +0000785{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 return PyUnicode_FromString(PyUnicode_GetDefaultEncoding());
Fred Drake8b4d01d2000-05-09 19:57:01 +0000787}
788
Tal Einatede0b6f2018-12-31 17:12:08 +0200789/*[clinic input]
790sys.getfilesystemencoding
791
792Return the encoding used to convert Unicode filenames to OS filenames.
793[clinic start generated code]*/
Fred Drake8b4d01d2000-05-09 19:57:01 +0000794
795static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200796sys_getfilesystemencoding_impl(PyObject *module)
797/*[clinic end generated code: output=1dc4bdbe9be44aa7 input=8475f8649b8c7d8c]*/
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000798{
Victor Stinner838f2642019-06-13 22:41:23 +0200799 PyThreadState *tstate = _PyThreadState_GET();
800 const PyConfig *config = &tstate->interp->config;
Victor Stinner709d23d2019-05-02 14:56:30 -0400801 return PyUnicode_FromWideChar(config->filesystem_encoding, -1);
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000802}
803
Tal Einatede0b6f2018-12-31 17:12:08 +0200804/*[clinic input]
805sys.getfilesystemencodeerrors
806
807Return the error mode used Unicode to OS filename conversion.
808[clinic start generated code]*/
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000809
Martin v. Löwis04dc25c2008-10-03 16:09:28 +0000810static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200811sys_getfilesystemencodeerrors_impl(PyObject *module)
812/*[clinic end generated code: output=ba77b36bbf7c96f5 input=22a1e8365566f1e5]*/
Steve Dowercc16be82016-09-08 10:35:16 -0700813{
Victor Stinner838f2642019-06-13 22:41:23 +0200814 PyThreadState *tstate = _PyThreadState_GET();
815 const PyConfig *config = &tstate->interp->config;
Victor Stinner709d23d2019-05-02 14:56:30 -0400816 return PyUnicode_FromWideChar(config->filesystem_errors, -1);
Steve Dowercc16be82016-09-08 10:35:16 -0700817}
818
Tal Einatede0b6f2018-12-31 17:12:08 +0200819/*[clinic input]
820sys.intern
821
822 string as s: unicode
823 /
824
825``Intern'' the given string.
826
827This enters the string in the (global) table of interned strings whose
828purpose is to speed up dictionary lookups. Return the string itself or
829the previously interned string object with the same value.
830[clinic start generated code]*/
Steve Dowercc16be82016-09-08 10:35:16 -0700831
832static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200833sys_intern_impl(PyObject *module, PyObject *s)
834/*[clinic end generated code: output=be680c24f5c9e5d6 input=849483c006924e2f]*/
Georg Brandl66a796e2006-12-19 20:50:34 +0000835{
Victor Stinner838f2642019-06-13 22:41:23 +0200836 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837 if (PyUnicode_CheckExact(s)) {
838 Py_INCREF(s);
839 PyUnicode_InternInPlace(&s);
840 return s;
841 }
842 else {
Victor Stinner838f2642019-06-13 22:41:23 +0200843 _PyErr_Format(tstate, PyExc_TypeError,
Victor Stinnera102ed72020-02-07 02:24:48 +0100844 "can't intern %.400s", Py_TYPE(s)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 return NULL;
846 }
Georg Brandl66a796e2006-12-19 20:50:34 +0000847}
848
Georg Brandl66a796e2006-12-19 20:50:34 +0000849
Fred Drake5755ce62001-06-27 19:19:46 +0000850/*
851 * Cached interned string objects used for calling the profile and
852 * trace functions. Initialized by trace_init().
853 */
Nick Coghlan5a851672017-09-08 10:14:16 +1000854static PyObject *whatstrings[8] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
Fred Drake5755ce62001-06-27 19:19:46 +0000855
856static int
857trace_init(void)
858{
Nick Coghlan5a851672017-09-08 10:14:16 +1000859 static const char * const whatnames[8] = {
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200860 "call", "exception", "line", "return",
Nick Coghlan5a851672017-09-08 10:14:16 +1000861 "c_call", "c_exception", "c_return",
862 "opcode"
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200863 };
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 PyObject *name;
865 int i;
Nick Coghlan5a851672017-09-08 10:14:16 +1000866 for (i = 0; i < 8; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 if (whatstrings[i] == NULL) {
868 name = PyUnicode_InternFromString(whatnames[i]);
869 if (name == NULL)
870 return -1;
871 whatstrings[i] = name;
872 }
873 }
874 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000875}
876
877
878static PyObject *
Victor Stinner309d7cc2020-03-13 16:39:12 +0100879call_trampoline(PyThreadState *tstate, PyObject* callback,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 PyFrameObject *frame, int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000881{
Victor Stinner78da82b2016-08-20 01:22:57 +0200882 if (PyFrame_FastToLocalsWithError(frame) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 return NULL;
Victor Stinner78da82b2016-08-20 01:22:57 +0200884 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100885
Victor Stinner838f2642019-06-13 22:41:23 +0200886 PyObject *stack[3];
Victor Stinner78da82b2016-08-20 01:22:57 +0200887 stack[0] = (PyObject *)frame;
888 stack[1] = whatstrings[what];
889 stack[2] = (arg != NULL) ? arg : Py_None;
Fred Drake5755ce62001-06-27 19:19:46 +0000890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 /* call the Python-level function */
Victor Stinner309d7cc2020-03-13 16:39:12 +0100892 PyObject *result = _PyObject_FastCallTstate(tstate, callback, stack, 3);
Fred Drake5755ce62001-06-27 19:19:46 +0000893
Victor Stinner78da82b2016-08-20 01:22:57 +0200894 PyFrame_LocalsToFast(frame, 1);
895 if (result == NULL) {
896 PyTraceBack_Here(frame);
897 }
898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 return result;
Fred Drake5755ce62001-06-27 19:19:46 +0000900}
901
902static int
903profile_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000905{
Victor Stinner309d7cc2020-03-13 16:39:12 +0100906 if (arg == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 arg = Py_None;
Victor Stinner309d7cc2020-03-13 16:39:12 +0100908 }
909
910 PyThreadState *tstate = _PyThreadState_GET();
911 PyObject *result = call_trampoline(tstate, self, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 if (result == NULL) {
Victor Stinner309d7cc2020-03-13 16:39:12 +0100913 _PyEval_SetProfile(tstate, NULL, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 return -1;
915 }
Victor Stinner309d7cc2020-03-13 16:39:12 +0100916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 Py_DECREF(result);
918 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000919}
920
921static int
922trace_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000924{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 PyObject *callback;
Victor Stinner309d7cc2020-03-13 16:39:12 +0100926 if (what == PyTrace_CALL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 callback = self;
Victor Stinner309d7cc2020-03-13 16:39:12 +0100928 }
929 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000930 callback = frame->f_trace;
Victor Stinner309d7cc2020-03-13 16:39:12 +0100931 }
932 if (callback == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 return 0;
Victor Stinner309d7cc2020-03-13 16:39:12 +0100934 }
935
936 PyThreadState *tstate = _PyThreadState_GET();
937 PyObject *result = call_trampoline(tstate, callback, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 if (result == NULL) {
Victor Stinner309d7cc2020-03-13 16:39:12 +0100939 _PyEval_SetTrace(tstate, NULL, NULL);
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200940 Py_CLEAR(frame->f_trace);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 return -1;
942 }
Victor Stinner309d7cc2020-03-13 16:39:12 +0100943
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 if (result != Py_None) {
Serhiy Storchakaec397562016-04-06 09:50:03 +0300945 Py_XSETREF(frame->f_trace, result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 }
947 else {
948 Py_DECREF(result);
949 }
950 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000951}
Fred Draked0838392001-06-16 21:02:31 +0000952
Fred Drake8b4d01d2000-05-09 19:57:01 +0000953static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000954sys_settrace(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000955{
Victor Stinner309d7cc2020-03-13 16:39:12 +0100956 if (trace_init() == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 return NULL;
Victor Stinner309d7cc2020-03-13 16:39:12 +0100958 }
959
960 PyThreadState *tstate = _PyThreadState_GET();
961 if (args == Py_None) {
962 if (_PyEval_SetTrace(tstate, NULL, NULL) < 0) {
963 return NULL;
964 }
965 }
966 else {
967 if (_PyEval_SetTrace(tstate, trace_trampoline, args) < 0) {
968 return NULL;
969 }
970 }
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200971 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000972}
973
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000974PyDoc_STRVAR(settrace_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000975"settrace(function)\n\
976\n\
977Set the global debug tracing function. It will be called on each\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000978function call. See the debugger chapter in the library manual."
979);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000980
Tal Einatede0b6f2018-12-31 17:12:08 +0200981/*[clinic input]
982sys.gettrace
983
984Return the global debug tracing function set with sys.settrace.
985
986See the debugger chapter in the library manual.
987[clinic start generated code]*/
988
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000989static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200990sys_gettrace_impl(PyObject *module)
991/*[clinic end generated code: output=e97e3a4d8c971b6e input=373b51bb2147f4d8]*/
Christian Heimes9bd667a2008-01-20 15:14:11 +0000992{
Victor Stinner50b48572018-11-01 01:51:40 +0100993 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 PyObject *temp = tstate->c_traceobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 if (temp == NULL)
997 temp = Py_None;
998 Py_INCREF(temp);
999 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +00001000}
1001
Christian Heimes9bd667a2008-01-20 15:14:11 +00001002static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001003sys_setprofile(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +00001004{
Victor Stinner309d7cc2020-03-13 16:39:12 +01001005 if (trace_init() == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 return NULL;
Victor Stinner309d7cc2020-03-13 16:39:12 +01001007 }
1008
1009 PyThreadState *tstate = _PyThreadState_GET();
1010 if (args == Py_None) {
1011 if (_PyEval_SetProfile(tstate, NULL, NULL) < 0) {
1012 return NULL;
1013 }
1014 }
1015 else {
1016 if (_PyEval_SetProfile(tstate, profile_trampoline, args) < 0) {
1017 return NULL;
1018 }
1019 }
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001020 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +00001021}
1022
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001023PyDoc_STRVAR(setprofile_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001024"setprofile(function)\n\
1025\n\
1026Set the profiling function. It will be called on each function call\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001027and return. See the profiler chapter in the library manual."
1028);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001029
Tal Einatede0b6f2018-12-31 17:12:08 +02001030/*[clinic input]
1031sys.getprofile
1032
1033Return the profiling function set with sys.setprofile.
1034
1035See the profiler chapter in the library manual.
1036[clinic start generated code]*/
1037
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001038static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001039sys_getprofile_impl(PyObject *module)
1040/*[clinic end generated code: output=579b96b373448188 input=1b3209d89a32965d]*/
Christian Heimes9bd667a2008-01-20 15:14:11 +00001041{
Victor Stinner50b48572018-11-01 01:51:40 +01001042 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 PyObject *temp = tstate->c_profileobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +00001044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 if (temp == NULL)
1046 temp = Py_None;
1047 Py_INCREF(temp);
1048 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +00001049}
1050
Tim Peterse5e065b2003-07-06 18:36:54 +00001051
Tal Einatede0b6f2018-12-31 17:12:08 +02001052/*[clinic input]
1053sys.setswitchinterval
1054
1055 interval: double
1056 /
1057
1058Set the ideal thread switching delay inside the Python interpreter.
1059
1060The actual frequency of switching threads can be lower if the
1061interpreter executes long sequences of uninterruptible code
1062(this is implementation-specific and workload-dependent).
1063
1064The parameter must represent the desired switching delay in seconds
1065A typical value is 0.005 (5 milliseconds).
1066[clinic start generated code]*/
Tim Peterse5e065b2003-07-06 18:36:54 +00001067
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001068static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001069sys_setswitchinterval_impl(PyObject *module, double interval)
1070/*[clinic end generated code: output=65a19629e5153983 input=561b477134df91d9]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001071{
Victor Stinner838f2642019-06-13 22:41:23 +02001072 PyThreadState *tstate = _PyThreadState_GET();
Tal Einatede0b6f2018-12-31 17:12:08 +02001073 if (interval <= 0.0) {
Victor Stinner838f2642019-06-13 22:41:23 +02001074 _PyErr_SetString(tstate, PyExc_ValueError,
1075 "switch interval must be strictly positive");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 return NULL;
1077 }
Tal Einatede0b6f2018-12-31 17:12:08 +02001078 _PyEval_SetSwitchInterval((unsigned long) (1e6 * interval));
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001079 Py_RETURN_NONE;
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001080}
1081
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001082
Tal Einatede0b6f2018-12-31 17:12:08 +02001083/*[clinic input]
1084sys.getswitchinterval -> double
1085
1086Return the current thread switch interval; see sys.setswitchinterval().
1087[clinic start generated code]*/
1088
1089static double
1090sys_getswitchinterval_impl(PyObject *module)
1091/*[clinic end generated code: output=a38c277c85b5096d input=bdf9d39c0ebbbb6f]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001092{
Tal Einatede0b6f2018-12-31 17:12:08 +02001093 return 1e-6 * _PyEval_GetSwitchInterval();
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001094}
1095
Tal Einatede0b6f2018-12-31 17:12:08 +02001096/*[clinic input]
1097sys.setrecursionlimit
1098
1099 limit as new_limit: int
1100 /
1101
1102Set the maximum depth of the Python interpreter stack to n.
1103
1104This limit prevents infinite recursion from causing an overflow of the C
1105stack and crashing Python. The highest possible limit is platform-
1106dependent.
1107[clinic start generated code]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001108
Tim Peterse5e065b2003-07-06 18:36:54 +00001109static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001110sys_setrecursionlimit_impl(PyObject *module, int new_limit)
1111/*[clinic end generated code: output=35e1c64754800ace input=b0f7a23393924af3]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001112{
Tal Einatede0b6f2018-12-31 17:12:08 +02001113 int mark;
Victor Stinner838f2642019-06-13 22:41:23 +02001114 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner50856d52015-10-13 00:11:21 +02001115
Victor Stinner50856d52015-10-13 00:11:21 +02001116 if (new_limit < 1) {
Victor Stinner838f2642019-06-13 22:41:23 +02001117 _PyErr_SetString(tstate, PyExc_ValueError,
1118 "recursion limit must be greater or equal than 1");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 return NULL;
1120 }
Victor Stinner50856d52015-10-13 00:11:21 +02001121
1122 /* Issue #25274: When the recursion depth hits the recursion limit in
1123 _Py_CheckRecursiveCall(), the overflowed flag of the thread state is
1124 set to 1 and a RecursionError is raised. The overflowed flag is reset
1125 to 0 when the recursion depth goes below the low-water mark: see
1126 Py_LeaveRecursiveCall().
1127
1128 Reject too low new limit if the current recursion depth is higher than
1129 the new low-water mark. Otherwise it may not be possible anymore to
1130 reset the overflowed flag to 0. */
1131 mark = _Py_RecursionLimitLowerWaterMark(new_limit);
Victor Stinner50856d52015-10-13 00:11:21 +02001132 if (tstate->recursion_depth >= mark) {
Victor Stinner838f2642019-06-13 22:41:23 +02001133 _PyErr_Format(tstate, PyExc_RecursionError,
1134 "cannot set the recursion limit to %i at "
1135 "the recursion depth %i: the limit is too low",
1136 new_limit, tstate->recursion_depth);
Victor Stinner50856d52015-10-13 00:11:21 +02001137 return NULL;
1138 }
1139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001140 Py_SetRecursionLimit(new_limit);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001141 Py_RETURN_NONE;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001142}
1143
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001144/*[clinic input]
1145sys.set_coroutine_origin_tracking_depth
1146
1147 depth: int
1148
1149Enable or disable origin tracking for coroutine objects in this thread.
1150
Tal Einatede0b6f2018-12-31 17:12:08 +02001151Coroutine objects will track 'depth' frames of traceback information
1152about where they came from, available in their cr_origin attribute.
1153
1154Set a depth of 0 to disable.
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001155[clinic start generated code]*/
1156
1157static PyObject *
1158sys_set_coroutine_origin_tracking_depth_impl(PyObject *module, int depth)
Tal Einatede0b6f2018-12-31 17:12:08 +02001159/*[clinic end generated code: output=0a2123c1cc6759c5 input=a1d0a05f89d2c426]*/
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001160{
Victor Stinner838f2642019-06-13 22:41:23 +02001161 PyThreadState *tstate = _PyThreadState_GET();
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001162 if (depth < 0) {
Victor Stinner838f2642019-06-13 22:41:23 +02001163 _PyErr_SetString(tstate, PyExc_ValueError, "depth must be >= 0");
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001164 return NULL;
1165 }
Victor Stinner838f2642019-06-13 22:41:23 +02001166 _PyEval_SetCoroutineOriginTrackingDepth(tstate, depth);
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001167 Py_RETURN_NONE;
1168}
1169
1170/*[clinic input]
1171sys.get_coroutine_origin_tracking_depth -> int
1172
1173Check status of origin tracking for coroutine objects in this thread.
1174[clinic start generated code]*/
1175
1176static int
1177sys_get_coroutine_origin_tracking_depth_impl(PyObject *module)
1178/*[clinic end generated code: output=3699f7be95a3afb8 input=335266a71205b61a]*/
1179{
1180 return _PyEval_GetCoroutineOriginTrackingDepth();
1181}
1182
Yury Selivanoveb636452016-09-08 22:01:51 -07001183static PyTypeObject AsyncGenHooksType;
1184
1185PyDoc_STRVAR(asyncgen_hooks_doc,
1186"asyncgen_hooks\n\
1187\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07001188A named tuple providing information about asynchronous\n\
Yury Selivanoveb636452016-09-08 22:01:51 -07001189generators hooks. The attributes are read only.");
1190
1191static PyStructSequence_Field asyncgen_hooks_fields[] = {
1192 {"firstiter", "Hook to intercept first iteration"},
1193 {"finalizer", "Hook to intercept finalization"},
1194 {0}
1195};
1196
1197static PyStructSequence_Desc asyncgen_hooks_desc = {
1198 "asyncgen_hooks", /* name */
1199 asyncgen_hooks_doc, /* doc */
1200 asyncgen_hooks_fields , /* fields */
1201 2
1202};
1203
Yury Selivanoveb636452016-09-08 22:01:51 -07001204static PyObject *
1205sys_set_asyncgen_hooks(PyObject *self, PyObject *args, PyObject *kw)
1206{
1207 static char *keywords[] = {"firstiter", "finalizer", NULL};
1208 PyObject *firstiter = NULL;
1209 PyObject *finalizer = NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02001210 PyThreadState *tstate = _PyThreadState_GET();
Yury Selivanoveb636452016-09-08 22:01:51 -07001211
1212 if (!PyArg_ParseTupleAndKeywords(
1213 args, kw, "|OO", keywords,
1214 &firstiter, &finalizer)) {
1215 return NULL;
1216 }
1217
1218 if (finalizer && finalizer != Py_None) {
1219 if (!PyCallable_Check(finalizer)) {
Victor Stinner838f2642019-06-13 22:41:23 +02001220 _PyErr_Format(tstate, PyExc_TypeError,
1221 "callable finalizer expected, got %.50s",
1222 Py_TYPE(finalizer)->tp_name);
Yury Selivanoveb636452016-09-08 22:01:51 -07001223 return NULL;
1224 }
Zackery Spytz79ceccd2020-03-26 06:11:13 -06001225 if (_PyEval_SetAsyncGenFinalizer(finalizer) < 0) {
1226 return NULL;
1227 }
Yury Selivanoveb636452016-09-08 22:01:51 -07001228 }
Zackery Spytz79ceccd2020-03-26 06:11:13 -06001229 else if (finalizer == Py_None && _PyEval_SetAsyncGenFinalizer(NULL) < 0) {
1230 return NULL;
Yury Selivanoveb636452016-09-08 22:01:51 -07001231 }
1232
1233 if (firstiter && firstiter != Py_None) {
1234 if (!PyCallable_Check(firstiter)) {
Victor Stinner838f2642019-06-13 22:41:23 +02001235 _PyErr_Format(tstate, PyExc_TypeError,
1236 "callable firstiter expected, got %.50s",
1237 Py_TYPE(firstiter)->tp_name);
Yury Selivanoveb636452016-09-08 22:01:51 -07001238 return NULL;
1239 }
Zackery Spytz79ceccd2020-03-26 06:11:13 -06001240 if (_PyEval_SetAsyncGenFirstiter(firstiter) < 0) {
1241 return NULL;
1242 }
Yury Selivanoveb636452016-09-08 22:01:51 -07001243 }
Zackery Spytz79ceccd2020-03-26 06:11:13 -06001244 else if (firstiter == Py_None && _PyEval_SetAsyncGenFirstiter(NULL) < 0) {
1245 return NULL;
Yury Selivanoveb636452016-09-08 22:01:51 -07001246 }
1247
1248 Py_RETURN_NONE;
1249}
1250
1251PyDoc_STRVAR(set_asyncgen_hooks_doc,
Tal Einatede0b6f2018-12-31 17:12:08 +02001252"set_asyncgen_hooks(* [, firstiter] [, finalizer])\n\
Yury Selivanoveb636452016-09-08 22:01:51 -07001253\n\
1254Set a finalizer for async generators objects."
1255);
1256
Tal Einatede0b6f2018-12-31 17:12:08 +02001257/*[clinic input]
1258sys.get_asyncgen_hooks
1259
1260Return the installed asynchronous generators hooks.
1261
1262This returns a namedtuple of the form (firstiter, finalizer).
1263[clinic start generated code]*/
1264
Yury Selivanoveb636452016-09-08 22:01:51 -07001265static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001266sys_get_asyncgen_hooks_impl(PyObject *module)
1267/*[clinic end generated code: output=53a253707146f6cf input=3676b9ea62b14625]*/
Yury Selivanoveb636452016-09-08 22:01:51 -07001268{
1269 PyObject *res;
1270 PyObject *firstiter = _PyEval_GetAsyncGenFirstiter();
1271 PyObject *finalizer = _PyEval_GetAsyncGenFinalizer();
1272
1273 res = PyStructSequence_New(&AsyncGenHooksType);
1274 if (res == NULL) {
1275 return NULL;
1276 }
1277
1278 if (firstiter == NULL) {
1279 firstiter = Py_None;
1280 }
1281
1282 if (finalizer == NULL) {
1283 finalizer = Py_None;
1284 }
1285
1286 Py_INCREF(firstiter);
1287 PyStructSequence_SET_ITEM(res, 0, firstiter);
1288
1289 Py_INCREF(finalizer);
1290 PyStructSequence_SET_ITEM(res, 1, finalizer);
1291
1292 return res;
1293}
1294
Yury Selivanoveb636452016-09-08 22:01:51 -07001295
Mark Dickinsondc787d22010-05-23 13:33:13 +00001296static PyTypeObject Hash_InfoType;
1297
1298PyDoc_STRVAR(hash_info_doc,
1299"hash_info\n\
1300\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07001301A named tuple providing parameters used for computing\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +01001302hashes. The attributes are read only.");
Mark Dickinsondc787d22010-05-23 13:33:13 +00001303
1304static PyStructSequence_Field hash_info_fields[] = {
1305 {"width", "width of the type used for hashing, in bits"},
1306 {"modulus", "prime number giving the modulus on which the hash "
1307 "function is based"},
1308 {"inf", "value to be used for hash of a positive infinity"},
1309 {"nan", "value to be used for hash of a nan"},
1310 {"imag", "multiplier used for the imaginary part of a complex number"},
Christian Heimes985ecdc2013-11-20 11:46:18 +01001311 {"algorithm", "name of the algorithm for hashing of str, bytes and "
1312 "memoryviews"},
1313 {"hash_bits", "internal output size of hash algorithm"},
1314 {"seed_bits", "seed size of hash algorithm"},
1315 {"cutoff", "small string optimization cutoff"},
Mark Dickinsondc787d22010-05-23 13:33:13 +00001316 {NULL, NULL}
1317};
1318
1319static PyStructSequence_Desc hash_info_desc = {
1320 "sys.hash_info",
1321 hash_info_doc,
1322 hash_info_fields,
Christian Heimes985ecdc2013-11-20 11:46:18 +01001323 9,
Mark Dickinsondc787d22010-05-23 13:33:13 +00001324};
1325
Matthias Klosed885e952010-07-06 10:53:30 +00001326static PyObject *
Victor Stinner838f2642019-06-13 22:41:23 +02001327get_hash_info(PyThreadState *tstate)
Mark Dickinsondc787d22010-05-23 13:33:13 +00001328{
1329 PyObject *hash_info;
1330 int field = 0;
Christian Heimes985ecdc2013-11-20 11:46:18 +01001331 PyHash_FuncDef *hashfunc;
Mark Dickinsondc787d22010-05-23 13:33:13 +00001332 hash_info = PyStructSequence_New(&Hash_InfoType);
1333 if (hash_info == NULL)
1334 return NULL;
Christian Heimes985ecdc2013-11-20 11:46:18 +01001335 hashfunc = PyHash_GetFuncDef();
Mark Dickinsondc787d22010-05-23 13:33:13 +00001336 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001337 PyLong_FromLong(8*sizeof(Py_hash_t)));
Mark Dickinsondc787d22010-05-23 13:33:13 +00001338 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8035bc52010-10-23 16:20:50 +00001339 PyLong_FromSsize_t(_PyHASH_MODULUS));
Mark Dickinsondc787d22010-05-23 13:33:13 +00001340 PyStructSequence_SET_ITEM(hash_info, field++,
1341 PyLong_FromLong(_PyHASH_INF));
1342 PyStructSequence_SET_ITEM(hash_info, field++,
1343 PyLong_FromLong(_PyHASH_NAN));
1344 PyStructSequence_SET_ITEM(hash_info, field++,
1345 PyLong_FromLong(_PyHASH_IMAG));
Christian Heimes985ecdc2013-11-20 11:46:18 +01001346 PyStructSequence_SET_ITEM(hash_info, field++,
1347 PyUnicode_FromString(hashfunc->name));
1348 PyStructSequence_SET_ITEM(hash_info, field++,
1349 PyLong_FromLong(hashfunc->hash_bits));
1350 PyStructSequence_SET_ITEM(hash_info, field++,
1351 PyLong_FromLong(hashfunc->seed_bits));
1352 PyStructSequence_SET_ITEM(hash_info, field++,
1353 PyLong_FromLong(Py_HASH_CUTOFF));
Victor Stinner838f2642019-06-13 22:41:23 +02001354 if (_PyErr_Occurred(tstate)) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00001355 Py_CLEAR(hash_info);
1356 return NULL;
1357 }
1358 return hash_info;
1359}
Tal Einatede0b6f2018-12-31 17:12:08 +02001360/*[clinic input]
1361sys.getrecursionlimit
Mark Dickinsondc787d22010-05-23 13:33:13 +00001362
Tal Einatede0b6f2018-12-31 17:12:08 +02001363Return the current value of the recursion limit.
Mark Dickinsondc787d22010-05-23 13:33:13 +00001364
Tal Einatede0b6f2018-12-31 17:12:08 +02001365The recursion limit is the maximum depth of the Python interpreter
1366stack. This limit prevents infinite recursion from causing an overflow
1367of the C stack and crashing Python.
1368[clinic start generated code]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001369
1370static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001371sys_getrecursionlimit_impl(PyObject *module)
1372/*[clinic end generated code: output=d571fb6b4549ef2e input=1c6129fd2efaeea8]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001373{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001374 return PyLong_FromLong(Py_GetRecursionLimit());
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001375}
1376
Mark Hammond8696ebc2002-10-08 02:44:31 +00001377#ifdef MS_WINDOWS
Mark Hammond8696ebc2002-10-08 02:44:31 +00001378
Eric Smithf7bb5782010-01-27 00:44:57 +00001379static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};
1380
1381static PyStructSequence_Field windows_version_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001382 {"major", "Major version number"},
1383 {"minor", "Minor version number"},
1384 {"build", "Build number"},
1385 {"platform", "Operating system platform"},
1386 {"service_pack", "Latest Service Pack installed on the system"},
1387 {"service_pack_major", "Service Pack major version number"},
1388 {"service_pack_minor", "Service Pack minor version number"},
1389 {"suite_mask", "Bit mask identifying available product suites"},
1390 {"product_type", "System product type"},
Steve Dower74f4af72016-09-17 17:27:48 -07001391 {"platform_version", "Diagnostic version number"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001392 {0}
Eric Smithf7bb5782010-01-27 00:44:57 +00001393};
1394
1395static PyStructSequence_Desc windows_version_desc = {
Tal Einatede0b6f2018-12-31 17:12:08 +02001396 "sys.getwindowsversion", /* name */
1397 sys_getwindowsversion__doc__, /* doc */
1398 windows_version_fields, /* fields */
1399 5 /* For backward compatibility,
1400 only the first 5 items are accessible
1401 via indexing, the rest are name only */
Eric Smithf7bb5782010-01-27 00:44:57 +00001402};
1403
Steve Dower3e96f322015-03-02 08:01:10 -08001404/* Disable deprecation warnings about GetVersionEx as the result is
1405 being passed straight through to the caller, who is responsible for
1406 using it correctly. */
1407#pragma warning(push)
1408#pragma warning(disable:4996)
1409
Tal Einatede0b6f2018-12-31 17:12:08 +02001410/*[clinic input]
1411sys.getwindowsversion
1412
1413Return info about the running version of Windows as a named tuple.
1414
1415The members are named: major, minor, build, platform, service_pack,
1416service_pack_major, service_pack_minor, suite_mask, product_type and
1417platform_version. For backward compatibility, only the first 5 items
1418are available by indexing. All elements are numbers, except
1419service_pack and platform_type which are strings, and platform_version
1420which is a 3-tuple. Platform is always 2. Product_type may be 1 for a
1421workstation, 2 for a domain controller, 3 for a server.
1422Platform_version is a 3-tuple containing a version number that is
1423intended for identifying the OS rather than feature detection.
1424[clinic start generated code]*/
1425
Mark Hammond8696ebc2002-10-08 02:44:31 +00001426static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001427sys_getwindowsversion_impl(PyObject *module)
1428/*[clinic end generated code: output=1ec063280b932857 input=73a228a328fee63a]*/
Mark Hammond8696ebc2002-10-08 02:44:31 +00001429{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001430 PyObject *version;
1431 int pos = 0;
Minmin Gong8ebc6452019-02-02 20:26:55 -08001432 OSVERSIONINFOEXW ver;
Steve Dower74f4af72016-09-17 17:27:48 -07001433 DWORD realMajor, realMinor, realBuild;
1434 HANDLE hKernel32;
1435 wchar_t kernel32_path[MAX_PATH];
1436 LPVOID verblock;
1437 DWORD verblock_size;
Victor Stinner838f2642019-06-13 22:41:23 +02001438 PyThreadState *tstate = _PyThreadState_GET();
Steve Dower74f4af72016-09-17 17:27:48 -07001439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001440 ver.dwOSVersionInfoSize = sizeof(ver);
Minmin Gong8ebc6452019-02-02 20:26:55 -08001441 if (!GetVersionExW((OSVERSIONINFOW*) &ver))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001442 return PyErr_SetFromWindowsErr(0);
Eric Smithf7bb5782010-01-27 00:44:57 +00001443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001444 version = PyStructSequence_New(&WindowsVersionType);
1445 if (version == NULL)
1446 return NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +00001447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion));
1449 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion));
1450 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber));
1451 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId));
Minmin Gong8ebc6452019-02-02 20:26:55 -08001452 PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromWideChar(ver.szCSDVersion, -1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor));
1454 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor));
1455 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask));
1456 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType));
Eric Smithf7bb5782010-01-27 00:44:57 +00001457
Steve Dower74f4af72016-09-17 17:27:48 -07001458 realMajor = ver.dwMajorVersion;
1459 realMinor = ver.dwMinorVersion;
1460 realBuild = ver.dwBuildNumber;
1461
1462 // GetVersion will lie if we are running in a compatibility mode.
1463 // We need to read the version info from a system file resource
1464 // to accurately identify the OS version. If we fail for any reason,
1465 // just return whatever GetVersion said.
Tony Roberts4860f012019-02-02 18:16:42 +01001466 Py_BEGIN_ALLOW_THREADS
Steve Dower74f4af72016-09-17 17:27:48 -07001467 hKernel32 = GetModuleHandleW(L"kernel32.dll");
Tony Roberts4860f012019-02-02 18:16:42 +01001468 Py_END_ALLOW_THREADS
Steve Dower74f4af72016-09-17 17:27:48 -07001469 if (hKernel32 && GetModuleFileNameW(hKernel32, kernel32_path, MAX_PATH) &&
1470 (verblock_size = GetFileVersionInfoSizeW(kernel32_path, NULL)) &&
1471 (verblock = PyMem_RawMalloc(verblock_size))) {
1472 VS_FIXEDFILEINFO *ffi;
1473 UINT ffi_len;
1474
1475 if (GetFileVersionInfoW(kernel32_path, 0, verblock_size, verblock) &&
1476 VerQueryValueW(verblock, L"", (LPVOID)&ffi, &ffi_len)) {
1477 realMajor = HIWORD(ffi->dwProductVersionMS);
1478 realMinor = LOWORD(ffi->dwProductVersionMS);
1479 realBuild = HIWORD(ffi->dwProductVersionLS);
1480 }
1481 PyMem_RawFree(verblock);
1482 }
Segev Finer48fb7662017-06-04 20:52:27 +03001483 PyStructSequence_SET_ITEM(version, pos++, Py_BuildValue("(kkk)",
1484 realMajor,
1485 realMinor,
1486 realBuild
Steve Dower74f4af72016-09-17 17:27:48 -07001487 ));
1488
Victor Stinner838f2642019-06-13 22:41:23 +02001489 if (_PyErr_Occurred(tstate)) {
Serhiy Storchaka48d761e2013-12-17 15:11:24 +02001490 Py_DECREF(version);
1491 return NULL;
1492 }
Steve Dower74f4af72016-09-17 17:27:48 -07001493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001494 return version;
Mark Hammond8696ebc2002-10-08 02:44:31 +00001495}
1496
Steve Dower3e96f322015-03-02 08:01:10 -08001497#pragma warning(pop)
1498
Tal Einatede0b6f2018-12-31 17:12:08 +02001499/*[clinic input]
1500sys._enablelegacywindowsfsencoding
1501
1502Changes the default filesystem encoding to mbcs:replace.
1503
1504This is done for consistency with earlier versions of Python. See PEP
1505529 for more information.
1506
1507This is equivalent to defining the PYTHONLEGACYWINDOWSFSENCODING
1508environment variable before launching Python.
1509[clinic start generated code]*/
Steve Dowercc16be82016-09-08 10:35:16 -07001510
1511static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001512sys__enablelegacywindowsfsencoding_impl(PyObject *module)
1513/*[clinic end generated code: output=f5c3855b45e24fe9 input=2bfa931a20704492]*/
Steve Dowercc16be82016-09-08 10:35:16 -07001514{
Victor Stinner709d23d2019-05-02 14:56:30 -04001515 if (_PyUnicode_EnableLegacyWindowsFSEncoding() < 0) {
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001516 return NULL;
1517 }
Steve Dowercc16be82016-09-08 10:35:16 -07001518 Py_RETURN_NONE;
1519}
1520
Mark Hammond8696ebc2002-10-08 02:44:31 +00001521#endif /* MS_WINDOWS */
1522
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001523#ifdef HAVE_DLOPEN
Tal Einatede0b6f2018-12-31 17:12:08 +02001524
1525/*[clinic input]
1526sys.setdlopenflags
1527
1528 flags as new_val: int
1529 /
1530
1531Set the flags used by the interpreter for dlopen calls.
1532
1533This is used, for example, when the interpreter loads extension
1534modules. Among other things, this will enable a lazy resolving of
1535symbols when importing a module, if called as sys.setdlopenflags(0).
1536To share symbols across extension modules, call as
1537sys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag
1538modules can be found in the os module (RTLD_xxx constants, e.g.
1539os.RTLD_LAZY).
1540[clinic start generated code]*/
1541
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001542static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001543sys_setdlopenflags_impl(PyObject *module, int new_val)
1544/*[clinic end generated code: output=ec918b7fe0a37281 input=4c838211e857a77f]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001545{
Victor Stinner838f2642019-06-13 22:41:23 +02001546 PyThreadState *tstate = _PyThreadState_GET();
1547 tstate->interp->dlopenflags = new_val;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001548 Py_RETURN_NONE;
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001549}
1550
Tal Einatede0b6f2018-12-31 17:12:08 +02001551
1552/*[clinic input]
1553sys.getdlopenflags
1554
1555Return the current value of the flags that are used for dlopen calls.
1556
1557The flag constants are defined in the os module.
1558[clinic start generated code]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001559
1560static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001561sys_getdlopenflags_impl(PyObject *module)
1562/*[clinic end generated code: output=e92cd1bc5005da6e input=dc4ea0899c53b4b6]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001563{
Victor Stinner838f2642019-06-13 22:41:23 +02001564 PyThreadState *tstate = _PyThreadState_GET();
1565 return PyLong_FromLong(tstate->interp->dlopenflags);
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001566}
1567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001568#endif /* HAVE_DLOPEN */
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001569
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001570#ifdef USE_MALLOPT
1571/* Link with -lmalloc (or -lmpc) on an SGI */
1572#include <malloc.h>
1573
Tal Einatede0b6f2018-12-31 17:12:08 +02001574/*[clinic input]
1575sys.mdebug
1576
1577 flag: int
1578 /
1579[clinic start generated code]*/
1580
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001581static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001582sys_mdebug_impl(PyObject *module, int flag)
1583/*[clinic end generated code: output=5431d545847c3637 input=151d150ae1636f8a]*/
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001584{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 int flag;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 mallopt(M_DEBUG, flag);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001587 Py_RETURN_NONE;
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001588}
1589#endif /* USE_MALLOPT */
1590
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001591size_t
1592_PySys_GetSizeOf(PyObject *o)
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001593{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 PyObject *res = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 PyObject *method;
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001596 Py_ssize_t size;
Victor Stinner838f2642019-06-13 22:41:23 +02001597 PyThreadState *tstate = _PyThreadState_GET();
Benjamin Petersona5758c02009-05-09 18:15:04 +00001598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001599 /* Make sure the type is initialized. float gets initialized late */
Victor Stinner838f2642019-06-13 22:41:23 +02001600 if (PyType_Ready(Py_TYPE(o)) < 0) {
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001601 return (size_t)-1;
Victor Stinner838f2642019-06-13 22:41:23 +02001602 }
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001603
Benjamin Petersonce798522012-01-22 11:24:29 -05001604 method = _PyObject_LookupSpecial(o, &PyId___sizeof__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 if (method == NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +02001606 if (!_PyErr_Occurred(tstate)) {
1607 _PyErr_Format(tstate, PyExc_TypeError,
1608 "Type %.100s doesn't define __sizeof__",
1609 Py_TYPE(o)->tp_name);
1610 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001611 }
1612 else {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001613 res = _PyObject_CallNoArg(method);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001614 Py_DECREF(method);
1615 }
1616
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001617 if (res == NULL)
1618 return (size_t)-1;
1619
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001620 size = PyLong_AsSsize_t(res);
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001621 Py_DECREF(res);
Victor Stinner838f2642019-06-13 22:41:23 +02001622 if (size == -1 && _PyErr_Occurred(tstate))
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001623 return (size_t)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001624
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001625 if (size < 0) {
Victor Stinner838f2642019-06-13 22:41:23 +02001626 _PyErr_SetString(tstate, PyExc_ValueError,
1627 "__sizeof__() should return >= 0");
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001628 return (size_t)-1;
1629 }
1630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001631 /* add gc_head size */
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001632 if (PyObject_IS_GC(o))
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001633 return ((size_t)size) + sizeof(PyGC_Head);
1634 return (size_t)size;
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001635}
1636
1637static PyObject *
1638sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
1639{
1640 static char *kwlist[] = {"object", "default", 0};
1641 size_t size;
1642 PyObject *o, *dflt = NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02001643 PyThreadState *tstate = _PyThreadState_GET();
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001644
1645 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
Victor Stinner838f2642019-06-13 22:41:23 +02001646 kwlist, &o, &dflt)) {
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001647 return NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02001648 }
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001649
1650 size = _PySys_GetSizeOf(o);
1651
Victor Stinner838f2642019-06-13 22:41:23 +02001652 if (size == (size_t)-1 && _PyErr_Occurred(tstate)) {
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001653 /* Has a default value been given */
Victor Stinner838f2642019-06-13 22:41:23 +02001654 if (dflt != NULL && _PyErr_ExceptionMatches(tstate, PyExc_TypeError)) {
1655 _PyErr_Clear(tstate);
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001656 Py_INCREF(dflt);
1657 return dflt;
1658 }
1659 else
1660 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001661 }
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001662
1663 return PyLong_FromSize_t(size);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001664}
1665
1666PyDoc_STRVAR(getsizeof_doc,
Tal Einatede0b6f2018-12-31 17:12:08 +02001667"getsizeof(object [, default]) -> int\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001668\n\
1669Return the size of object in bytes.");
1670
Tal Einatede0b6f2018-12-31 17:12:08 +02001671/*[clinic input]
1672sys.getrefcount -> Py_ssize_t
1673
1674 object: object
1675 /
1676
1677Return the reference count of object.
1678
1679The count returned is generally one higher than you might expect,
1680because it includes the (temporary) reference as an argument to
1681getrefcount().
1682[clinic start generated code]*/
1683
1684static Py_ssize_t
1685sys_getrefcount_impl(PyObject *module, PyObject *object)
1686/*[clinic end generated code: output=5fd477f2264b85b2 input=bf474efd50a21535]*/
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001687{
Victor Stinnera93c51e2020-02-07 00:38:59 +01001688 return Py_REFCNT(object);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001689}
1690
Tim Peters4be93d02002-07-07 19:59:50 +00001691#ifdef Py_REF_DEBUG
Tal Einatede0b6f2018-12-31 17:12:08 +02001692/*[clinic input]
1693sys.gettotalrefcount -> Py_ssize_t
1694[clinic start generated code]*/
1695
1696static Py_ssize_t
1697sys_gettotalrefcount_impl(PyObject *module)
1698/*[clinic end generated code: output=4103886cf17c25bc input=53b744faa5d2e4f6]*/
Mark Hammond440d8982000-06-20 08:12:48 +00001699{
Tal Einatede0b6f2018-12-31 17:12:08 +02001700 return _Py_GetRefTotal();
Mark Hammond440d8982000-06-20 08:12:48 +00001701}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001702#endif /* Py_REF_DEBUG */
Mark Hammond440d8982000-06-20 08:12:48 +00001703
Tal Einatede0b6f2018-12-31 17:12:08 +02001704/*[clinic input]
1705sys.getallocatedblocks -> Py_ssize_t
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001706
Tal Einatede0b6f2018-12-31 17:12:08 +02001707Return the number of memory blocks currently allocated.
1708[clinic start generated code]*/
1709
1710static Py_ssize_t
1711sys_getallocatedblocks_impl(PyObject *module)
1712/*[clinic end generated code: output=f0c4e873f0b6dcf7 input=dab13ee346a0673e]*/
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001713{
Tal Einatede0b6f2018-12-31 17:12:08 +02001714 return _Py_GetAllocatedBlocks();
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001715}
1716
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001717
Tal Einatede0b6f2018-12-31 17:12:08 +02001718/*[clinic input]
1719sys._getframe
1720
1721 depth: int = 0
1722 /
1723
1724Return a frame object from the call stack.
1725
1726If optional integer depth is given, return the frame object that many
1727calls below the top of the stack. If that is deeper than the call
1728stack, ValueError is raised. The default for depth is zero, returning
1729the frame at the top of the call stack.
1730
1731This function should be used for internal and specialized purposes
1732only.
1733[clinic start generated code]*/
Barry Warsawb6a54d22000-12-06 21:47:46 +00001734
1735static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001736sys__getframe_impl(PyObject *module, int depth)
1737/*[clinic end generated code: output=d438776c04d59804 input=c1be8a6464b11ee5]*/
Barry Warsawb6a54d22000-12-06 21:47:46 +00001738{
Victor Stinner838f2642019-06-13 22:41:23 +02001739 PyThreadState *tstate = _PyThreadState_GET();
1740 PyFrameObject *f = tstate->frame;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001741
Steve Dowerb82e17e2019-05-23 08:45:22 -07001742 if (PySys_Audit("sys._getframe", "O", f) < 0) {
1743 return NULL;
1744 }
1745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001746 while (depth > 0 && f != NULL) {
1747 f = f->f_back;
1748 --depth;
1749 }
1750 if (f == NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +02001751 _PyErr_SetString(tstate, PyExc_ValueError,
1752 "call stack is not deep enough");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001753 return NULL;
1754 }
1755 Py_INCREF(f);
1756 return (PyObject*)f;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001757}
1758
Tal Einatede0b6f2018-12-31 17:12:08 +02001759/*[clinic input]
1760sys._current_frames
1761
1762Return a dict mapping each thread's thread id to its current stack frame.
1763
1764This function should be used for specialized purposes only.
1765[clinic start generated code]*/
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001766
1767static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001768sys__current_frames_impl(PyObject *module)
1769/*[clinic end generated code: output=d2a41ac0a0a3809a input=2a9049c5f5033691]*/
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001770{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001771 return _PyThread_CurrentFrames();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001772}
1773
Tal Einatede0b6f2018-12-31 17:12:08 +02001774/*[clinic input]
1775sys.call_tracing
1776
1777 func: object
1778 args as funcargs: object(subclass_of='&PyTuple_Type')
1779 /
1780
1781Call func(*args), while tracing is enabled.
1782
1783The tracing state is saved, and restored afterwards. This is intended
1784to be called from a debugger from a checkpoint, to recursively debug
1785some other code.
1786[clinic start generated code]*/
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001787
1788static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001789sys_call_tracing_impl(PyObject *module, PyObject *func, PyObject *funcargs)
1790/*[clinic end generated code: output=7e4999853cd4e5a6 input=5102e8b11049f92f]*/
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001791{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 return _PyEval_CallTracing(func, funcargs);
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001793}
1794
Victor Stinner048afd92016-11-28 11:59:04 +01001795
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001796#ifdef __cplusplus
1797extern "C" {
1798#endif
1799
Tal Einatede0b6f2018-12-31 17:12:08 +02001800/*[clinic input]
1801sys._debugmallocstats
1802
1803Print summary info to stderr about the state of pymalloc's structures.
1804
1805In Py_DEBUG mode, also perform some expensive internal consistency
1806checks.
1807[clinic start generated code]*/
1808
David Malcolm49526f42012-06-22 14:55:41 -04001809static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001810sys__debugmallocstats_impl(PyObject *module)
1811/*[clinic end generated code: output=ec3565f8c7cee46a input=33c0c9c416f98424]*/
David Malcolm49526f42012-06-22 14:55:41 -04001812{
1813#ifdef WITH_PYMALLOC
Victor Stinner6bf992a2017-12-06 17:26:10 +01001814 if (_PyObject_DebugMallocStats(stderr)) {
Victor Stinner34be8072016-03-14 12:04:26 +01001815 fputc('\n', stderr);
1816 }
David Malcolm49526f42012-06-22 14:55:41 -04001817#endif
1818 _PyObject_DebugTypeStats(stderr);
1819
1820 Py_RETURN_NONE;
1821}
David Malcolm49526f42012-06-22 14:55:41 -04001822
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001823#ifdef Py_TRACE_REFS
Guido van Rossumded690f1996-05-24 20:48:31 +00001824/* Defined in objects.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001825extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001826#endif
Guido van Rossumded690f1996-05-24 20:48:31 +00001827
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001828#ifdef DYNAMIC_EXECUTION_PROFILE
1829/* Defined in ceval.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001830extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001831#endif
1832
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001833#ifdef __cplusplus
1834}
1835#endif
1836
Tal Einatede0b6f2018-12-31 17:12:08 +02001837
1838/*[clinic input]
1839sys._clear_type_cache
1840
1841Clear the internal type lookup cache.
1842[clinic start generated code]*/
1843
Christian Heimes15ebc882008-02-04 18:48:49 +00001844static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001845sys__clear_type_cache_impl(PyObject *module)
1846/*[clinic end generated code: output=20e48ca54a6f6971 input=127f3e04a8d9b555]*/
Christian Heimes15ebc882008-02-04 18:48:49 +00001847{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 PyType_ClearCache();
1849 Py_RETURN_NONE;
Christian Heimes15ebc882008-02-04 18:48:49 +00001850}
1851
Tal Einatede0b6f2018-12-31 17:12:08 +02001852/*[clinic input]
1853sys.is_finalizing
1854
1855Return True if Python is exiting.
1856[clinic start generated code]*/
1857
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001858static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001859sys_is_finalizing_impl(PyObject *module)
1860/*[clinic end generated code: output=735b5ff7962ab281 input=f0df747a039948a5]*/
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001861{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001862 return PyBool_FromLong(_Py_IsFinalizing());
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001863}
1864
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001865#ifdef ANDROID_API_LEVEL
Tal Einatede0b6f2018-12-31 17:12:08 +02001866/*[clinic input]
1867sys.getandroidapilevel
1868
1869Return the build time API version of Android as an integer.
1870[clinic start generated code]*/
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001871
1872static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001873sys_getandroidapilevel_impl(PyObject *module)
1874/*[clinic end generated code: output=214abf183a1c70c1 input=3e6d6c9fcdd24ac6]*/
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001875{
1876 return PyLong_FromLong(ANDROID_API_LEVEL);
1877}
1878#endif /* ANDROID_API_LEVEL */
1879
1880
Steve Dowerb82e17e2019-05-23 08:45:22 -07001881
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001882static PyMethodDef sys_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 /* Might as well keep this in alphabetic order */
Steve Dowerb82e17e2019-05-23 08:45:22 -07001884 SYS_ADDAUDITHOOK_METHODDEF
1885 {"audit", (PyCFunction)(void(*)(void))sys_audit, METH_FASTCALL, audit_doc },
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001886 {"breakpointhook", (PyCFunction)(void(*)(void))sys_breakpointhook,
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04001887 METH_FASTCALL | METH_KEYWORDS, breakpointhook_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001888 SYS__CLEAR_TYPE_CACHE_METHODDEF
1889 SYS__CURRENT_FRAMES_METHODDEF
1890 SYS_DISPLAYHOOK_METHODDEF
1891 SYS_EXC_INFO_METHODDEF
1892 SYS_EXCEPTHOOK_METHODDEF
1893 SYS_EXIT_METHODDEF
1894 SYS_GETDEFAULTENCODING_METHODDEF
1895 SYS_GETDLOPENFLAGS_METHODDEF
1896 SYS_GETALLOCATEDBLOCKS_METHODDEF
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001897#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001898 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001899#endif
Tal Einatede0b6f2018-12-31 17:12:08 +02001900 SYS_GETFILESYSTEMENCODING_METHODDEF
1901 SYS_GETFILESYSTEMENCODEERRORS_METHODDEF
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001902#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 {"getobjects", _Py_GetObjects, METH_VARARGS},
Tim Peters4be93d02002-07-07 19:59:50 +00001904#endif
Tal Einatede0b6f2018-12-31 17:12:08 +02001905 SYS_GETTOTALREFCOUNT_METHODDEF
1906 SYS_GETREFCOUNT_METHODDEF
1907 SYS_GETRECURSIONLIMIT_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001908 {"getsizeof", (PyCFunction)(void(*)(void))sys_getsizeof,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001909 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001910 SYS__GETFRAME_METHODDEF
1911 SYS_GETWINDOWSVERSION_METHODDEF
1912 SYS__ENABLELEGACYWINDOWSFSENCODING_METHODDEF
1913 SYS_INTERN_METHODDEF
1914 SYS_IS_FINALIZING_METHODDEF
1915 SYS_MDEBUG_METHODDEF
Tal Einatede0b6f2018-12-31 17:12:08 +02001916 SYS_SETSWITCHINTERVAL_METHODDEF
1917 SYS_GETSWITCHINTERVAL_METHODDEF
1918 SYS_SETDLOPENFLAGS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001919 {"setprofile", sys_setprofile, METH_O, setprofile_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001920 SYS_GETPROFILE_METHODDEF
1921 SYS_SETRECURSIONLIMIT_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001922 {"settrace", sys_settrace, METH_O, settrace_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001923 SYS_GETTRACE_METHODDEF
1924 SYS_CALL_TRACING_METHODDEF
1925 SYS__DEBUGMALLOCSTATS_METHODDEF
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001926 SYS_SET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
1927 SYS_GET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001928 {"set_asyncgen_hooks", (PyCFunction)(void(*)(void))sys_set_asyncgen_hooks,
Yury Selivanoveb636452016-09-08 22:01:51 -07001929 METH_VARARGS | METH_KEYWORDS, set_asyncgen_hooks_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001930 SYS_GET_ASYNCGEN_HOOKS_METHODDEF
1931 SYS_GETANDROIDAPILEVEL_METHODDEF
Victor Stinneref9d9b62019-05-22 11:28:22 +02001932 SYS_UNRAISABLEHOOK_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001933 {NULL, NULL} /* sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +00001934};
1935
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001936static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001937list_builtin_module_names(void)
Guido van Rossum34679b71993-01-26 13:33:44 +00001938{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001939 PyObject *list = PyList_New(0);
1940 int i;
1941 if (list == NULL)
1942 return NULL;
1943 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1944 PyObject *name = PyUnicode_FromString(
1945 PyImport_Inittab[i].name);
1946 if (name == NULL)
1947 break;
1948 PyList_Append(list, name);
1949 Py_DECREF(name);
1950 }
1951 if (PyList_Sort(list) != 0) {
1952 Py_DECREF(list);
1953 list = NULL;
1954 }
1955 if (list) {
1956 PyObject *v = PyList_AsTuple(list);
1957 Py_DECREF(list);
1958 list = v;
1959 }
1960 return list;
Guido van Rossum34679b71993-01-26 13:33:44 +00001961}
1962
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001963/* Pre-initialization support for sys.warnoptions and sys._xoptions
1964 *
1965 * Modern internal code paths:
1966 * These APIs get called after _Py_InitializeCore and get to use the
1967 * regular CPython list, dict, and unicode APIs.
1968 *
1969 * Legacy embedding code paths:
1970 * The multi-phase initialization API isn't public yet, so embedding
1971 * apps still need to be able configure sys.warnoptions and sys._xoptions
1972 * before they call Py_Initialize. To support this, we stash copies of
1973 * the supplied wchar * sequences in linked lists, and then migrate the
1974 * contents of those lists to the sys module in _PyInitializeCore.
1975 *
1976 */
1977
1978struct _preinit_entry {
1979 wchar_t *value;
1980 struct _preinit_entry *next;
1981};
1982
1983typedef struct _preinit_entry *_Py_PreInitEntry;
1984
1985static _Py_PreInitEntry _preinit_warnoptions = NULL;
1986static _Py_PreInitEntry _preinit_xoptions = NULL;
1987
1988static _Py_PreInitEntry
1989_alloc_preinit_entry(const wchar_t *value)
1990{
1991 /* To get this to work, we have to initialize the runtime implicitly */
1992 _PyRuntime_Initialize();
1993
1994 /* Force default allocator, so we can ensure that it also gets used to
1995 * destroy the linked list in _clear_preinit_entries.
1996 */
1997 PyMemAllocatorEx old_alloc;
1998 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1999
2000 _Py_PreInitEntry node = PyMem_RawCalloc(1, sizeof(*node));
2001 if (node != NULL) {
2002 node->value = _PyMem_RawWcsdup(value);
2003 if (node->value == NULL) {
2004 PyMem_RawFree(node);
2005 node = NULL;
2006 };
2007 };
2008
2009 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2010 return node;
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002011}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002012
2013static int
2014_append_preinit_entry(_Py_PreInitEntry *optionlist, const wchar_t *value)
2015{
2016 _Py_PreInitEntry new_entry = _alloc_preinit_entry(value);
2017 if (new_entry == NULL) {
2018 return -1;
2019 }
2020 /* We maintain the linked list in this order so it's easy to play back
2021 * the add commands in the same order later on in _Py_InitializeCore
2022 */
2023 _Py_PreInitEntry last_entry = *optionlist;
2024 if (last_entry == NULL) {
2025 *optionlist = new_entry;
2026 } else {
2027 while (last_entry->next != NULL) {
2028 last_entry = last_entry->next;
2029 }
2030 last_entry->next = new_entry;
2031 }
2032 return 0;
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002033}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002034
2035static void
2036_clear_preinit_entries(_Py_PreInitEntry *optionlist)
2037{
2038 _Py_PreInitEntry current = *optionlist;
2039 *optionlist = NULL;
2040 /* Deallocate the nodes and their contents using the default allocator */
2041 PyMemAllocatorEx old_alloc;
2042 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2043 while (current != NULL) {
2044 _Py_PreInitEntry next = current->next;
2045 PyMem_RawFree(current->value);
2046 PyMem_RawFree(current);
2047 current = next;
2048 }
2049 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002050}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002051
Victor Stinner120b7072019-08-23 18:03:08 +01002052
2053PyStatus
Victor Stinnerfb4ae152019-09-30 01:40:17 +02002054_PySys_ReadPreinitWarnOptions(PyWideStringList *options)
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002055{
Victor Stinner120b7072019-08-23 18:03:08 +01002056 PyStatus status;
2057 _Py_PreInitEntry entry;
2058
2059 for (entry = _preinit_warnoptions; entry != NULL; entry = entry->next) {
Victor Stinnerfb4ae152019-09-30 01:40:17 +02002060 status = PyWideStringList_Append(options, entry->value);
Victor Stinner120b7072019-08-23 18:03:08 +01002061 if (_PyStatus_EXCEPTION(status)) {
2062 return status;
2063 }
2064 }
2065
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002066 _clear_preinit_entries(&_preinit_warnoptions);
Victor Stinner120b7072019-08-23 18:03:08 +01002067 return _PyStatus_OK();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002068}
2069
Victor Stinner120b7072019-08-23 18:03:08 +01002070
2071PyStatus
2072_PySys_ReadPreinitXOptions(PyConfig *config)
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002073{
Victor Stinner120b7072019-08-23 18:03:08 +01002074 PyStatus status;
2075 _Py_PreInitEntry entry;
2076
2077 for (entry = _preinit_xoptions; entry != NULL; entry = entry->next) {
2078 status = PyWideStringList_Append(&config->xoptions, entry->value);
2079 if (_PyStatus_EXCEPTION(status)) {
2080 return status;
2081 }
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002082 }
2083
Victor Stinner120b7072019-08-23 18:03:08 +01002084 _clear_preinit_entries(&_preinit_xoptions);
2085 return _PyStatus_OK();
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002086}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002087
Victor Stinner120b7072019-08-23 18:03:08 +01002088
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002089static PyObject *
Victor Stinner838f2642019-06-13 22:41:23 +02002090get_warnoptions(PyThreadState *tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002091{
Victor Stinner838f2642019-06-13 22:41:23 +02002092 PyObject *warnoptions = sys_get_object_id(tstate, &PyId_warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002093 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002094 /* PEP432 TODO: we can reach this if warnoptions is NULL in the main
2095 * interpreter config. When that happens, we need to properly set
2096 * the `warnoptions` reference in the main interpreter config as well.
2097 *
2098 * For Python 3.7, we shouldn't be able to get here due to the
2099 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
2100 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
2101 * call optional for embedding applications, thus making this
2102 * reachable again.
2103 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002104 warnoptions = PyList_New(0);
Victor Stinner838f2642019-06-13 22:41:23 +02002105 if (warnoptions == NULL) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002106 return NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02002107 }
2108 if (sys_set_object_id(tstate, &PyId_warnoptions, warnoptions)) {
Eric Snowdae02762017-09-14 00:35:58 -07002109 Py_DECREF(warnoptions);
2110 return NULL;
2111 }
2112 Py_DECREF(warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002113 }
2114 return warnoptions;
2115}
Guido van Rossum23fff912000-12-15 22:02:05 +00002116
2117void
2118PySys_ResetWarnOptions(void)
2119{
Victor Stinner50b48572018-11-01 01:51:40 +01002120 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002121 if (tstate == NULL) {
2122 _clear_preinit_entries(&_preinit_warnoptions);
2123 return;
2124 }
2125
Victor Stinner838f2642019-06-13 22:41:23 +02002126 PyObject *warnoptions = sys_get_object_id(tstate, &PyId_warnoptions);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002127 if (warnoptions == NULL || !PyList_Check(warnoptions))
2128 return;
2129 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
Guido van Rossum23fff912000-12-15 22:02:05 +00002130}
2131
Victor Stinnere1b29952018-10-30 14:31:42 +01002132static int
Victor Stinner838f2642019-06-13 22:41:23 +02002133_PySys_AddWarnOptionWithError(PyThreadState *tstate, PyObject *option)
Guido van Rossum23fff912000-12-15 22:02:05 +00002134{
Victor Stinner838f2642019-06-13 22:41:23 +02002135 PyObject *warnoptions = get_warnoptions(tstate);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002136 if (warnoptions == NULL) {
2137 return -1;
2138 }
2139 if (PyList_Append(warnoptions, option)) {
2140 return -1;
2141 }
2142 return 0;
2143}
2144
2145void
2146PySys_AddWarnOptionUnicode(PyObject *option)
2147{
Victor Stinner838f2642019-06-13 22:41:23 +02002148 PyThreadState *tstate = _PyThreadState_GET();
2149 if (_PySys_AddWarnOptionWithError(tstate, option) < 0) {
Victor Stinnere1b29952018-10-30 14:31:42 +01002150 /* No return value, therefore clear error state if possible */
Victor Stinner838f2642019-06-13 22:41:23 +02002151 if (tstate) {
2152 _PyErr_Clear(tstate);
Victor Stinnere1b29952018-10-30 14:31:42 +01002153 }
2154 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00002155}
2156
2157void
2158PySys_AddWarnOption(const wchar_t *s)
2159{
Victor Stinner50b48572018-11-01 01:51:40 +01002160 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002161 if (tstate == NULL) {
2162 _append_preinit_entry(&_preinit_warnoptions, s);
2163 return;
2164 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00002165 PyObject *unicode;
2166 unicode = PyUnicode_FromWideChar(s, -1);
2167 if (unicode == NULL)
2168 return;
2169 PySys_AddWarnOptionUnicode(unicode);
2170 Py_DECREF(unicode);
Guido van Rossum23fff912000-12-15 22:02:05 +00002171}
2172
Christian Heimes33fe8092008-04-13 13:53:33 +00002173int
2174PySys_HasWarnOptions(void)
2175{
Victor Stinner838f2642019-06-13 22:41:23 +02002176 PyThreadState *tstate = _PyThreadState_GET();
2177 PyObject *warnoptions = sys_get_object_id(tstate, &PyId_warnoptions);
Serhiy Storchakadffccc62018-12-10 13:50:22 +02002178 return (warnoptions != NULL && PyList_Check(warnoptions)
2179 && PyList_GET_SIZE(warnoptions) > 0);
Christian Heimes33fe8092008-04-13 13:53:33 +00002180}
2181
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002182static PyObject *
Victor Stinner838f2642019-06-13 22:41:23 +02002183get_xoptions(PyThreadState *tstate)
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002184{
Victor Stinner838f2642019-06-13 22:41:23 +02002185 PyObject *xoptions = sys_get_object_id(tstate, &PyId__xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002186 if (xoptions == NULL || !PyDict_Check(xoptions)) {
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002187 /* PEP432 TODO: we can reach this if xoptions is NULL in the main
2188 * interpreter config. When that happens, we need to properly set
2189 * the `xoptions` reference in the main interpreter config as well.
2190 *
2191 * For Python 3.7, we shouldn't be able to get here due to the
2192 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
2193 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
2194 * call optional for embedding applications, thus making this
2195 * reachable again.
2196 */
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002197 xoptions = PyDict_New();
Victor Stinner838f2642019-06-13 22:41:23 +02002198 if (xoptions == NULL) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002199 return NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02002200 }
2201 if (sys_set_object_id(tstate, &PyId__xoptions, xoptions)) {
Eric Snowdae02762017-09-14 00:35:58 -07002202 Py_DECREF(xoptions);
2203 return NULL;
2204 }
2205 Py_DECREF(xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002206 }
2207 return xoptions;
2208}
2209
Victor Stinnere1b29952018-10-30 14:31:42 +01002210static int
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002211_PySys_AddXOptionWithError(const wchar_t *s)
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002212{
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002213 PyObject *name = NULL, *value = NULL;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002214
Victor Stinner838f2642019-06-13 22:41:23 +02002215 PyThreadState *tstate = _PyThreadState_GET();
2216 PyObject *opts = get_xoptions(tstate);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002217 if (opts == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002218 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002219 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002220
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002221 const wchar_t *name_end = wcschr(s, L'=');
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002222 if (!name_end) {
2223 name = PyUnicode_FromWideChar(s, -1);
2224 value = Py_True;
2225 Py_INCREF(value);
2226 }
2227 else {
2228 name = PyUnicode_FromWideChar(s, name_end - s);
2229 value = PyUnicode_FromWideChar(name_end + 1, -1);
2230 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002231 if (name == NULL || value == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002232 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002233 }
2234 if (PyDict_SetItem(opts, name, value) < 0) {
2235 goto error;
2236 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002237 Py_DECREF(name);
2238 Py_DECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002239 return 0;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002240
2241error:
2242 Py_XDECREF(name);
2243 Py_XDECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002244 return -1;
2245}
2246
2247void
2248PySys_AddXOption(const wchar_t *s)
2249{
Victor Stinner50b48572018-11-01 01:51:40 +01002250 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002251 if (tstate == NULL) {
2252 _append_preinit_entry(&_preinit_xoptions, s);
2253 return;
2254 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002255 if (_PySys_AddXOptionWithError(s) < 0) {
2256 /* No return value, therefore clear error state if possible */
Victor Stinner120b7072019-08-23 18:03:08 +01002257 _PyErr_Clear(tstate);
Victor Stinner0cae6092016-11-11 01:43:56 +01002258 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002259}
2260
2261PyObject *
2262PySys_GetXOptions(void)
2263{
Victor Stinner838f2642019-06-13 22:41:23 +02002264 PyThreadState *tstate = _PyThreadState_GET();
2265 return get_xoptions(tstate);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002266}
2267
Guido van Rossum40552d01998-08-06 03:34:39 +00002268/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
2269 Two literals concatenated works just fine. If you have a K&R compiler
2270 or other abomination that however *does* understand longer strings,
2271 get rid of the !!! comment in the middle and the quotes that surround it. */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002272PyDoc_VAR(sys_doc) =
2273PyDoc_STR(
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002274"This module provides access to some objects used or maintained by the\n\
2275interpreter and to functions that interact strongly with the interpreter.\n\
2276\n\
2277Dynamic objects:\n\
2278\n\
2279argv -- command line arguments; argv[0] is the script pathname if known\n\
2280path -- module search path; path[0] is the script directory, else ''\n\
2281modules -- dictionary of loaded modules\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002282\n\
2283displayhook -- called to show results in an interactive session\n\
2284excepthook -- called to handle any uncaught exception other than SystemExit\n\
2285 To customize printing in an interactive session or to install a custom\n\
2286 top-level exception handler, assign other functions to replace these.\n\
2287\n\
Benjamin Peterson06157a42008-07-15 00:28:36 +00002288stdin -- standard input file object; used by input()\n\
Georg Brandl88fc6642007-02-09 21:28:07 +00002289stdout -- standard output file object; used by print()\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002290stderr -- standard error object; used for error messages\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002291 By assigning other file objects (or objects that behave like files)\n\
2292 to these, it is possible to redirect all of the interpreter's I/O.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002293\n\
2294last_type -- type of last uncaught exception\n\
2295last_value -- value of last uncaught exception\n\
2296last_traceback -- traceback of last uncaught exception\n\
2297 These three are only available in an interactive session after a\n\
2298 traceback has been printed.\n\
Guido van Rossuma71b5f41999-01-14 19:07:00 +00002299"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002300)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002301/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002302PyDoc_STR(
Guido van Rossuma71b5f41999-01-14 19:07:00 +00002303"\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002304Static objects:\n\
2305\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002306builtin_module_names -- tuple of module names built into this interpreter\n\
2307copyright -- copyright notice pertaining to this interpreter\n\
2308exec_prefix -- prefix used to find the machine-specific Python library\n\
Petri Lehtinen4b0eab62012-02-02 21:23:15 +02002309executable -- absolute path of the executable binary of the Python interpreter\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07002310float_info -- a named tuple with information about the float implementation.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002311float_repr_style -- string indicating the style of repr() output for floats\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07002312hash_info -- a named tuple with information about the hash algorithm.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002313hexversion -- version information encoded as a single integer\n\
Barry Warsaw409da152012-06-03 16:18:47 -04002314implementation -- Python implementation information.\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07002315int_info -- a named tuple with information about the int implementation.\n\
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00002316maxsize -- the largest supported length of containers.\n\
Serhiy Storchakad3faf432015-01-18 11:28:37 +02002317maxunicode -- the value of the largest Unicode code point\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002318platform -- platform identifier\n\
2319prefix -- prefix used to find the Python library\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07002320thread_info -- a named tuple with information about the thread implementation.\n\
Fred Drake801c08d2000-04-13 15:29:10 +00002321version -- the version of this interpreter as a string\n\
Eric Smith0e5b5622009-02-06 01:32:42 +00002322version_info -- version information as a named tuple\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002323"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002324)
Steve Dowercc16be82016-09-08 10:35:16 -07002325#ifdef MS_COREDLL
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002326/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002327PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002328"dllhandle -- [Windows only] integer handle of the Python DLL\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002329winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002330"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002331)
Steve Dowercc16be82016-09-08 10:35:16 -07002332#endif /* MS_COREDLL */
2333#ifdef MS_WINDOWS
2334/* concatenating string here */
2335PyDoc_STR(
oldkaa0735f2018-02-02 16:52:55 +08002336"_enablelegacywindowsfsencoding -- [Windows only]\n\
Steve Dowercc16be82016-09-08 10:35:16 -07002337"
2338)
2339#endif
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002340PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002341"__stdin__ -- the original stdin; don't touch!\n\
2342__stdout__ -- the original stdout; don't touch!\n\
2343__stderr__ -- the original stderr; don't touch!\n\
2344__displayhook__ -- the original displayhook; don't touch!\n\
2345__excepthook__ -- the original excepthook; don't touch!\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002346\n\
2347Functions:\n\
2348\n\
Georg Brandl1a3284e2007-12-02 09:40:06 +00002349displayhook() -- print an object to the screen, and save it in builtins._\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002350excepthook() -- print an exception and its traceback to sys.stderr\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002351exc_info() -- return thread-safe information about the current exception\n\
2352exit() -- exit the interpreter by raising SystemExit\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002353getdlopenflags() -- returns flags to be used for dlopen() calls\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002354getprofile() -- get the global profiling function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002355getrefcount() -- return the reference count for an object (plus one :-)\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002356getrecursionlimit() -- return the max recursion depth for the interpreter\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002357getsizeof() -- return the size of an object in bytes\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002358gettrace() -- get the global debug tracing function\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002359setdlopenflags() -- set the flags to be used for dlopen() calls\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002360setprofile() -- set the global profiling function\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002361setrecursionlimit() -- set the max recursion depth for the interpreter\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002362settrace() -- set the global debug tracing function\n\
Fred Drakeccede592000-08-14 20:59:57 +00002363"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002364)
Fred Drakeccede592000-08-14 20:59:57 +00002365/* end of sys_doc */ ;
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002366
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002367
2368PyDoc_STRVAR(flags__doc__,
2369"sys.flags\n\
2370\n\
2371Flags provided through command line arguments or environment vars.");
2372
2373static PyTypeObject FlagsType;
2374
2375static PyStructSequence_Field flags_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002376 {"debug", "-d"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002377 {"inspect", "-i"},
2378 {"interactive", "-i"},
2379 {"optimize", "-O or -OO"},
2380 {"dont_write_bytecode", "-B"},
2381 {"no_user_site", "-s"},
2382 {"no_site", "-S"},
2383 {"ignore_environment", "-E"},
2384 {"verbose", "-v"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385 /* {"unbuffered", "-u"}, */
2386 /* {"skip_first", "-x"}, */
Georg Brandl8aa7e992010-12-28 18:30:18 +00002387 {"bytes_warning", "-b"},
2388 {"quiet", "-q"},
Georg Brandl09a7c722012-02-20 21:31:46 +01002389 {"hash_randomization", "-R"},
Christian Heimesad73a9c2013-08-10 16:36:18 +02002390 {"isolated", "-I"},
Victor Stinner5e3806f2017-11-30 11:40:24 +01002391 {"dev_mode", "-X dev"},
Victor Stinner91106cd2017-12-13 12:29:09 +01002392 {"utf8_mode", "-X utf8"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002393 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002394};
2395
2396static PyStructSequence_Desc flags_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002397 "sys.flags", /* name */
2398 flags__doc__, /* doc */
2399 flags_fields, /* fields */
Victor Stinner91106cd2017-12-13 12:29:09 +01002400 15
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002401};
2402
2403static PyObject*
Victor Stinner01b1cc12019-11-20 02:27:56 +01002404make_flags(PyThreadState *tstate)
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002405{
Victor Stinner01b1cc12019-11-20 02:27:56 +01002406 PyInterpreterState *interp = tstate->interp;
2407 const PyPreConfig *preconfig = &interp->runtime->preconfig;
2408 const PyConfig *config = &interp->config;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002409
Victor Stinner01b1cc12019-11-20 02:27:56 +01002410 PyObject *seq = PyStructSequence_New(&FlagsType);
2411 if (seq == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002412 return NULL;
Victor Stinner01b1cc12019-11-20 02:27:56 +01002413 }
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002414
Victor Stinner01b1cc12019-11-20 02:27:56 +01002415 int pos = 0;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002416#define SetFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002417 PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002418
Victor Stinnerfbca9082018-08-30 00:50:45 +02002419 SetFlag(config->parser_debug);
2420 SetFlag(config->inspect);
2421 SetFlag(config->interactive);
2422 SetFlag(config->optimization_level);
2423 SetFlag(!config->write_bytecode);
2424 SetFlag(!config->user_site_directory);
2425 SetFlag(!config->site_import);
Victor Stinner20004952019-03-26 02:31:11 +01002426 SetFlag(!config->use_environment);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002427 SetFlag(config->verbose);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002428 /* SetFlag(saw_unbuffered_flag); */
2429 /* SetFlag(skipfirstline); */
Victor Stinnerfbca9082018-08-30 00:50:45 +02002430 SetFlag(config->bytes_warning);
2431 SetFlag(config->quiet);
2432 SetFlag(config->use_hash_seed == 0 || config->hash_seed != 0);
Victor Stinner20004952019-03-26 02:31:11 +01002433 SetFlag(config->isolated);
2434 PyStructSequence_SET_ITEM(seq, pos++, PyBool_FromLong(config->dev_mode));
2435 SetFlag(preconfig->utf8_mode);
Victor Stinner91106cd2017-12-13 12:29:09 +01002436#undef SetFlag
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002437
Victor Stinner838f2642019-06-13 22:41:23 +02002438 if (_PyErr_Occurred(tstate)) {
Serhiy Storchaka87a854d2013-12-17 14:59:42 +02002439 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002440 return NULL;
2441 }
2442 return seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002443}
2444
Eric Smith0e5b5622009-02-06 01:32:42 +00002445PyDoc_STRVAR(version_info__doc__,
2446"sys.version_info\n\
2447\n\
2448Version information as a named tuple.");
2449
2450static PyTypeObject VersionInfoType;
2451
2452static PyStructSequence_Field version_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002453 {"major", "Major release number"},
2454 {"minor", "Minor release number"},
2455 {"micro", "Patch release number"},
Ned Deilyda4887a2016-11-04 17:03:34 -04002456 {"releaselevel", "'alpha', 'beta', 'candidate', or 'final'"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002457 {"serial", "Serial release number"},
2458 {0}
Eric Smith0e5b5622009-02-06 01:32:42 +00002459};
2460
2461static PyStructSequence_Desc version_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002462 "sys.version_info", /* name */
2463 version_info__doc__, /* doc */
2464 version_info_fields, /* fields */
2465 5
Eric Smith0e5b5622009-02-06 01:32:42 +00002466};
2467
2468static PyObject *
Victor Stinner838f2642019-06-13 22:41:23 +02002469make_version_info(PyThreadState *tstate)
Eric Smith0e5b5622009-02-06 01:32:42 +00002470{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002471 PyObject *version_info;
2472 char *s;
2473 int pos = 0;
Eric Smith0e5b5622009-02-06 01:32:42 +00002474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002475 version_info = PyStructSequence_New(&VersionInfoType);
2476 if (version_info == NULL) {
2477 return NULL;
2478 }
Eric Smith0e5b5622009-02-06 01:32:42 +00002479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002480 /*
2481 * These release level checks are mutually exclusive and cover
2482 * the field, so don't get too fancy with the pre-processor!
2483 */
Eric Smith0e5b5622009-02-06 01:32:42 +00002484#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002485 s = "alpha";
Eric Smith0e5b5622009-02-06 01:32:42 +00002486#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002487 s = "beta";
Eric Smith0e5b5622009-02-06 01:32:42 +00002488#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002489 s = "candidate";
Eric Smith0e5b5622009-02-06 01:32:42 +00002490#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002491 s = "final";
Eric Smith0e5b5622009-02-06 01:32:42 +00002492#endif
2493
2494#define SetIntItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002495 PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002496#define SetStrItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002497 PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002499 SetIntItem(PY_MAJOR_VERSION);
2500 SetIntItem(PY_MINOR_VERSION);
2501 SetIntItem(PY_MICRO_VERSION);
2502 SetStrItem(s);
2503 SetIntItem(PY_RELEASE_SERIAL);
Eric Smith0e5b5622009-02-06 01:32:42 +00002504#undef SetIntItem
2505#undef SetStrItem
2506
Victor Stinner838f2642019-06-13 22:41:23 +02002507 if (_PyErr_Occurred(tstate)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002508 Py_CLEAR(version_info);
2509 return NULL;
2510 }
2511 return version_info;
Eric Smith0e5b5622009-02-06 01:32:42 +00002512}
2513
Brett Cannon3adc7b72012-07-09 14:22:12 -04002514/* sys.implementation values */
2515#define NAME "cpython"
2516const char *_PySys_ImplName = NAME;
Victor Stinnercf01b682015-11-05 11:21:38 +01002517#define MAJOR Py_STRINGIFY(PY_MAJOR_VERSION)
2518#define MINOR Py_STRINGIFY(PY_MINOR_VERSION)
Ned Deily529ea5d2014-06-30 23:31:14 -07002519#define TAG NAME "-" MAJOR MINOR
Brett Cannon3adc7b72012-07-09 14:22:12 -04002520const char *_PySys_ImplCacheTag = TAG;
2521#undef NAME
Brett Cannon3adc7b72012-07-09 14:22:12 -04002522#undef MAJOR
2523#undef MINOR
2524#undef TAG
2525
Barry Warsaw409da152012-06-03 16:18:47 -04002526static PyObject *
2527make_impl_info(PyObject *version_info)
2528{
2529 int res;
2530 PyObject *impl_info, *value, *ns;
2531
2532 impl_info = PyDict_New();
2533 if (impl_info == NULL)
2534 return NULL;
2535
2536 /* populate the dict */
2537
Brett Cannon3adc7b72012-07-09 14:22:12 -04002538 value = PyUnicode_FromString(_PySys_ImplName);
Barry Warsaw409da152012-06-03 16:18:47 -04002539 if (value == NULL)
2540 goto error;
2541 res = PyDict_SetItemString(impl_info, "name", value);
2542 Py_DECREF(value);
2543 if (res < 0)
2544 goto error;
2545
Brett Cannon3adc7b72012-07-09 14:22:12 -04002546 value = PyUnicode_FromString(_PySys_ImplCacheTag);
Barry Warsaw409da152012-06-03 16:18:47 -04002547 if (value == NULL)
2548 goto error;
2549 res = PyDict_SetItemString(impl_info, "cache_tag", value);
2550 Py_DECREF(value);
2551 if (res < 0)
2552 goto error;
Barry Warsaw409da152012-06-03 16:18:47 -04002553
2554 res = PyDict_SetItemString(impl_info, "version", version_info);
2555 if (res < 0)
2556 goto error;
2557
2558 value = PyLong_FromLong(PY_VERSION_HEX);
2559 if (value == NULL)
2560 goto error;
2561 res = PyDict_SetItemString(impl_info, "hexversion", value);
2562 Py_DECREF(value);
2563 if (res < 0)
2564 goto error;
2565
doko@ubuntu.com55532312016-06-14 08:55:19 +02002566#ifdef MULTIARCH
2567 value = PyUnicode_FromString(MULTIARCH);
2568 if (value == NULL)
2569 goto error;
2570 res = PyDict_SetItemString(impl_info, "_multiarch", value);
2571 Py_DECREF(value);
2572 if (res < 0)
2573 goto error;
2574#endif
2575
Barry Warsaw409da152012-06-03 16:18:47 -04002576 /* dict ready */
2577
2578 ns = _PyNamespace_New(impl_info);
2579 Py_DECREF(impl_info);
2580 return ns;
2581
2582error:
2583 Py_CLEAR(impl_info);
2584 return NULL;
2585}
2586
Martin v. Löwis1a214512008-06-11 05:26:20 +00002587static struct PyModuleDef sysmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002588 PyModuleDef_HEAD_INIT,
2589 "sys",
2590 sys_doc,
2591 -1, /* multiple "initialization" just copies the module dict. */
2592 sys_methods,
2593 NULL,
2594 NULL,
2595 NULL,
2596 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002597};
2598
Eric Snow6b4be192017-05-22 21:36:03 -07002599/* Updating the sys namespace, returning NULL pointer on error */
Victor Stinner8fea2522013-10-27 17:15:42 +01002600#define SET_SYS_FROM_STRING_BORROW(key, value) \
Victor Stinner58049602013-07-22 22:40:00 +02002601 do { \
Victor Stinner58049602013-07-22 22:40:00 +02002602 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002603 if (v == NULL) { \
2604 goto err_occurred; \
2605 } \
Victor Stinner58049602013-07-22 22:40:00 +02002606 res = PyDict_SetItemString(sysdict, key, v); \
2607 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002608 goto err_occurred; \
Victor Stinner8fea2522013-10-27 17:15:42 +01002609 } \
2610 } while (0)
2611#define SET_SYS_FROM_STRING(key, value) \
2612 do { \
Victor Stinner8fea2522013-10-27 17:15:42 +01002613 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002614 if (v == NULL) { \
2615 goto err_occurred; \
2616 } \
Victor Stinner8fea2522013-10-27 17:15:42 +01002617 res = PyDict_SetItemString(sysdict, key, v); \
2618 Py_DECREF(v); \
2619 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002620 goto err_occurred; \
Victor Stinner58049602013-07-22 22:40:00 +02002621 } \
2622 } while (0)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002623
Victor Stinner331a6a52019-05-27 16:39:22 +02002624static PyStatus
Victor Stinner01b1cc12019-11-20 02:27:56 +01002625_PySys_InitCore(PyThreadState *tstate, PyObject *sysdict)
Eric Snow6b4be192017-05-22 21:36:03 -07002626{
Victor Stinnerab672812019-01-23 15:04:40 +01002627 PyObject *version_info;
Eric Snow6b4be192017-05-22 21:36:03 -07002628 int res;
2629
Nick Coghland6009512014-11-20 21:39:37 +10002630 /* stdin/stdout/stderr are set in pylifecycle.c */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002631
Victor Stinner8fea2522013-10-27 17:15:42 +01002632 SET_SYS_FROM_STRING_BORROW("__displayhook__",
2633 PyDict_GetItemString(sysdict, "displayhook"));
2634 SET_SYS_FROM_STRING_BORROW("__excepthook__",
2635 PyDict_GetItemString(sysdict, "excepthook"));
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04002636 SET_SYS_FROM_STRING_BORROW(
2637 "__breakpointhook__",
2638 PyDict_GetItemString(sysdict, "breakpointhook"));
Victor Stinneref9d9b62019-05-22 11:28:22 +02002639 SET_SYS_FROM_STRING_BORROW("__unraisablehook__",
2640 PyDict_GetItemString(sysdict, "unraisablehook"));
2641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002642 SET_SYS_FROM_STRING("version",
2643 PyUnicode_FromString(Py_GetVersion()));
2644 SET_SYS_FROM_STRING("hexversion",
2645 PyLong_FromLong(PY_VERSION_HEX));
Ned Deily5c4b0d02017-03-04 00:19:55 -05002646 SET_SYS_FROM_STRING("_git",
2647 Py_BuildValue("(szz)", "CPython", _Py_gitidentifier(),
2648 _Py_gitversion()));
INADA Naoki6b42eb12017-06-29 15:31:38 +09002649 SET_SYS_FROM_STRING("_framework", PyUnicode_FromString(_PYTHONFRAMEWORK));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002650 SET_SYS_FROM_STRING("api_version",
2651 PyLong_FromLong(PYTHON_API_VERSION));
2652 SET_SYS_FROM_STRING("copyright",
2653 PyUnicode_FromString(Py_GetCopyright()));
2654 SET_SYS_FROM_STRING("platform",
2655 PyUnicode_FromString(Py_GetPlatform()));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002656 SET_SYS_FROM_STRING("maxsize",
2657 PyLong_FromSsize_t(PY_SSIZE_T_MAX));
2658 SET_SYS_FROM_STRING("float_info",
2659 PyFloat_GetInfo());
2660 SET_SYS_FROM_STRING("int_info",
2661 PyLong_GetInfo());
Mark Dickinsondc787d22010-05-23 13:33:13 +00002662 /* initialize hash_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002663 if (Hash_InfoType.tp_name == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002664 if (PyStructSequence_InitType2(&Hash_InfoType, &hash_info_desc) < 0) {
2665 goto type_init_failed;
2666 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002667 }
Mark Dickinsondc787d22010-05-23 13:33:13 +00002668 SET_SYS_FROM_STRING("hash_info",
Victor Stinner838f2642019-06-13 22:41:23 +02002669 get_hash_info(tstate));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002670 SET_SYS_FROM_STRING("maxunicode",
Ezio Melotti48a2f8f2011-09-29 00:18:19 +03002671 PyLong_FromLong(0x10FFFF));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002672 SET_SYS_FROM_STRING("builtin_module_names",
2673 list_builtin_module_names());
Christian Heimes743e0cd2012-10-17 23:52:17 +02002674#if PY_BIG_ENDIAN
2675 SET_SYS_FROM_STRING("byteorder",
2676 PyUnicode_FromString("big"));
2677#else
2678 SET_SYS_FROM_STRING("byteorder",
2679 PyUnicode_FromString("little"));
2680#endif
Fred Drake099325e2000-08-14 15:47:03 +00002681
Guido van Rossum8b9ea871996-08-23 18:14:47 +00002682#ifdef MS_COREDLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002683 SET_SYS_FROM_STRING("dllhandle",
2684 PyLong_FromVoidPtr(PyWin_DLLhModule));
2685 SET_SYS_FROM_STRING("winver",
2686 PyUnicode_FromString(PyWin_DLLVersionString));
Guido van Rossumc606fe11996-04-09 02:37:57 +00002687#endif
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00002688#ifdef ABIFLAGS
2689 SET_SYS_FROM_STRING("abiflags",
2690 PyUnicode_FromString(ABIFLAGS));
2691#endif
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002693 /* version_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002694 if (VersionInfoType.tp_name == NULL) {
2695 if (PyStructSequence_InitType2(&VersionInfoType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002696 &version_info_desc) < 0) {
2697 goto type_init_failed;
2698 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002699 }
Victor Stinner838f2642019-06-13 22:41:23 +02002700 version_info = make_version_info(tstate);
Barry Warsaw409da152012-06-03 16:18:47 -04002701 SET_SYS_FROM_STRING("version_info", version_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002702 /* prevent user from creating new instances */
2703 VersionInfoType.tp_init = NULL;
2704 VersionInfoType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002705 res = PyDict_DelItemString(VersionInfoType.tp_dict, "__new__");
Victor Stinner838f2642019-06-13 22:41:23 +02002706 if (res < 0 && _PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
2707 _PyErr_Clear(tstate);
2708 }
Eric Smith0e5b5622009-02-06 01:32:42 +00002709
Barry Warsaw409da152012-06-03 16:18:47 -04002710 /* implementation */
2711 SET_SYS_FROM_STRING("implementation", make_impl_info(version_info));
2712
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002713 /* flags */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002714 if (FlagsType.tp_name == 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002715 if (PyStructSequence_InitType2(&FlagsType, &flags_desc) < 0) {
2716 goto type_init_failed;
2717 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002718 }
Victor Stinner43125222019-04-24 18:23:53 +02002719 /* Set flags to their default values (updated by _PySys_InitMain()) */
Victor Stinner01b1cc12019-11-20 02:27:56 +01002720 SET_SYS_FROM_STRING("flags", make_flags(tstate));
Eric Smithf7bb5782010-01-27 00:44:57 +00002721
2722#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002723 /* getwindowsversion */
2724 if (WindowsVersionType.tp_name == 0)
Victor Stinner1c8f0592013-07-22 22:24:54 +02002725 if (PyStructSequence_InitType2(&WindowsVersionType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002726 &windows_version_desc) < 0) {
2727 goto type_init_failed;
2728 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002729 /* prevent user from creating new instances */
2730 WindowsVersionType.tp_init = NULL;
2731 WindowsVersionType.tp_new = NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02002732 assert(!_PyErr_Occurred(tstate));
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002733 res = PyDict_DelItemString(WindowsVersionType.tp_dict, "__new__");
Victor Stinner838f2642019-06-13 22:41:23 +02002734 if (res < 0 && _PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
2735 _PyErr_Clear(tstate);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002736 }
Eric Smithf7bb5782010-01-27 00:44:57 +00002737#endif
2738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002739 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002740#ifndef PY_NO_SHORT_FLOAT_REPR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002741 SET_SYS_FROM_STRING("float_repr_style",
2742 PyUnicode_FromString("short"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002743#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002744 SET_SYS_FROM_STRING("float_repr_style",
2745 PyUnicode_FromString("legacy"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002746#endif
2747
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002748 SET_SYS_FROM_STRING("thread_info", PyThread_GetInfo());
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002749
Yury Selivanoveb636452016-09-08 22:01:51 -07002750 /* initialize asyncgen_hooks */
2751 if (AsyncGenHooksType.tp_name == NULL) {
2752 if (PyStructSequence_InitType2(
2753 &AsyncGenHooksType, &asyncgen_hooks_desc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002754 goto type_init_failed;
Yury Selivanoveb636452016-09-08 22:01:51 -07002755 }
2756 }
2757
Victor Stinner838f2642019-06-13 22:41:23 +02002758 if (_PyErr_Occurred(tstate)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002759 goto err_occurred;
2760 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002761 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002762
2763type_init_failed:
Victor Stinner331a6a52019-05-27 16:39:22 +02002764 return _PyStatus_ERR("failed to initialize a type");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002765
2766err_occurred:
Victor Stinner331a6a52019-05-27 16:39:22 +02002767 return _PyStatus_ERR("can't initialize sys module");
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002768}
2769
Eric Snow6b4be192017-05-22 21:36:03 -07002770/* Updating the sys namespace, returning integer error codes */
Eric Snow6b4be192017-05-22 21:36:03 -07002771#define SET_SYS_FROM_STRING_INT_RESULT(key, value) \
2772 do { \
2773 PyObject *v = (value); \
2774 if (v == NULL) \
2775 return -1; \
2776 res = PyDict_SetItemString(sysdict, key, v); \
2777 Py_DECREF(v); \
2778 if (res < 0) { \
2779 return res; \
2780 } \
2781 } while (0)
2782
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002783
2784static int
2785sys_add_xoption(PyObject *opts, const wchar_t *s)
2786{
2787 PyObject *name, *value;
2788
2789 const wchar_t *name_end = wcschr(s, L'=');
2790 if (!name_end) {
2791 name = PyUnicode_FromWideChar(s, -1);
2792 value = Py_True;
2793 Py_INCREF(value);
2794 }
2795 else {
2796 name = PyUnicode_FromWideChar(s, name_end - s);
2797 value = PyUnicode_FromWideChar(name_end + 1, -1);
2798 }
2799 if (name == NULL || value == NULL) {
2800 goto error;
2801 }
2802 if (PyDict_SetItem(opts, name, value) < 0) {
2803 goto error;
2804 }
2805 Py_DECREF(name);
2806 Py_DECREF(value);
2807 return 0;
2808
2809error:
2810 Py_XDECREF(name);
2811 Py_XDECREF(value);
2812 return -1;
2813}
2814
2815
2816static PyObject*
Victor Stinner331a6a52019-05-27 16:39:22 +02002817sys_create_xoptions_dict(const PyConfig *config)
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002818{
2819 Py_ssize_t nxoption = config->xoptions.length;
2820 wchar_t * const * xoptions = config->xoptions.items;
2821 PyObject *dict = PyDict_New();
2822 if (dict == NULL) {
2823 return NULL;
2824 }
2825
2826 for (Py_ssize_t i=0; i < nxoption; i++) {
2827 const wchar_t *option = xoptions[i];
2828 if (sys_add_xoption(dict, option) < 0) {
2829 Py_DECREF(dict);
2830 return NULL;
2831 }
2832 }
2833
2834 return dict;
2835}
2836
2837
Eric Snow6b4be192017-05-22 21:36:03 -07002838int
Victor Stinner01b1cc12019-11-20 02:27:56 +01002839_PySys_InitMain(PyThreadState *tstate)
Eric Snow6b4be192017-05-22 21:36:03 -07002840{
Victor Stinner838f2642019-06-13 22:41:23 +02002841 PyObject *sysdict = tstate->interp->sysdict;
2842 const PyConfig *config = &tstate->interp->config;
Eric Snow6b4be192017-05-22 21:36:03 -07002843 int res;
2844
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002845#define COPY_LIST(KEY, VALUE) \
Victor Stinner37cd9822018-11-16 11:55:35 +01002846 do { \
Victor Stinner331a6a52019-05-27 16:39:22 +02002847 PyObject *list = _PyWideStringList_AsList(&(VALUE)); \
Victor Stinner37cd9822018-11-16 11:55:35 +01002848 if (list == NULL) { \
2849 return -1; \
2850 } \
2851 SET_SYS_FROM_STRING_BORROW(KEY, list); \
2852 Py_DECREF(list); \
2853 } while (0)
2854
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002855#define SET_SYS_FROM_WSTR(KEY, VALUE) \
2856 do { \
2857 PyObject *str = PyUnicode_FromWideChar(VALUE, -1); \
2858 if (str == NULL) { \
2859 return -1; \
2860 } \
2861 SET_SYS_FROM_STRING_BORROW(KEY, str); \
2862 Py_DECREF(str); \
2863 } while (0)
Victor Stinner37cd9822018-11-16 11:55:35 +01002864
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002865 COPY_LIST("path", config->module_search_paths);
2866
2867 SET_SYS_FROM_WSTR("executable", config->executable);
Steve Dower9048c492019-06-29 10:34:11 -07002868 SET_SYS_FROM_WSTR("_base_executable", config->base_executable);
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002869 SET_SYS_FROM_WSTR("prefix", config->prefix);
2870 SET_SYS_FROM_WSTR("base_prefix", config->base_prefix);
2871 SET_SYS_FROM_WSTR("exec_prefix", config->exec_prefix);
2872 SET_SYS_FROM_WSTR("base_exec_prefix", config->base_exec_prefix);
Victor Stinner8510f432020-03-10 09:53:09 +01002873 {
2874 PyObject *str = PyUnicode_FromString(PLATLIBDIR);
2875 if (str == NULL) {
2876 return -1;
2877 }
2878 SET_SYS_FROM_STRING("platlibdir", str);
2879 }
Victor Stinner41264f12017-12-15 02:05:29 +01002880
Carl Meyerb193fa92018-06-15 22:40:56 -06002881 if (config->pycache_prefix != NULL) {
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002882 SET_SYS_FROM_WSTR("pycache_prefix", config->pycache_prefix);
Carl Meyerb193fa92018-06-15 22:40:56 -06002883 } else {
2884 PyDict_SetItemString(sysdict, "pycache_prefix", Py_None);
2885 }
2886
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002887 COPY_LIST("argv", config->argv);
2888 COPY_LIST("warnoptions", config->warnoptions);
2889
2890 PyObject *xoptions = sys_create_xoptions_dict(config);
2891 if (xoptions == NULL) {
2892 return -1;
Victor Stinner41264f12017-12-15 02:05:29 +01002893 }
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002894 SET_SYS_FROM_STRING_BORROW("_xoptions", xoptions);
Pablo Galindo34ef64f2019-03-27 12:43:47 +00002895 Py_DECREF(xoptions);
Victor Stinner41264f12017-12-15 02:05:29 +01002896
Victor Stinner37cd9822018-11-16 11:55:35 +01002897#undef COPY_LIST
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002898#undef SET_SYS_FROM_WSTR
Victor Stinner37cd9822018-11-16 11:55:35 +01002899
Victor Stinner8510f432020-03-10 09:53:09 +01002900
Eric Snow6b4be192017-05-22 21:36:03 -07002901 /* Set flags to their final values */
Victor Stinner01b1cc12019-11-20 02:27:56 +01002902 SET_SYS_FROM_STRING_INT_RESULT("flags", make_flags(tstate));
Eric Snow6b4be192017-05-22 21:36:03 -07002903 /* prevent user from creating new instances */
2904 FlagsType.tp_init = NULL;
2905 FlagsType.tp_new = NULL;
2906 res = PyDict_DelItemString(FlagsType.tp_dict, "__new__");
2907 if (res < 0) {
Victor Stinner838f2642019-06-13 22:41:23 +02002908 if (!_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
Eric Snow6b4be192017-05-22 21:36:03 -07002909 return res;
2910 }
Victor Stinner838f2642019-06-13 22:41:23 +02002911 _PyErr_Clear(tstate);
Eric Snow6b4be192017-05-22 21:36:03 -07002912 }
2913
2914 SET_SYS_FROM_STRING_INT_RESULT("dont_write_bytecode",
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002915 PyBool_FromLong(!config->write_bytecode));
Eric Snow6b4be192017-05-22 21:36:03 -07002916
Victor Stinner838f2642019-06-13 22:41:23 +02002917 if (get_warnoptions(tstate) == NULL) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002918 return -1;
Victor Stinner838f2642019-06-13 22:41:23 +02002919 }
Victor Stinner865de272017-06-08 13:27:47 +02002920
Victor Stinner838f2642019-06-13 22:41:23 +02002921 if (get_xoptions(tstate) == NULL)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002922 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002923
Victor Stinner838f2642019-06-13 22:41:23 +02002924 if (_PyErr_Occurred(tstate)) {
2925 goto err_occurred;
2926 }
2927
Eric Snow6b4be192017-05-22 21:36:03 -07002928 return 0;
Victor Stinner41264f12017-12-15 02:05:29 +01002929
2930err_occurred:
2931 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002932}
2933
Victor Stinner8510f432020-03-10 09:53:09 +01002934#undef SET_SYS_FROM_STRING
Victor Stinner41264f12017-12-15 02:05:29 +01002935#undef SET_SYS_FROM_STRING_BORROW
Eric Snow6b4be192017-05-22 21:36:03 -07002936#undef SET_SYS_FROM_STRING_INT_RESULT
Eric Snow6b4be192017-05-22 21:36:03 -07002937
Victor Stinnerab672812019-01-23 15:04:40 +01002938
2939/* Set up a preliminary stderr printer until we have enough
2940 infrastructure for the io module in place.
2941
2942 Use UTF-8/surrogateescape and ignore EAGAIN errors. */
Victor Stinner81fe5bd2019-12-06 02:43:30 +01002943static PyStatus
Victor Stinnerab672812019-01-23 15:04:40 +01002944_PySys_SetPreliminaryStderr(PyObject *sysdict)
2945{
2946 PyObject *pstderr = PyFile_NewStdPrinter(fileno(stderr));
2947 if (pstderr == NULL) {
2948 goto error;
2949 }
2950 if (_PyDict_SetItemId(sysdict, &PyId_stderr, pstderr) < 0) {
2951 goto error;
2952 }
2953 if (PyDict_SetItemString(sysdict, "__stderr__", pstderr) < 0) {
2954 goto error;
2955 }
2956 Py_DECREF(pstderr);
Victor Stinner331a6a52019-05-27 16:39:22 +02002957 return _PyStatus_OK();
Victor Stinnerab672812019-01-23 15:04:40 +01002958
2959error:
2960 Py_XDECREF(pstderr);
Victor Stinner331a6a52019-05-27 16:39:22 +02002961 return _PyStatus_ERR("can't set preliminary stderr");
Victor Stinnerab672812019-01-23 15:04:40 +01002962}
2963
2964
2965/* Create sys module without all attributes: _PySys_InitMain() should be called
2966 later to add remaining attributes. */
Victor Stinner331a6a52019-05-27 16:39:22 +02002967PyStatus
Victor Stinner01b1cc12019-11-20 02:27:56 +01002968_PySys_Create(PyThreadState *tstate, PyObject **sysmod_p)
Victor Stinnerab672812019-01-23 15:04:40 +01002969{
Victor Stinner81fe5bd2019-12-06 02:43:30 +01002970 assert(!_PyErr_Occurred(tstate));
2971
Victor Stinnerb45d2592019-06-20 00:05:23 +02002972 PyInterpreterState *interp = tstate->interp;
Victor Stinner838f2642019-06-13 22:41:23 +02002973
Victor Stinnerab672812019-01-23 15:04:40 +01002974 PyObject *modules = PyDict_New();
2975 if (modules == NULL) {
Victor Stinner81fe5bd2019-12-06 02:43:30 +01002976 goto error;
Victor Stinnerab672812019-01-23 15:04:40 +01002977 }
2978 interp->modules = modules;
2979
2980 PyObject *sysmod = _PyModule_CreateInitialized(&sysmodule, PYTHON_API_VERSION);
2981 if (sysmod == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002982 return _PyStatus_ERR("failed to create a module object");
Victor Stinnerab672812019-01-23 15:04:40 +01002983 }
2984
2985 PyObject *sysdict = PyModule_GetDict(sysmod);
2986 if (sysdict == NULL) {
Victor Stinner81fe5bd2019-12-06 02:43:30 +01002987 goto error;
Victor Stinnerab672812019-01-23 15:04:40 +01002988 }
2989 Py_INCREF(sysdict);
2990 interp->sysdict = sysdict;
2991
2992 if (PyDict_SetItemString(sysdict, "modules", interp->modules) < 0) {
Victor Stinner81fe5bd2019-12-06 02:43:30 +01002993 goto error;
Victor Stinnerab672812019-01-23 15:04:40 +01002994 }
2995
Victor Stinner331a6a52019-05-27 16:39:22 +02002996 PyStatus status = _PySys_SetPreliminaryStderr(sysdict);
2997 if (_PyStatus_EXCEPTION(status)) {
2998 return status;
Victor Stinnerab672812019-01-23 15:04:40 +01002999 }
3000
Victor Stinner01b1cc12019-11-20 02:27:56 +01003001 status = _PySys_InitCore(tstate, sysdict);
Victor Stinner331a6a52019-05-27 16:39:22 +02003002 if (_PyStatus_EXCEPTION(status)) {
3003 return status;
Victor Stinnerab672812019-01-23 15:04:40 +01003004 }
3005
Victor Stinner81fe5bd2019-12-06 02:43:30 +01003006 if (_PyImport_FixupBuiltin(sysmod, "sys", interp->modules) < 0) {
3007 goto error;
3008 }
3009
3010 assert(!_PyErr_Occurred(tstate));
Victor Stinnerab672812019-01-23 15:04:40 +01003011
3012 *sysmod_p = sysmod;
Victor Stinner331a6a52019-05-27 16:39:22 +02003013 return _PyStatus_OK();
Victor Stinner81fe5bd2019-12-06 02:43:30 +01003014
3015error:
3016 return _PyStatus_ERR("can't initialize sys module");
Victor Stinnerab672812019-01-23 15:04:40 +01003017}
3018
3019
Guido van Rossum65bf9f21997-04-29 18:33:38 +00003020static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00003021makepathobject(const wchar_t *path, wchar_t delim)
Guido van Rossum5b3138b1990-11-18 17:41:40 +00003022{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003023 int i, n;
3024 const wchar_t *p;
3025 PyObject *v, *w;
Tim Peters216b78b2006-01-06 02:40:53 +00003026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003027 n = 1;
3028 p = path;
3029 while ((p = wcschr(p, delim)) != NULL) {
3030 n++;
3031 p++;
3032 }
3033 v = PyList_New(n);
3034 if (v == NULL)
3035 return NULL;
3036 for (i = 0; ; i++) {
3037 p = wcschr(path, delim);
3038 if (p == NULL)
3039 p = path + wcslen(path); /* End of string */
3040 w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
3041 if (w == NULL) {
3042 Py_DECREF(v);
3043 return NULL;
3044 }
Zackery Spytz99d56b52018-12-08 07:16:55 -07003045 PyList_SET_ITEM(v, i, w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003046 if (*p == '\0')
3047 break;
3048 path = p+1;
3049 }
3050 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003051}
3052
3053void
Martin v. Löwis790465f2008-04-05 20:41:37 +00003054PySys_SetPath(const wchar_t *path)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003055{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003056 PyObject *v;
3057 if ((v = makepathobject(path, DELIM)) == NULL)
3058 Py_FatalError("can't create sys.path");
Victor Stinner838f2642019-06-13 22:41:23 +02003059 PyThreadState *tstate = _PyThreadState_GET();
3060 if (sys_set_object_id(tstate, &PyId_path, v) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003061 Py_FatalError("can't assign sys.path");
Victor Stinner838f2642019-06-13 22:41:23 +02003062 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003063 Py_DECREF(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00003064}
3065
Guido van Rossum65bf9f21997-04-29 18:33:38 +00003066static PyObject *
Victor Stinner74f65682019-03-15 15:08:05 +01003067make_sys_argv(int argc, wchar_t * const * argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00003068{
Victor Stinner74f65682019-03-15 15:08:05 +01003069 PyObject *list = PyList_New(argc);
3070 if (list == NULL) {
3071 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003072 }
Victor Stinner74f65682019-03-15 15:08:05 +01003073
3074 for (Py_ssize_t i = 0; i < argc; i++) {
3075 PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
3076 if (v == NULL) {
3077 Py_DECREF(list);
3078 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003079 }
Victor Stinner74f65682019-03-15 15:08:05 +01003080 PyList_SET_ITEM(list, i, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003081 }
Victor Stinner74f65682019-03-15 15:08:05 +01003082 return list;
Guido van Rossum3f5da241990-12-20 15:06:42 +00003083}
3084
Victor Stinner11a247d2017-12-13 21:05:57 +01003085void
3086PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
Victor Stinnerd5dda982017-12-13 17:31:16 +01003087{
Victor Stinnerc4868252019-08-23 11:04:16 +01003088 wchar_t* empty_argv[1] = {L""};
Victor Stinner838f2642019-06-13 22:41:23 +02003089 PyThreadState *tstate = _PyThreadState_GET();
3090
Victor Stinner74f65682019-03-15 15:08:05 +01003091 if (argc < 1 || argv == NULL) {
3092 /* Ensure at least one (empty) argument is seen */
Victor Stinner74f65682019-03-15 15:08:05 +01003093 argv = empty_argv;
3094 argc = 1;
3095 }
3096
3097 PyObject *av = make_sys_argv(argc, argv);
Victor Stinnerd5dda982017-12-13 17:31:16 +01003098 if (av == NULL) {
Victor Stinner11a247d2017-12-13 21:05:57 +01003099 Py_FatalError("no mem for sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01003100 }
Victor Stinner838f2642019-06-13 22:41:23 +02003101 if (sys_set_object(tstate, "argv", av) != 0) {
Victor Stinnerd5dda982017-12-13 17:31:16 +01003102 Py_DECREF(av);
Victor Stinner11a247d2017-12-13 21:05:57 +01003103 Py_FatalError("can't assign sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01003104 }
3105 Py_DECREF(av);
3106
3107 if (updatepath) {
3108 /* If argv[0] is not '-c' nor '-m', prepend argv[0] to sys.path.
3109 If argv[0] is a symlink, use the real path. */
Victor Stinner331a6a52019-05-27 16:39:22 +02003110 const PyWideStringList argv_list = {.length = argc, .items = argv};
Victor Stinnerdcf61712019-03-19 16:09:27 +01003111 PyObject *path0 = NULL;
3112 if (_PyPathConfig_ComputeSysPath0(&argv_list, &path0)) {
3113 if (path0 == NULL) {
3114 Py_FatalError("can't compute path0 from argv");
Victor Stinner11a247d2017-12-13 21:05:57 +01003115 }
Victor Stinnerdcf61712019-03-19 16:09:27 +01003116
Victor Stinner838f2642019-06-13 22:41:23 +02003117 PyObject *sys_path = sys_get_object_id(tstate, &PyId_path);
Victor Stinnerdcf61712019-03-19 16:09:27 +01003118 if (sys_path != NULL) {
3119 if (PyList_Insert(sys_path, 0, path0) < 0) {
3120 Py_DECREF(path0);
3121 Py_FatalError("can't prepend path0 to sys.path");
3122 }
3123 }
3124 Py_DECREF(path0);
Victor Stinner11a247d2017-12-13 21:05:57 +01003125 }
Victor Stinnerd5dda982017-12-13 17:31:16 +01003126 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003127}
Guido van Rossuma890e681998-05-12 14:59:24 +00003128
Antoine Pitrouf978fac2010-05-21 17:25:34 +00003129void
3130PySys_SetArgv(int argc, wchar_t **argv)
3131{
Christian Heimesad73a9c2013-08-10 16:36:18 +02003132 PySys_SetArgvEx(argc, argv, Py_IsolatedFlag == 0);
Antoine Pitrouf978fac2010-05-21 17:25:34 +00003133}
3134
Victor Stinner14284c22010-04-23 12:02:30 +00003135/* Reimplementation of PyFile_WriteString() no calling indirectly
3136 PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
3137
3138static int
Victor Stinner79766632010-08-16 17:36:42 +00003139sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
Victor Stinner14284c22010-04-23 12:02:30 +00003140{
Victor Stinnerecccc4f2010-06-08 20:46:00 +00003141 if (file == NULL)
3142 return -1;
Jeroen Demeyerb1263d52019-06-28 11:49:00 +02003143 assert(unicode != NULL);
Jeroen Demeyer59ad1102019-07-11 10:59:05 +02003144 PyObject *result = _PyObject_CallMethodIdOneArg(file, &PyId_write, unicode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003145 if (result == NULL) {
Jeroen Demeyerb1263d52019-06-28 11:49:00 +02003146 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003147 }
Jeroen Demeyerb1263d52019-06-28 11:49:00 +02003148 Py_DECREF(result);
3149 return 0;
Victor Stinner14284c22010-04-23 12:02:30 +00003150}
3151
Victor Stinner79766632010-08-16 17:36:42 +00003152static int
3153sys_pyfile_write(const char *text, PyObject *file)
3154{
3155 PyObject *unicode = NULL;
3156 int err;
3157
3158 if (file == NULL)
3159 return -1;
3160
3161 unicode = PyUnicode_FromString(text);
3162 if (unicode == NULL)
3163 return -1;
3164
3165 err = sys_pyfile_write_unicode(unicode, file);
3166 Py_DECREF(unicode);
3167 return err;
3168}
Guido van Rossuma890e681998-05-12 14:59:24 +00003169
3170/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
3171 Adapted from code submitted by Just van Rossum.
3172
3173 PySys_WriteStdout(format, ...)
3174 PySys_WriteStderr(format, ...)
3175
3176 The first function writes to sys.stdout; the second to sys.stderr. When
3177 there is a problem, they write to the real (C level) stdout or stderr;
Guido van Rossum8442af31998-10-12 18:22:10 +00003178 no exceptions are raised.
Guido van Rossuma890e681998-05-12 14:59:24 +00003179
Victor Stinner14284c22010-04-23 12:02:30 +00003180 PyErr_CheckSignals() is not called to avoid the execution of the Python
Victor Stinner79766632010-08-16 17:36:42 +00003181 signal handlers: they may raise a new exception whereas sys_write()
3182 ignores all exceptions.
Victor Stinner14284c22010-04-23 12:02:30 +00003183
Guido van Rossuma890e681998-05-12 14:59:24 +00003184 Both take a printf-style format string as their first argument followed
3185 by a variable length argument list determined by the format string.
3186
3187 *** WARNING ***
3188
3189 The format should limit the total size of the formatted output string to
3190 1000 bytes. In particular, this means that no unrestricted "%s" formats
3191 should occur; these should be limited using "%.<N>s where <N> is a
3192 decimal number calculated so that <N> plus the maximum size of other
3193 formatted text does not exceed 1000 bytes. Also watch out for "%f",
3194 which can print hundreds of digits for very large numbers.
3195
3196 */
3197
3198static void
Victor Stinner09054372013-11-06 22:41:44 +01003199sys_write(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Guido van Rossuma890e681998-05-12 14:59:24 +00003200{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003201 PyObject *file;
3202 PyObject *error_type, *error_value, *error_traceback;
3203 char buffer[1001];
3204 int written;
Victor Stinner838f2642019-06-13 22:41:23 +02003205 PyThreadState *tstate = _PyThreadState_GET();
Guido van Rossuma890e681998-05-12 14:59:24 +00003206
Victor Stinner838f2642019-06-13 22:41:23 +02003207 _PyErr_Fetch(tstate, &error_type, &error_value, &error_traceback);
3208 file = sys_get_object_id(tstate, key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003209 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
3210 if (sys_pyfile_write(buffer, file) != 0) {
Victor Stinner838f2642019-06-13 22:41:23 +02003211 _PyErr_Clear(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003212 fputs(buffer, fp);
3213 }
3214 if (written < 0 || (size_t)written >= sizeof(buffer)) {
3215 const char *truncated = "... truncated";
Victor Stinner79766632010-08-16 17:36:42 +00003216 if (sys_pyfile_write(truncated, file) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003217 fputs(truncated, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003218 }
Victor Stinner838f2642019-06-13 22:41:23 +02003219 _PyErr_Restore(tstate, error_type, error_value, error_traceback);
Guido van Rossuma890e681998-05-12 14:59:24 +00003220}
3221
3222void
Guido van Rossuma890e681998-05-12 14:59:24 +00003223PySys_WriteStdout(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00003224{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003225 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00003226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003227 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003228 sys_write(&PyId_stdout, stdout, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003229 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00003230}
3231
3232void
Guido van Rossuma890e681998-05-12 14:59:24 +00003233PySys_WriteStderr(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00003234{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003235 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00003236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003237 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003238 sys_write(&PyId_stderr, stderr, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00003239 va_end(va);
3240}
3241
3242static void
Victor Stinner09054372013-11-06 22:41:44 +01003243sys_format(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Victor Stinner79766632010-08-16 17:36:42 +00003244{
3245 PyObject *file, *message;
3246 PyObject *error_type, *error_value, *error_traceback;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02003247 const char *utf8;
Victor Stinner838f2642019-06-13 22:41:23 +02003248 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner79766632010-08-16 17:36:42 +00003249
Victor Stinner838f2642019-06-13 22:41:23 +02003250 _PyErr_Fetch(tstate, &error_type, &error_value, &error_traceback);
3251 file = sys_get_object_id(tstate, key);
Victor Stinner79766632010-08-16 17:36:42 +00003252 message = PyUnicode_FromFormatV(format, va);
3253 if (message != NULL) {
3254 if (sys_pyfile_write_unicode(message, file) != 0) {
Victor Stinner838f2642019-06-13 22:41:23 +02003255 _PyErr_Clear(tstate);
Serhiy Storchaka06515832016-11-20 09:13:07 +02003256 utf8 = PyUnicode_AsUTF8(message);
Victor Stinner79766632010-08-16 17:36:42 +00003257 if (utf8 != NULL)
3258 fputs(utf8, fp);
3259 }
3260 Py_DECREF(message);
3261 }
Victor Stinner838f2642019-06-13 22:41:23 +02003262 _PyErr_Restore(tstate, error_type, error_value, error_traceback);
Victor Stinner79766632010-08-16 17:36:42 +00003263}
3264
3265void
3266PySys_FormatStdout(const char *format, ...)
3267{
3268 va_list va;
3269
3270 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003271 sys_format(&PyId_stdout, stdout, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00003272 va_end(va);
3273}
3274
3275void
3276PySys_FormatStderr(const char *format, ...)
3277{
3278 va_list va;
3279
3280 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003281 sys_format(&PyId_stderr, stderr, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003282 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00003283}