blob: 8da839c5a592ecf02c488cc59c7a5a20c3263fb7 [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);
184 eventArgs = Py_VaBuildValue(argFormat, args);
185 if (eventArgs && !PyTuple_Check(eventArgs)) {
186 PyObject *argTuple = PyTuple_Pack(1, eventArgs);
187 Py_DECREF(eventArgs);
188 eventArgs = argTuple;
189 }
190 } else {
191 eventArgs = PyTuple_New(0);
192 }
193 if (!eventArgs) {
194 goto exit;
195 }
196
197 /* Call global hooks */
198 for (; e; e = e->next) {
199 if (e->hookCFunction(event, eventArgs, e->userData) < 0) {
200 goto exit;
201 }
202 }
203
204 /* Dtrace USDT point */
205 if (dtrace) {
206 PyDTrace_AUDIT(event, (void *)eventArgs);
207 }
208
209 /* Call interpreter hooks */
Victor Stinner838f2642019-06-13 22:41:23 +0200210 PyInterpreterState *is = ts ? ts->interp : NULL;
Steve Dowerb82e17e2019-05-23 08:45:22 -0700211 if (is && is->audit_hooks) {
212 eventName = PyUnicode_FromString(event);
213 if (!eventName) {
214 goto exit;
215 }
216
217 hooks = PyObject_GetIter(is->audit_hooks);
218 if (!hooks) {
219 goto exit;
220 }
221
222 /* Disallow tracing in hooks unless explicitly enabled */
223 ts->tracing++;
224 ts->use_tracing = 0;
225 while ((hook = PyIter_Next(hooks)) != NULL) {
226 PyObject *o;
227 int canTrace = -1;
228 o = PyObject_GetAttrString(hook, "__cantrace__");
229 if (o) {
230 canTrace = PyObject_IsTrue(o);
231 Py_DECREF(o);
Victor Stinner838f2642019-06-13 22:41:23 +0200232 } else if (_PyErr_Occurred(ts) &&
233 _PyErr_ExceptionMatches(ts, PyExc_AttributeError)) {
234 _PyErr_Clear(ts);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700235 canTrace = 0;
236 }
237 if (canTrace < 0) {
238 break;
239 }
240 if (canTrace) {
241 ts->use_tracing = (ts->c_tracefunc || ts->c_profilefunc);
242 ts->tracing--;
243 }
244 o = PyObject_CallFunctionObjArgs(hook, eventName,
245 eventArgs, NULL);
246 if (canTrace) {
247 ts->tracing++;
248 ts->use_tracing = 0;
249 }
250 if (!o) {
251 break;
252 }
253 Py_DECREF(o);
254 Py_CLEAR(hook);
255 }
256 ts->use_tracing = (ts->c_tracefunc || ts->c_profilefunc);
257 ts->tracing--;
Victor Stinner838f2642019-06-13 22:41:23 +0200258 if (_PyErr_Occurred(ts)) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700259 goto exit;
260 }
261 }
262
263 res = 0;
264
265exit:
266 Py_XDECREF(hook);
267 Py_XDECREF(hooks);
268 Py_XDECREF(eventName);
269 Py_XDECREF(eventArgs);
270
271 if (ts) {
272 if (!res) {
Victor Stinner838f2642019-06-13 22:41:23 +0200273 _PyErr_Restore(ts, exc_type, exc_value, exc_tb);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700274 } else {
Victor Stinner838f2642019-06-13 22:41:23 +0200275 assert(_PyErr_Occurred(ts));
Steve Dowerb82e17e2019-05-23 08:45:22 -0700276 Py_XDECREF(exc_type);
277 Py_XDECREF(exc_value);
278 Py_XDECREF(exc_tb);
279 }
280 }
281
282 return res;
283}
284
285/* We expose this function primarily for our own cleanup during
286 * finalization. In general, it should not need to be called,
287 * and as such it is not defined in any header files.
288 */
Victor Stinner838f2642019-06-13 22:41:23 +0200289void
290_PySys_ClearAuditHooks(void)
291{
Steve Dowerb82e17e2019-05-23 08:45:22 -0700292 /* Must be finalizing to clear hooks */
293 _PyRuntimeState *runtime = &_PyRuntime;
294 PyThreadState *ts = _PyRuntimeState_GetThreadState(runtime);
295 assert(!ts || _Py_CURRENTLY_FINALIZING(runtime, ts));
Victor Stinner838f2642019-06-13 22:41:23 +0200296 if (!ts || !_Py_CURRENTLY_FINALIZING(runtime, ts)) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700297 return;
Victor Stinner838f2642019-06-13 22:41:23 +0200298 }
Steve Dowerb82e17e2019-05-23 08:45:22 -0700299
Victor Stinner838f2642019-06-13 22:41:23 +0200300 const PyConfig *config = &ts->interp->config;
301 if (config->verbose) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700302 PySys_WriteStderr("# clear sys.audit hooks\n");
303 }
304
305 /* Hooks can abort later hooks for this event, but cannot
306 abort the clear operation itself. */
307 PySys_Audit("cpython._PySys_ClearAuditHooks", NULL);
Victor Stinner838f2642019-06-13 22:41:23 +0200308 _PyErr_Clear(ts);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700309
Victor Stinner0fd2c302019-06-04 03:15:09 +0200310 _Py_AuditHookEntry *e = _PyRuntime.audit_hook_head, *n;
311 _PyRuntime.audit_hook_head = NULL;
Steve Dowerb82e17e2019-05-23 08:45:22 -0700312 while (e) {
313 n = e->next;
314 PyMem_RawFree(e);
315 e = n;
316 }
317}
318
319int
320PySys_AddAuditHook(Py_AuditHookFunction hook, void *userData)
321{
Victor Stinner838f2642019-06-13 22:41:23 +0200322 _PyRuntimeState *runtime = &_PyRuntime;
323 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
324
Steve Dowerb82e17e2019-05-23 08:45:22 -0700325 /* Invoke existing audit hooks to allow them an opportunity to abort. */
326 /* Cannot invoke hooks until we are initialized */
Victor Stinner838f2642019-06-13 22:41:23 +0200327 if (runtime->initialized) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700328 if (PySys_Audit("sys.addaudithook", NULL) < 0) {
Victor Stinner838f2642019-06-13 22:41:23 +0200329 if (_PyErr_ExceptionMatches(tstate, PyExc_Exception)) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700330 /* We do not report errors derived from Exception */
Victor Stinner838f2642019-06-13 22:41:23 +0200331 _PyErr_Clear(tstate);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700332 return 0;
333 }
334 return -1;
335 }
336 }
337
Victor Stinner0fd2c302019-06-04 03:15:09 +0200338 _Py_AuditHookEntry *e = _PyRuntime.audit_hook_head;
Steve Dowerb82e17e2019-05-23 08:45:22 -0700339 if (!e) {
340 e = (_Py_AuditHookEntry*)PyMem_RawMalloc(sizeof(_Py_AuditHookEntry));
Victor Stinner0fd2c302019-06-04 03:15:09 +0200341 _PyRuntime.audit_hook_head = e;
Steve Dowerb82e17e2019-05-23 08:45:22 -0700342 } else {
Victor Stinner838f2642019-06-13 22:41:23 +0200343 while (e->next) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700344 e = e->next;
Victor Stinner838f2642019-06-13 22:41:23 +0200345 }
Steve Dowerb82e17e2019-05-23 08:45:22 -0700346 e = e->next = (_Py_AuditHookEntry*)PyMem_RawMalloc(
347 sizeof(_Py_AuditHookEntry));
348 }
349
350 if (!e) {
Victor Stinner838f2642019-06-13 22:41:23 +0200351 if (runtime->initialized) {
352 _PyErr_NoMemory(tstate);
353 }
Steve Dowerb82e17e2019-05-23 08:45:22 -0700354 return -1;
355 }
356
357 e->next = NULL;
358 e->hookCFunction = (Py_AuditHookFunction)hook;
359 e->userData = userData;
360
361 return 0;
362}
363
364/*[clinic input]
365sys.addaudithook
366
367 hook: object
368
369Adds a new audit hook callback.
370[clinic start generated code]*/
371
372static PyObject *
373sys_addaudithook_impl(PyObject *module, PyObject *hook)
374/*[clinic end generated code: output=4f9c17aaeb02f44e input=0f3e191217a45e34]*/
375{
Victor Stinner838f2642019-06-13 22:41:23 +0200376 PyThreadState *tstate = _PyThreadState_GET();
377
Steve Dowerb82e17e2019-05-23 08:45:22 -0700378 /* Invoke existing audit hooks to allow them an opportunity to abort. */
379 if (PySys_Audit("sys.addaudithook", NULL) < 0) {
Victor Stinner838f2642019-06-13 22:41:23 +0200380 if (_PyErr_ExceptionMatches(tstate, PyExc_Exception)) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700381 /* We do not report errors derived from Exception */
Victor Stinner838f2642019-06-13 22:41:23 +0200382 _PyErr_Clear(tstate);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700383 Py_RETURN_NONE;
384 }
385 return NULL;
386 }
387
Victor Stinner838f2642019-06-13 22:41:23 +0200388 PyInterpreterState *is = tstate->interp;
Steve Dowerb82e17e2019-05-23 08:45:22 -0700389
390 if (is->audit_hooks == NULL) {
391 is->audit_hooks = PyList_New(0);
392 if (is->audit_hooks == NULL) {
393 return NULL;
394 }
395 }
396
397 if (PyList_Append(is->audit_hooks, hook) < 0) {
398 return NULL;
399 }
400
401 Py_RETURN_NONE;
402}
403
404PyDoc_STRVAR(audit_doc,
405"audit(event, *args)\n\
406\n\
407Passes the event to any audit hooks that are attached.");
408
409static PyObject *
410sys_audit(PyObject *self, PyObject *const *args, Py_ssize_t argc)
411{
Victor Stinner838f2642019-06-13 22:41:23 +0200412 PyThreadState *tstate = _PyThreadState_GET();
413
Steve Dowerb82e17e2019-05-23 08:45:22 -0700414 if (argc == 0) {
Victor Stinner838f2642019-06-13 22:41:23 +0200415 _PyErr_SetString(tstate, PyExc_TypeError,
416 "audit() missing 1 required positional argument: "
417 "'event'");
Steve Dowerb82e17e2019-05-23 08:45:22 -0700418 return NULL;
419 }
420
Victor Stinner838f2642019-06-13 22:41:23 +0200421 if (!should_audit(tstate)) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700422 Py_RETURN_NONE;
423 }
424
425 PyObject *auditEvent = args[0];
426 if (!auditEvent) {
Victor Stinner838f2642019-06-13 22:41:23 +0200427 _PyErr_SetString(tstate, PyExc_TypeError,
428 "expected str for argument 'event'");
Steve Dowerb82e17e2019-05-23 08:45:22 -0700429 return NULL;
430 }
431 if (!PyUnicode_Check(auditEvent)) {
Victor Stinner838f2642019-06-13 22:41:23 +0200432 _PyErr_Format(tstate, PyExc_TypeError,
433 "expected str for argument 'event', not %.200s",
434 Py_TYPE(auditEvent)->tp_name);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700435 return NULL;
436 }
437 const char *event = PyUnicode_AsUTF8(auditEvent);
438 if (!event) {
439 return NULL;
440 }
441
442 PyObject *auditArgs = _PyTuple_FromArray(args + 1, argc - 1);
443 if (!auditArgs) {
444 return NULL;
445 }
446
447 int res = PySys_Audit(event, "O", auditArgs);
448 Py_DECREF(auditArgs);
449
450 if (res < 0) {
451 return NULL;
452 }
453
454 Py_RETURN_NONE;
455}
456
457
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400458static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +0200459sys_breakpointhook(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *keywords)
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400460{
Victor Stinner838f2642019-06-13 22:41:23 +0200461 PyThreadState *tstate = _PyThreadState_GET();
462 assert(!_PyErr_Occurred(tstate));
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300463 char *envar = Py_GETENV("PYTHONBREAKPOINT");
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400464
465 if (envar == NULL || strlen(envar) == 0) {
466 envar = "pdb.set_trace";
467 }
468 else if (!strcmp(envar, "0")) {
469 /* The breakpoint is explicitly no-op'd. */
470 Py_RETURN_NONE;
471 }
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300472 /* According to POSIX the string returned by getenv() might be invalidated
473 * or the string content might be overwritten by a subsequent call to
474 * getenv(). Since importing a module can performs the getenv() calls,
475 * we need to save a copy of envar. */
476 envar = _PyMem_RawStrdup(envar);
477 if (envar == NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +0200478 _PyErr_NoMemory(tstate);
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300479 return NULL;
480 }
Serhiy Storchaka4ae06c52017-12-12 13:55:04 +0200481 const char *last_dot = strrchr(envar, '.');
482 const char *attrname = NULL;
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400483 PyObject *modulepath = NULL;
484
485 if (last_dot == NULL) {
486 /* The breakpoint is a built-in, e.g. PYTHONBREAKPOINT=int */
487 modulepath = PyUnicode_FromString("builtins");
488 attrname = envar;
489 }
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200490 else if (last_dot != envar) {
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400491 /* Split on the last dot; */
492 modulepath = PyUnicode_FromStringAndSize(envar, last_dot - envar);
493 attrname = last_dot + 1;
494 }
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200495 else {
496 goto warn;
497 }
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400498 if (modulepath == NULL) {
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300499 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400500 return NULL;
501 }
502
Anthony Sottiledce345c2018-11-01 10:25:05 -0700503 PyObject *module = PyImport_Import(modulepath);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400504 Py_DECREF(modulepath);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400505
506 if (module == NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +0200507 if (_PyErr_ExceptionMatches(tstate, PyExc_ImportError)) {
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200508 goto warn;
509 }
510 PyMem_RawFree(envar);
511 return NULL;
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400512 }
513
514 PyObject *hook = PyObject_GetAttrString(module, attrname);
515 Py_DECREF(module);
516
517 if (hook == NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +0200518 if (_PyErr_ExceptionMatches(tstate, PyExc_AttributeError)) {
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200519 goto warn;
520 }
521 PyMem_RawFree(envar);
522 return NULL;
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400523 }
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300524 PyMem_RawFree(envar);
Jeroen Demeyeraacc77f2019-05-29 20:31:52 +0200525 PyObject *retval = _PyObject_Vectorcall(hook, args, nargs, keywords);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400526 Py_DECREF(hook);
527 return retval;
528
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200529 warn:
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400530 /* If any of the imports went wrong, then warn and ignore. */
Victor Stinner838f2642019-06-13 22:41:23 +0200531 _PyErr_Clear(tstate);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400532 int status = PyErr_WarnFormat(
533 PyExc_RuntimeWarning, 0,
534 "Ignoring unimportable $PYTHONBREAKPOINT: \"%s\"", envar);
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300535 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400536 if (status < 0) {
537 /* Printing the warning raised an exception. */
538 return NULL;
539 }
540 /* The warning was (probably) issued. */
541 Py_RETURN_NONE;
542}
543
544PyDoc_STRVAR(breakpointhook_doc,
545"breakpointhook(*args, **kws)\n"
546"\n"
547"This hook function is called by built-in breakpoint().\n"
548);
549
Victor Stinner13d49ee2010-12-04 17:24:33 +0000550/* Write repr(o) to sys.stdout using sys.stdout.encoding and 'backslashreplace'
551 error handler. If sys.stdout has a buffer attribute, use
552 sys.stdout.buffer.write(encoded), otherwise redecode the string and use
553 sys.stdout.write(redecoded).
554
555 Helper function for sys_displayhook(). */
556static int
Victor Stinner838f2642019-06-13 22:41:23 +0200557sys_displayhook_unencodable(PyThreadState *tstate, PyObject *outf, PyObject *o)
Victor Stinner13d49ee2010-12-04 17:24:33 +0000558{
559 PyObject *stdout_encoding = NULL;
560 PyObject *encoded, *escaped_str, *repr_str, *buffer, *result;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200561 const char *stdout_encoding_str;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000562 int ret;
563
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200564 stdout_encoding = _PyObject_GetAttrId(outf, &PyId_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000565 if (stdout_encoding == NULL)
566 goto error;
Serhiy Storchaka06515832016-11-20 09:13:07 +0200567 stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000568 if (stdout_encoding_str == NULL)
569 goto error;
570
571 repr_str = PyObject_Repr(o);
572 if (repr_str == NULL)
573 goto error;
574 encoded = PyUnicode_AsEncodedString(repr_str,
575 stdout_encoding_str,
576 "backslashreplace");
577 Py_DECREF(repr_str);
578 if (encoded == NULL)
579 goto error;
580
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200581 buffer = _PyObject_GetAttrId(outf, &PyId_buffer);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000582 if (buffer) {
Victor Stinner7e425412016-12-09 00:36:19 +0100583 result = _PyObject_CallMethodIdObjArgs(buffer, &PyId_write, encoded, NULL);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000584 Py_DECREF(buffer);
585 Py_DECREF(encoded);
586 if (result == NULL)
587 goto error;
588 Py_DECREF(result);
589 }
590 else {
Victor Stinner838f2642019-06-13 22:41:23 +0200591 _PyErr_Clear(tstate);
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 Stinner13d49ee2010-12-04 17:24:33 +0000628 int err;
Victor Stinner838f2642019-06-13 22:41:23 +0200629 PyThreadState *tstate = _PyThreadState_GET();
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000630
Eric Snow3f9eee62017-09-15 16:35:20 -0600631 builtins = _PyImport_GetModuleId(&PyId_builtins);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 if (builtins == NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +0200633 if (!_PyErr_Occurred(tstate)) {
634 _PyErr_SetString(tstate, PyExc_RuntimeError,
635 "lost builtins module");
Stefan Krah027b09c2019-03-25 21:50:58 +0100636 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000637 return NULL;
638 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600639 Py_DECREF(builtins);
Moshe Zadka03897ea2001-07-23 13:32:43 +0000640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 /* Print value except if None */
642 /* After printing, also assign to '_' */
643 /* Before, set '_' to None to avoid recursion */
644 if (o == Py_None) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200645 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 }
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200647 if (_PyObject_SetAttrId(builtins, &PyId__, Py_None) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 return NULL;
Victor Stinner838f2642019-06-13 22:41:23 +0200649 outf = sys_get_object_id(tstate, &PyId_stdout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 if (outf == NULL || outf == Py_None) {
Victor Stinner838f2642019-06-13 22:41:23 +0200651 _PyErr_SetString(tstate, PyExc_RuntimeError, "lost sys.stdout");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 return NULL;
653 }
Victor Stinner13d49ee2010-12-04 17:24:33 +0000654 if (PyFile_WriteObject(o, outf, 0) != 0) {
Victor Stinner838f2642019-06-13 22:41:23 +0200655 if (_PyErr_ExceptionMatches(tstate, PyExc_UnicodeEncodeError)) {
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);
659 err = sys_displayhook_unencodable(tstate, outf, o);
660 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
753 status: object = NULL
754 /
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)
766/*[clinic end generated code: output=13870986c1ab2ec0 input=a737351f86685e9c]*/
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,
844 "can't intern %.400s", s->ob_type->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 Stinnerfdeb6ec2013-12-13 02:01:38 +0100879call_trampoline(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 Stinner838f2642019-06-13 22:41:23 +0200892 PyObject *result = _PyObject_FastCall(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{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 if (arg == NULL)
909 arg = Py_None;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100910 result = call_trampoline(self, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911 if (result == NULL) {
912 PyEval_SetProfile(NULL, NULL);
913 return -1;
914 }
915 Py_DECREF(result);
916 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000917}
918
919static int
920trace_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000922{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 PyObject *callback;
924 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 if (what == PyTrace_CALL)
927 callback = self;
928 else
929 callback = frame->f_trace;
930 if (callback == NULL)
931 return 0;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100932 result = call_trampoline(callback, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 if (result == NULL) {
934 PyEval_SetTrace(NULL, NULL);
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200935 Py_CLEAR(frame->f_trace);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 return -1;
937 }
938 if (result != Py_None) {
Serhiy Storchakaec397562016-04-06 09:50:03 +0300939 Py_XSETREF(frame->f_trace, result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 }
941 else {
942 Py_DECREF(result);
943 }
944 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000945}
Fred Draked0838392001-06-16 21:02:31 +0000946
Fred Drake8b4d01d2000-05-09 19:57:01 +0000947static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000948sys_settrace(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000949{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 if (trace_init() == -1)
951 return NULL;
952 if (args == Py_None)
953 PyEval_SetTrace(NULL, NULL);
954 else
955 PyEval_SetTrace(trace_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200956 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000957}
958
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000959PyDoc_STRVAR(settrace_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000960"settrace(function)\n\
961\n\
962Set the global debug tracing function. It will be called on each\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000963function call. See the debugger chapter in the library manual."
964);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000965
Tal Einatede0b6f2018-12-31 17:12:08 +0200966/*[clinic input]
967sys.gettrace
968
969Return the global debug tracing function set with sys.settrace.
970
971See the debugger chapter in the library manual.
972[clinic start generated code]*/
973
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000974static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200975sys_gettrace_impl(PyObject *module)
976/*[clinic end generated code: output=e97e3a4d8c971b6e input=373b51bb2147f4d8]*/
Christian Heimes9bd667a2008-01-20 15:14:11 +0000977{
Victor Stinner50b48572018-11-01 01:51:40 +0100978 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 PyObject *temp = tstate->c_traceobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 if (temp == NULL)
982 temp = Py_None;
983 Py_INCREF(temp);
984 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000985}
986
Christian Heimes9bd667a2008-01-20 15:14:11 +0000987static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000988sys_setprofile(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000989{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 if (trace_init() == -1)
991 return NULL;
992 if (args == Py_None)
993 PyEval_SetProfile(NULL, NULL);
994 else
995 PyEval_SetProfile(profile_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200996 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000997}
998
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000999PyDoc_STRVAR(setprofile_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001000"setprofile(function)\n\
1001\n\
1002Set the profiling function. It will be called on each function call\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001003and return. See the profiler chapter in the library manual."
1004);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001005
Tal Einatede0b6f2018-12-31 17:12:08 +02001006/*[clinic input]
1007sys.getprofile
1008
1009Return the profiling function set with sys.setprofile.
1010
1011See the profiler chapter in the library manual.
1012[clinic start generated code]*/
1013
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001014static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001015sys_getprofile_impl(PyObject *module)
1016/*[clinic end generated code: output=579b96b373448188 input=1b3209d89a32965d]*/
Christian Heimes9bd667a2008-01-20 15:14:11 +00001017{
Victor Stinner50b48572018-11-01 01:51:40 +01001018 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 PyObject *temp = tstate->c_profileobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +00001020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 if (temp == NULL)
1022 temp = Py_None;
1023 Py_INCREF(temp);
1024 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +00001025}
1026
Tal Einatede0b6f2018-12-31 17:12:08 +02001027/*[clinic input]
1028sys.setcheckinterval
1029
1030 n: int
1031 /
1032
1033Set the async event check interval to n instructions.
1034
1035This tells the Python interpreter to check for asynchronous events
1036every n instructions.
1037
1038This also affects how often thread switches occur.
1039[clinic start generated code]*/
Christian Heimes9bd667a2008-01-20 15:14:11 +00001040
1041static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001042sys_setcheckinterval_impl(PyObject *module, int n)
1043/*[clinic end generated code: output=3f686cef07e6e178 input=7a35b17bf22a6227]*/
Guido van Rossuma0d7a231995-01-09 17:46:13 +00001044{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1046 "sys.getcheckinterval() and sys.setcheckinterval() "
1047 "are deprecated. Use sys.setswitchinterval() "
Victor Stinner838f2642019-06-13 22:41:23 +02001048 "instead.", 1) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 return NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02001050 }
Victor Stinnercaba55b2018-08-03 15:33:52 +02001051
Victor Stinner838f2642019-06-13 22:41:23 +02001052 PyThreadState *tstate = _PyThreadState_GET();
1053 tstate->interp->check_interval = n;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001054 Py_RETURN_NONE;
Guido van Rossuma0d7a231995-01-09 17:46:13 +00001055}
1056
Tal Einatede0b6f2018-12-31 17:12:08 +02001057/*[clinic input]
1058sys.getcheckinterval
1059
1060Return the current check interval; see sys.setcheckinterval().
1061[clinic start generated code]*/
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001062
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001063static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001064sys_getcheckinterval_impl(PyObject *module)
1065/*[clinic end generated code: output=1b5060bf2b23a47c input=4b6589cbcca1db4e]*/
Tim Peterse5e065b2003-07-06 18:36:54 +00001066{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1068 "sys.getcheckinterval() and sys.setcheckinterval() "
1069 "are deprecated. Use sys.getswitchinterval() "
Victor Stinner838f2642019-06-13 22:41:23 +02001070 "instead.", 1) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 return NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02001072 }
1073
1074 PyThreadState *tstate = _PyThreadState_GET();
1075 return PyLong_FromLong(tstate->interp->check_interval);
Tim Peterse5e065b2003-07-06 18:36:54 +00001076}
1077
Tal Einatede0b6f2018-12-31 17:12:08 +02001078/*[clinic input]
1079sys.setswitchinterval
1080
1081 interval: double
1082 /
1083
1084Set the ideal thread switching delay inside the Python interpreter.
1085
1086The actual frequency of switching threads can be lower if the
1087interpreter executes long sequences of uninterruptible code
1088(this is implementation-specific and workload-dependent).
1089
1090The parameter must represent the desired switching delay in seconds
1091A typical value is 0.005 (5 milliseconds).
1092[clinic start generated code]*/
Tim Peterse5e065b2003-07-06 18:36:54 +00001093
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001094static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001095sys_setswitchinterval_impl(PyObject *module, double interval)
1096/*[clinic end generated code: output=65a19629e5153983 input=561b477134df91d9]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001097{
Victor Stinner838f2642019-06-13 22:41:23 +02001098 PyThreadState *tstate = _PyThreadState_GET();
Tal Einatede0b6f2018-12-31 17:12:08 +02001099 if (interval <= 0.0) {
Victor Stinner838f2642019-06-13 22:41:23 +02001100 _PyErr_SetString(tstate, PyExc_ValueError,
1101 "switch interval must be strictly positive");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 return NULL;
1103 }
Tal Einatede0b6f2018-12-31 17:12:08 +02001104 _PyEval_SetSwitchInterval((unsigned long) (1e6 * interval));
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001105 Py_RETURN_NONE;
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001106}
1107
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001108
Tal Einatede0b6f2018-12-31 17:12:08 +02001109/*[clinic input]
1110sys.getswitchinterval -> double
1111
1112Return the current thread switch interval; see sys.setswitchinterval().
1113[clinic start generated code]*/
1114
1115static double
1116sys_getswitchinterval_impl(PyObject *module)
1117/*[clinic end generated code: output=a38c277c85b5096d input=bdf9d39c0ebbbb6f]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001118{
Tal Einatede0b6f2018-12-31 17:12:08 +02001119 return 1e-6 * _PyEval_GetSwitchInterval();
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001120}
1121
Tal Einatede0b6f2018-12-31 17:12:08 +02001122/*[clinic input]
1123sys.setrecursionlimit
1124
1125 limit as new_limit: int
1126 /
1127
1128Set the maximum depth of the Python interpreter stack to n.
1129
1130This limit prevents infinite recursion from causing an overflow of the C
1131stack and crashing Python. The highest possible limit is platform-
1132dependent.
1133[clinic start generated code]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001134
Tim Peterse5e065b2003-07-06 18:36:54 +00001135static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001136sys_setrecursionlimit_impl(PyObject *module, int new_limit)
1137/*[clinic end generated code: output=35e1c64754800ace input=b0f7a23393924af3]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001138{
Tal Einatede0b6f2018-12-31 17:12:08 +02001139 int mark;
Victor Stinner838f2642019-06-13 22:41:23 +02001140 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner50856d52015-10-13 00:11:21 +02001141
Victor Stinner50856d52015-10-13 00:11:21 +02001142 if (new_limit < 1) {
Victor Stinner838f2642019-06-13 22:41:23 +02001143 _PyErr_SetString(tstate, PyExc_ValueError,
1144 "recursion limit must be greater or equal than 1");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 return NULL;
1146 }
Victor Stinner50856d52015-10-13 00:11:21 +02001147
1148 /* Issue #25274: When the recursion depth hits the recursion limit in
1149 _Py_CheckRecursiveCall(), the overflowed flag of the thread state is
1150 set to 1 and a RecursionError is raised. The overflowed flag is reset
1151 to 0 when the recursion depth goes below the low-water mark: see
1152 Py_LeaveRecursiveCall().
1153
1154 Reject too low new limit if the current recursion depth is higher than
1155 the new low-water mark. Otherwise it may not be possible anymore to
1156 reset the overflowed flag to 0. */
1157 mark = _Py_RecursionLimitLowerWaterMark(new_limit);
Victor Stinner50856d52015-10-13 00:11:21 +02001158 if (tstate->recursion_depth >= mark) {
Victor Stinner838f2642019-06-13 22:41:23 +02001159 _PyErr_Format(tstate, PyExc_RecursionError,
1160 "cannot set the recursion limit to %i at "
1161 "the recursion depth %i: the limit is too low",
1162 new_limit, tstate->recursion_depth);
Victor Stinner50856d52015-10-13 00:11:21 +02001163 return NULL;
1164 }
1165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 Py_SetRecursionLimit(new_limit);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001167 Py_RETURN_NONE;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001168}
1169
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001170/*[clinic input]
1171sys.set_coroutine_origin_tracking_depth
1172
1173 depth: int
1174
1175Enable or disable origin tracking for coroutine objects in this thread.
1176
Tal Einatede0b6f2018-12-31 17:12:08 +02001177Coroutine objects will track 'depth' frames of traceback information
1178about where they came from, available in their cr_origin attribute.
1179
1180Set a depth of 0 to disable.
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001181[clinic start generated code]*/
1182
1183static PyObject *
1184sys_set_coroutine_origin_tracking_depth_impl(PyObject *module, int depth)
Tal Einatede0b6f2018-12-31 17:12:08 +02001185/*[clinic end generated code: output=0a2123c1cc6759c5 input=a1d0a05f89d2c426]*/
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001186{
Victor Stinner838f2642019-06-13 22:41:23 +02001187 PyThreadState *tstate = _PyThreadState_GET();
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001188 if (depth < 0) {
Victor Stinner838f2642019-06-13 22:41:23 +02001189 _PyErr_SetString(tstate, PyExc_ValueError, "depth must be >= 0");
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001190 return NULL;
1191 }
Victor Stinner838f2642019-06-13 22:41:23 +02001192 _PyEval_SetCoroutineOriginTrackingDepth(tstate, depth);
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001193 Py_RETURN_NONE;
1194}
1195
1196/*[clinic input]
1197sys.get_coroutine_origin_tracking_depth -> int
1198
1199Check status of origin tracking for coroutine objects in this thread.
1200[clinic start generated code]*/
1201
1202static int
1203sys_get_coroutine_origin_tracking_depth_impl(PyObject *module)
1204/*[clinic end generated code: output=3699f7be95a3afb8 input=335266a71205b61a]*/
1205{
1206 return _PyEval_GetCoroutineOriginTrackingDepth();
1207}
1208
Yury Selivanoveb636452016-09-08 22:01:51 -07001209static PyTypeObject AsyncGenHooksType;
1210
1211PyDoc_STRVAR(asyncgen_hooks_doc,
1212"asyncgen_hooks\n\
1213\n\
1214A struct sequence providing information about asynhronous\n\
1215generators hooks. The attributes are read only.");
1216
1217static PyStructSequence_Field asyncgen_hooks_fields[] = {
1218 {"firstiter", "Hook to intercept first iteration"},
1219 {"finalizer", "Hook to intercept finalization"},
1220 {0}
1221};
1222
1223static PyStructSequence_Desc asyncgen_hooks_desc = {
1224 "asyncgen_hooks", /* name */
1225 asyncgen_hooks_doc, /* doc */
1226 asyncgen_hooks_fields , /* fields */
1227 2
1228};
1229
Yury Selivanoveb636452016-09-08 22:01:51 -07001230static PyObject *
1231sys_set_asyncgen_hooks(PyObject *self, PyObject *args, PyObject *kw)
1232{
1233 static char *keywords[] = {"firstiter", "finalizer", NULL};
1234 PyObject *firstiter = NULL;
1235 PyObject *finalizer = NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02001236 PyThreadState *tstate = _PyThreadState_GET();
Yury Selivanoveb636452016-09-08 22:01:51 -07001237
1238 if (!PyArg_ParseTupleAndKeywords(
1239 args, kw, "|OO", keywords,
1240 &firstiter, &finalizer)) {
1241 return NULL;
1242 }
1243
1244 if (finalizer && finalizer != Py_None) {
1245 if (!PyCallable_Check(finalizer)) {
Victor Stinner838f2642019-06-13 22:41:23 +02001246 _PyErr_Format(tstate, PyExc_TypeError,
1247 "callable finalizer expected, got %.50s",
1248 Py_TYPE(finalizer)->tp_name);
Yury Selivanoveb636452016-09-08 22:01:51 -07001249 return NULL;
1250 }
1251 _PyEval_SetAsyncGenFinalizer(finalizer);
1252 }
1253 else if (finalizer == Py_None) {
1254 _PyEval_SetAsyncGenFinalizer(NULL);
1255 }
1256
1257 if (firstiter && firstiter != Py_None) {
1258 if (!PyCallable_Check(firstiter)) {
Victor Stinner838f2642019-06-13 22:41:23 +02001259 _PyErr_Format(tstate, PyExc_TypeError,
1260 "callable firstiter expected, got %.50s",
1261 Py_TYPE(firstiter)->tp_name);
Yury Selivanoveb636452016-09-08 22:01:51 -07001262 return NULL;
1263 }
1264 _PyEval_SetAsyncGenFirstiter(firstiter);
1265 }
1266 else if (firstiter == Py_None) {
1267 _PyEval_SetAsyncGenFirstiter(NULL);
1268 }
1269
1270 Py_RETURN_NONE;
1271}
1272
1273PyDoc_STRVAR(set_asyncgen_hooks_doc,
Tal Einatede0b6f2018-12-31 17:12:08 +02001274"set_asyncgen_hooks(* [, firstiter] [, finalizer])\n\
Yury Selivanoveb636452016-09-08 22:01:51 -07001275\n\
1276Set a finalizer for async generators objects."
1277);
1278
Tal Einatede0b6f2018-12-31 17:12:08 +02001279/*[clinic input]
1280sys.get_asyncgen_hooks
1281
1282Return the installed asynchronous generators hooks.
1283
1284This returns a namedtuple of the form (firstiter, finalizer).
1285[clinic start generated code]*/
1286
Yury Selivanoveb636452016-09-08 22:01:51 -07001287static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001288sys_get_asyncgen_hooks_impl(PyObject *module)
1289/*[clinic end generated code: output=53a253707146f6cf input=3676b9ea62b14625]*/
Yury Selivanoveb636452016-09-08 22:01:51 -07001290{
1291 PyObject *res;
1292 PyObject *firstiter = _PyEval_GetAsyncGenFirstiter();
1293 PyObject *finalizer = _PyEval_GetAsyncGenFinalizer();
1294
1295 res = PyStructSequence_New(&AsyncGenHooksType);
1296 if (res == NULL) {
1297 return NULL;
1298 }
1299
1300 if (firstiter == NULL) {
1301 firstiter = Py_None;
1302 }
1303
1304 if (finalizer == NULL) {
1305 finalizer = Py_None;
1306 }
1307
1308 Py_INCREF(firstiter);
1309 PyStructSequence_SET_ITEM(res, 0, firstiter);
1310
1311 Py_INCREF(finalizer);
1312 PyStructSequence_SET_ITEM(res, 1, finalizer);
1313
1314 return res;
1315}
1316
Yury Selivanoveb636452016-09-08 22:01:51 -07001317
Mark Dickinsondc787d22010-05-23 13:33:13 +00001318static PyTypeObject Hash_InfoType;
1319
1320PyDoc_STRVAR(hash_info_doc,
1321"hash_info\n\
1322\n\
1323A struct sequence providing parameters used for computing\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +01001324hashes. The attributes are read only.");
Mark Dickinsondc787d22010-05-23 13:33:13 +00001325
1326static PyStructSequence_Field hash_info_fields[] = {
1327 {"width", "width of the type used for hashing, in bits"},
1328 {"modulus", "prime number giving the modulus on which the hash "
1329 "function is based"},
1330 {"inf", "value to be used for hash of a positive infinity"},
1331 {"nan", "value to be used for hash of a nan"},
1332 {"imag", "multiplier used for the imaginary part of a complex number"},
Christian Heimes985ecdc2013-11-20 11:46:18 +01001333 {"algorithm", "name of the algorithm for hashing of str, bytes and "
1334 "memoryviews"},
1335 {"hash_bits", "internal output size of hash algorithm"},
1336 {"seed_bits", "seed size of hash algorithm"},
1337 {"cutoff", "small string optimization cutoff"},
Mark Dickinsondc787d22010-05-23 13:33:13 +00001338 {NULL, NULL}
1339};
1340
1341static PyStructSequence_Desc hash_info_desc = {
1342 "sys.hash_info",
1343 hash_info_doc,
1344 hash_info_fields,
Christian Heimes985ecdc2013-11-20 11:46:18 +01001345 9,
Mark Dickinsondc787d22010-05-23 13:33:13 +00001346};
1347
Matthias Klosed885e952010-07-06 10:53:30 +00001348static PyObject *
Victor Stinner838f2642019-06-13 22:41:23 +02001349get_hash_info(PyThreadState *tstate)
Mark Dickinsondc787d22010-05-23 13:33:13 +00001350{
1351 PyObject *hash_info;
1352 int field = 0;
Christian Heimes985ecdc2013-11-20 11:46:18 +01001353 PyHash_FuncDef *hashfunc;
Mark Dickinsondc787d22010-05-23 13:33:13 +00001354 hash_info = PyStructSequence_New(&Hash_InfoType);
1355 if (hash_info == NULL)
1356 return NULL;
Christian Heimes985ecdc2013-11-20 11:46:18 +01001357 hashfunc = PyHash_GetFuncDef();
Mark Dickinsondc787d22010-05-23 13:33:13 +00001358 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001359 PyLong_FromLong(8*sizeof(Py_hash_t)));
Mark Dickinsondc787d22010-05-23 13:33:13 +00001360 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8035bc52010-10-23 16:20:50 +00001361 PyLong_FromSsize_t(_PyHASH_MODULUS));
Mark Dickinsondc787d22010-05-23 13:33:13 +00001362 PyStructSequence_SET_ITEM(hash_info, field++,
1363 PyLong_FromLong(_PyHASH_INF));
1364 PyStructSequence_SET_ITEM(hash_info, field++,
1365 PyLong_FromLong(_PyHASH_NAN));
1366 PyStructSequence_SET_ITEM(hash_info, field++,
1367 PyLong_FromLong(_PyHASH_IMAG));
Christian Heimes985ecdc2013-11-20 11:46:18 +01001368 PyStructSequence_SET_ITEM(hash_info, field++,
1369 PyUnicode_FromString(hashfunc->name));
1370 PyStructSequence_SET_ITEM(hash_info, field++,
1371 PyLong_FromLong(hashfunc->hash_bits));
1372 PyStructSequence_SET_ITEM(hash_info, field++,
1373 PyLong_FromLong(hashfunc->seed_bits));
1374 PyStructSequence_SET_ITEM(hash_info, field++,
1375 PyLong_FromLong(Py_HASH_CUTOFF));
Victor Stinner838f2642019-06-13 22:41:23 +02001376 if (_PyErr_Occurred(tstate)) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00001377 Py_CLEAR(hash_info);
1378 return NULL;
1379 }
1380 return hash_info;
1381}
Tal Einatede0b6f2018-12-31 17:12:08 +02001382/*[clinic input]
1383sys.getrecursionlimit
Mark Dickinsondc787d22010-05-23 13:33:13 +00001384
Tal Einatede0b6f2018-12-31 17:12:08 +02001385Return the current value of the recursion limit.
Mark Dickinsondc787d22010-05-23 13:33:13 +00001386
Tal Einatede0b6f2018-12-31 17:12:08 +02001387The recursion limit is the maximum depth of the Python interpreter
1388stack. This limit prevents infinite recursion from causing an overflow
1389of the C stack and crashing Python.
1390[clinic start generated code]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001391
1392static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001393sys_getrecursionlimit_impl(PyObject *module)
1394/*[clinic end generated code: output=d571fb6b4549ef2e input=1c6129fd2efaeea8]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001395{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001396 return PyLong_FromLong(Py_GetRecursionLimit());
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001397}
1398
Mark Hammond8696ebc2002-10-08 02:44:31 +00001399#ifdef MS_WINDOWS
Mark Hammond8696ebc2002-10-08 02:44:31 +00001400
Eric Smithf7bb5782010-01-27 00:44:57 +00001401static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};
1402
1403static PyStructSequence_Field windows_version_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001404 {"major", "Major version number"},
1405 {"minor", "Minor version number"},
1406 {"build", "Build number"},
1407 {"platform", "Operating system platform"},
1408 {"service_pack", "Latest Service Pack installed on the system"},
1409 {"service_pack_major", "Service Pack major version number"},
1410 {"service_pack_minor", "Service Pack minor version number"},
1411 {"suite_mask", "Bit mask identifying available product suites"},
1412 {"product_type", "System product type"},
Steve Dower74f4af72016-09-17 17:27:48 -07001413 {"platform_version", "Diagnostic version number"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 {0}
Eric Smithf7bb5782010-01-27 00:44:57 +00001415};
1416
1417static PyStructSequence_Desc windows_version_desc = {
Tal Einatede0b6f2018-12-31 17:12:08 +02001418 "sys.getwindowsversion", /* name */
1419 sys_getwindowsversion__doc__, /* doc */
1420 windows_version_fields, /* fields */
1421 5 /* For backward compatibility,
1422 only the first 5 items are accessible
1423 via indexing, the rest are name only */
Eric Smithf7bb5782010-01-27 00:44:57 +00001424};
1425
Steve Dower3e96f322015-03-02 08:01:10 -08001426/* Disable deprecation warnings about GetVersionEx as the result is
1427 being passed straight through to the caller, who is responsible for
1428 using it correctly. */
1429#pragma warning(push)
1430#pragma warning(disable:4996)
1431
Tal Einatede0b6f2018-12-31 17:12:08 +02001432/*[clinic input]
1433sys.getwindowsversion
1434
1435Return info about the running version of Windows as a named tuple.
1436
1437The members are named: major, minor, build, platform, service_pack,
1438service_pack_major, service_pack_minor, suite_mask, product_type and
1439platform_version. For backward compatibility, only the first 5 items
1440are available by indexing. All elements are numbers, except
1441service_pack and platform_type which are strings, and platform_version
1442which is a 3-tuple. Platform is always 2. Product_type may be 1 for a
1443workstation, 2 for a domain controller, 3 for a server.
1444Platform_version is a 3-tuple containing a version number that is
1445intended for identifying the OS rather than feature detection.
1446[clinic start generated code]*/
1447
Mark Hammond8696ebc2002-10-08 02:44:31 +00001448static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001449sys_getwindowsversion_impl(PyObject *module)
1450/*[clinic end generated code: output=1ec063280b932857 input=73a228a328fee63a]*/
Mark Hammond8696ebc2002-10-08 02:44:31 +00001451{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001452 PyObject *version;
1453 int pos = 0;
Minmin Gong8ebc6452019-02-02 20:26:55 -08001454 OSVERSIONINFOEXW ver;
Steve Dower74f4af72016-09-17 17:27:48 -07001455 DWORD realMajor, realMinor, realBuild;
1456 HANDLE hKernel32;
1457 wchar_t kernel32_path[MAX_PATH];
1458 LPVOID verblock;
1459 DWORD verblock_size;
Victor Stinner838f2642019-06-13 22:41:23 +02001460 PyThreadState *tstate = _PyThreadState_GET();
Steve Dower74f4af72016-09-17 17:27:48 -07001461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001462 ver.dwOSVersionInfoSize = sizeof(ver);
Minmin Gong8ebc6452019-02-02 20:26:55 -08001463 if (!GetVersionExW((OSVERSIONINFOW*) &ver))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001464 return PyErr_SetFromWindowsErr(0);
Eric Smithf7bb5782010-01-27 00:44:57 +00001465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001466 version = PyStructSequence_New(&WindowsVersionType);
1467 if (version == NULL)
1468 return NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +00001469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001470 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion));
1471 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion));
1472 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber));
1473 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId));
Minmin Gong8ebc6452019-02-02 20:26:55 -08001474 PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromWideChar(ver.szCSDVersion, -1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001475 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor));
1476 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor));
1477 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask));
1478 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType));
Eric Smithf7bb5782010-01-27 00:44:57 +00001479
Steve Dower74f4af72016-09-17 17:27:48 -07001480 realMajor = ver.dwMajorVersion;
1481 realMinor = ver.dwMinorVersion;
1482 realBuild = ver.dwBuildNumber;
1483
1484 // GetVersion will lie if we are running in a compatibility mode.
1485 // We need to read the version info from a system file resource
1486 // to accurately identify the OS version. If we fail for any reason,
1487 // just return whatever GetVersion said.
Tony Roberts4860f012019-02-02 18:16:42 +01001488 Py_BEGIN_ALLOW_THREADS
Steve Dower74f4af72016-09-17 17:27:48 -07001489 hKernel32 = GetModuleHandleW(L"kernel32.dll");
Tony Roberts4860f012019-02-02 18:16:42 +01001490 Py_END_ALLOW_THREADS
Steve Dower74f4af72016-09-17 17:27:48 -07001491 if (hKernel32 && GetModuleFileNameW(hKernel32, kernel32_path, MAX_PATH) &&
1492 (verblock_size = GetFileVersionInfoSizeW(kernel32_path, NULL)) &&
1493 (verblock = PyMem_RawMalloc(verblock_size))) {
1494 VS_FIXEDFILEINFO *ffi;
1495 UINT ffi_len;
1496
1497 if (GetFileVersionInfoW(kernel32_path, 0, verblock_size, verblock) &&
1498 VerQueryValueW(verblock, L"", (LPVOID)&ffi, &ffi_len)) {
1499 realMajor = HIWORD(ffi->dwProductVersionMS);
1500 realMinor = LOWORD(ffi->dwProductVersionMS);
1501 realBuild = HIWORD(ffi->dwProductVersionLS);
1502 }
1503 PyMem_RawFree(verblock);
1504 }
Segev Finer48fb7662017-06-04 20:52:27 +03001505 PyStructSequence_SET_ITEM(version, pos++, Py_BuildValue("(kkk)",
1506 realMajor,
1507 realMinor,
1508 realBuild
Steve Dower74f4af72016-09-17 17:27:48 -07001509 ));
1510
Victor Stinner838f2642019-06-13 22:41:23 +02001511 if (_PyErr_Occurred(tstate)) {
Serhiy Storchaka48d761e2013-12-17 15:11:24 +02001512 Py_DECREF(version);
1513 return NULL;
1514 }
Steve Dower74f4af72016-09-17 17:27:48 -07001515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001516 return version;
Mark Hammond8696ebc2002-10-08 02:44:31 +00001517}
1518
Steve Dower3e96f322015-03-02 08:01:10 -08001519#pragma warning(pop)
1520
Tal Einatede0b6f2018-12-31 17:12:08 +02001521/*[clinic input]
1522sys._enablelegacywindowsfsencoding
1523
1524Changes the default filesystem encoding to mbcs:replace.
1525
1526This is done for consistency with earlier versions of Python. See PEP
1527529 for more information.
1528
1529This is equivalent to defining the PYTHONLEGACYWINDOWSFSENCODING
1530environment variable before launching Python.
1531[clinic start generated code]*/
Steve Dowercc16be82016-09-08 10:35:16 -07001532
1533static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001534sys__enablelegacywindowsfsencoding_impl(PyObject *module)
1535/*[clinic end generated code: output=f5c3855b45e24fe9 input=2bfa931a20704492]*/
Steve Dowercc16be82016-09-08 10:35:16 -07001536{
Victor Stinner709d23d2019-05-02 14:56:30 -04001537 if (_PyUnicode_EnableLegacyWindowsFSEncoding() < 0) {
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001538 return NULL;
1539 }
Steve Dowercc16be82016-09-08 10:35:16 -07001540 Py_RETURN_NONE;
1541}
1542
Mark Hammond8696ebc2002-10-08 02:44:31 +00001543#endif /* MS_WINDOWS */
1544
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001545#ifdef HAVE_DLOPEN
Tal Einatede0b6f2018-12-31 17:12:08 +02001546
1547/*[clinic input]
1548sys.setdlopenflags
1549
1550 flags as new_val: int
1551 /
1552
1553Set the flags used by the interpreter for dlopen calls.
1554
1555This is used, for example, when the interpreter loads extension
1556modules. Among other things, this will enable a lazy resolving of
1557symbols when importing a module, if called as sys.setdlopenflags(0).
1558To share symbols across extension modules, call as
1559sys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag
1560modules can be found in the os module (RTLD_xxx constants, e.g.
1561os.RTLD_LAZY).
1562[clinic start generated code]*/
1563
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001564static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001565sys_setdlopenflags_impl(PyObject *module, int new_val)
1566/*[clinic end generated code: output=ec918b7fe0a37281 input=4c838211e857a77f]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001567{
Victor Stinner838f2642019-06-13 22:41:23 +02001568 PyThreadState *tstate = _PyThreadState_GET();
1569 tstate->interp->dlopenflags = new_val;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001570 Py_RETURN_NONE;
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001571}
1572
Tal Einatede0b6f2018-12-31 17:12:08 +02001573
1574/*[clinic input]
1575sys.getdlopenflags
1576
1577Return the current value of the flags that are used for dlopen calls.
1578
1579The flag constants are defined in the os module.
1580[clinic start generated code]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001581
1582static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001583sys_getdlopenflags_impl(PyObject *module)
1584/*[clinic end generated code: output=e92cd1bc5005da6e input=dc4ea0899c53b4b6]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001585{
Victor Stinner838f2642019-06-13 22:41:23 +02001586 PyThreadState *tstate = _PyThreadState_GET();
1587 return PyLong_FromLong(tstate->interp->dlopenflags);
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001588}
1589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001590#endif /* HAVE_DLOPEN */
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001591
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001592#ifdef USE_MALLOPT
1593/* Link with -lmalloc (or -lmpc) on an SGI */
1594#include <malloc.h>
1595
Tal Einatede0b6f2018-12-31 17:12:08 +02001596/*[clinic input]
1597sys.mdebug
1598
1599 flag: int
1600 /
1601[clinic start generated code]*/
1602
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001603static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001604sys_mdebug_impl(PyObject *module, int flag)
1605/*[clinic end generated code: output=5431d545847c3637 input=151d150ae1636f8a]*/
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001606{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 int flag;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001608 mallopt(M_DEBUG, flag);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001609 Py_RETURN_NONE;
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001610}
1611#endif /* USE_MALLOPT */
1612
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001613size_t
1614_PySys_GetSizeOf(PyObject *o)
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001615{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 PyObject *res = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001617 PyObject *method;
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001618 Py_ssize_t size;
Victor Stinner838f2642019-06-13 22:41:23 +02001619 PyThreadState *tstate = _PyThreadState_GET();
Benjamin Petersona5758c02009-05-09 18:15:04 +00001620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001621 /* Make sure the type is initialized. float gets initialized late */
Victor Stinner838f2642019-06-13 22:41:23 +02001622 if (PyType_Ready(Py_TYPE(o)) < 0) {
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001623 return (size_t)-1;
Victor Stinner838f2642019-06-13 22:41:23 +02001624 }
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001625
Benjamin Petersonce798522012-01-22 11:24:29 -05001626 method = _PyObject_LookupSpecial(o, &PyId___sizeof__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001627 if (method == NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +02001628 if (!_PyErr_Occurred(tstate)) {
1629 _PyErr_Format(tstate, PyExc_TypeError,
1630 "Type %.100s doesn't define __sizeof__",
1631 Py_TYPE(o)->tp_name);
1632 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001633 }
1634 else {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001635 res = _PyObject_CallNoArg(method);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001636 Py_DECREF(method);
1637 }
1638
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001639 if (res == NULL)
1640 return (size_t)-1;
1641
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001642 size = PyLong_AsSsize_t(res);
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001643 Py_DECREF(res);
Victor Stinner838f2642019-06-13 22:41:23 +02001644 if (size == -1 && _PyErr_Occurred(tstate))
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001645 return (size_t)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001646
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001647 if (size < 0) {
Victor Stinner838f2642019-06-13 22:41:23 +02001648 _PyErr_SetString(tstate, PyExc_ValueError,
1649 "__sizeof__() should return >= 0");
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001650 return (size_t)-1;
1651 }
1652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001653 /* add gc_head size */
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001654 if (PyObject_IS_GC(o))
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001655 return ((size_t)size) + sizeof(PyGC_Head);
1656 return (size_t)size;
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001657}
1658
1659static PyObject *
1660sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
1661{
1662 static char *kwlist[] = {"object", "default", 0};
1663 size_t size;
1664 PyObject *o, *dflt = NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02001665 PyThreadState *tstate = _PyThreadState_GET();
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001666
1667 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
Victor Stinner838f2642019-06-13 22:41:23 +02001668 kwlist, &o, &dflt)) {
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001669 return NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02001670 }
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001671
1672 size = _PySys_GetSizeOf(o);
1673
Victor Stinner838f2642019-06-13 22:41:23 +02001674 if (size == (size_t)-1 && _PyErr_Occurred(tstate)) {
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001675 /* Has a default value been given */
Victor Stinner838f2642019-06-13 22:41:23 +02001676 if (dflt != NULL && _PyErr_ExceptionMatches(tstate, PyExc_TypeError)) {
1677 _PyErr_Clear(tstate);
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001678 Py_INCREF(dflt);
1679 return dflt;
1680 }
1681 else
1682 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001683 }
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001684
1685 return PyLong_FromSize_t(size);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001686}
1687
1688PyDoc_STRVAR(getsizeof_doc,
Tal Einatede0b6f2018-12-31 17:12:08 +02001689"getsizeof(object [, default]) -> int\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001690\n\
1691Return the size of object in bytes.");
1692
Tal Einatede0b6f2018-12-31 17:12:08 +02001693/*[clinic input]
1694sys.getrefcount -> Py_ssize_t
1695
1696 object: object
1697 /
1698
1699Return the reference count of object.
1700
1701The count returned is generally one higher than you might expect,
1702because it includes the (temporary) reference as an argument to
1703getrefcount().
1704[clinic start generated code]*/
1705
1706static Py_ssize_t
1707sys_getrefcount_impl(PyObject *module, PyObject *object)
1708/*[clinic end generated code: output=5fd477f2264b85b2 input=bf474efd50a21535]*/
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001709{
Tal Einatede0b6f2018-12-31 17:12:08 +02001710 return object->ob_refcnt;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001711}
1712
Tim Peters4be93d02002-07-07 19:59:50 +00001713#ifdef Py_REF_DEBUG
Tal Einatede0b6f2018-12-31 17:12:08 +02001714/*[clinic input]
1715sys.gettotalrefcount -> Py_ssize_t
1716[clinic start generated code]*/
1717
1718static Py_ssize_t
1719sys_gettotalrefcount_impl(PyObject *module)
1720/*[clinic end generated code: output=4103886cf17c25bc input=53b744faa5d2e4f6]*/
Mark Hammond440d8982000-06-20 08:12:48 +00001721{
Tal Einatede0b6f2018-12-31 17:12:08 +02001722 return _Py_GetRefTotal();
Mark Hammond440d8982000-06-20 08:12:48 +00001723}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001724#endif /* Py_REF_DEBUG */
Mark Hammond440d8982000-06-20 08:12:48 +00001725
Tal Einatede0b6f2018-12-31 17:12:08 +02001726/*[clinic input]
1727sys.getallocatedblocks -> Py_ssize_t
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001728
Tal Einatede0b6f2018-12-31 17:12:08 +02001729Return the number of memory blocks currently allocated.
1730[clinic start generated code]*/
1731
1732static Py_ssize_t
1733sys_getallocatedblocks_impl(PyObject *module)
1734/*[clinic end generated code: output=f0c4e873f0b6dcf7 input=dab13ee346a0673e]*/
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001735{
Tal Einatede0b6f2018-12-31 17:12:08 +02001736 return _Py_GetAllocatedBlocks();
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001737}
1738
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001739#ifdef COUNT_ALLOCS
Tal Einatede0b6f2018-12-31 17:12:08 +02001740/*[clinic input]
1741sys.getcounts
1742[clinic start generated code]*/
1743
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001744static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001745sys_getcounts_impl(PyObject *module)
1746/*[clinic end generated code: output=20df00bc164f43cb input=ad2ec7bda5424953]*/
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001747{
Pablo Galindo49c75a82018-10-28 15:02:17 +00001748 extern PyObject *_Py_get_counts(void);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001749
Pablo Galindo49c75a82018-10-28 15:02:17 +00001750 return _Py_get_counts();
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001751}
1752#endif
1753
Tal Einatede0b6f2018-12-31 17:12:08 +02001754/*[clinic input]
1755sys._getframe
1756
1757 depth: int = 0
1758 /
1759
1760Return a frame object from the call stack.
1761
1762If optional integer depth is given, return the frame object that many
1763calls below the top of the stack. If that is deeper than the call
1764stack, ValueError is raised. The default for depth is zero, returning
1765the frame at the top of the call stack.
1766
1767This function should be used for internal and specialized purposes
1768only.
1769[clinic start generated code]*/
Barry Warsawb6a54d22000-12-06 21:47:46 +00001770
1771static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001772sys__getframe_impl(PyObject *module, int depth)
1773/*[clinic end generated code: output=d438776c04d59804 input=c1be8a6464b11ee5]*/
Barry Warsawb6a54d22000-12-06 21:47:46 +00001774{
Victor Stinner838f2642019-06-13 22:41:23 +02001775 PyThreadState *tstate = _PyThreadState_GET();
1776 PyFrameObject *f = tstate->frame;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001777
Steve Dowerb82e17e2019-05-23 08:45:22 -07001778 if (PySys_Audit("sys._getframe", "O", f) < 0) {
1779 return NULL;
1780 }
1781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001782 while (depth > 0 && f != NULL) {
1783 f = f->f_back;
1784 --depth;
1785 }
1786 if (f == NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +02001787 _PyErr_SetString(tstate, PyExc_ValueError,
1788 "call stack is not deep enough");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001789 return NULL;
1790 }
1791 Py_INCREF(f);
1792 return (PyObject*)f;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001793}
1794
Tal Einatede0b6f2018-12-31 17:12:08 +02001795/*[clinic input]
1796sys._current_frames
1797
1798Return a dict mapping each thread's thread id to its current stack frame.
1799
1800This function should be used for specialized purposes only.
1801[clinic start generated code]*/
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001802
1803static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001804sys__current_frames_impl(PyObject *module)
1805/*[clinic end generated code: output=d2a41ac0a0a3809a input=2a9049c5f5033691]*/
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001806{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001807 return _PyThread_CurrentFrames();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001808}
1809
Tal Einatede0b6f2018-12-31 17:12:08 +02001810/*[clinic input]
1811sys.call_tracing
1812
1813 func: object
1814 args as funcargs: object(subclass_of='&PyTuple_Type')
1815 /
1816
1817Call func(*args), while tracing is enabled.
1818
1819The tracing state is saved, and restored afterwards. This is intended
1820to be called from a debugger from a checkpoint, to recursively debug
1821some other code.
1822[clinic start generated code]*/
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001823
1824static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001825sys_call_tracing_impl(PyObject *module, PyObject *func, PyObject *funcargs)
1826/*[clinic end generated code: output=7e4999853cd4e5a6 input=5102e8b11049f92f]*/
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001827{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001828 return _PyEval_CallTracing(func, funcargs);
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001829}
1830
Tal Einatede0b6f2018-12-31 17:12:08 +02001831/*[clinic input]
1832sys.callstats
1833
1834Return a tuple of function call statistics.
1835
1836A tuple is returned only if CALL_PROFILE was defined when Python was
1837built. Otherwise, this returns None.
1838
1839When enabled, this function returns detailed, implementation-specific
1840details about the number of function calls executed. The return value
1841is a 11-tuple where the entries in the tuple are counts of:
18420. all function calls
18431. calls to PyFunction_Type objects
18442. PyFunction calls that do not create an argument tuple
18453. PyFunction calls that do not create an argument tuple
1846 and bypass PyEval_EvalCodeEx()
18474. PyMethod calls
18485. PyMethod calls on bound methods
18496. PyType calls
18507. PyCFunction calls
18518. generator calls
18529. All other calls
185310. Number of stack pops performed by call_function()
1854[clinic start generated code]*/
Barry Warsawb6a54d22000-12-06 21:47:46 +00001855
Victor Stinner048afd92016-11-28 11:59:04 +01001856static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001857sys_callstats_impl(PyObject *module)
1858/*[clinic end generated code: output=edc4a74957fa8def input=d447d8d224d5d175]*/
Victor Stinner048afd92016-11-28 11:59:04 +01001859{
1860 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1861 "sys.callstats() has been deprecated in Python 3.7 "
1862 "and will be removed in the future", 1) < 0) {
1863 return NULL;
1864 }
1865
1866 Py_RETURN_NONE;
1867}
1868
1869
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001870#ifdef __cplusplus
1871extern "C" {
1872#endif
1873
Tal Einatede0b6f2018-12-31 17:12:08 +02001874/*[clinic input]
1875sys._debugmallocstats
1876
1877Print summary info to stderr about the state of pymalloc's structures.
1878
1879In Py_DEBUG mode, also perform some expensive internal consistency
1880checks.
1881[clinic start generated code]*/
1882
David Malcolm49526f42012-06-22 14:55:41 -04001883static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001884sys__debugmallocstats_impl(PyObject *module)
1885/*[clinic end generated code: output=ec3565f8c7cee46a input=33c0c9c416f98424]*/
David Malcolm49526f42012-06-22 14:55:41 -04001886{
1887#ifdef WITH_PYMALLOC
Victor Stinner6bf992a2017-12-06 17:26:10 +01001888 if (_PyObject_DebugMallocStats(stderr)) {
Victor Stinner34be8072016-03-14 12:04:26 +01001889 fputc('\n', stderr);
1890 }
David Malcolm49526f42012-06-22 14:55:41 -04001891#endif
1892 _PyObject_DebugTypeStats(stderr);
1893
1894 Py_RETURN_NONE;
1895}
David Malcolm49526f42012-06-22 14:55:41 -04001896
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001897#ifdef Py_TRACE_REFS
Guido van Rossumded690f1996-05-24 20:48:31 +00001898/* Defined in objects.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001899extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001900#endif
Guido van Rossumded690f1996-05-24 20:48:31 +00001901
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001902#ifdef DYNAMIC_EXECUTION_PROFILE
1903/* Defined in ceval.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001904extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001905#endif
1906
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001907#ifdef __cplusplus
1908}
1909#endif
1910
Tal Einatede0b6f2018-12-31 17:12:08 +02001911
1912/*[clinic input]
1913sys._clear_type_cache
1914
1915Clear the internal type lookup cache.
1916[clinic start generated code]*/
1917
Christian Heimes15ebc882008-02-04 18:48:49 +00001918static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001919sys__clear_type_cache_impl(PyObject *module)
1920/*[clinic end generated code: output=20e48ca54a6f6971 input=127f3e04a8d9b555]*/
Christian Heimes15ebc882008-02-04 18:48:49 +00001921{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001922 PyType_ClearCache();
1923 Py_RETURN_NONE;
Christian Heimes15ebc882008-02-04 18:48:49 +00001924}
1925
Tal Einatede0b6f2018-12-31 17:12:08 +02001926/*[clinic input]
1927sys.is_finalizing
1928
1929Return True if Python is exiting.
1930[clinic start generated code]*/
1931
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001932static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001933sys_is_finalizing_impl(PyObject *module)
1934/*[clinic end generated code: output=735b5ff7962ab281 input=f0df747a039948a5]*/
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001935{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001936 return PyBool_FromLong(_Py_IsFinalizing());
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001937}
1938
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001939#ifdef ANDROID_API_LEVEL
Tal Einatede0b6f2018-12-31 17:12:08 +02001940/*[clinic input]
1941sys.getandroidapilevel
1942
1943Return the build time API version of Android as an integer.
1944[clinic start generated code]*/
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001945
1946static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001947sys_getandroidapilevel_impl(PyObject *module)
1948/*[clinic end generated code: output=214abf183a1c70c1 input=3e6d6c9fcdd24ac6]*/
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001949{
1950 return PyLong_FromLong(ANDROID_API_LEVEL);
1951}
1952#endif /* ANDROID_API_LEVEL */
1953
1954
Steve Dowerb82e17e2019-05-23 08:45:22 -07001955
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001956static PyMethodDef sys_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001957 /* Might as well keep this in alphabetic order */
Steve Dowerb82e17e2019-05-23 08:45:22 -07001958 SYS_ADDAUDITHOOK_METHODDEF
1959 {"audit", (PyCFunction)(void(*)(void))sys_audit, METH_FASTCALL, audit_doc },
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001960 {"breakpointhook", (PyCFunction)(void(*)(void))sys_breakpointhook,
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04001961 METH_FASTCALL | METH_KEYWORDS, breakpointhook_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001962 SYS_CALLSTATS_METHODDEF
1963 SYS__CLEAR_TYPE_CACHE_METHODDEF
1964 SYS__CURRENT_FRAMES_METHODDEF
1965 SYS_DISPLAYHOOK_METHODDEF
1966 SYS_EXC_INFO_METHODDEF
1967 SYS_EXCEPTHOOK_METHODDEF
1968 SYS_EXIT_METHODDEF
1969 SYS_GETDEFAULTENCODING_METHODDEF
1970 SYS_GETDLOPENFLAGS_METHODDEF
1971 SYS_GETALLOCATEDBLOCKS_METHODDEF
1972 SYS_GETCOUNTS_METHODDEF
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001973#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001974 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001975#endif
Tal Einatede0b6f2018-12-31 17:12:08 +02001976 SYS_GETFILESYSTEMENCODING_METHODDEF
1977 SYS_GETFILESYSTEMENCODEERRORS_METHODDEF
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001978#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001979 {"getobjects", _Py_GetObjects, METH_VARARGS},
Tim Peters4be93d02002-07-07 19:59:50 +00001980#endif
Tal Einatede0b6f2018-12-31 17:12:08 +02001981 SYS_GETTOTALREFCOUNT_METHODDEF
1982 SYS_GETREFCOUNT_METHODDEF
1983 SYS_GETRECURSIONLIMIT_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001984 {"getsizeof", (PyCFunction)(void(*)(void))sys_getsizeof,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001986 SYS__GETFRAME_METHODDEF
1987 SYS_GETWINDOWSVERSION_METHODDEF
1988 SYS__ENABLELEGACYWINDOWSFSENCODING_METHODDEF
1989 SYS_INTERN_METHODDEF
1990 SYS_IS_FINALIZING_METHODDEF
1991 SYS_MDEBUG_METHODDEF
1992 SYS_SETCHECKINTERVAL_METHODDEF
1993 SYS_GETCHECKINTERVAL_METHODDEF
1994 SYS_SETSWITCHINTERVAL_METHODDEF
1995 SYS_GETSWITCHINTERVAL_METHODDEF
1996 SYS_SETDLOPENFLAGS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001997 {"setprofile", sys_setprofile, METH_O, setprofile_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001998 SYS_GETPROFILE_METHODDEF
1999 SYS_SETRECURSIONLIMIT_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002000 {"settrace", sys_settrace, METH_O, settrace_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02002001 SYS_GETTRACE_METHODDEF
2002 SYS_CALL_TRACING_METHODDEF
2003 SYS__DEBUGMALLOCSTATS_METHODDEF
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08002004 SYS_SET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
2005 SYS_GET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002006 {"set_asyncgen_hooks", (PyCFunction)(void(*)(void))sys_set_asyncgen_hooks,
Yury Selivanoveb636452016-09-08 22:01:51 -07002007 METH_VARARGS | METH_KEYWORDS, set_asyncgen_hooks_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02002008 SYS_GET_ASYNCGEN_HOOKS_METHODDEF
2009 SYS_GETANDROIDAPILEVEL_METHODDEF
Victor Stinneref9d9b62019-05-22 11:28:22 +02002010 SYS_UNRAISABLEHOOK_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002011 {NULL, NULL} /* sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +00002012};
2013
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002014static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002015list_builtin_module_names(void)
Guido van Rossum34679b71993-01-26 13:33:44 +00002016{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002017 PyObject *list = PyList_New(0);
2018 int i;
2019 if (list == NULL)
2020 return NULL;
2021 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
2022 PyObject *name = PyUnicode_FromString(
2023 PyImport_Inittab[i].name);
2024 if (name == NULL)
2025 break;
2026 PyList_Append(list, name);
2027 Py_DECREF(name);
2028 }
2029 if (PyList_Sort(list) != 0) {
2030 Py_DECREF(list);
2031 list = NULL;
2032 }
2033 if (list) {
2034 PyObject *v = PyList_AsTuple(list);
2035 Py_DECREF(list);
2036 list = v;
2037 }
2038 return list;
Guido van Rossum34679b71993-01-26 13:33:44 +00002039}
2040
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002041/* Pre-initialization support for sys.warnoptions and sys._xoptions
2042 *
2043 * Modern internal code paths:
2044 * These APIs get called after _Py_InitializeCore and get to use the
2045 * regular CPython list, dict, and unicode APIs.
2046 *
2047 * Legacy embedding code paths:
2048 * The multi-phase initialization API isn't public yet, so embedding
2049 * apps still need to be able configure sys.warnoptions and sys._xoptions
2050 * before they call Py_Initialize. To support this, we stash copies of
2051 * the supplied wchar * sequences in linked lists, and then migrate the
2052 * contents of those lists to the sys module in _PyInitializeCore.
2053 *
2054 */
2055
2056struct _preinit_entry {
2057 wchar_t *value;
2058 struct _preinit_entry *next;
2059};
2060
2061typedef struct _preinit_entry *_Py_PreInitEntry;
2062
2063static _Py_PreInitEntry _preinit_warnoptions = NULL;
2064static _Py_PreInitEntry _preinit_xoptions = NULL;
2065
2066static _Py_PreInitEntry
2067_alloc_preinit_entry(const wchar_t *value)
2068{
2069 /* To get this to work, we have to initialize the runtime implicitly */
2070 _PyRuntime_Initialize();
2071
2072 /* Force default allocator, so we can ensure that it also gets used to
2073 * destroy the linked list in _clear_preinit_entries.
2074 */
2075 PyMemAllocatorEx old_alloc;
2076 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2077
2078 _Py_PreInitEntry node = PyMem_RawCalloc(1, sizeof(*node));
2079 if (node != NULL) {
2080 node->value = _PyMem_RawWcsdup(value);
2081 if (node->value == NULL) {
2082 PyMem_RawFree(node);
2083 node = NULL;
2084 };
2085 };
2086
2087 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2088 return node;
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002089}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002090
2091static int
2092_append_preinit_entry(_Py_PreInitEntry *optionlist, const wchar_t *value)
2093{
2094 _Py_PreInitEntry new_entry = _alloc_preinit_entry(value);
2095 if (new_entry == NULL) {
2096 return -1;
2097 }
2098 /* We maintain the linked list in this order so it's easy to play back
2099 * the add commands in the same order later on in _Py_InitializeCore
2100 */
2101 _Py_PreInitEntry last_entry = *optionlist;
2102 if (last_entry == NULL) {
2103 *optionlist = new_entry;
2104 } else {
2105 while (last_entry->next != NULL) {
2106 last_entry = last_entry->next;
2107 }
2108 last_entry->next = new_entry;
2109 }
2110 return 0;
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002111}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002112
2113static void
2114_clear_preinit_entries(_Py_PreInitEntry *optionlist)
2115{
2116 _Py_PreInitEntry current = *optionlist;
2117 *optionlist = NULL;
2118 /* Deallocate the nodes and their contents using the default allocator */
2119 PyMemAllocatorEx old_alloc;
2120 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2121 while (current != NULL) {
2122 _Py_PreInitEntry next = current->next;
2123 PyMem_RawFree(current->value);
2124 PyMem_RawFree(current);
2125 current = next;
2126 }
2127 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002128}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002129
2130static void
2131_clear_all_preinit_options(void)
2132{
2133 _clear_preinit_entries(&_preinit_warnoptions);
2134 _clear_preinit_entries(&_preinit_xoptions);
2135}
2136
2137static int
Victor Stinner838f2642019-06-13 22:41:23 +02002138sys_read_preinit_options(PyThreadState *tstate)
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002139{
2140 /* Rerun the add commands with the actual sys module available */
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002141 if (tstate == NULL) {
2142 /* Still don't have a thread state, so something is wrong! */
2143 return -1;
2144 }
2145 _Py_PreInitEntry entry = _preinit_warnoptions;
2146 while (entry != NULL) {
2147 PySys_AddWarnOption(entry->value);
2148 entry = entry->next;
2149 }
2150 entry = _preinit_xoptions;
2151 while (entry != NULL) {
2152 PySys_AddXOption(entry->value);
2153 entry = entry->next;
2154 }
2155
2156 _clear_all_preinit_options();
2157 return 0;
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002158}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002159
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002160static PyObject *
Victor Stinner838f2642019-06-13 22:41:23 +02002161get_warnoptions(PyThreadState *tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002162{
Victor Stinner838f2642019-06-13 22:41:23 +02002163 PyObject *warnoptions = sys_get_object_id(tstate, &PyId_warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002164 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002165 /* PEP432 TODO: we can reach this if warnoptions is NULL in the main
2166 * interpreter config. When that happens, we need to properly set
2167 * the `warnoptions` reference in the main interpreter config as well.
2168 *
2169 * For Python 3.7, we shouldn't be able to get here due to the
2170 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
2171 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
2172 * call optional for embedding applications, thus making this
2173 * reachable again.
2174 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002175 warnoptions = PyList_New(0);
Victor Stinner838f2642019-06-13 22:41:23 +02002176 if (warnoptions == NULL) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002177 return NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02002178 }
2179 if (sys_set_object_id(tstate, &PyId_warnoptions, warnoptions)) {
Eric Snowdae02762017-09-14 00:35:58 -07002180 Py_DECREF(warnoptions);
2181 return NULL;
2182 }
2183 Py_DECREF(warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002184 }
2185 return warnoptions;
2186}
Guido van Rossum23fff912000-12-15 22:02:05 +00002187
2188void
2189PySys_ResetWarnOptions(void)
2190{
Victor Stinner50b48572018-11-01 01:51:40 +01002191 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002192 if (tstate == NULL) {
2193 _clear_preinit_entries(&_preinit_warnoptions);
2194 return;
2195 }
2196
Victor Stinner838f2642019-06-13 22:41:23 +02002197 PyObject *warnoptions = sys_get_object_id(tstate, &PyId_warnoptions);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002198 if (warnoptions == NULL || !PyList_Check(warnoptions))
2199 return;
2200 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
Guido van Rossum23fff912000-12-15 22:02:05 +00002201}
2202
Victor Stinnere1b29952018-10-30 14:31:42 +01002203static int
Victor Stinner838f2642019-06-13 22:41:23 +02002204_PySys_AddWarnOptionWithError(PyThreadState *tstate, PyObject *option)
Guido van Rossum23fff912000-12-15 22:02:05 +00002205{
Victor Stinner838f2642019-06-13 22:41:23 +02002206 PyObject *warnoptions = get_warnoptions(tstate);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002207 if (warnoptions == NULL) {
2208 return -1;
2209 }
2210 if (PyList_Append(warnoptions, option)) {
2211 return -1;
2212 }
2213 return 0;
2214}
2215
2216void
2217PySys_AddWarnOptionUnicode(PyObject *option)
2218{
Victor Stinner838f2642019-06-13 22:41:23 +02002219 PyThreadState *tstate = _PyThreadState_GET();
2220 if (_PySys_AddWarnOptionWithError(tstate, option) < 0) {
Victor Stinnere1b29952018-10-30 14:31:42 +01002221 /* No return value, therefore clear error state if possible */
Victor Stinner838f2642019-06-13 22:41:23 +02002222 if (tstate) {
2223 _PyErr_Clear(tstate);
Victor Stinnere1b29952018-10-30 14:31:42 +01002224 }
2225 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00002226}
2227
2228void
2229PySys_AddWarnOption(const wchar_t *s)
2230{
Victor Stinner50b48572018-11-01 01:51:40 +01002231 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002232 if (tstate == NULL) {
2233 _append_preinit_entry(&_preinit_warnoptions, s);
2234 return;
2235 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00002236 PyObject *unicode;
2237 unicode = PyUnicode_FromWideChar(s, -1);
2238 if (unicode == NULL)
2239 return;
2240 PySys_AddWarnOptionUnicode(unicode);
2241 Py_DECREF(unicode);
Guido van Rossum23fff912000-12-15 22:02:05 +00002242}
2243
Christian Heimes33fe8092008-04-13 13:53:33 +00002244int
2245PySys_HasWarnOptions(void)
2246{
Victor Stinner838f2642019-06-13 22:41:23 +02002247 PyThreadState *tstate = _PyThreadState_GET();
2248 PyObject *warnoptions = sys_get_object_id(tstate, &PyId_warnoptions);
Serhiy Storchakadffccc62018-12-10 13:50:22 +02002249 return (warnoptions != NULL && PyList_Check(warnoptions)
2250 && PyList_GET_SIZE(warnoptions) > 0);
Christian Heimes33fe8092008-04-13 13:53:33 +00002251}
2252
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002253static PyObject *
Victor Stinner838f2642019-06-13 22:41:23 +02002254get_xoptions(PyThreadState *tstate)
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002255{
Victor Stinner838f2642019-06-13 22:41:23 +02002256 PyObject *xoptions = sys_get_object_id(tstate, &PyId__xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002257 if (xoptions == NULL || !PyDict_Check(xoptions)) {
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002258 /* PEP432 TODO: we can reach this if xoptions is NULL in the main
2259 * interpreter config. When that happens, we need to properly set
2260 * the `xoptions` reference in the main interpreter config as well.
2261 *
2262 * For Python 3.7, we shouldn't be able to get here due to the
2263 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
2264 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
2265 * call optional for embedding applications, thus making this
2266 * reachable again.
2267 */
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002268 xoptions = PyDict_New();
Victor Stinner838f2642019-06-13 22:41:23 +02002269 if (xoptions == NULL) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002270 return NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02002271 }
2272 if (sys_set_object_id(tstate, &PyId__xoptions, xoptions)) {
Eric Snowdae02762017-09-14 00:35:58 -07002273 Py_DECREF(xoptions);
2274 return NULL;
2275 }
2276 Py_DECREF(xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002277 }
2278 return xoptions;
2279}
2280
Victor Stinnere1b29952018-10-30 14:31:42 +01002281static int
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002282_PySys_AddXOptionWithError(const wchar_t *s)
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002283{
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002284 PyObject *name = NULL, *value = NULL;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002285
Victor Stinner838f2642019-06-13 22:41:23 +02002286 PyThreadState *tstate = _PyThreadState_GET();
2287 PyObject *opts = get_xoptions(tstate);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002288 if (opts == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002289 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002290 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002291
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002292 const wchar_t *name_end = wcschr(s, L'=');
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002293 if (!name_end) {
2294 name = PyUnicode_FromWideChar(s, -1);
2295 value = Py_True;
2296 Py_INCREF(value);
2297 }
2298 else {
2299 name = PyUnicode_FromWideChar(s, name_end - s);
2300 value = PyUnicode_FromWideChar(name_end + 1, -1);
2301 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002302 if (name == NULL || value == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002303 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002304 }
2305 if (PyDict_SetItem(opts, name, value) < 0) {
2306 goto error;
2307 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002308 Py_DECREF(name);
2309 Py_DECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002310 return 0;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002311
2312error:
2313 Py_XDECREF(name);
2314 Py_XDECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002315 return -1;
2316}
2317
2318void
2319PySys_AddXOption(const wchar_t *s)
2320{
Victor Stinner50b48572018-11-01 01:51:40 +01002321 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002322 if (tstate == NULL) {
2323 _append_preinit_entry(&_preinit_xoptions, s);
2324 return;
2325 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002326 if (_PySys_AddXOptionWithError(s) < 0) {
2327 /* No return value, therefore clear error state if possible */
Victor Stinner838f2642019-06-13 22:41:23 +02002328 if (tstate) {
2329 _PyErr_Clear(tstate);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002330 }
Victor Stinner0cae6092016-11-11 01:43:56 +01002331 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002332}
2333
2334PyObject *
2335PySys_GetXOptions(void)
2336{
Victor Stinner838f2642019-06-13 22:41:23 +02002337 PyThreadState *tstate = _PyThreadState_GET();
2338 return get_xoptions(tstate);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002339}
2340
Guido van Rossum40552d01998-08-06 03:34:39 +00002341/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
2342 Two literals concatenated works just fine. If you have a K&R compiler
2343 or other abomination that however *does* understand longer strings,
2344 get rid of the !!! comment in the middle and the quotes that surround it. */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002345PyDoc_VAR(sys_doc) =
2346PyDoc_STR(
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002347"This module provides access to some objects used or maintained by the\n\
2348interpreter and to functions that interact strongly with the interpreter.\n\
2349\n\
2350Dynamic objects:\n\
2351\n\
2352argv -- command line arguments; argv[0] is the script pathname if known\n\
2353path -- module search path; path[0] is the script directory, else ''\n\
2354modules -- dictionary of loaded modules\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002355\n\
2356displayhook -- called to show results in an interactive session\n\
2357excepthook -- called to handle any uncaught exception other than SystemExit\n\
2358 To customize printing in an interactive session or to install a custom\n\
2359 top-level exception handler, assign other functions to replace these.\n\
2360\n\
Benjamin Peterson06157a42008-07-15 00:28:36 +00002361stdin -- standard input file object; used by input()\n\
Georg Brandl88fc6642007-02-09 21:28:07 +00002362stdout -- standard output file object; used by print()\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002363stderr -- standard error object; used for error messages\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002364 By assigning other file objects (or objects that behave like files)\n\
2365 to these, it is possible to redirect all of the interpreter's I/O.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002366\n\
2367last_type -- type of last uncaught exception\n\
2368last_value -- value of last uncaught exception\n\
2369last_traceback -- traceback of last uncaught exception\n\
2370 These three are only available in an interactive session after a\n\
2371 traceback has been printed.\n\
Guido van Rossuma71b5f41999-01-14 19:07:00 +00002372"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002373)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002374/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002375PyDoc_STR(
Guido van Rossuma71b5f41999-01-14 19:07:00 +00002376"\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002377Static objects:\n\
2378\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002379builtin_module_names -- tuple of module names built into this interpreter\n\
2380copyright -- copyright notice pertaining to this interpreter\n\
2381exec_prefix -- prefix used to find the machine-specific Python library\n\
Petri Lehtinen4b0eab62012-02-02 21:23:15 +02002382executable -- absolute path of the executable binary of the Python interpreter\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002383float_info -- a struct sequence with information about the float implementation.\n\
2384float_repr_style -- string indicating the style of repr() output for floats\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +01002385hash_info -- a struct sequence with information about the hash algorithm.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002386hexversion -- version information encoded as a single integer\n\
Barry Warsaw409da152012-06-03 16:18:47 -04002387implementation -- Python implementation information.\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00002388int_info -- a struct sequence with information about the int implementation.\n\
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00002389maxsize -- the largest supported length of containers.\n\
Serhiy Storchakad3faf432015-01-18 11:28:37 +02002390maxunicode -- the value of the largest Unicode code point\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002391platform -- platform identifier\n\
2392prefix -- prefix used to find the Python library\n\
2393thread_info -- a struct sequence with information about the thread implementation.\n\
Fred Drake801c08d2000-04-13 15:29:10 +00002394version -- the version of this interpreter as a string\n\
Eric Smith0e5b5622009-02-06 01:32:42 +00002395version_info -- version information as a named tuple\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002396"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002397)
Steve Dowercc16be82016-09-08 10:35:16 -07002398#ifdef MS_COREDLL
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002399/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002400PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002401"dllhandle -- [Windows only] integer handle of the Python DLL\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002402winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002403"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002404)
Steve Dowercc16be82016-09-08 10:35:16 -07002405#endif /* MS_COREDLL */
2406#ifdef MS_WINDOWS
2407/* concatenating string here */
2408PyDoc_STR(
oldkaa0735f2018-02-02 16:52:55 +08002409"_enablelegacywindowsfsencoding -- [Windows only]\n\
Steve Dowercc16be82016-09-08 10:35:16 -07002410"
2411)
2412#endif
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002413PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002414"__stdin__ -- the original stdin; don't touch!\n\
2415__stdout__ -- the original stdout; don't touch!\n\
2416__stderr__ -- the original stderr; don't touch!\n\
2417__displayhook__ -- the original displayhook; don't touch!\n\
2418__excepthook__ -- the original excepthook; don't touch!\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002419\n\
2420Functions:\n\
2421\n\
Georg Brandl1a3284e2007-12-02 09:40:06 +00002422displayhook() -- print an object to the screen, and save it in builtins._\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002423excepthook() -- print an exception and its traceback to sys.stderr\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002424exc_info() -- return thread-safe information about the current exception\n\
2425exit() -- exit the interpreter by raising SystemExit\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002426getdlopenflags() -- returns flags to be used for dlopen() calls\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002427getprofile() -- get the global profiling function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002428getrefcount() -- return the reference count for an object (plus one :-)\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002429getrecursionlimit() -- return the max recursion depth for the interpreter\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002430getsizeof() -- return the size of an object in bytes\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002431gettrace() -- get the global debug tracing function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002432setcheckinterval() -- control how often the interpreter checks for events\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002433setdlopenflags() -- set the flags to be used for dlopen() calls\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002434setprofile() -- set the global profiling function\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002435setrecursionlimit() -- set the max recursion depth for the interpreter\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002436settrace() -- set the global debug tracing function\n\
Fred Drakeccede592000-08-14 20:59:57 +00002437"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002438)
Fred Drakeccede592000-08-14 20:59:57 +00002439/* end of sys_doc */ ;
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002440
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002441
2442PyDoc_STRVAR(flags__doc__,
2443"sys.flags\n\
2444\n\
2445Flags provided through command line arguments or environment vars.");
2446
2447static PyTypeObject FlagsType;
2448
2449static PyStructSequence_Field flags_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002450 {"debug", "-d"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002451 {"inspect", "-i"},
2452 {"interactive", "-i"},
2453 {"optimize", "-O or -OO"},
2454 {"dont_write_bytecode", "-B"},
2455 {"no_user_site", "-s"},
2456 {"no_site", "-S"},
2457 {"ignore_environment", "-E"},
2458 {"verbose", "-v"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002459 /* {"unbuffered", "-u"}, */
2460 /* {"skip_first", "-x"}, */
Georg Brandl8aa7e992010-12-28 18:30:18 +00002461 {"bytes_warning", "-b"},
2462 {"quiet", "-q"},
Georg Brandl09a7c722012-02-20 21:31:46 +01002463 {"hash_randomization", "-R"},
Christian Heimesad73a9c2013-08-10 16:36:18 +02002464 {"isolated", "-I"},
Victor Stinner5e3806f2017-11-30 11:40:24 +01002465 {"dev_mode", "-X dev"},
Victor Stinner91106cd2017-12-13 12:29:09 +01002466 {"utf8_mode", "-X utf8"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002467 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002468};
2469
2470static PyStructSequence_Desc flags_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002471 "sys.flags", /* name */
2472 flags__doc__, /* doc */
2473 flags_fields, /* fields */
Victor Stinner91106cd2017-12-13 12:29:09 +01002474 15
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002475};
2476
2477static PyObject*
Victor Stinner838f2642019-06-13 22:41:23 +02002478make_flags(_PyRuntimeState *runtime, PyThreadState *tstate)
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002479{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002480 int pos = 0;
2481 PyObject *seq;
Victor Stinner331a6a52019-05-27 16:39:22 +02002482 const PyPreConfig *preconfig = &runtime->preconfig;
Victor Stinner838f2642019-06-13 22:41:23 +02002483 const PyConfig *config = &tstate->interp->config;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002485 seq = PyStructSequence_New(&FlagsType);
2486 if (seq == NULL)
2487 return NULL;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002488
2489#define SetFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002490 PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002491
Victor Stinnerfbca9082018-08-30 00:50:45 +02002492 SetFlag(config->parser_debug);
2493 SetFlag(config->inspect);
2494 SetFlag(config->interactive);
2495 SetFlag(config->optimization_level);
2496 SetFlag(!config->write_bytecode);
2497 SetFlag(!config->user_site_directory);
2498 SetFlag(!config->site_import);
Victor Stinner20004952019-03-26 02:31:11 +01002499 SetFlag(!config->use_environment);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002500 SetFlag(config->verbose);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002501 /* SetFlag(saw_unbuffered_flag); */
2502 /* SetFlag(skipfirstline); */
Victor Stinnerfbca9082018-08-30 00:50:45 +02002503 SetFlag(config->bytes_warning);
2504 SetFlag(config->quiet);
2505 SetFlag(config->use_hash_seed == 0 || config->hash_seed != 0);
Victor Stinner20004952019-03-26 02:31:11 +01002506 SetFlag(config->isolated);
2507 PyStructSequence_SET_ITEM(seq, pos++, PyBool_FromLong(config->dev_mode));
2508 SetFlag(preconfig->utf8_mode);
Victor Stinner91106cd2017-12-13 12:29:09 +01002509#undef SetFlag
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002510
Victor Stinner838f2642019-06-13 22:41:23 +02002511 if (_PyErr_Occurred(tstate)) {
Serhiy Storchaka87a854d2013-12-17 14:59:42 +02002512 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002513 return NULL;
2514 }
2515 return seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002516}
2517
Eric Smith0e5b5622009-02-06 01:32:42 +00002518PyDoc_STRVAR(version_info__doc__,
2519"sys.version_info\n\
2520\n\
2521Version information as a named tuple.");
2522
2523static PyTypeObject VersionInfoType;
2524
2525static PyStructSequence_Field version_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002526 {"major", "Major release number"},
2527 {"minor", "Minor release number"},
2528 {"micro", "Patch release number"},
Ned Deilyda4887a2016-11-04 17:03:34 -04002529 {"releaselevel", "'alpha', 'beta', 'candidate', or 'final'"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002530 {"serial", "Serial release number"},
2531 {0}
Eric Smith0e5b5622009-02-06 01:32:42 +00002532};
2533
2534static PyStructSequence_Desc version_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002535 "sys.version_info", /* name */
2536 version_info__doc__, /* doc */
2537 version_info_fields, /* fields */
2538 5
Eric Smith0e5b5622009-02-06 01:32:42 +00002539};
2540
2541static PyObject *
Victor Stinner838f2642019-06-13 22:41:23 +02002542make_version_info(PyThreadState *tstate)
Eric Smith0e5b5622009-02-06 01:32:42 +00002543{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002544 PyObject *version_info;
2545 char *s;
2546 int pos = 0;
Eric Smith0e5b5622009-02-06 01:32:42 +00002547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002548 version_info = PyStructSequence_New(&VersionInfoType);
2549 if (version_info == NULL) {
2550 return NULL;
2551 }
Eric Smith0e5b5622009-02-06 01:32:42 +00002552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002553 /*
2554 * These release level checks are mutually exclusive and cover
2555 * the field, so don't get too fancy with the pre-processor!
2556 */
Eric Smith0e5b5622009-02-06 01:32:42 +00002557#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002558 s = "alpha";
Eric Smith0e5b5622009-02-06 01:32:42 +00002559#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002560 s = "beta";
Eric Smith0e5b5622009-02-06 01:32:42 +00002561#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002562 s = "candidate";
Eric Smith0e5b5622009-02-06 01:32:42 +00002563#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002564 s = "final";
Eric Smith0e5b5622009-02-06 01:32:42 +00002565#endif
2566
2567#define SetIntItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002568 PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002569#define SetStrItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002570 PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002572 SetIntItem(PY_MAJOR_VERSION);
2573 SetIntItem(PY_MINOR_VERSION);
2574 SetIntItem(PY_MICRO_VERSION);
2575 SetStrItem(s);
2576 SetIntItem(PY_RELEASE_SERIAL);
Eric Smith0e5b5622009-02-06 01:32:42 +00002577#undef SetIntItem
2578#undef SetStrItem
2579
Victor Stinner838f2642019-06-13 22:41:23 +02002580 if (_PyErr_Occurred(tstate)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002581 Py_CLEAR(version_info);
2582 return NULL;
2583 }
2584 return version_info;
Eric Smith0e5b5622009-02-06 01:32:42 +00002585}
2586
Brett Cannon3adc7b72012-07-09 14:22:12 -04002587/* sys.implementation values */
2588#define NAME "cpython"
2589const char *_PySys_ImplName = NAME;
Victor Stinnercf01b682015-11-05 11:21:38 +01002590#define MAJOR Py_STRINGIFY(PY_MAJOR_VERSION)
2591#define MINOR Py_STRINGIFY(PY_MINOR_VERSION)
Ned Deily529ea5d2014-06-30 23:31:14 -07002592#define TAG NAME "-" MAJOR MINOR
Brett Cannon3adc7b72012-07-09 14:22:12 -04002593const char *_PySys_ImplCacheTag = TAG;
2594#undef NAME
Brett Cannon3adc7b72012-07-09 14:22:12 -04002595#undef MAJOR
2596#undef MINOR
2597#undef TAG
2598
Barry Warsaw409da152012-06-03 16:18:47 -04002599static PyObject *
2600make_impl_info(PyObject *version_info)
2601{
2602 int res;
2603 PyObject *impl_info, *value, *ns;
2604
2605 impl_info = PyDict_New();
2606 if (impl_info == NULL)
2607 return NULL;
2608
2609 /* populate the dict */
2610
Brett Cannon3adc7b72012-07-09 14:22:12 -04002611 value = PyUnicode_FromString(_PySys_ImplName);
Barry Warsaw409da152012-06-03 16:18:47 -04002612 if (value == NULL)
2613 goto error;
2614 res = PyDict_SetItemString(impl_info, "name", value);
2615 Py_DECREF(value);
2616 if (res < 0)
2617 goto error;
2618
Brett Cannon3adc7b72012-07-09 14:22:12 -04002619 value = PyUnicode_FromString(_PySys_ImplCacheTag);
Barry Warsaw409da152012-06-03 16:18:47 -04002620 if (value == NULL)
2621 goto error;
2622 res = PyDict_SetItemString(impl_info, "cache_tag", value);
2623 Py_DECREF(value);
2624 if (res < 0)
2625 goto error;
Barry Warsaw409da152012-06-03 16:18:47 -04002626
2627 res = PyDict_SetItemString(impl_info, "version", version_info);
2628 if (res < 0)
2629 goto error;
2630
2631 value = PyLong_FromLong(PY_VERSION_HEX);
2632 if (value == NULL)
2633 goto error;
2634 res = PyDict_SetItemString(impl_info, "hexversion", value);
2635 Py_DECREF(value);
2636 if (res < 0)
2637 goto error;
2638
doko@ubuntu.com55532312016-06-14 08:55:19 +02002639#ifdef MULTIARCH
2640 value = PyUnicode_FromString(MULTIARCH);
2641 if (value == NULL)
2642 goto error;
2643 res = PyDict_SetItemString(impl_info, "_multiarch", value);
2644 Py_DECREF(value);
2645 if (res < 0)
2646 goto error;
2647#endif
2648
Barry Warsaw409da152012-06-03 16:18:47 -04002649 /* dict ready */
2650
2651 ns = _PyNamespace_New(impl_info);
2652 Py_DECREF(impl_info);
2653 return ns;
2654
2655error:
2656 Py_CLEAR(impl_info);
2657 return NULL;
2658}
2659
Martin v. Löwis1a214512008-06-11 05:26:20 +00002660static struct PyModuleDef sysmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002661 PyModuleDef_HEAD_INIT,
2662 "sys",
2663 sys_doc,
2664 -1, /* multiple "initialization" just copies the module dict. */
2665 sys_methods,
2666 NULL,
2667 NULL,
2668 NULL,
2669 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002670};
2671
Eric Snow6b4be192017-05-22 21:36:03 -07002672/* Updating the sys namespace, returning NULL pointer on error */
Victor Stinner8fea2522013-10-27 17:15:42 +01002673#define SET_SYS_FROM_STRING_BORROW(key, value) \
Victor Stinner58049602013-07-22 22:40:00 +02002674 do { \
Victor Stinner58049602013-07-22 22:40:00 +02002675 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002676 if (v == NULL) { \
2677 goto err_occurred; \
2678 } \
Victor Stinner58049602013-07-22 22:40:00 +02002679 res = PyDict_SetItemString(sysdict, key, v); \
2680 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002681 goto err_occurred; \
Victor Stinner8fea2522013-10-27 17:15:42 +01002682 } \
2683 } while (0)
2684#define SET_SYS_FROM_STRING(key, value) \
2685 do { \
Victor Stinner8fea2522013-10-27 17:15:42 +01002686 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002687 if (v == NULL) { \
2688 goto err_occurred; \
2689 } \
Victor Stinner8fea2522013-10-27 17:15:42 +01002690 res = PyDict_SetItemString(sysdict, key, v); \
2691 Py_DECREF(v); \
2692 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002693 goto err_occurred; \
Victor Stinner58049602013-07-22 22:40:00 +02002694 } \
2695 } while (0)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002696
Victor Stinner331a6a52019-05-27 16:39:22 +02002697static PyStatus
Victor Stinner838f2642019-06-13 22:41:23 +02002698_PySys_InitCore(_PyRuntimeState *runtime, PyThreadState *tstate,
Victor Stinner0fd2c302019-06-04 03:15:09 +02002699 PyObject *sysdict)
Eric Snow6b4be192017-05-22 21:36:03 -07002700{
Victor Stinnerab672812019-01-23 15:04:40 +01002701 PyObject *version_info;
Eric Snow6b4be192017-05-22 21:36:03 -07002702 int res;
2703
Nick Coghland6009512014-11-20 21:39:37 +10002704 /* stdin/stdout/stderr are set in pylifecycle.c */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002705
Victor Stinner8fea2522013-10-27 17:15:42 +01002706 SET_SYS_FROM_STRING_BORROW("__displayhook__",
2707 PyDict_GetItemString(sysdict, "displayhook"));
2708 SET_SYS_FROM_STRING_BORROW("__excepthook__",
2709 PyDict_GetItemString(sysdict, "excepthook"));
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04002710 SET_SYS_FROM_STRING_BORROW(
2711 "__breakpointhook__",
2712 PyDict_GetItemString(sysdict, "breakpointhook"));
Victor Stinneref9d9b62019-05-22 11:28:22 +02002713 SET_SYS_FROM_STRING_BORROW("__unraisablehook__",
2714 PyDict_GetItemString(sysdict, "unraisablehook"));
2715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002716 SET_SYS_FROM_STRING("version",
2717 PyUnicode_FromString(Py_GetVersion()));
2718 SET_SYS_FROM_STRING("hexversion",
2719 PyLong_FromLong(PY_VERSION_HEX));
Ned Deily5c4b0d02017-03-04 00:19:55 -05002720 SET_SYS_FROM_STRING("_git",
2721 Py_BuildValue("(szz)", "CPython", _Py_gitidentifier(),
2722 _Py_gitversion()));
INADA Naoki6b42eb12017-06-29 15:31:38 +09002723 SET_SYS_FROM_STRING("_framework", PyUnicode_FromString(_PYTHONFRAMEWORK));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002724 SET_SYS_FROM_STRING("api_version",
2725 PyLong_FromLong(PYTHON_API_VERSION));
2726 SET_SYS_FROM_STRING("copyright",
2727 PyUnicode_FromString(Py_GetCopyright()));
2728 SET_SYS_FROM_STRING("platform",
2729 PyUnicode_FromString(Py_GetPlatform()));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002730 SET_SYS_FROM_STRING("maxsize",
2731 PyLong_FromSsize_t(PY_SSIZE_T_MAX));
2732 SET_SYS_FROM_STRING("float_info",
2733 PyFloat_GetInfo());
2734 SET_SYS_FROM_STRING("int_info",
2735 PyLong_GetInfo());
Mark Dickinsondc787d22010-05-23 13:33:13 +00002736 /* initialize hash_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002737 if (Hash_InfoType.tp_name == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002738 if (PyStructSequence_InitType2(&Hash_InfoType, &hash_info_desc) < 0) {
2739 goto type_init_failed;
2740 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002741 }
Mark Dickinsondc787d22010-05-23 13:33:13 +00002742 SET_SYS_FROM_STRING("hash_info",
Victor Stinner838f2642019-06-13 22:41:23 +02002743 get_hash_info(tstate));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002744 SET_SYS_FROM_STRING("maxunicode",
Ezio Melotti48a2f8f2011-09-29 00:18:19 +03002745 PyLong_FromLong(0x10FFFF));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002746 SET_SYS_FROM_STRING("builtin_module_names",
2747 list_builtin_module_names());
Christian Heimes743e0cd2012-10-17 23:52:17 +02002748#if PY_BIG_ENDIAN
2749 SET_SYS_FROM_STRING("byteorder",
2750 PyUnicode_FromString("big"));
2751#else
2752 SET_SYS_FROM_STRING("byteorder",
2753 PyUnicode_FromString("little"));
2754#endif
Fred Drake099325e2000-08-14 15:47:03 +00002755
Guido van Rossum8b9ea871996-08-23 18:14:47 +00002756#ifdef MS_COREDLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002757 SET_SYS_FROM_STRING("dllhandle",
2758 PyLong_FromVoidPtr(PyWin_DLLhModule));
2759 SET_SYS_FROM_STRING("winver",
2760 PyUnicode_FromString(PyWin_DLLVersionString));
Guido van Rossumc606fe11996-04-09 02:37:57 +00002761#endif
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00002762#ifdef ABIFLAGS
2763 SET_SYS_FROM_STRING("abiflags",
2764 PyUnicode_FromString(ABIFLAGS));
2765#endif
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002766
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002767 /* version_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002768 if (VersionInfoType.tp_name == NULL) {
2769 if (PyStructSequence_InitType2(&VersionInfoType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002770 &version_info_desc) < 0) {
2771 goto type_init_failed;
2772 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002773 }
Victor Stinner838f2642019-06-13 22:41:23 +02002774 version_info = make_version_info(tstate);
Barry Warsaw409da152012-06-03 16:18:47 -04002775 SET_SYS_FROM_STRING("version_info", version_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002776 /* prevent user from creating new instances */
2777 VersionInfoType.tp_init = NULL;
2778 VersionInfoType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002779 res = PyDict_DelItemString(VersionInfoType.tp_dict, "__new__");
Victor Stinner838f2642019-06-13 22:41:23 +02002780 if (res < 0 && _PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
2781 _PyErr_Clear(tstate);
2782 }
Eric Smith0e5b5622009-02-06 01:32:42 +00002783
Barry Warsaw409da152012-06-03 16:18:47 -04002784 /* implementation */
2785 SET_SYS_FROM_STRING("implementation", make_impl_info(version_info));
2786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002787 /* flags */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002788 if (FlagsType.tp_name == 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002789 if (PyStructSequence_InitType2(&FlagsType, &flags_desc) < 0) {
2790 goto type_init_failed;
2791 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002792 }
Victor Stinner43125222019-04-24 18:23:53 +02002793 /* Set flags to their default values (updated by _PySys_InitMain()) */
Victor Stinner838f2642019-06-13 22:41:23 +02002794 SET_SYS_FROM_STRING("flags", make_flags(runtime, tstate));
Eric Smithf7bb5782010-01-27 00:44:57 +00002795
2796#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002797 /* getwindowsversion */
2798 if (WindowsVersionType.tp_name == 0)
Victor Stinner1c8f0592013-07-22 22:24:54 +02002799 if (PyStructSequence_InitType2(&WindowsVersionType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002800 &windows_version_desc) < 0) {
2801 goto type_init_failed;
2802 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002803 /* prevent user from creating new instances */
2804 WindowsVersionType.tp_init = NULL;
2805 WindowsVersionType.tp_new = NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02002806 assert(!_PyErr_Occurred(tstate));
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002807 res = PyDict_DelItemString(WindowsVersionType.tp_dict, "__new__");
Victor Stinner838f2642019-06-13 22:41:23 +02002808 if (res < 0 && _PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
2809 _PyErr_Clear(tstate);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002810 }
Eric Smithf7bb5782010-01-27 00:44:57 +00002811#endif
2812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002813 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002814#ifndef PY_NO_SHORT_FLOAT_REPR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002815 SET_SYS_FROM_STRING("float_repr_style",
2816 PyUnicode_FromString("short"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002817#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002818 SET_SYS_FROM_STRING("float_repr_style",
2819 PyUnicode_FromString("legacy"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002820#endif
2821
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002822 SET_SYS_FROM_STRING("thread_info", PyThread_GetInfo());
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002823
Yury Selivanoveb636452016-09-08 22:01:51 -07002824 /* initialize asyncgen_hooks */
2825 if (AsyncGenHooksType.tp_name == NULL) {
2826 if (PyStructSequence_InitType2(
2827 &AsyncGenHooksType, &asyncgen_hooks_desc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002828 goto type_init_failed;
Yury Selivanoveb636452016-09-08 22:01:51 -07002829 }
2830 }
2831
Victor Stinner838f2642019-06-13 22:41:23 +02002832 if (_PyErr_Occurred(tstate)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002833 goto err_occurred;
2834 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002835 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002836
2837type_init_failed:
Victor Stinner331a6a52019-05-27 16:39:22 +02002838 return _PyStatus_ERR("failed to initialize a type");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002839
2840err_occurred:
Victor Stinner331a6a52019-05-27 16:39:22 +02002841 return _PyStatus_ERR("can't initialize sys module");
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002842}
2843
Eric Snow6b4be192017-05-22 21:36:03 -07002844#undef SET_SYS_FROM_STRING
Eric Snow6b4be192017-05-22 21:36:03 -07002845
2846/* Updating the sys namespace, returning integer error codes */
Eric Snow6b4be192017-05-22 21:36:03 -07002847#define SET_SYS_FROM_STRING_INT_RESULT(key, value) \
2848 do { \
2849 PyObject *v = (value); \
2850 if (v == NULL) \
2851 return -1; \
2852 res = PyDict_SetItemString(sysdict, key, v); \
2853 Py_DECREF(v); \
2854 if (res < 0) { \
2855 return res; \
2856 } \
2857 } while (0)
2858
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002859
2860static int
2861sys_add_xoption(PyObject *opts, const wchar_t *s)
2862{
2863 PyObject *name, *value;
2864
2865 const wchar_t *name_end = wcschr(s, L'=');
2866 if (!name_end) {
2867 name = PyUnicode_FromWideChar(s, -1);
2868 value = Py_True;
2869 Py_INCREF(value);
2870 }
2871 else {
2872 name = PyUnicode_FromWideChar(s, name_end - s);
2873 value = PyUnicode_FromWideChar(name_end + 1, -1);
2874 }
2875 if (name == NULL || value == NULL) {
2876 goto error;
2877 }
2878 if (PyDict_SetItem(opts, name, value) < 0) {
2879 goto error;
2880 }
2881 Py_DECREF(name);
2882 Py_DECREF(value);
2883 return 0;
2884
2885error:
2886 Py_XDECREF(name);
2887 Py_XDECREF(value);
2888 return -1;
2889}
2890
2891
2892static PyObject*
Victor Stinner331a6a52019-05-27 16:39:22 +02002893sys_create_xoptions_dict(const PyConfig *config)
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002894{
2895 Py_ssize_t nxoption = config->xoptions.length;
2896 wchar_t * const * xoptions = config->xoptions.items;
2897 PyObject *dict = PyDict_New();
2898 if (dict == NULL) {
2899 return NULL;
2900 }
2901
2902 for (Py_ssize_t i=0; i < nxoption; i++) {
2903 const wchar_t *option = xoptions[i];
2904 if (sys_add_xoption(dict, option) < 0) {
2905 Py_DECREF(dict);
2906 return NULL;
2907 }
2908 }
2909
2910 return dict;
2911}
2912
2913
Eric Snow6b4be192017-05-22 21:36:03 -07002914int
Victor Stinner838f2642019-06-13 22:41:23 +02002915_PySys_InitMain(_PyRuntimeState *runtime, PyThreadState *tstate)
Eric Snow6b4be192017-05-22 21:36:03 -07002916{
Victor Stinner838f2642019-06-13 22:41:23 +02002917 PyObject *sysdict = tstate->interp->sysdict;
2918 const PyConfig *config = &tstate->interp->config;
Eric Snow6b4be192017-05-22 21:36:03 -07002919 int res;
2920
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002921#define COPY_LIST(KEY, VALUE) \
Victor Stinner37cd9822018-11-16 11:55:35 +01002922 do { \
Victor Stinner331a6a52019-05-27 16:39:22 +02002923 PyObject *list = _PyWideStringList_AsList(&(VALUE)); \
Victor Stinner37cd9822018-11-16 11:55:35 +01002924 if (list == NULL) { \
2925 return -1; \
2926 } \
2927 SET_SYS_FROM_STRING_BORROW(KEY, list); \
2928 Py_DECREF(list); \
2929 } while (0)
2930
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002931#define SET_SYS_FROM_WSTR(KEY, VALUE) \
2932 do { \
2933 PyObject *str = PyUnicode_FromWideChar(VALUE, -1); \
2934 if (str == NULL) { \
2935 return -1; \
2936 } \
2937 SET_SYS_FROM_STRING_BORROW(KEY, str); \
2938 Py_DECREF(str); \
2939 } while (0)
Victor Stinner37cd9822018-11-16 11:55:35 +01002940
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002941 COPY_LIST("path", config->module_search_paths);
2942
2943 SET_SYS_FROM_WSTR("executable", config->executable);
2944 SET_SYS_FROM_WSTR("prefix", config->prefix);
2945 SET_SYS_FROM_WSTR("base_prefix", config->base_prefix);
2946 SET_SYS_FROM_WSTR("exec_prefix", config->exec_prefix);
2947 SET_SYS_FROM_WSTR("base_exec_prefix", config->base_exec_prefix);
Victor Stinner41264f12017-12-15 02:05:29 +01002948
Carl Meyerb193fa92018-06-15 22:40:56 -06002949 if (config->pycache_prefix != NULL) {
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002950 SET_SYS_FROM_WSTR("pycache_prefix", config->pycache_prefix);
Carl Meyerb193fa92018-06-15 22:40:56 -06002951 } else {
2952 PyDict_SetItemString(sysdict, "pycache_prefix", Py_None);
2953 }
2954
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002955 COPY_LIST("argv", config->argv);
2956 COPY_LIST("warnoptions", config->warnoptions);
2957
2958 PyObject *xoptions = sys_create_xoptions_dict(config);
2959 if (xoptions == NULL) {
2960 return -1;
Victor Stinner41264f12017-12-15 02:05:29 +01002961 }
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002962 SET_SYS_FROM_STRING_BORROW("_xoptions", xoptions);
Pablo Galindo34ef64f2019-03-27 12:43:47 +00002963 Py_DECREF(xoptions);
Victor Stinner41264f12017-12-15 02:05:29 +01002964
Victor Stinner37cd9822018-11-16 11:55:35 +01002965#undef COPY_LIST
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002966#undef SET_SYS_FROM_WSTR
Victor Stinner37cd9822018-11-16 11:55:35 +01002967
Eric Snow6b4be192017-05-22 21:36:03 -07002968 /* Set flags to their final values */
Victor Stinner838f2642019-06-13 22:41:23 +02002969 SET_SYS_FROM_STRING_INT_RESULT("flags", make_flags(runtime, tstate));
Eric Snow6b4be192017-05-22 21:36:03 -07002970 /* prevent user from creating new instances */
2971 FlagsType.tp_init = NULL;
2972 FlagsType.tp_new = NULL;
2973 res = PyDict_DelItemString(FlagsType.tp_dict, "__new__");
2974 if (res < 0) {
Victor Stinner838f2642019-06-13 22:41:23 +02002975 if (!_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
Eric Snow6b4be192017-05-22 21:36:03 -07002976 return res;
2977 }
Victor Stinner838f2642019-06-13 22:41:23 +02002978 _PyErr_Clear(tstate);
Eric Snow6b4be192017-05-22 21:36:03 -07002979 }
2980
2981 SET_SYS_FROM_STRING_INT_RESULT("dont_write_bytecode",
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002982 PyBool_FromLong(!config->write_bytecode));
Eric Snow6b4be192017-05-22 21:36:03 -07002983
Victor Stinner838f2642019-06-13 22:41:23 +02002984 if (get_warnoptions(tstate) == NULL) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002985 return -1;
Victor Stinner838f2642019-06-13 22:41:23 +02002986 }
Victor Stinner865de272017-06-08 13:27:47 +02002987
Victor Stinner838f2642019-06-13 22:41:23 +02002988 if (get_xoptions(tstate) == NULL)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002989 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002990
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002991 /* Transfer any sys.warnoptions and sys._xoptions set directly
2992 * by an embedding application from the linked list to the module. */
Victor Stinner838f2642019-06-13 22:41:23 +02002993 if (sys_read_preinit_options(tstate) != 0)
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002994 return -1;
2995
Victor Stinner838f2642019-06-13 22:41:23 +02002996 if (_PyErr_Occurred(tstate)) {
2997 goto err_occurred;
2998 }
2999
Eric Snow6b4be192017-05-22 21:36:03 -07003000 return 0;
Victor Stinner41264f12017-12-15 02:05:29 +01003001
3002err_occurred:
3003 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07003004}
3005
Victor Stinner41264f12017-12-15 02:05:29 +01003006#undef SET_SYS_FROM_STRING_BORROW
Eric Snow6b4be192017-05-22 21:36:03 -07003007#undef SET_SYS_FROM_STRING_INT_RESULT
Eric Snow6b4be192017-05-22 21:36:03 -07003008
Victor Stinnerab672812019-01-23 15:04:40 +01003009
3010/* Set up a preliminary stderr printer until we have enough
3011 infrastructure for the io module in place.
3012
3013 Use UTF-8/surrogateescape and ignore EAGAIN errors. */
Victor Stinner331a6a52019-05-27 16:39:22 +02003014PyStatus
Victor Stinnerab672812019-01-23 15:04:40 +01003015_PySys_SetPreliminaryStderr(PyObject *sysdict)
3016{
3017 PyObject *pstderr = PyFile_NewStdPrinter(fileno(stderr));
3018 if (pstderr == NULL) {
3019 goto error;
3020 }
3021 if (_PyDict_SetItemId(sysdict, &PyId_stderr, pstderr) < 0) {
3022 goto error;
3023 }
3024 if (PyDict_SetItemString(sysdict, "__stderr__", pstderr) < 0) {
3025 goto error;
3026 }
3027 Py_DECREF(pstderr);
Victor Stinner331a6a52019-05-27 16:39:22 +02003028 return _PyStatus_OK();
Victor Stinnerab672812019-01-23 15:04:40 +01003029
3030error:
3031 Py_XDECREF(pstderr);
Victor Stinner331a6a52019-05-27 16:39:22 +02003032 return _PyStatus_ERR("can't set preliminary stderr");
Victor Stinnerab672812019-01-23 15:04:40 +01003033}
3034
3035
3036/* Create sys module without all attributes: _PySys_InitMain() should be called
3037 later to add remaining attributes. */
Victor Stinner331a6a52019-05-27 16:39:22 +02003038PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +02003039_PySys_Create(_PyRuntimeState *runtime, PyThreadState *tstate,
Victor Stinner0fd2c302019-06-04 03:15:09 +02003040 PyObject **sysmod_p)
Victor Stinnerab672812019-01-23 15:04:40 +01003041{
Victor Stinnerb45d2592019-06-20 00:05:23 +02003042 PyInterpreterState *interp = tstate->interp;
Victor Stinner838f2642019-06-13 22:41:23 +02003043
Victor Stinnerab672812019-01-23 15:04:40 +01003044 PyObject *modules = PyDict_New();
3045 if (modules == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02003046 return _PyStatus_ERR("can't make modules dictionary");
Victor Stinnerab672812019-01-23 15:04:40 +01003047 }
3048 interp->modules = modules;
3049
3050 PyObject *sysmod = _PyModule_CreateInitialized(&sysmodule, PYTHON_API_VERSION);
3051 if (sysmod == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02003052 return _PyStatus_ERR("failed to create a module object");
Victor Stinnerab672812019-01-23 15:04:40 +01003053 }
3054
3055 PyObject *sysdict = PyModule_GetDict(sysmod);
3056 if (sysdict == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02003057 return _PyStatus_ERR("can't initialize sys dict");
Victor Stinnerab672812019-01-23 15:04:40 +01003058 }
3059 Py_INCREF(sysdict);
3060 interp->sysdict = sysdict;
3061
3062 if (PyDict_SetItemString(sysdict, "modules", interp->modules) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +02003063 return _PyStatus_ERR("can't initialize sys module");
Victor Stinnerab672812019-01-23 15:04:40 +01003064 }
3065
Victor Stinner331a6a52019-05-27 16:39:22 +02003066 PyStatus status = _PySys_SetPreliminaryStderr(sysdict);
3067 if (_PyStatus_EXCEPTION(status)) {
3068 return status;
Victor Stinnerab672812019-01-23 15:04:40 +01003069 }
3070
Victor Stinner838f2642019-06-13 22:41:23 +02003071 status = _PySys_InitCore(runtime, tstate, sysdict);
Victor Stinner331a6a52019-05-27 16:39:22 +02003072 if (_PyStatus_EXCEPTION(status)) {
3073 return status;
Victor Stinnerab672812019-01-23 15:04:40 +01003074 }
3075
3076 _PyImport_FixupBuiltin(sysmod, "sys", interp->modules);
3077
3078 *sysmod_p = sysmod;
Victor Stinner331a6a52019-05-27 16:39:22 +02003079 return _PyStatus_OK();
Victor Stinnerab672812019-01-23 15:04:40 +01003080}
3081
3082
Guido van Rossum65bf9f21997-04-29 18:33:38 +00003083static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00003084makepathobject(const wchar_t *path, wchar_t delim)
Guido van Rossum5b3138b1990-11-18 17:41:40 +00003085{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003086 int i, n;
3087 const wchar_t *p;
3088 PyObject *v, *w;
Tim Peters216b78b2006-01-06 02:40:53 +00003089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003090 n = 1;
3091 p = path;
3092 while ((p = wcschr(p, delim)) != NULL) {
3093 n++;
3094 p++;
3095 }
3096 v = PyList_New(n);
3097 if (v == NULL)
3098 return NULL;
3099 for (i = 0; ; i++) {
3100 p = wcschr(path, delim);
3101 if (p == NULL)
3102 p = path + wcslen(path); /* End of string */
3103 w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
3104 if (w == NULL) {
3105 Py_DECREF(v);
3106 return NULL;
3107 }
Zackery Spytz99d56b52018-12-08 07:16:55 -07003108 PyList_SET_ITEM(v, i, w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003109 if (*p == '\0')
3110 break;
3111 path = p+1;
3112 }
3113 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003114}
3115
3116void
Martin v. Löwis790465f2008-04-05 20:41:37 +00003117PySys_SetPath(const wchar_t *path)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003118{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003119 PyObject *v;
3120 if ((v = makepathobject(path, DELIM)) == NULL)
3121 Py_FatalError("can't create sys.path");
Victor Stinner838f2642019-06-13 22:41:23 +02003122 PyThreadState *tstate = _PyThreadState_GET();
3123 if (sys_set_object_id(tstate, &PyId_path, v) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003124 Py_FatalError("can't assign sys.path");
Victor Stinner838f2642019-06-13 22:41:23 +02003125 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003126 Py_DECREF(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00003127}
3128
Guido van Rossum65bf9f21997-04-29 18:33:38 +00003129static PyObject *
Victor Stinner74f65682019-03-15 15:08:05 +01003130make_sys_argv(int argc, wchar_t * const * argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00003131{
Victor Stinner74f65682019-03-15 15:08:05 +01003132 PyObject *list = PyList_New(argc);
3133 if (list == NULL) {
3134 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003135 }
Victor Stinner74f65682019-03-15 15:08:05 +01003136
3137 for (Py_ssize_t i = 0; i < argc; i++) {
3138 PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
3139 if (v == NULL) {
3140 Py_DECREF(list);
3141 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003142 }
Victor Stinner74f65682019-03-15 15:08:05 +01003143 PyList_SET_ITEM(list, i, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003144 }
Victor Stinner74f65682019-03-15 15:08:05 +01003145 return list;
Guido van Rossum3f5da241990-12-20 15:06:42 +00003146}
3147
Victor Stinner11a247d2017-12-13 21:05:57 +01003148void
3149PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
Victor Stinnerd5dda982017-12-13 17:31:16 +01003150{
Victor Stinner838f2642019-06-13 22:41:23 +02003151 PyThreadState *tstate = _PyThreadState_GET();
3152
Victor Stinner74f65682019-03-15 15:08:05 +01003153 if (argc < 1 || argv == NULL) {
3154 /* Ensure at least one (empty) argument is seen */
3155 wchar_t* empty_argv[1] = {L""};
3156 argv = empty_argv;
3157 argc = 1;
3158 }
3159
3160 PyObject *av = make_sys_argv(argc, argv);
Victor Stinnerd5dda982017-12-13 17:31:16 +01003161 if (av == NULL) {
Victor Stinner11a247d2017-12-13 21:05:57 +01003162 Py_FatalError("no mem for sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01003163 }
Victor Stinner838f2642019-06-13 22:41:23 +02003164 if (sys_set_object(tstate, "argv", av) != 0) {
Victor Stinnerd5dda982017-12-13 17:31:16 +01003165 Py_DECREF(av);
Victor Stinner11a247d2017-12-13 21:05:57 +01003166 Py_FatalError("can't assign sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01003167 }
3168 Py_DECREF(av);
3169
3170 if (updatepath) {
3171 /* If argv[0] is not '-c' nor '-m', prepend argv[0] to sys.path.
3172 If argv[0] is a symlink, use the real path. */
Victor Stinner331a6a52019-05-27 16:39:22 +02003173 const PyWideStringList argv_list = {.length = argc, .items = argv};
Victor Stinnerdcf61712019-03-19 16:09:27 +01003174 PyObject *path0 = NULL;
3175 if (_PyPathConfig_ComputeSysPath0(&argv_list, &path0)) {
3176 if (path0 == NULL) {
3177 Py_FatalError("can't compute path0 from argv");
Victor Stinner11a247d2017-12-13 21:05:57 +01003178 }
Victor Stinnerdcf61712019-03-19 16:09:27 +01003179
Victor Stinner838f2642019-06-13 22:41:23 +02003180 PyObject *sys_path = sys_get_object_id(tstate, &PyId_path);
Victor Stinnerdcf61712019-03-19 16:09:27 +01003181 if (sys_path != NULL) {
3182 if (PyList_Insert(sys_path, 0, path0) < 0) {
3183 Py_DECREF(path0);
3184 Py_FatalError("can't prepend path0 to sys.path");
3185 }
3186 }
3187 Py_DECREF(path0);
Victor Stinner11a247d2017-12-13 21:05:57 +01003188 }
Victor Stinnerd5dda982017-12-13 17:31:16 +01003189 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003190}
Guido van Rossuma890e681998-05-12 14:59:24 +00003191
Antoine Pitrouf978fac2010-05-21 17:25:34 +00003192void
3193PySys_SetArgv(int argc, wchar_t **argv)
3194{
Christian Heimesad73a9c2013-08-10 16:36:18 +02003195 PySys_SetArgvEx(argc, argv, Py_IsolatedFlag == 0);
Antoine Pitrouf978fac2010-05-21 17:25:34 +00003196}
3197
Victor Stinner14284c22010-04-23 12:02:30 +00003198/* Reimplementation of PyFile_WriteString() no calling indirectly
3199 PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
3200
3201static int
Victor Stinner79766632010-08-16 17:36:42 +00003202sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
Victor Stinner14284c22010-04-23 12:02:30 +00003203{
Victor Stinnerc3ccaae2016-08-20 01:24:22 +02003204 PyObject *writer = NULL, *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003205 int err;
Victor Stinner14284c22010-04-23 12:02:30 +00003206
Victor Stinnerecccc4f2010-06-08 20:46:00 +00003207 if (file == NULL)
3208 return -1;
3209
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003210 writer = _PyObject_GetAttrId(file, &PyId_write);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003211 if (writer == NULL)
3212 goto error;
Victor Stinner14284c22010-04-23 12:02:30 +00003213
Victor Stinner7bfb42d2016-12-05 17:04:32 +01003214 result = PyObject_CallFunctionObjArgs(writer, unicode, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003215 if (result == NULL) {
3216 goto error;
3217 } else {
3218 err = 0;
3219 goto finally;
3220 }
Victor Stinner14284c22010-04-23 12:02:30 +00003221
3222error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003223 err = -1;
Victor Stinner14284c22010-04-23 12:02:30 +00003224finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003225 Py_XDECREF(writer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003226 Py_XDECREF(result);
3227 return err;
Victor Stinner14284c22010-04-23 12:02:30 +00003228}
3229
Victor Stinner79766632010-08-16 17:36:42 +00003230static int
3231sys_pyfile_write(const char *text, PyObject *file)
3232{
3233 PyObject *unicode = NULL;
3234 int err;
3235
3236 if (file == NULL)
3237 return -1;
3238
3239 unicode = PyUnicode_FromString(text);
3240 if (unicode == NULL)
3241 return -1;
3242
3243 err = sys_pyfile_write_unicode(unicode, file);
3244 Py_DECREF(unicode);
3245 return err;
3246}
Guido van Rossuma890e681998-05-12 14:59:24 +00003247
3248/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
3249 Adapted from code submitted by Just van Rossum.
3250
3251 PySys_WriteStdout(format, ...)
3252 PySys_WriteStderr(format, ...)
3253
3254 The first function writes to sys.stdout; the second to sys.stderr. When
3255 there is a problem, they write to the real (C level) stdout or stderr;
Guido van Rossum8442af31998-10-12 18:22:10 +00003256 no exceptions are raised.
Guido van Rossuma890e681998-05-12 14:59:24 +00003257
Victor Stinner14284c22010-04-23 12:02:30 +00003258 PyErr_CheckSignals() is not called to avoid the execution of the Python
Victor Stinner79766632010-08-16 17:36:42 +00003259 signal handlers: they may raise a new exception whereas sys_write()
3260 ignores all exceptions.
Victor Stinner14284c22010-04-23 12:02:30 +00003261
Guido van Rossuma890e681998-05-12 14:59:24 +00003262 Both take a printf-style format string as their first argument followed
3263 by a variable length argument list determined by the format string.
3264
3265 *** WARNING ***
3266
3267 The format should limit the total size of the formatted output string to
3268 1000 bytes. In particular, this means that no unrestricted "%s" formats
3269 should occur; these should be limited using "%.<N>s where <N> is a
3270 decimal number calculated so that <N> plus the maximum size of other
3271 formatted text does not exceed 1000 bytes. Also watch out for "%f",
3272 which can print hundreds of digits for very large numbers.
3273
3274 */
3275
3276static void
Victor Stinner09054372013-11-06 22:41:44 +01003277sys_write(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Guido van Rossuma890e681998-05-12 14:59:24 +00003278{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003279 PyObject *file;
3280 PyObject *error_type, *error_value, *error_traceback;
3281 char buffer[1001];
3282 int written;
Victor Stinner838f2642019-06-13 22:41:23 +02003283 PyThreadState *tstate = _PyThreadState_GET();
Guido van Rossuma890e681998-05-12 14:59:24 +00003284
Victor Stinner838f2642019-06-13 22:41:23 +02003285 _PyErr_Fetch(tstate, &error_type, &error_value, &error_traceback);
3286 file = sys_get_object_id(tstate, key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003287 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
3288 if (sys_pyfile_write(buffer, file) != 0) {
Victor Stinner838f2642019-06-13 22:41:23 +02003289 _PyErr_Clear(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003290 fputs(buffer, fp);
3291 }
3292 if (written < 0 || (size_t)written >= sizeof(buffer)) {
3293 const char *truncated = "... truncated";
Victor Stinner79766632010-08-16 17:36:42 +00003294 if (sys_pyfile_write(truncated, file) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003295 fputs(truncated, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003296 }
Victor Stinner838f2642019-06-13 22:41:23 +02003297 _PyErr_Restore(tstate, error_type, error_value, error_traceback);
Guido van Rossuma890e681998-05-12 14:59:24 +00003298}
3299
3300void
Guido van Rossuma890e681998-05-12 14:59:24 +00003301PySys_WriteStdout(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00003302{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003303 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00003304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003305 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003306 sys_write(&PyId_stdout, stdout, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003307 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00003308}
3309
3310void
Guido van Rossuma890e681998-05-12 14:59:24 +00003311PySys_WriteStderr(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00003312{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003313 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00003314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003315 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003316 sys_write(&PyId_stderr, stderr, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00003317 va_end(va);
3318}
3319
3320static void
Victor Stinner09054372013-11-06 22:41:44 +01003321sys_format(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Victor Stinner79766632010-08-16 17:36:42 +00003322{
3323 PyObject *file, *message;
3324 PyObject *error_type, *error_value, *error_traceback;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02003325 const char *utf8;
Victor Stinner838f2642019-06-13 22:41:23 +02003326 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner79766632010-08-16 17:36:42 +00003327
Victor Stinner838f2642019-06-13 22:41:23 +02003328 _PyErr_Fetch(tstate, &error_type, &error_value, &error_traceback);
3329 file = sys_get_object_id(tstate, key);
Victor Stinner79766632010-08-16 17:36:42 +00003330 message = PyUnicode_FromFormatV(format, va);
3331 if (message != NULL) {
3332 if (sys_pyfile_write_unicode(message, file) != 0) {
Victor Stinner838f2642019-06-13 22:41:23 +02003333 _PyErr_Clear(tstate);
Serhiy Storchaka06515832016-11-20 09:13:07 +02003334 utf8 = PyUnicode_AsUTF8(message);
Victor Stinner79766632010-08-16 17:36:42 +00003335 if (utf8 != NULL)
3336 fputs(utf8, fp);
3337 }
3338 Py_DECREF(message);
3339 }
Victor Stinner838f2642019-06-13 22:41:23 +02003340 _PyErr_Restore(tstate, error_type, error_value, error_traceback);
Victor Stinner79766632010-08-16 17:36:42 +00003341}
3342
3343void
3344PySys_FormatStdout(const char *format, ...)
3345{
3346 va_list va;
3347
3348 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003349 sys_format(&PyId_stdout, stdout, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00003350 va_end(va);
3351}
3352
3353void
3354PySys_FormatStderr(const char *format, ...)
3355{
3356 va_list va;
3357
3358 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003359 sys_format(&PyId_stderr, stderr, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003360 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00003361}