blob: d1a6c6a02618149d7b8724d4ec9c95c9a494a682 [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);
Zackery Spytz08286d52019-06-21 09:31:59 -0600185 va_end(args);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700186 if (eventArgs && !PyTuple_Check(eventArgs)) {
187 PyObject *argTuple = PyTuple_Pack(1, eventArgs);
188 Py_DECREF(eventArgs);
189 eventArgs = argTuple;
190 }
191 } else {
192 eventArgs = PyTuple_New(0);
193 }
194 if (!eventArgs) {
195 goto exit;
196 }
197
198 /* Call global hooks */
199 for (; e; e = e->next) {
200 if (e->hookCFunction(event, eventArgs, e->userData) < 0) {
201 goto exit;
202 }
203 }
204
205 /* Dtrace USDT point */
206 if (dtrace) {
207 PyDTrace_AUDIT(event, (void *)eventArgs);
208 }
209
210 /* Call interpreter hooks */
Victor Stinner838f2642019-06-13 22:41:23 +0200211 PyInterpreterState *is = ts ? ts->interp : NULL;
Steve Dowerb82e17e2019-05-23 08:45:22 -0700212 if (is && is->audit_hooks) {
213 eventName = PyUnicode_FromString(event);
214 if (!eventName) {
215 goto exit;
216 }
217
218 hooks = PyObject_GetIter(is->audit_hooks);
219 if (!hooks) {
220 goto exit;
221 }
222
223 /* Disallow tracing in hooks unless explicitly enabled */
224 ts->tracing++;
225 ts->use_tracing = 0;
226 while ((hook = PyIter_Next(hooks)) != NULL) {
227 PyObject *o;
228 int canTrace = -1;
229 o = PyObject_GetAttrString(hook, "__cantrace__");
230 if (o) {
231 canTrace = PyObject_IsTrue(o);
232 Py_DECREF(o);
Victor Stinner838f2642019-06-13 22:41:23 +0200233 } else if (_PyErr_Occurred(ts) &&
234 _PyErr_ExceptionMatches(ts, PyExc_AttributeError)) {
235 _PyErr_Clear(ts);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700236 canTrace = 0;
237 }
238 if (canTrace < 0) {
239 break;
240 }
241 if (canTrace) {
242 ts->use_tracing = (ts->c_tracefunc || ts->c_profilefunc);
243 ts->tracing--;
244 }
245 o = PyObject_CallFunctionObjArgs(hook, eventName,
246 eventArgs, NULL);
247 if (canTrace) {
248 ts->tracing++;
249 ts->use_tracing = 0;
250 }
251 if (!o) {
252 break;
253 }
254 Py_DECREF(o);
255 Py_CLEAR(hook);
256 }
257 ts->use_tracing = (ts->c_tracefunc || ts->c_profilefunc);
258 ts->tracing--;
Victor Stinner838f2642019-06-13 22:41:23 +0200259 if (_PyErr_Occurred(ts)) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700260 goto exit;
261 }
262 }
263
264 res = 0;
265
266exit:
267 Py_XDECREF(hook);
268 Py_XDECREF(hooks);
269 Py_XDECREF(eventName);
270 Py_XDECREF(eventArgs);
271
272 if (ts) {
273 if (!res) {
Victor Stinner838f2642019-06-13 22:41:23 +0200274 _PyErr_Restore(ts, exc_type, exc_value, exc_tb);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700275 } else {
Victor Stinner838f2642019-06-13 22:41:23 +0200276 assert(_PyErr_Occurred(ts));
Steve Dowerb82e17e2019-05-23 08:45:22 -0700277 Py_XDECREF(exc_type);
278 Py_XDECREF(exc_value);
279 Py_XDECREF(exc_tb);
280 }
281 }
282
283 return res;
284}
285
286/* We expose this function primarily for our own cleanup during
287 * finalization. In general, it should not need to be called,
288 * and as such it is not defined in any header files.
289 */
Victor Stinner838f2642019-06-13 22:41:23 +0200290void
291_PySys_ClearAuditHooks(void)
292{
Steve Dowerb82e17e2019-05-23 08:45:22 -0700293 /* Must be finalizing to clear hooks */
294 _PyRuntimeState *runtime = &_PyRuntime;
295 PyThreadState *ts = _PyRuntimeState_GetThreadState(runtime);
296 assert(!ts || _Py_CURRENTLY_FINALIZING(runtime, ts));
Victor Stinner838f2642019-06-13 22:41:23 +0200297 if (!ts || !_Py_CURRENTLY_FINALIZING(runtime, ts)) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700298 return;
Victor Stinner838f2642019-06-13 22:41:23 +0200299 }
Steve Dowerb82e17e2019-05-23 08:45:22 -0700300
Victor Stinner838f2642019-06-13 22:41:23 +0200301 const PyConfig *config = &ts->interp->config;
302 if (config->verbose) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700303 PySys_WriteStderr("# clear sys.audit hooks\n");
304 }
305
306 /* Hooks can abort later hooks for this event, but cannot
307 abort the clear operation itself. */
308 PySys_Audit("cpython._PySys_ClearAuditHooks", NULL);
Victor Stinner838f2642019-06-13 22:41:23 +0200309 _PyErr_Clear(ts);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700310
Victor Stinner0fd2c302019-06-04 03:15:09 +0200311 _Py_AuditHookEntry *e = _PyRuntime.audit_hook_head, *n;
312 _PyRuntime.audit_hook_head = NULL;
Steve Dowerb82e17e2019-05-23 08:45:22 -0700313 while (e) {
314 n = e->next;
315 PyMem_RawFree(e);
316 e = n;
317 }
318}
319
320int
321PySys_AddAuditHook(Py_AuditHookFunction hook, void *userData)
322{
Victor Stinner838f2642019-06-13 22:41:23 +0200323 _PyRuntimeState *runtime = &_PyRuntime;
324 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
325
Steve Dowerb82e17e2019-05-23 08:45:22 -0700326 /* Invoke existing audit hooks to allow them an opportunity to abort. */
327 /* Cannot invoke hooks until we are initialized */
Victor Stinner838f2642019-06-13 22:41:23 +0200328 if (runtime->initialized) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700329 if (PySys_Audit("sys.addaudithook", NULL) < 0) {
Victor Stinner838f2642019-06-13 22:41:23 +0200330 if (_PyErr_ExceptionMatches(tstate, PyExc_Exception)) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700331 /* We do not report errors derived from Exception */
Victor Stinner838f2642019-06-13 22:41:23 +0200332 _PyErr_Clear(tstate);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700333 return 0;
334 }
335 return -1;
336 }
337 }
338
Victor Stinner0fd2c302019-06-04 03:15:09 +0200339 _Py_AuditHookEntry *e = _PyRuntime.audit_hook_head;
Steve Dowerb82e17e2019-05-23 08:45:22 -0700340 if (!e) {
341 e = (_Py_AuditHookEntry*)PyMem_RawMalloc(sizeof(_Py_AuditHookEntry));
Victor Stinner0fd2c302019-06-04 03:15:09 +0200342 _PyRuntime.audit_hook_head = e;
Steve Dowerb82e17e2019-05-23 08:45:22 -0700343 } else {
Victor Stinner838f2642019-06-13 22:41:23 +0200344 while (e->next) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700345 e = e->next;
Victor Stinner838f2642019-06-13 22:41:23 +0200346 }
Steve Dowerb82e17e2019-05-23 08:45:22 -0700347 e = e->next = (_Py_AuditHookEntry*)PyMem_RawMalloc(
348 sizeof(_Py_AuditHookEntry));
349 }
350
351 if (!e) {
Victor Stinner838f2642019-06-13 22:41:23 +0200352 if (runtime->initialized) {
353 _PyErr_NoMemory(tstate);
354 }
Steve Dowerb82e17e2019-05-23 08:45:22 -0700355 return -1;
356 }
357
358 e->next = NULL;
359 e->hookCFunction = (Py_AuditHookFunction)hook;
360 e->userData = userData;
361
362 return 0;
363}
364
365/*[clinic input]
366sys.addaudithook
367
368 hook: object
369
370Adds a new audit hook callback.
371[clinic start generated code]*/
372
373static PyObject *
374sys_addaudithook_impl(PyObject *module, PyObject *hook)
375/*[clinic end generated code: output=4f9c17aaeb02f44e input=0f3e191217a45e34]*/
376{
Victor Stinner838f2642019-06-13 22:41:23 +0200377 PyThreadState *tstate = _PyThreadState_GET();
378
Steve Dowerb82e17e2019-05-23 08:45:22 -0700379 /* Invoke existing audit hooks to allow them an opportunity to abort. */
380 if (PySys_Audit("sys.addaudithook", NULL) < 0) {
Victor Stinner838f2642019-06-13 22:41:23 +0200381 if (_PyErr_ExceptionMatches(tstate, PyExc_Exception)) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700382 /* We do not report errors derived from Exception */
Victor Stinner838f2642019-06-13 22:41:23 +0200383 _PyErr_Clear(tstate);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700384 Py_RETURN_NONE;
385 }
386 return NULL;
387 }
388
Victor Stinner838f2642019-06-13 22:41:23 +0200389 PyInterpreterState *is = tstate->interp;
Steve Dowerb82e17e2019-05-23 08:45:22 -0700390
391 if (is->audit_hooks == NULL) {
392 is->audit_hooks = PyList_New(0);
393 if (is->audit_hooks == NULL) {
394 return NULL;
395 }
396 }
397
398 if (PyList_Append(is->audit_hooks, hook) < 0) {
399 return NULL;
400 }
401
402 Py_RETURN_NONE;
403}
404
405PyDoc_STRVAR(audit_doc,
406"audit(event, *args)\n\
407\n\
408Passes the event to any audit hooks that are attached.");
409
410static PyObject *
411sys_audit(PyObject *self, PyObject *const *args, Py_ssize_t argc)
412{
Victor Stinner838f2642019-06-13 22:41:23 +0200413 PyThreadState *tstate = _PyThreadState_GET();
414
Steve Dowerb82e17e2019-05-23 08:45:22 -0700415 if (argc == 0) {
Victor Stinner838f2642019-06-13 22:41:23 +0200416 _PyErr_SetString(tstate, PyExc_TypeError,
417 "audit() missing 1 required positional argument: "
418 "'event'");
Steve Dowerb82e17e2019-05-23 08:45:22 -0700419 return NULL;
420 }
421
Victor Stinner838f2642019-06-13 22:41:23 +0200422 if (!should_audit(tstate)) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700423 Py_RETURN_NONE;
424 }
425
426 PyObject *auditEvent = args[0];
427 if (!auditEvent) {
Victor Stinner838f2642019-06-13 22:41:23 +0200428 _PyErr_SetString(tstate, PyExc_TypeError,
429 "expected str for argument 'event'");
Steve Dowerb82e17e2019-05-23 08:45:22 -0700430 return NULL;
431 }
432 if (!PyUnicode_Check(auditEvent)) {
Victor Stinner838f2642019-06-13 22:41:23 +0200433 _PyErr_Format(tstate, PyExc_TypeError,
434 "expected str for argument 'event', not %.200s",
435 Py_TYPE(auditEvent)->tp_name);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700436 return NULL;
437 }
438 const char *event = PyUnicode_AsUTF8(auditEvent);
439 if (!event) {
440 return NULL;
441 }
442
443 PyObject *auditArgs = _PyTuple_FromArray(args + 1, argc - 1);
444 if (!auditArgs) {
445 return NULL;
446 }
447
448 int res = PySys_Audit(event, "O", auditArgs);
449 Py_DECREF(auditArgs);
450
451 if (res < 0) {
452 return NULL;
453 }
454
455 Py_RETURN_NONE;
456}
457
458
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400459static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +0200460sys_breakpointhook(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *keywords)
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400461{
Victor Stinner838f2642019-06-13 22:41:23 +0200462 PyThreadState *tstate = _PyThreadState_GET();
463 assert(!_PyErr_Occurred(tstate));
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300464 char *envar = Py_GETENV("PYTHONBREAKPOINT");
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400465
466 if (envar == NULL || strlen(envar) == 0) {
467 envar = "pdb.set_trace";
468 }
469 else if (!strcmp(envar, "0")) {
470 /* The breakpoint is explicitly no-op'd. */
471 Py_RETURN_NONE;
472 }
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300473 /* According to POSIX the string returned by getenv() might be invalidated
474 * or the string content might be overwritten by a subsequent call to
475 * getenv(). Since importing a module can performs the getenv() calls,
476 * we need to save a copy of envar. */
477 envar = _PyMem_RawStrdup(envar);
478 if (envar == NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +0200479 _PyErr_NoMemory(tstate);
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300480 return NULL;
481 }
Serhiy Storchaka4ae06c52017-12-12 13:55:04 +0200482 const char *last_dot = strrchr(envar, '.');
483 const char *attrname = NULL;
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400484 PyObject *modulepath = NULL;
485
486 if (last_dot == NULL) {
487 /* The breakpoint is a built-in, e.g. PYTHONBREAKPOINT=int */
488 modulepath = PyUnicode_FromString("builtins");
489 attrname = envar;
490 }
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200491 else if (last_dot != envar) {
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400492 /* Split on the last dot; */
493 modulepath = PyUnicode_FromStringAndSize(envar, last_dot - envar);
494 attrname = last_dot + 1;
495 }
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200496 else {
497 goto warn;
498 }
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400499 if (modulepath == NULL) {
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300500 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400501 return NULL;
502 }
503
Anthony Sottiledce345c2018-11-01 10:25:05 -0700504 PyObject *module = PyImport_Import(modulepath);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400505 Py_DECREF(modulepath);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400506
507 if (module == NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +0200508 if (_PyErr_ExceptionMatches(tstate, PyExc_ImportError)) {
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200509 goto warn;
510 }
511 PyMem_RawFree(envar);
512 return NULL;
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400513 }
514
515 PyObject *hook = PyObject_GetAttrString(module, attrname);
516 Py_DECREF(module);
517
518 if (hook == NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +0200519 if (_PyErr_ExceptionMatches(tstate, PyExc_AttributeError)) {
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200520 goto warn;
521 }
522 PyMem_RawFree(envar);
523 return NULL;
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400524 }
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300525 PyMem_RawFree(envar);
Jeroen Demeyeraacc77f2019-05-29 20:31:52 +0200526 PyObject *retval = _PyObject_Vectorcall(hook, args, nargs, keywords);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400527 Py_DECREF(hook);
528 return retval;
529
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200530 warn:
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400531 /* If any of the imports went wrong, then warn and ignore. */
Victor Stinner838f2642019-06-13 22:41:23 +0200532 _PyErr_Clear(tstate);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400533 int status = PyErr_WarnFormat(
534 PyExc_RuntimeWarning, 0,
535 "Ignoring unimportable $PYTHONBREAKPOINT: \"%s\"", envar);
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300536 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400537 if (status < 0) {
538 /* Printing the warning raised an exception. */
539 return NULL;
540 }
541 /* The warning was (probably) issued. */
542 Py_RETURN_NONE;
543}
544
545PyDoc_STRVAR(breakpointhook_doc,
546"breakpointhook(*args, **kws)\n"
547"\n"
548"This hook function is called by built-in breakpoint().\n"
549);
550
Victor Stinner13d49ee2010-12-04 17:24:33 +0000551/* Write repr(o) to sys.stdout using sys.stdout.encoding and 'backslashreplace'
552 error handler. If sys.stdout has a buffer attribute, use
553 sys.stdout.buffer.write(encoded), otherwise redecode the string and use
554 sys.stdout.write(redecoded).
555
556 Helper function for sys_displayhook(). */
557static int
Victor Stinner838f2642019-06-13 22:41:23 +0200558sys_displayhook_unencodable(PyThreadState *tstate, PyObject *outf, PyObject *o)
Victor Stinner13d49ee2010-12-04 17:24:33 +0000559{
560 PyObject *stdout_encoding = NULL;
561 PyObject *encoded, *escaped_str, *repr_str, *buffer, *result;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200562 const char *stdout_encoding_str;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000563 int ret;
564
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200565 stdout_encoding = _PyObject_GetAttrId(outf, &PyId_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000566 if (stdout_encoding == NULL)
567 goto error;
Serhiy Storchaka06515832016-11-20 09:13:07 +0200568 stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000569 if (stdout_encoding_str == NULL)
570 goto error;
571
572 repr_str = PyObject_Repr(o);
573 if (repr_str == NULL)
574 goto error;
575 encoded = PyUnicode_AsEncodedString(repr_str,
576 stdout_encoding_str,
577 "backslashreplace");
578 Py_DECREF(repr_str);
579 if (encoded == NULL)
580 goto error;
581
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200582 buffer = _PyObject_GetAttrId(outf, &PyId_buffer);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000583 if (buffer) {
Victor Stinner7e425412016-12-09 00:36:19 +0100584 result = _PyObject_CallMethodIdObjArgs(buffer, &PyId_write, encoded, NULL);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000585 Py_DECREF(buffer);
586 Py_DECREF(encoded);
587 if (result == NULL)
588 goto error;
589 Py_DECREF(result);
590 }
591 else {
Victor Stinner838f2642019-06-13 22:41:23 +0200592 _PyErr_Clear(tstate);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000593 escaped_str = PyUnicode_FromEncodedObject(encoded,
594 stdout_encoding_str,
595 "strict");
596 Py_DECREF(encoded);
597 if (PyFile_WriteObject(escaped_str, outf, Py_PRINT_RAW) != 0) {
598 Py_DECREF(escaped_str);
599 goto error;
600 }
601 Py_DECREF(escaped_str);
602 }
603 ret = 0;
604 goto finally;
605
606error:
607 ret = -1;
608finally:
609 Py_XDECREF(stdout_encoding);
610 return ret;
611}
612
Tal Einatede0b6f2018-12-31 17:12:08 +0200613/*[clinic input]
614sys.displayhook
615
616 object as o: object
617 /
618
619Print an object to sys.stdout and also save it in builtins._
620[clinic start generated code]*/
621
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000622static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200623sys_displayhook(PyObject *module, PyObject *o)
624/*[clinic end generated code: output=347477d006df92ed input=08ba730166d7ef72]*/
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000625{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000626 PyObject *outf;
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100627 PyObject *builtins;
628 static PyObject *newline = NULL;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000629 int err;
Victor Stinner838f2642019-06-13 22:41:23 +0200630 PyThreadState *tstate = _PyThreadState_GET();
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000631
Eric Snow3f9eee62017-09-15 16:35:20 -0600632 builtins = _PyImport_GetModuleId(&PyId_builtins);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000633 if (builtins == NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +0200634 if (!_PyErr_Occurred(tstate)) {
635 _PyErr_SetString(tstate, PyExc_RuntimeError,
636 "lost builtins module");
Stefan Krah027b09c2019-03-25 21:50:58 +0100637 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 return NULL;
639 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600640 Py_DECREF(builtins);
Moshe Zadka03897ea2001-07-23 13:32:43 +0000641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 /* Print value except if None */
643 /* After printing, also assign to '_' */
644 /* Before, set '_' to None to avoid recursion */
645 if (o == Py_None) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200646 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 }
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200648 if (_PyObject_SetAttrId(builtins, &PyId__, Py_None) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 return NULL;
Victor Stinner838f2642019-06-13 22:41:23 +0200650 outf = sys_get_object_id(tstate, &PyId_stdout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 if (outf == NULL || outf == Py_None) {
Victor Stinner838f2642019-06-13 22:41:23 +0200652 _PyErr_SetString(tstate, PyExc_RuntimeError, "lost sys.stdout");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 return NULL;
654 }
Victor Stinner13d49ee2010-12-04 17:24:33 +0000655 if (PyFile_WriteObject(o, outf, 0) != 0) {
Victor Stinner838f2642019-06-13 22:41:23 +0200656 if (_PyErr_ExceptionMatches(tstate, PyExc_UnicodeEncodeError)) {
Victor Stinner13d49ee2010-12-04 17:24:33 +0000657 /* repr(o) is not encodable to sys.stdout.encoding with
658 * sys.stdout.errors error handler (which is probably 'strict') */
Victor Stinner838f2642019-06-13 22:41:23 +0200659 _PyErr_Clear(tstate);
660 err = sys_displayhook_unencodable(tstate, outf, o);
661 if (err) {
Victor Stinner13d49ee2010-12-04 17:24:33 +0000662 return NULL;
Victor Stinner838f2642019-06-13 22:41:23 +0200663 }
Victor Stinner13d49ee2010-12-04 17:24:33 +0000664 }
665 else {
666 return NULL;
667 }
668 }
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100669 if (newline == NULL) {
670 newline = PyUnicode_FromString("\n");
671 if (newline == NULL)
672 return NULL;
673 }
674 if (PyFile_WriteObject(newline, outf, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 return NULL;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200676 if (_PyObject_SetAttrId(builtins, &PyId__, o) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200678 Py_RETURN_NONE;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000679}
680
Tal Einatede0b6f2018-12-31 17:12:08 +0200681
682/*[clinic input]
683sys.excepthook
684
685 exctype: object
686 value: object
687 traceback: object
688 /
689
690Handle an exception by displaying it with a traceback on sys.stderr.
691[clinic start generated code]*/
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000692
693static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200694sys_excepthook_impl(PyObject *module, PyObject *exctype, PyObject *value,
695 PyObject *traceback)
696/*[clinic end generated code: output=18d99fdda21b6b5e input=ecf606fa826f19d9]*/
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000697{
Tal Einatede0b6f2018-12-31 17:12:08 +0200698 PyErr_Display(exctype, value, traceback);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200699 Py_RETURN_NONE;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000700}
701
Tal Einatede0b6f2018-12-31 17:12:08 +0200702
703/*[clinic input]
704sys.exc_info
705
706Return current exception information: (type, value, traceback).
707
708Return information about the most recent exception caught by an except
709clause in the current stack frame or in an older stack frame.
710[clinic start generated code]*/
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000711
712static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200713sys_exc_info_impl(PyObject *module)
714/*[clinic end generated code: output=3afd0940cf3a4d30 input=b5c5bf077788a3e5]*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000715{
Victor Stinner50b48572018-11-01 01:51:40 +0100716 _PyErr_StackItem *err_info = _PyErr_GetTopmostException(_PyThreadState_GET());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 return Py_BuildValue(
718 "(OOO)",
Mark Shannonae3087c2017-10-22 22:41:51 +0100719 err_info->exc_type != NULL ? err_info->exc_type : Py_None,
720 err_info->exc_value != NULL ? err_info->exc_value : Py_None,
721 err_info->exc_traceback != NULL ?
722 err_info->exc_traceback : Py_None);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000723}
724
Tal Einatede0b6f2018-12-31 17:12:08 +0200725
726/*[clinic input]
Victor Stinneref9d9b62019-05-22 11:28:22 +0200727sys.unraisablehook
728
729 unraisable: object
730 /
731
732Handle an unraisable exception.
733
734The unraisable argument has the following attributes:
735
736* exc_type: Exception type.
Victor Stinner71c52e32019-05-27 08:57:14 +0200737* exc_value: Exception value, can be None.
738* exc_traceback: Exception traceback, can be None.
739* err_msg: Error message, can be None.
740* object: Object causing the exception, can be None.
Victor Stinneref9d9b62019-05-22 11:28:22 +0200741[clinic start generated code]*/
742
743static PyObject *
744sys_unraisablehook(PyObject *module, PyObject *unraisable)
Victor Stinner71c52e32019-05-27 08:57:14 +0200745/*[clinic end generated code: output=bb92838b32abaa14 input=ec3af148294af8d3]*/
Victor Stinneref9d9b62019-05-22 11:28:22 +0200746{
747 return _PyErr_WriteUnraisableDefaultHook(unraisable);
748}
749
750
751/*[clinic input]
Tal Einatede0b6f2018-12-31 17:12:08 +0200752sys.exit
753
754 status: object = NULL
755 /
756
757Exit the interpreter by raising SystemExit(status).
758
759If the status is omitted or None, it defaults to zero (i.e., success).
760If the status is an integer, it will be used as the system exit status.
761If it is another kind of object, it will be printed and the system
762exit status will be one (i.e., failure).
763[clinic start generated code]*/
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000764
765static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200766sys_exit_impl(PyObject *module, PyObject *status)
767/*[clinic end generated code: output=13870986c1ab2ec0 input=a737351f86685e9c]*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000768{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 /* Raise SystemExit so callers may catch it or clean up. */
Victor Stinner838f2642019-06-13 22:41:23 +0200770 PyThreadState *tstate = _PyThreadState_GET();
771 _PyErr_SetObject(tstate, PyExc_SystemExit, status);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000773}
774
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000775
Martin v. Löwis107b7da2001-11-09 20:59:39 +0000776
Tal Einatede0b6f2018-12-31 17:12:08 +0200777/*[clinic input]
778sys.getdefaultencoding
779
780Return the current default encoding used by the Unicode implementation.
781[clinic start generated code]*/
782
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000783static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200784sys_getdefaultencoding_impl(PyObject *module)
785/*[clinic end generated code: output=256d19dfcc0711e6 input=d416856ddbef6909]*/
Fred Drake8b4d01d2000-05-09 19:57:01 +0000786{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 return PyUnicode_FromString(PyUnicode_GetDefaultEncoding());
Fred Drake8b4d01d2000-05-09 19:57:01 +0000788}
789
Tal Einatede0b6f2018-12-31 17:12:08 +0200790/*[clinic input]
791sys.getfilesystemencoding
792
793Return the encoding used to convert Unicode filenames to OS filenames.
794[clinic start generated code]*/
Fred Drake8b4d01d2000-05-09 19:57:01 +0000795
796static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200797sys_getfilesystemencoding_impl(PyObject *module)
798/*[clinic end generated code: output=1dc4bdbe9be44aa7 input=8475f8649b8c7d8c]*/
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000799{
Victor Stinner838f2642019-06-13 22:41:23 +0200800 PyThreadState *tstate = _PyThreadState_GET();
801 const PyConfig *config = &tstate->interp->config;
Victor Stinner709d23d2019-05-02 14:56:30 -0400802 return PyUnicode_FromWideChar(config->filesystem_encoding, -1);
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000803}
804
Tal Einatede0b6f2018-12-31 17:12:08 +0200805/*[clinic input]
806sys.getfilesystemencodeerrors
807
808Return the error mode used Unicode to OS filename conversion.
809[clinic start generated code]*/
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000810
Martin v. Löwis04dc25c2008-10-03 16:09:28 +0000811static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200812sys_getfilesystemencodeerrors_impl(PyObject *module)
813/*[clinic end generated code: output=ba77b36bbf7c96f5 input=22a1e8365566f1e5]*/
Steve Dowercc16be82016-09-08 10:35:16 -0700814{
Victor Stinner838f2642019-06-13 22:41:23 +0200815 PyThreadState *tstate = _PyThreadState_GET();
816 const PyConfig *config = &tstate->interp->config;
Victor Stinner709d23d2019-05-02 14:56:30 -0400817 return PyUnicode_FromWideChar(config->filesystem_errors, -1);
Steve Dowercc16be82016-09-08 10:35:16 -0700818}
819
Tal Einatede0b6f2018-12-31 17:12:08 +0200820/*[clinic input]
821sys.intern
822
823 string as s: unicode
824 /
825
826``Intern'' the given string.
827
828This enters the string in the (global) table of interned strings whose
829purpose is to speed up dictionary lookups. Return the string itself or
830the previously interned string object with the same value.
831[clinic start generated code]*/
Steve Dowercc16be82016-09-08 10:35:16 -0700832
833static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200834sys_intern_impl(PyObject *module, PyObject *s)
835/*[clinic end generated code: output=be680c24f5c9e5d6 input=849483c006924e2f]*/
Georg Brandl66a796e2006-12-19 20:50:34 +0000836{
Victor Stinner838f2642019-06-13 22:41:23 +0200837 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 if (PyUnicode_CheckExact(s)) {
839 Py_INCREF(s);
840 PyUnicode_InternInPlace(&s);
841 return s;
842 }
843 else {
Victor Stinner838f2642019-06-13 22:41:23 +0200844 _PyErr_Format(tstate, PyExc_TypeError,
845 "can't intern %.400s", s->ob_type->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 return NULL;
847 }
Georg Brandl66a796e2006-12-19 20:50:34 +0000848}
849
Georg Brandl66a796e2006-12-19 20:50:34 +0000850
Fred Drake5755ce62001-06-27 19:19:46 +0000851/*
852 * Cached interned string objects used for calling the profile and
853 * trace functions. Initialized by trace_init().
854 */
Nick Coghlan5a851672017-09-08 10:14:16 +1000855static PyObject *whatstrings[8] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
Fred Drake5755ce62001-06-27 19:19:46 +0000856
857static int
858trace_init(void)
859{
Nick Coghlan5a851672017-09-08 10:14:16 +1000860 static const char * const whatnames[8] = {
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200861 "call", "exception", "line", "return",
Nick Coghlan5a851672017-09-08 10:14:16 +1000862 "c_call", "c_exception", "c_return",
863 "opcode"
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200864 };
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000865 PyObject *name;
866 int i;
Nick Coghlan5a851672017-09-08 10:14:16 +1000867 for (i = 0; i < 8; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 if (whatstrings[i] == NULL) {
869 name = PyUnicode_InternFromString(whatnames[i]);
870 if (name == NULL)
871 return -1;
872 whatstrings[i] = name;
873 }
874 }
875 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000876}
877
878
879static PyObject *
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100880call_trampoline(PyObject* callback,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 PyFrameObject *frame, int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000882{
Victor Stinner78da82b2016-08-20 01:22:57 +0200883 if (PyFrame_FastToLocalsWithError(frame) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 return NULL;
Victor Stinner78da82b2016-08-20 01:22:57 +0200885 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100886
Victor Stinner838f2642019-06-13 22:41:23 +0200887 PyObject *stack[3];
Victor Stinner78da82b2016-08-20 01:22:57 +0200888 stack[0] = (PyObject *)frame;
889 stack[1] = whatstrings[what];
890 stack[2] = (arg != NULL) ? arg : Py_None;
Fred Drake5755ce62001-06-27 19:19:46 +0000891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 /* call the Python-level function */
Victor Stinner838f2642019-06-13 22:41:23 +0200893 PyObject *result = _PyObject_FastCall(callback, stack, 3);
Fred Drake5755ce62001-06-27 19:19:46 +0000894
Victor Stinner78da82b2016-08-20 01:22:57 +0200895 PyFrame_LocalsToFast(frame, 1);
896 if (result == NULL) {
897 PyTraceBack_Here(frame);
898 }
899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 return result;
Fred Drake5755ce62001-06-27 19:19:46 +0000901}
902
903static int
904profile_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000906{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000908
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000909 if (arg == NULL)
910 arg = Py_None;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100911 result = call_trampoline(self, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 if (result == NULL) {
913 PyEval_SetProfile(NULL, NULL);
914 return -1;
915 }
916 Py_DECREF(result);
917 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000918}
919
920static int
921trace_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000923{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 PyObject *callback;
925 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 if (what == PyTrace_CALL)
928 callback = self;
929 else
930 callback = frame->f_trace;
931 if (callback == NULL)
932 return 0;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100933 result = call_trampoline(callback, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 if (result == NULL) {
935 PyEval_SetTrace(NULL, NULL);
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200936 Py_CLEAR(frame->f_trace);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 return -1;
938 }
939 if (result != Py_None) {
Serhiy Storchakaec397562016-04-06 09:50:03 +0300940 Py_XSETREF(frame->f_trace, result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 }
942 else {
943 Py_DECREF(result);
944 }
945 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000946}
Fred Draked0838392001-06-16 21:02:31 +0000947
Fred Drake8b4d01d2000-05-09 19:57:01 +0000948static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000949sys_settrace(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000950{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 if (trace_init() == -1)
952 return NULL;
953 if (args == Py_None)
954 PyEval_SetTrace(NULL, NULL);
955 else
956 PyEval_SetTrace(trace_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200957 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000958}
959
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000960PyDoc_STRVAR(settrace_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000961"settrace(function)\n\
962\n\
963Set the global debug tracing function. It will be called on each\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000964function call. See the debugger chapter in the library manual."
965);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000966
Tal Einatede0b6f2018-12-31 17:12:08 +0200967/*[clinic input]
968sys.gettrace
969
970Return the global debug tracing function set with sys.settrace.
971
972See the debugger chapter in the library manual.
973[clinic start generated code]*/
974
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000975static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200976sys_gettrace_impl(PyObject *module)
977/*[clinic end generated code: output=e97e3a4d8c971b6e input=373b51bb2147f4d8]*/
Christian Heimes9bd667a2008-01-20 15:14:11 +0000978{
Victor Stinner50b48572018-11-01 01:51:40 +0100979 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 PyObject *temp = tstate->c_traceobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 if (temp == NULL)
983 temp = Py_None;
984 Py_INCREF(temp);
985 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000986}
987
Christian Heimes9bd667a2008-01-20 15:14:11 +0000988static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000989sys_setprofile(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000990{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 if (trace_init() == -1)
992 return NULL;
993 if (args == Py_None)
994 PyEval_SetProfile(NULL, NULL);
995 else
996 PyEval_SetProfile(profile_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200997 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000998}
999
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001000PyDoc_STRVAR(setprofile_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001001"setprofile(function)\n\
1002\n\
1003Set the profiling function. It will be called on each function call\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001004and return. See the profiler chapter in the library manual."
1005);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001006
Tal Einatede0b6f2018-12-31 17:12:08 +02001007/*[clinic input]
1008sys.getprofile
1009
1010Return the profiling function set with sys.setprofile.
1011
1012See the profiler chapter in the library manual.
1013[clinic start generated code]*/
1014
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001015static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001016sys_getprofile_impl(PyObject *module)
1017/*[clinic end generated code: output=579b96b373448188 input=1b3209d89a32965d]*/
Christian Heimes9bd667a2008-01-20 15:14:11 +00001018{
Victor Stinner50b48572018-11-01 01:51:40 +01001019 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 PyObject *temp = tstate->c_profileobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +00001021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 if (temp == NULL)
1023 temp = Py_None;
1024 Py_INCREF(temp);
1025 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +00001026}
1027
Tal Einatede0b6f2018-12-31 17:12:08 +02001028/*[clinic input]
1029sys.setcheckinterval
1030
1031 n: int
1032 /
1033
1034Set the async event check interval to n instructions.
1035
1036This tells the Python interpreter to check for asynchronous events
1037every n instructions.
1038
1039This also affects how often thread switches occur.
1040[clinic start generated code]*/
Christian Heimes9bd667a2008-01-20 15:14:11 +00001041
1042static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001043sys_setcheckinterval_impl(PyObject *module, int n)
1044/*[clinic end generated code: output=3f686cef07e6e178 input=7a35b17bf22a6227]*/
Guido van Rossuma0d7a231995-01-09 17:46:13 +00001045{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1047 "sys.getcheckinterval() and sys.setcheckinterval() "
1048 "are deprecated. Use sys.setswitchinterval() "
Victor Stinner838f2642019-06-13 22:41:23 +02001049 "instead.", 1) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 return NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02001051 }
Victor Stinnercaba55b2018-08-03 15:33:52 +02001052
Victor Stinner838f2642019-06-13 22:41:23 +02001053 PyThreadState *tstate = _PyThreadState_GET();
1054 tstate->interp->check_interval = n;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001055 Py_RETURN_NONE;
Guido van Rossuma0d7a231995-01-09 17:46:13 +00001056}
1057
Tal Einatede0b6f2018-12-31 17:12:08 +02001058/*[clinic input]
1059sys.getcheckinterval
1060
1061Return the current check interval; see sys.setcheckinterval().
1062[clinic start generated code]*/
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001063
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001064static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001065sys_getcheckinterval_impl(PyObject *module)
1066/*[clinic end generated code: output=1b5060bf2b23a47c input=4b6589cbcca1db4e]*/
Tim Peterse5e065b2003-07-06 18:36:54 +00001067{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001068 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1069 "sys.getcheckinterval() and sys.setcheckinterval() "
1070 "are deprecated. Use sys.getswitchinterval() "
Victor Stinner838f2642019-06-13 22:41:23 +02001071 "instead.", 1) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 return NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02001073 }
1074
1075 PyThreadState *tstate = _PyThreadState_GET();
1076 return PyLong_FromLong(tstate->interp->check_interval);
Tim Peterse5e065b2003-07-06 18:36:54 +00001077}
1078
Tal Einatede0b6f2018-12-31 17:12:08 +02001079/*[clinic input]
1080sys.setswitchinterval
1081
1082 interval: double
1083 /
1084
1085Set the ideal thread switching delay inside the Python interpreter.
1086
1087The actual frequency of switching threads can be lower if the
1088interpreter executes long sequences of uninterruptible code
1089(this is implementation-specific and workload-dependent).
1090
1091The parameter must represent the desired switching delay in seconds
1092A typical value is 0.005 (5 milliseconds).
1093[clinic start generated code]*/
Tim Peterse5e065b2003-07-06 18:36:54 +00001094
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001095static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001096sys_setswitchinterval_impl(PyObject *module, double interval)
1097/*[clinic end generated code: output=65a19629e5153983 input=561b477134df91d9]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001098{
Victor Stinner838f2642019-06-13 22:41:23 +02001099 PyThreadState *tstate = _PyThreadState_GET();
Tal Einatede0b6f2018-12-31 17:12:08 +02001100 if (interval <= 0.0) {
Victor Stinner838f2642019-06-13 22:41:23 +02001101 _PyErr_SetString(tstate, PyExc_ValueError,
1102 "switch interval must be strictly positive");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001103 return NULL;
1104 }
Tal Einatede0b6f2018-12-31 17:12:08 +02001105 _PyEval_SetSwitchInterval((unsigned long) (1e6 * interval));
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001106 Py_RETURN_NONE;
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001107}
1108
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001109
Tal Einatede0b6f2018-12-31 17:12:08 +02001110/*[clinic input]
1111sys.getswitchinterval -> double
1112
1113Return the current thread switch interval; see sys.setswitchinterval().
1114[clinic start generated code]*/
1115
1116static double
1117sys_getswitchinterval_impl(PyObject *module)
1118/*[clinic end generated code: output=a38c277c85b5096d input=bdf9d39c0ebbbb6f]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001119{
Tal Einatede0b6f2018-12-31 17:12:08 +02001120 return 1e-6 * _PyEval_GetSwitchInterval();
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001121}
1122
Tal Einatede0b6f2018-12-31 17:12:08 +02001123/*[clinic input]
1124sys.setrecursionlimit
1125
1126 limit as new_limit: int
1127 /
1128
1129Set the maximum depth of the Python interpreter stack to n.
1130
1131This limit prevents infinite recursion from causing an overflow of the C
1132stack and crashing Python. The highest possible limit is platform-
1133dependent.
1134[clinic start generated code]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001135
Tim Peterse5e065b2003-07-06 18:36:54 +00001136static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001137sys_setrecursionlimit_impl(PyObject *module, int new_limit)
1138/*[clinic end generated code: output=35e1c64754800ace input=b0f7a23393924af3]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001139{
Tal Einatede0b6f2018-12-31 17:12:08 +02001140 int mark;
Victor Stinner838f2642019-06-13 22:41:23 +02001141 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner50856d52015-10-13 00:11:21 +02001142
Victor Stinner50856d52015-10-13 00:11:21 +02001143 if (new_limit < 1) {
Victor Stinner838f2642019-06-13 22:41:23 +02001144 _PyErr_SetString(tstate, PyExc_ValueError,
1145 "recursion limit must be greater or equal than 1");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 return NULL;
1147 }
Victor Stinner50856d52015-10-13 00:11:21 +02001148
1149 /* Issue #25274: When the recursion depth hits the recursion limit in
1150 _Py_CheckRecursiveCall(), the overflowed flag of the thread state is
1151 set to 1 and a RecursionError is raised. The overflowed flag is reset
1152 to 0 when the recursion depth goes below the low-water mark: see
1153 Py_LeaveRecursiveCall().
1154
1155 Reject too low new limit if the current recursion depth is higher than
1156 the new low-water mark. Otherwise it may not be possible anymore to
1157 reset the overflowed flag to 0. */
1158 mark = _Py_RecursionLimitLowerWaterMark(new_limit);
Victor Stinner50856d52015-10-13 00:11:21 +02001159 if (tstate->recursion_depth >= mark) {
Victor Stinner838f2642019-06-13 22:41:23 +02001160 _PyErr_Format(tstate, PyExc_RecursionError,
1161 "cannot set the recursion limit to %i at "
1162 "the recursion depth %i: the limit is too low",
1163 new_limit, tstate->recursion_depth);
Victor Stinner50856d52015-10-13 00:11:21 +02001164 return NULL;
1165 }
1166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001167 Py_SetRecursionLimit(new_limit);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001168 Py_RETURN_NONE;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001169}
1170
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001171/*[clinic input]
1172sys.set_coroutine_origin_tracking_depth
1173
1174 depth: int
1175
1176Enable or disable origin tracking for coroutine objects in this thread.
1177
Tal Einatede0b6f2018-12-31 17:12:08 +02001178Coroutine objects will track 'depth' frames of traceback information
1179about where they came from, available in their cr_origin attribute.
1180
1181Set a depth of 0 to disable.
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001182[clinic start generated code]*/
1183
1184static PyObject *
1185sys_set_coroutine_origin_tracking_depth_impl(PyObject *module, int depth)
Tal Einatede0b6f2018-12-31 17:12:08 +02001186/*[clinic end generated code: output=0a2123c1cc6759c5 input=a1d0a05f89d2c426]*/
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001187{
Victor Stinner838f2642019-06-13 22:41:23 +02001188 PyThreadState *tstate = _PyThreadState_GET();
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001189 if (depth < 0) {
Victor Stinner838f2642019-06-13 22:41:23 +02001190 _PyErr_SetString(tstate, PyExc_ValueError, "depth must be >= 0");
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001191 return NULL;
1192 }
Victor Stinner838f2642019-06-13 22:41:23 +02001193 _PyEval_SetCoroutineOriginTrackingDepth(tstate, depth);
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001194 Py_RETURN_NONE;
1195}
1196
1197/*[clinic input]
1198sys.get_coroutine_origin_tracking_depth -> int
1199
1200Check status of origin tracking for coroutine objects in this thread.
1201[clinic start generated code]*/
1202
1203static int
1204sys_get_coroutine_origin_tracking_depth_impl(PyObject *module)
1205/*[clinic end generated code: output=3699f7be95a3afb8 input=335266a71205b61a]*/
1206{
1207 return _PyEval_GetCoroutineOriginTrackingDepth();
1208}
1209
Yury Selivanoveb636452016-09-08 22:01:51 -07001210static PyTypeObject AsyncGenHooksType;
1211
1212PyDoc_STRVAR(asyncgen_hooks_doc,
1213"asyncgen_hooks\n\
1214\n\
1215A struct sequence providing information about asynhronous\n\
1216generators hooks. The attributes are read only.");
1217
1218static PyStructSequence_Field asyncgen_hooks_fields[] = {
1219 {"firstiter", "Hook to intercept first iteration"},
1220 {"finalizer", "Hook to intercept finalization"},
1221 {0}
1222};
1223
1224static PyStructSequence_Desc asyncgen_hooks_desc = {
1225 "asyncgen_hooks", /* name */
1226 asyncgen_hooks_doc, /* doc */
1227 asyncgen_hooks_fields , /* fields */
1228 2
1229};
1230
Yury Selivanoveb636452016-09-08 22:01:51 -07001231static PyObject *
1232sys_set_asyncgen_hooks(PyObject *self, PyObject *args, PyObject *kw)
1233{
1234 static char *keywords[] = {"firstiter", "finalizer", NULL};
1235 PyObject *firstiter = NULL;
1236 PyObject *finalizer = NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02001237 PyThreadState *tstate = _PyThreadState_GET();
Yury Selivanoveb636452016-09-08 22:01:51 -07001238
1239 if (!PyArg_ParseTupleAndKeywords(
1240 args, kw, "|OO", keywords,
1241 &firstiter, &finalizer)) {
1242 return NULL;
1243 }
1244
1245 if (finalizer && finalizer != Py_None) {
1246 if (!PyCallable_Check(finalizer)) {
Victor Stinner838f2642019-06-13 22:41:23 +02001247 _PyErr_Format(tstate, PyExc_TypeError,
1248 "callable finalizer expected, got %.50s",
1249 Py_TYPE(finalizer)->tp_name);
Yury Selivanoveb636452016-09-08 22:01:51 -07001250 return NULL;
1251 }
1252 _PyEval_SetAsyncGenFinalizer(finalizer);
1253 }
1254 else if (finalizer == Py_None) {
1255 _PyEval_SetAsyncGenFinalizer(NULL);
1256 }
1257
1258 if (firstiter && firstiter != Py_None) {
1259 if (!PyCallable_Check(firstiter)) {
Victor Stinner838f2642019-06-13 22:41:23 +02001260 _PyErr_Format(tstate, PyExc_TypeError,
1261 "callable firstiter expected, got %.50s",
1262 Py_TYPE(firstiter)->tp_name);
Yury Selivanoveb636452016-09-08 22:01:51 -07001263 return NULL;
1264 }
1265 _PyEval_SetAsyncGenFirstiter(firstiter);
1266 }
1267 else if (firstiter == Py_None) {
1268 _PyEval_SetAsyncGenFirstiter(NULL);
1269 }
1270
1271 Py_RETURN_NONE;
1272}
1273
1274PyDoc_STRVAR(set_asyncgen_hooks_doc,
Tal Einatede0b6f2018-12-31 17:12:08 +02001275"set_asyncgen_hooks(* [, firstiter] [, finalizer])\n\
Yury Selivanoveb636452016-09-08 22:01:51 -07001276\n\
1277Set a finalizer for async generators objects."
1278);
1279
Tal Einatede0b6f2018-12-31 17:12:08 +02001280/*[clinic input]
1281sys.get_asyncgen_hooks
1282
1283Return the installed asynchronous generators hooks.
1284
1285This returns a namedtuple of the form (firstiter, finalizer).
1286[clinic start generated code]*/
1287
Yury Selivanoveb636452016-09-08 22:01:51 -07001288static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001289sys_get_asyncgen_hooks_impl(PyObject *module)
1290/*[clinic end generated code: output=53a253707146f6cf input=3676b9ea62b14625]*/
Yury Selivanoveb636452016-09-08 22:01:51 -07001291{
1292 PyObject *res;
1293 PyObject *firstiter = _PyEval_GetAsyncGenFirstiter();
1294 PyObject *finalizer = _PyEval_GetAsyncGenFinalizer();
1295
1296 res = PyStructSequence_New(&AsyncGenHooksType);
1297 if (res == NULL) {
1298 return NULL;
1299 }
1300
1301 if (firstiter == NULL) {
1302 firstiter = Py_None;
1303 }
1304
1305 if (finalizer == NULL) {
1306 finalizer = Py_None;
1307 }
1308
1309 Py_INCREF(firstiter);
1310 PyStructSequence_SET_ITEM(res, 0, firstiter);
1311
1312 Py_INCREF(finalizer);
1313 PyStructSequence_SET_ITEM(res, 1, finalizer);
1314
1315 return res;
1316}
1317
Yury Selivanoveb636452016-09-08 22:01:51 -07001318
Mark Dickinsondc787d22010-05-23 13:33:13 +00001319static PyTypeObject Hash_InfoType;
1320
1321PyDoc_STRVAR(hash_info_doc,
1322"hash_info\n\
1323\n\
1324A struct sequence providing parameters used for computing\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +01001325hashes. The attributes are read only.");
Mark Dickinsondc787d22010-05-23 13:33:13 +00001326
1327static PyStructSequence_Field hash_info_fields[] = {
1328 {"width", "width of the type used for hashing, in bits"},
1329 {"modulus", "prime number giving the modulus on which the hash "
1330 "function is based"},
1331 {"inf", "value to be used for hash of a positive infinity"},
1332 {"nan", "value to be used for hash of a nan"},
1333 {"imag", "multiplier used for the imaginary part of a complex number"},
Christian Heimes985ecdc2013-11-20 11:46:18 +01001334 {"algorithm", "name of the algorithm for hashing of str, bytes and "
1335 "memoryviews"},
1336 {"hash_bits", "internal output size of hash algorithm"},
1337 {"seed_bits", "seed size of hash algorithm"},
1338 {"cutoff", "small string optimization cutoff"},
Mark Dickinsondc787d22010-05-23 13:33:13 +00001339 {NULL, NULL}
1340};
1341
1342static PyStructSequence_Desc hash_info_desc = {
1343 "sys.hash_info",
1344 hash_info_doc,
1345 hash_info_fields,
Christian Heimes985ecdc2013-11-20 11:46:18 +01001346 9,
Mark Dickinsondc787d22010-05-23 13:33:13 +00001347};
1348
Matthias Klosed885e952010-07-06 10:53:30 +00001349static PyObject *
Victor Stinner838f2642019-06-13 22:41:23 +02001350get_hash_info(PyThreadState *tstate)
Mark Dickinsondc787d22010-05-23 13:33:13 +00001351{
1352 PyObject *hash_info;
1353 int field = 0;
Christian Heimes985ecdc2013-11-20 11:46:18 +01001354 PyHash_FuncDef *hashfunc;
Mark Dickinsondc787d22010-05-23 13:33:13 +00001355 hash_info = PyStructSequence_New(&Hash_InfoType);
1356 if (hash_info == NULL)
1357 return NULL;
Christian Heimes985ecdc2013-11-20 11:46:18 +01001358 hashfunc = PyHash_GetFuncDef();
Mark Dickinsondc787d22010-05-23 13:33:13 +00001359 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001360 PyLong_FromLong(8*sizeof(Py_hash_t)));
Mark Dickinsondc787d22010-05-23 13:33:13 +00001361 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8035bc52010-10-23 16:20:50 +00001362 PyLong_FromSsize_t(_PyHASH_MODULUS));
Mark Dickinsondc787d22010-05-23 13:33:13 +00001363 PyStructSequence_SET_ITEM(hash_info, field++,
1364 PyLong_FromLong(_PyHASH_INF));
1365 PyStructSequence_SET_ITEM(hash_info, field++,
1366 PyLong_FromLong(_PyHASH_NAN));
1367 PyStructSequence_SET_ITEM(hash_info, field++,
1368 PyLong_FromLong(_PyHASH_IMAG));
Christian Heimes985ecdc2013-11-20 11:46:18 +01001369 PyStructSequence_SET_ITEM(hash_info, field++,
1370 PyUnicode_FromString(hashfunc->name));
1371 PyStructSequence_SET_ITEM(hash_info, field++,
1372 PyLong_FromLong(hashfunc->hash_bits));
1373 PyStructSequence_SET_ITEM(hash_info, field++,
1374 PyLong_FromLong(hashfunc->seed_bits));
1375 PyStructSequence_SET_ITEM(hash_info, field++,
1376 PyLong_FromLong(Py_HASH_CUTOFF));
Victor Stinner838f2642019-06-13 22:41:23 +02001377 if (_PyErr_Occurred(tstate)) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00001378 Py_CLEAR(hash_info);
1379 return NULL;
1380 }
1381 return hash_info;
1382}
Tal Einatede0b6f2018-12-31 17:12:08 +02001383/*[clinic input]
1384sys.getrecursionlimit
Mark Dickinsondc787d22010-05-23 13:33:13 +00001385
Tal Einatede0b6f2018-12-31 17:12:08 +02001386Return the current value of the recursion limit.
Mark Dickinsondc787d22010-05-23 13:33:13 +00001387
Tal Einatede0b6f2018-12-31 17:12:08 +02001388The recursion limit is the maximum depth of the Python interpreter
1389stack. This limit prevents infinite recursion from causing an overflow
1390of the C stack and crashing Python.
1391[clinic start generated code]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001392
1393static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001394sys_getrecursionlimit_impl(PyObject *module)
1395/*[clinic end generated code: output=d571fb6b4549ef2e input=1c6129fd2efaeea8]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001396{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397 return PyLong_FromLong(Py_GetRecursionLimit());
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001398}
1399
Mark Hammond8696ebc2002-10-08 02:44:31 +00001400#ifdef MS_WINDOWS
Mark Hammond8696ebc2002-10-08 02:44:31 +00001401
Eric Smithf7bb5782010-01-27 00:44:57 +00001402static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};
1403
1404static PyStructSequence_Field windows_version_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001405 {"major", "Major version number"},
1406 {"minor", "Minor version number"},
1407 {"build", "Build number"},
1408 {"platform", "Operating system platform"},
1409 {"service_pack", "Latest Service Pack installed on the system"},
1410 {"service_pack_major", "Service Pack major version number"},
1411 {"service_pack_minor", "Service Pack minor version number"},
1412 {"suite_mask", "Bit mask identifying available product suites"},
1413 {"product_type", "System product type"},
Steve Dower74f4af72016-09-17 17:27:48 -07001414 {"platform_version", "Diagnostic version number"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 {0}
Eric Smithf7bb5782010-01-27 00:44:57 +00001416};
1417
1418static PyStructSequence_Desc windows_version_desc = {
Tal Einatede0b6f2018-12-31 17:12:08 +02001419 "sys.getwindowsversion", /* name */
1420 sys_getwindowsversion__doc__, /* doc */
1421 windows_version_fields, /* fields */
1422 5 /* For backward compatibility,
1423 only the first 5 items are accessible
1424 via indexing, the rest are name only */
Eric Smithf7bb5782010-01-27 00:44:57 +00001425};
1426
Steve Dower3e96f322015-03-02 08:01:10 -08001427/* Disable deprecation warnings about GetVersionEx as the result is
1428 being passed straight through to the caller, who is responsible for
1429 using it correctly. */
1430#pragma warning(push)
1431#pragma warning(disable:4996)
1432
Tal Einatede0b6f2018-12-31 17:12:08 +02001433/*[clinic input]
1434sys.getwindowsversion
1435
1436Return info about the running version of Windows as a named tuple.
1437
1438The members are named: major, minor, build, platform, service_pack,
1439service_pack_major, service_pack_minor, suite_mask, product_type and
1440platform_version. For backward compatibility, only the first 5 items
1441are available by indexing. All elements are numbers, except
1442service_pack and platform_type which are strings, and platform_version
1443which is a 3-tuple. Platform is always 2. Product_type may be 1 for a
1444workstation, 2 for a domain controller, 3 for a server.
1445Platform_version is a 3-tuple containing a version number that is
1446intended for identifying the OS rather than feature detection.
1447[clinic start generated code]*/
1448
Mark Hammond8696ebc2002-10-08 02:44:31 +00001449static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001450sys_getwindowsversion_impl(PyObject *module)
1451/*[clinic end generated code: output=1ec063280b932857 input=73a228a328fee63a]*/
Mark Hammond8696ebc2002-10-08 02:44:31 +00001452{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 PyObject *version;
1454 int pos = 0;
Minmin Gong8ebc6452019-02-02 20:26:55 -08001455 OSVERSIONINFOEXW ver;
Steve Dower74f4af72016-09-17 17:27:48 -07001456 DWORD realMajor, realMinor, realBuild;
1457 HANDLE hKernel32;
1458 wchar_t kernel32_path[MAX_PATH];
1459 LPVOID verblock;
1460 DWORD verblock_size;
Victor Stinner838f2642019-06-13 22:41:23 +02001461 PyThreadState *tstate = _PyThreadState_GET();
Steve Dower74f4af72016-09-17 17:27:48 -07001462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001463 ver.dwOSVersionInfoSize = sizeof(ver);
Minmin Gong8ebc6452019-02-02 20:26:55 -08001464 if (!GetVersionExW((OSVERSIONINFOW*) &ver))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001465 return PyErr_SetFromWindowsErr(0);
Eric Smithf7bb5782010-01-27 00:44:57 +00001466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001467 version = PyStructSequence_New(&WindowsVersionType);
1468 if (version == NULL)
1469 return NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +00001470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001471 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion));
1472 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion));
1473 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber));
1474 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId));
Minmin Gong8ebc6452019-02-02 20:26:55 -08001475 PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromWideChar(ver.szCSDVersion, -1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001476 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor));
1477 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor));
1478 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask));
1479 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType));
Eric Smithf7bb5782010-01-27 00:44:57 +00001480
Steve Dower74f4af72016-09-17 17:27:48 -07001481 realMajor = ver.dwMajorVersion;
1482 realMinor = ver.dwMinorVersion;
1483 realBuild = ver.dwBuildNumber;
1484
1485 // GetVersion will lie if we are running in a compatibility mode.
1486 // We need to read the version info from a system file resource
1487 // to accurately identify the OS version. If we fail for any reason,
1488 // just return whatever GetVersion said.
Tony Roberts4860f012019-02-02 18:16:42 +01001489 Py_BEGIN_ALLOW_THREADS
Steve Dower74f4af72016-09-17 17:27:48 -07001490 hKernel32 = GetModuleHandleW(L"kernel32.dll");
Tony Roberts4860f012019-02-02 18:16:42 +01001491 Py_END_ALLOW_THREADS
Steve Dower74f4af72016-09-17 17:27:48 -07001492 if (hKernel32 && GetModuleFileNameW(hKernel32, kernel32_path, MAX_PATH) &&
1493 (verblock_size = GetFileVersionInfoSizeW(kernel32_path, NULL)) &&
1494 (verblock = PyMem_RawMalloc(verblock_size))) {
1495 VS_FIXEDFILEINFO *ffi;
1496 UINT ffi_len;
1497
1498 if (GetFileVersionInfoW(kernel32_path, 0, verblock_size, verblock) &&
1499 VerQueryValueW(verblock, L"", (LPVOID)&ffi, &ffi_len)) {
1500 realMajor = HIWORD(ffi->dwProductVersionMS);
1501 realMinor = LOWORD(ffi->dwProductVersionMS);
1502 realBuild = HIWORD(ffi->dwProductVersionLS);
1503 }
1504 PyMem_RawFree(verblock);
1505 }
Segev Finer48fb7662017-06-04 20:52:27 +03001506 PyStructSequence_SET_ITEM(version, pos++, Py_BuildValue("(kkk)",
1507 realMajor,
1508 realMinor,
1509 realBuild
Steve Dower74f4af72016-09-17 17:27:48 -07001510 ));
1511
Victor Stinner838f2642019-06-13 22:41:23 +02001512 if (_PyErr_Occurred(tstate)) {
Serhiy Storchaka48d761e2013-12-17 15:11:24 +02001513 Py_DECREF(version);
1514 return NULL;
1515 }
Steve Dower74f4af72016-09-17 17:27:48 -07001516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 return version;
Mark Hammond8696ebc2002-10-08 02:44:31 +00001518}
1519
Steve Dower3e96f322015-03-02 08:01:10 -08001520#pragma warning(pop)
1521
Tal Einatede0b6f2018-12-31 17:12:08 +02001522/*[clinic input]
1523sys._enablelegacywindowsfsencoding
1524
1525Changes the default filesystem encoding to mbcs:replace.
1526
1527This is done for consistency with earlier versions of Python. See PEP
1528529 for more information.
1529
1530This is equivalent to defining the PYTHONLEGACYWINDOWSFSENCODING
1531environment variable before launching Python.
1532[clinic start generated code]*/
Steve Dowercc16be82016-09-08 10:35:16 -07001533
1534static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001535sys__enablelegacywindowsfsencoding_impl(PyObject *module)
1536/*[clinic end generated code: output=f5c3855b45e24fe9 input=2bfa931a20704492]*/
Steve Dowercc16be82016-09-08 10:35:16 -07001537{
Victor Stinner709d23d2019-05-02 14:56:30 -04001538 if (_PyUnicode_EnableLegacyWindowsFSEncoding() < 0) {
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001539 return NULL;
1540 }
Steve Dowercc16be82016-09-08 10:35:16 -07001541 Py_RETURN_NONE;
1542}
1543
Mark Hammond8696ebc2002-10-08 02:44:31 +00001544#endif /* MS_WINDOWS */
1545
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001546#ifdef HAVE_DLOPEN
Tal Einatede0b6f2018-12-31 17:12:08 +02001547
1548/*[clinic input]
1549sys.setdlopenflags
1550
1551 flags as new_val: int
1552 /
1553
1554Set the flags used by the interpreter for dlopen calls.
1555
1556This is used, for example, when the interpreter loads extension
1557modules. Among other things, this will enable a lazy resolving of
1558symbols when importing a module, if called as sys.setdlopenflags(0).
1559To share symbols across extension modules, call as
1560sys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag
1561modules can be found in the os module (RTLD_xxx constants, e.g.
1562os.RTLD_LAZY).
1563[clinic start generated code]*/
1564
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001565static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001566sys_setdlopenflags_impl(PyObject *module, int new_val)
1567/*[clinic end generated code: output=ec918b7fe0a37281 input=4c838211e857a77f]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001568{
Victor Stinner838f2642019-06-13 22:41:23 +02001569 PyThreadState *tstate = _PyThreadState_GET();
1570 tstate->interp->dlopenflags = new_val;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001571 Py_RETURN_NONE;
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001572}
1573
Tal Einatede0b6f2018-12-31 17:12:08 +02001574
1575/*[clinic input]
1576sys.getdlopenflags
1577
1578Return the current value of the flags that are used for dlopen calls.
1579
1580The flag constants are defined in the os module.
1581[clinic start generated code]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001582
1583static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001584sys_getdlopenflags_impl(PyObject *module)
1585/*[clinic end generated code: output=e92cd1bc5005da6e input=dc4ea0899c53b4b6]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001586{
Victor Stinner838f2642019-06-13 22:41:23 +02001587 PyThreadState *tstate = _PyThreadState_GET();
1588 return PyLong_FromLong(tstate->interp->dlopenflags);
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001589}
1590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591#endif /* HAVE_DLOPEN */
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001592
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001593#ifdef USE_MALLOPT
1594/* Link with -lmalloc (or -lmpc) on an SGI */
1595#include <malloc.h>
1596
Tal Einatede0b6f2018-12-31 17:12:08 +02001597/*[clinic input]
1598sys.mdebug
1599
1600 flag: int
1601 /
1602[clinic start generated code]*/
1603
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001604static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001605sys_mdebug_impl(PyObject *module, int flag)
1606/*[clinic end generated code: output=5431d545847c3637 input=151d150ae1636f8a]*/
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001607{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001608 int flag;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 mallopt(M_DEBUG, flag);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001610 Py_RETURN_NONE;
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001611}
1612#endif /* USE_MALLOPT */
1613
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001614size_t
1615_PySys_GetSizeOf(PyObject *o)
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001616{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001617 PyObject *res = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 PyObject *method;
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001619 Py_ssize_t size;
Victor Stinner838f2642019-06-13 22:41:23 +02001620 PyThreadState *tstate = _PyThreadState_GET();
Benjamin Petersona5758c02009-05-09 18:15:04 +00001621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 /* Make sure the type is initialized. float gets initialized late */
Victor Stinner838f2642019-06-13 22:41:23 +02001623 if (PyType_Ready(Py_TYPE(o)) < 0) {
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001624 return (size_t)-1;
Victor Stinner838f2642019-06-13 22:41:23 +02001625 }
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001626
Benjamin Petersonce798522012-01-22 11:24:29 -05001627 method = _PyObject_LookupSpecial(o, &PyId___sizeof__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001628 if (method == NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +02001629 if (!_PyErr_Occurred(tstate)) {
1630 _PyErr_Format(tstate, PyExc_TypeError,
1631 "Type %.100s doesn't define __sizeof__",
1632 Py_TYPE(o)->tp_name);
1633 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001634 }
1635 else {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001636 res = _PyObject_CallNoArg(method);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001637 Py_DECREF(method);
1638 }
1639
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001640 if (res == NULL)
1641 return (size_t)-1;
1642
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001643 size = PyLong_AsSsize_t(res);
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001644 Py_DECREF(res);
Victor Stinner838f2642019-06-13 22:41:23 +02001645 if (size == -1 && _PyErr_Occurred(tstate))
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001646 return (size_t)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001647
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001648 if (size < 0) {
Victor Stinner838f2642019-06-13 22:41:23 +02001649 _PyErr_SetString(tstate, PyExc_ValueError,
1650 "__sizeof__() should return >= 0");
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001651 return (size_t)-1;
1652 }
1653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 /* add gc_head size */
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001655 if (PyObject_IS_GC(o))
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001656 return ((size_t)size) + sizeof(PyGC_Head);
1657 return (size_t)size;
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001658}
1659
1660static PyObject *
1661sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
1662{
1663 static char *kwlist[] = {"object", "default", 0};
1664 size_t size;
1665 PyObject *o, *dflt = NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02001666 PyThreadState *tstate = _PyThreadState_GET();
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001667
1668 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
Victor Stinner838f2642019-06-13 22:41:23 +02001669 kwlist, &o, &dflt)) {
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001670 return NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02001671 }
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001672
1673 size = _PySys_GetSizeOf(o);
1674
Victor Stinner838f2642019-06-13 22:41:23 +02001675 if (size == (size_t)-1 && _PyErr_Occurred(tstate)) {
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001676 /* Has a default value been given */
Victor Stinner838f2642019-06-13 22:41:23 +02001677 if (dflt != NULL && _PyErr_ExceptionMatches(tstate, PyExc_TypeError)) {
1678 _PyErr_Clear(tstate);
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001679 Py_INCREF(dflt);
1680 return dflt;
1681 }
1682 else
1683 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001684 }
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001685
1686 return PyLong_FromSize_t(size);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001687}
1688
1689PyDoc_STRVAR(getsizeof_doc,
Tal Einatede0b6f2018-12-31 17:12:08 +02001690"getsizeof(object [, default]) -> int\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001691\n\
1692Return the size of object in bytes.");
1693
Tal Einatede0b6f2018-12-31 17:12:08 +02001694/*[clinic input]
1695sys.getrefcount -> Py_ssize_t
1696
1697 object: object
1698 /
1699
1700Return the reference count of object.
1701
1702The count returned is generally one higher than you might expect,
1703because it includes the (temporary) reference as an argument to
1704getrefcount().
1705[clinic start generated code]*/
1706
1707static Py_ssize_t
1708sys_getrefcount_impl(PyObject *module, PyObject *object)
1709/*[clinic end generated code: output=5fd477f2264b85b2 input=bf474efd50a21535]*/
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001710{
Tal Einatede0b6f2018-12-31 17:12:08 +02001711 return object->ob_refcnt;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001712}
1713
Tim Peters4be93d02002-07-07 19:59:50 +00001714#ifdef Py_REF_DEBUG
Tal Einatede0b6f2018-12-31 17:12:08 +02001715/*[clinic input]
1716sys.gettotalrefcount -> Py_ssize_t
1717[clinic start generated code]*/
1718
1719static Py_ssize_t
1720sys_gettotalrefcount_impl(PyObject *module)
1721/*[clinic end generated code: output=4103886cf17c25bc input=53b744faa5d2e4f6]*/
Mark Hammond440d8982000-06-20 08:12:48 +00001722{
Tal Einatede0b6f2018-12-31 17:12:08 +02001723 return _Py_GetRefTotal();
Mark Hammond440d8982000-06-20 08:12:48 +00001724}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001725#endif /* Py_REF_DEBUG */
Mark Hammond440d8982000-06-20 08:12:48 +00001726
Tal Einatede0b6f2018-12-31 17:12:08 +02001727/*[clinic input]
1728sys.getallocatedblocks -> Py_ssize_t
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001729
Tal Einatede0b6f2018-12-31 17:12:08 +02001730Return the number of memory blocks currently allocated.
1731[clinic start generated code]*/
1732
1733static Py_ssize_t
1734sys_getallocatedblocks_impl(PyObject *module)
1735/*[clinic end generated code: output=f0c4e873f0b6dcf7 input=dab13ee346a0673e]*/
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001736{
Tal Einatede0b6f2018-12-31 17:12:08 +02001737 return _Py_GetAllocatedBlocks();
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001738}
1739
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001740#ifdef COUNT_ALLOCS
Tal Einatede0b6f2018-12-31 17:12:08 +02001741/*[clinic input]
1742sys.getcounts
1743[clinic start generated code]*/
1744
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001745static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001746sys_getcounts_impl(PyObject *module)
1747/*[clinic end generated code: output=20df00bc164f43cb input=ad2ec7bda5424953]*/
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001748{
Pablo Galindo49c75a82018-10-28 15:02:17 +00001749 extern PyObject *_Py_get_counts(void);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001750
Pablo Galindo49c75a82018-10-28 15:02:17 +00001751 return _Py_get_counts();
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001752}
1753#endif
1754
Tal Einatede0b6f2018-12-31 17:12:08 +02001755/*[clinic input]
1756sys._getframe
1757
1758 depth: int = 0
1759 /
1760
1761Return a frame object from the call stack.
1762
1763If optional integer depth is given, return the frame object that many
1764calls below the top of the stack. If that is deeper than the call
1765stack, ValueError is raised. The default for depth is zero, returning
1766the frame at the top of the call stack.
1767
1768This function should be used for internal and specialized purposes
1769only.
1770[clinic start generated code]*/
Barry Warsawb6a54d22000-12-06 21:47:46 +00001771
1772static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001773sys__getframe_impl(PyObject *module, int depth)
1774/*[clinic end generated code: output=d438776c04d59804 input=c1be8a6464b11ee5]*/
Barry Warsawb6a54d22000-12-06 21:47:46 +00001775{
Victor Stinner838f2642019-06-13 22:41:23 +02001776 PyThreadState *tstate = _PyThreadState_GET();
1777 PyFrameObject *f = tstate->frame;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001778
Steve Dowerb82e17e2019-05-23 08:45:22 -07001779 if (PySys_Audit("sys._getframe", "O", f) < 0) {
1780 return NULL;
1781 }
1782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 while (depth > 0 && f != NULL) {
1784 f = f->f_back;
1785 --depth;
1786 }
1787 if (f == NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +02001788 _PyErr_SetString(tstate, PyExc_ValueError,
1789 "call stack is not deep enough");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001790 return NULL;
1791 }
1792 Py_INCREF(f);
1793 return (PyObject*)f;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001794}
1795
Tal Einatede0b6f2018-12-31 17:12:08 +02001796/*[clinic input]
1797sys._current_frames
1798
1799Return a dict mapping each thread's thread id to its current stack frame.
1800
1801This function should be used for specialized purposes only.
1802[clinic start generated code]*/
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001803
1804static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001805sys__current_frames_impl(PyObject *module)
1806/*[clinic end generated code: output=d2a41ac0a0a3809a input=2a9049c5f5033691]*/
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001807{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001808 return _PyThread_CurrentFrames();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001809}
1810
Tal Einatede0b6f2018-12-31 17:12:08 +02001811/*[clinic input]
1812sys.call_tracing
1813
1814 func: object
1815 args as funcargs: object(subclass_of='&PyTuple_Type')
1816 /
1817
1818Call func(*args), while tracing is enabled.
1819
1820The tracing state is saved, and restored afterwards. This is intended
1821to be called from a debugger from a checkpoint, to recursively debug
1822some other code.
1823[clinic start generated code]*/
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001824
1825static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001826sys_call_tracing_impl(PyObject *module, PyObject *func, PyObject *funcargs)
1827/*[clinic end generated code: output=7e4999853cd4e5a6 input=5102e8b11049f92f]*/
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001828{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001829 return _PyEval_CallTracing(func, funcargs);
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001830}
1831
Tal Einatede0b6f2018-12-31 17:12:08 +02001832/*[clinic input]
1833sys.callstats
1834
1835Return a tuple of function call statistics.
1836
1837A tuple is returned only if CALL_PROFILE was defined when Python was
1838built. Otherwise, this returns None.
1839
1840When enabled, this function returns detailed, implementation-specific
1841details about the number of function calls executed. The return value
1842is a 11-tuple where the entries in the tuple are counts of:
18430. all function calls
18441. calls to PyFunction_Type objects
18452. PyFunction calls that do not create an argument tuple
18463. PyFunction calls that do not create an argument tuple
1847 and bypass PyEval_EvalCodeEx()
18484. PyMethod calls
18495. PyMethod calls on bound methods
18506. PyType calls
18517. PyCFunction calls
18528. generator calls
18539. All other calls
185410. Number of stack pops performed by call_function()
1855[clinic start generated code]*/
Barry Warsawb6a54d22000-12-06 21:47:46 +00001856
Victor Stinner048afd92016-11-28 11:59:04 +01001857static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001858sys_callstats_impl(PyObject *module)
1859/*[clinic end generated code: output=edc4a74957fa8def input=d447d8d224d5d175]*/
Victor Stinner048afd92016-11-28 11:59:04 +01001860{
1861 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1862 "sys.callstats() has been deprecated in Python 3.7 "
1863 "and will be removed in the future", 1) < 0) {
1864 return NULL;
1865 }
1866
1867 Py_RETURN_NONE;
1868}
1869
1870
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001871#ifdef __cplusplus
1872extern "C" {
1873#endif
1874
Tal Einatede0b6f2018-12-31 17:12:08 +02001875/*[clinic input]
1876sys._debugmallocstats
1877
1878Print summary info to stderr about the state of pymalloc's structures.
1879
1880In Py_DEBUG mode, also perform some expensive internal consistency
1881checks.
1882[clinic start generated code]*/
1883
David Malcolm49526f42012-06-22 14:55:41 -04001884static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001885sys__debugmallocstats_impl(PyObject *module)
1886/*[clinic end generated code: output=ec3565f8c7cee46a input=33c0c9c416f98424]*/
David Malcolm49526f42012-06-22 14:55:41 -04001887{
1888#ifdef WITH_PYMALLOC
Victor Stinner6bf992a2017-12-06 17:26:10 +01001889 if (_PyObject_DebugMallocStats(stderr)) {
Victor Stinner34be807c2016-03-14 12:04:26 +01001890 fputc('\n', stderr);
1891 }
David Malcolm49526f42012-06-22 14:55:41 -04001892#endif
1893 _PyObject_DebugTypeStats(stderr);
1894
1895 Py_RETURN_NONE;
1896}
David Malcolm49526f42012-06-22 14:55:41 -04001897
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001898#ifdef Py_TRACE_REFS
Guido van Rossumded690f1996-05-24 20:48:31 +00001899/* Defined in objects.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001900extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001901#endif
Guido van Rossumded690f1996-05-24 20:48:31 +00001902
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001903#ifdef DYNAMIC_EXECUTION_PROFILE
1904/* Defined in ceval.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001905extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001906#endif
1907
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001908#ifdef __cplusplus
1909}
1910#endif
1911
Tal Einatede0b6f2018-12-31 17:12:08 +02001912
1913/*[clinic input]
1914sys._clear_type_cache
1915
1916Clear the internal type lookup cache.
1917[clinic start generated code]*/
1918
Christian Heimes15ebc882008-02-04 18:48:49 +00001919static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001920sys__clear_type_cache_impl(PyObject *module)
1921/*[clinic end generated code: output=20e48ca54a6f6971 input=127f3e04a8d9b555]*/
Christian Heimes15ebc882008-02-04 18:48:49 +00001922{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001923 PyType_ClearCache();
1924 Py_RETURN_NONE;
Christian Heimes15ebc882008-02-04 18:48:49 +00001925}
1926
Tal Einatede0b6f2018-12-31 17:12:08 +02001927/*[clinic input]
1928sys.is_finalizing
1929
1930Return True if Python is exiting.
1931[clinic start generated code]*/
1932
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001933static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001934sys_is_finalizing_impl(PyObject *module)
1935/*[clinic end generated code: output=735b5ff7962ab281 input=f0df747a039948a5]*/
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001936{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001937 return PyBool_FromLong(_Py_IsFinalizing());
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001938}
1939
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001940#ifdef ANDROID_API_LEVEL
Tal Einatede0b6f2018-12-31 17:12:08 +02001941/*[clinic input]
1942sys.getandroidapilevel
1943
1944Return the build time API version of Android as an integer.
1945[clinic start generated code]*/
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001946
1947static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001948sys_getandroidapilevel_impl(PyObject *module)
1949/*[clinic end generated code: output=214abf183a1c70c1 input=3e6d6c9fcdd24ac6]*/
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001950{
1951 return PyLong_FromLong(ANDROID_API_LEVEL);
1952}
1953#endif /* ANDROID_API_LEVEL */
1954
1955
Steve Dowerb82e17e2019-05-23 08:45:22 -07001956
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001957static PyMethodDef sys_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001958 /* Might as well keep this in alphabetic order */
Steve Dowerb82e17e2019-05-23 08:45:22 -07001959 SYS_ADDAUDITHOOK_METHODDEF
1960 {"audit", (PyCFunction)(void(*)(void))sys_audit, METH_FASTCALL, audit_doc },
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001961 {"breakpointhook", (PyCFunction)(void(*)(void))sys_breakpointhook,
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04001962 METH_FASTCALL | METH_KEYWORDS, breakpointhook_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001963 SYS_CALLSTATS_METHODDEF
1964 SYS__CLEAR_TYPE_CACHE_METHODDEF
1965 SYS__CURRENT_FRAMES_METHODDEF
1966 SYS_DISPLAYHOOK_METHODDEF
1967 SYS_EXC_INFO_METHODDEF
1968 SYS_EXCEPTHOOK_METHODDEF
1969 SYS_EXIT_METHODDEF
1970 SYS_GETDEFAULTENCODING_METHODDEF
1971 SYS_GETDLOPENFLAGS_METHODDEF
1972 SYS_GETALLOCATEDBLOCKS_METHODDEF
1973 SYS_GETCOUNTS_METHODDEF
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001974#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001975 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001976#endif
Tal Einatede0b6f2018-12-31 17:12:08 +02001977 SYS_GETFILESYSTEMENCODING_METHODDEF
1978 SYS_GETFILESYSTEMENCODEERRORS_METHODDEF
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001979#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001980 {"getobjects", _Py_GetObjects, METH_VARARGS},
Tim Peters4be93d02002-07-07 19:59:50 +00001981#endif
Tal Einatede0b6f2018-12-31 17:12:08 +02001982 SYS_GETTOTALREFCOUNT_METHODDEF
1983 SYS_GETREFCOUNT_METHODDEF
1984 SYS_GETRECURSIONLIMIT_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001985 {"getsizeof", (PyCFunction)(void(*)(void))sys_getsizeof,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001986 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001987 SYS__GETFRAME_METHODDEF
1988 SYS_GETWINDOWSVERSION_METHODDEF
1989 SYS__ENABLELEGACYWINDOWSFSENCODING_METHODDEF
1990 SYS_INTERN_METHODDEF
1991 SYS_IS_FINALIZING_METHODDEF
1992 SYS_MDEBUG_METHODDEF
1993 SYS_SETCHECKINTERVAL_METHODDEF
1994 SYS_GETCHECKINTERVAL_METHODDEF
1995 SYS_SETSWITCHINTERVAL_METHODDEF
1996 SYS_GETSWITCHINTERVAL_METHODDEF
1997 SYS_SETDLOPENFLAGS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 {"setprofile", sys_setprofile, METH_O, setprofile_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001999 SYS_GETPROFILE_METHODDEF
2000 SYS_SETRECURSIONLIMIT_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002001 {"settrace", sys_settrace, METH_O, settrace_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02002002 SYS_GETTRACE_METHODDEF
2003 SYS_CALL_TRACING_METHODDEF
2004 SYS__DEBUGMALLOCSTATS_METHODDEF
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08002005 SYS_SET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
2006 SYS_GET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002007 {"set_asyncgen_hooks", (PyCFunction)(void(*)(void))sys_set_asyncgen_hooks,
Yury Selivanoveb636452016-09-08 22:01:51 -07002008 METH_VARARGS | METH_KEYWORDS, set_asyncgen_hooks_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02002009 SYS_GET_ASYNCGEN_HOOKS_METHODDEF
2010 SYS_GETANDROIDAPILEVEL_METHODDEF
Victor Stinneref9d9b62019-05-22 11:28:22 +02002011 SYS_UNRAISABLEHOOK_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012 {NULL, NULL} /* sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +00002013};
2014
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002015static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002016list_builtin_module_names(void)
Guido van Rossum34679b71993-01-26 13:33:44 +00002017{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002018 PyObject *list = PyList_New(0);
2019 int i;
2020 if (list == NULL)
2021 return NULL;
2022 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
2023 PyObject *name = PyUnicode_FromString(
2024 PyImport_Inittab[i].name);
2025 if (name == NULL)
2026 break;
2027 PyList_Append(list, name);
2028 Py_DECREF(name);
2029 }
2030 if (PyList_Sort(list) != 0) {
2031 Py_DECREF(list);
2032 list = NULL;
2033 }
2034 if (list) {
2035 PyObject *v = PyList_AsTuple(list);
2036 Py_DECREF(list);
2037 list = v;
2038 }
2039 return list;
Guido van Rossum34679b71993-01-26 13:33:44 +00002040}
2041
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002042/* Pre-initialization support for sys.warnoptions and sys._xoptions
2043 *
2044 * Modern internal code paths:
2045 * These APIs get called after _Py_InitializeCore and get to use the
2046 * regular CPython list, dict, and unicode APIs.
2047 *
2048 * Legacy embedding code paths:
2049 * The multi-phase initialization API isn't public yet, so embedding
2050 * apps still need to be able configure sys.warnoptions and sys._xoptions
2051 * before they call Py_Initialize. To support this, we stash copies of
2052 * the supplied wchar * sequences in linked lists, and then migrate the
2053 * contents of those lists to the sys module in _PyInitializeCore.
2054 *
2055 */
2056
2057struct _preinit_entry {
2058 wchar_t *value;
2059 struct _preinit_entry *next;
2060};
2061
2062typedef struct _preinit_entry *_Py_PreInitEntry;
2063
2064static _Py_PreInitEntry _preinit_warnoptions = NULL;
2065static _Py_PreInitEntry _preinit_xoptions = NULL;
2066
2067static _Py_PreInitEntry
2068_alloc_preinit_entry(const wchar_t *value)
2069{
2070 /* To get this to work, we have to initialize the runtime implicitly */
2071 _PyRuntime_Initialize();
2072
2073 /* Force default allocator, so we can ensure that it also gets used to
2074 * destroy the linked list in _clear_preinit_entries.
2075 */
2076 PyMemAllocatorEx old_alloc;
2077 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2078
2079 _Py_PreInitEntry node = PyMem_RawCalloc(1, sizeof(*node));
2080 if (node != NULL) {
2081 node->value = _PyMem_RawWcsdup(value);
2082 if (node->value == NULL) {
2083 PyMem_RawFree(node);
2084 node = NULL;
2085 };
2086 };
2087
2088 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2089 return node;
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002090}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002091
2092static int
2093_append_preinit_entry(_Py_PreInitEntry *optionlist, const wchar_t *value)
2094{
2095 _Py_PreInitEntry new_entry = _alloc_preinit_entry(value);
2096 if (new_entry == NULL) {
2097 return -1;
2098 }
2099 /* We maintain the linked list in this order so it's easy to play back
2100 * the add commands in the same order later on in _Py_InitializeCore
2101 */
2102 _Py_PreInitEntry last_entry = *optionlist;
2103 if (last_entry == NULL) {
2104 *optionlist = new_entry;
2105 } else {
2106 while (last_entry->next != NULL) {
2107 last_entry = last_entry->next;
2108 }
2109 last_entry->next = new_entry;
2110 }
2111 return 0;
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002112}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002113
2114static void
2115_clear_preinit_entries(_Py_PreInitEntry *optionlist)
2116{
2117 _Py_PreInitEntry current = *optionlist;
2118 *optionlist = NULL;
2119 /* Deallocate the nodes and their contents using the default allocator */
2120 PyMemAllocatorEx old_alloc;
2121 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2122 while (current != NULL) {
2123 _Py_PreInitEntry next = current->next;
2124 PyMem_RawFree(current->value);
2125 PyMem_RawFree(current);
2126 current = next;
2127 }
2128 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002129}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002130
2131static void
2132_clear_all_preinit_options(void)
2133{
2134 _clear_preinit_entries(&_preinit_warnoptions);
2135 _clear_preinit_entries(&_preinit_xoptions);
2136}
2137
2138static int
Victor Stinner838f2642019-06-13 22:41:23 +02002139sys_read_preinit_options(PyThreadState *tstate)
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002140{
2141 /* Rerun the add commands with the actual sys module available */
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002142 if (tstate == NULL) {
2143 /* Still don't have a thread state, so something is wrong! */
2144 return -1;
2145 }
2146 _Py_PreInitEntry entry = _preinit_warnoptions;
2147 while (entry != NULL) {
2148 PySys_AddWarnOption(entry->value);
2149 entry = entry->next;
2150 }
2151 entry = _preinit_xoptions;
2152 while (entry != NULL) {
2153 PySys_AddXOption(entry->value);
2154 entry = entry->next;
2155 }
2156
2157 _clear_all_preinit_options();
2158 return 0;
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002159}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002160
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002161static PyObject *
Victor Stinner838f2642019-06-13 22:41:23 +02002162get_warnoptions(PyThreadState *tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002163{
Victor Stinner838f2642019-06-13 22:41:23 +02002164 PyObject *warnoptions = sys_get_object_id(tstate, &PyId_warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002165 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002166 /* PEP432 TODO: we can reach this if warnoptions is NULL in the main
2167 * interpreter config. When that happens, we need to properly set
2168 * the `warnoptions` reference in the main interpreter config as well.
2169 *
2170 * For Python 3.7, we shouldn't be able to get here due to the
2171 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
2172 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
2173 * call optional for embedding applications, thus making this
2174 * reachable again.
2175 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002176 warnoptions = PyList_New(0);
Victor Stinner838f2642019-06-13 22:41:23 +02002177 if (warnoptions == NULL) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002178 return NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02002179 }
2180 if (sys_set_object_id(tstate, &PyId_warnoptions, warnoptions)) {
Eric Snowdae02762017-09-14 00:35:58 -07002181 Py_DECREF(warnoptions);
2182 return NULL;
2183 }
2184 Py_DECREF(warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002185 }
2186 return warnoptions;
2187}
Guido van Rossum23fff912000-12-15 22:02:05 +00002188
2189void
2190PySys_ResetWarnOptions(void)
2191{
Victor Stinner50b48572018-11-01 01:51:40 +01002192 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002193 if (tstate == NULL) {
2194 _clear_preinit_entries(&_preinit_warnoptions);
2195 return;
2196 }
2197
Victor Stinner838f2642019-06-13 22:41:23 +02002198 PyObject *warnoptions = sys_get_object_id(tstate, &PyId_warnoptions);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002199 if (warnoptions == NULL || !PyList_Check(warnoptions))
2200 return;
2201 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
Guido van Rossum23fff912000-12-15 22:02:05 +00002202}
2203
Victor Stinnere1b29952018-10-30 14:31:42 +01002204static int
Victor Stinner838f2642019-06-13 22:41:23 +02002205_PySys_AddWarnOptionWithError(PyThreadState *tstate, PyObject *option)
Guido van Rossum23fff912000-12-15 22:02:05 +00002206{
Victor Stinner838f2642019-06-13 22:41:23 +02002207 PyObject *warnoptions = get_warnoptions(tstate);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002208 if (warnoptions == NULL) {
2209 return -1;
2210 }
2211 if (PyList_Append(warnoptions, option)) {
2212 return -1;
2213 }
2214 return 0;
2215}
2216
2217void
2218PySys_AddWarnOptionUnicode(PyObject *option)
2219{
Victor Stinner838f2642019-06-13 22:41:23 +02002220 PyThreadState *tstate = _PyThreadState_GET();
2221 if (_PySys_AddWarnOptionWithError(tstate, option) < 0) {
Victor Stinnere1b29952018-10-30 14:31:42 +01002222 /* No return value, therefore clear error state if possible */
Victor Stinner838f2642019-06-13 22:41:23 +02002223 if (tstate) {
2224 _PyErr_Clear(tstate);
Victor Stinnere1b29952018-10-30 14:31:42 +01002225 }
2226 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00002227}
2228
2229void
2230PySys_AddWarnOption(const wchar_t *s)
2231{
Victor Stinner50b48572018-11-01 01:51:40 +01002232 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002233 if (tstate == NULL) {
2234 _append_preinit_entry(&_preinit_warnoptions, s);
2235 return;
2236 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00002237 PyObject *unicode;
2238 unicode = PyUnicode_FromWideChar(s, -1);
2239 if (unicode == NULL)
2240 return;
2241 PySys_AddWarnOptionUnicode(unicode);
2242 Py_DECREF(unicode);
Guido van Rossum23fff912000-12-15 22:02:05 +00002243}
2244
Christian Heimes33fe8092008-04-13 13:53:33 +00002245int
2246PySys_HasWarnOptions(void)
2247{
Victor Stinner838f2642019-06-13 22:41:23 +02002248 PyThreadState *tstate = _PyThreadState_GET();
2249 PyObject *warnoptions = sys_get_object_id(tstate, &PyId_warnoptions);
Serhiy Storchakadffccc62018-12-10 13:50:22 +02002250 return (warnoptions != NULL && PyList_Check(warnoptions)
2251 && PyList_GET_SIZE(warnoptions) > 0);
Christian Heimes33fe8092008-04-13 13:53:33 +00002252}
2253
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002254static PyObject *
Victor Stinner838f2642019-06-13 22:41:23 +02002255get_xoptions(PyThreadState *tstate)
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002256{
Victor Stinner838f2642019-06-13 22:41:23 +02002257 PyObject *xoptions = sys_get_object_id(tstate, &PyId__xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002258 if (xoptions == NULL || !PyDict_Check(xoptions)) {
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002259 /* PEP432 TODO: we can reach this if xoptions is NULL in the main
2260 * interpreter config. When that happens, we need to properly set
2261 * the `xoptions` reference in the main interpreter config as well.
2262 *
2263 * For Python 3.7, we shouldn't be able to get here due to the
2264 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
2265 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
2266 * call optional for embedding applications, thus making this
2267 * reachable again.
2268 */
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002269 xoptions = PyDict_New();
Victor Stinner838f2642019-06-13 22:41:23 +02002270 if (xoptions == NULL) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002271 return NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02002272 }
2273 if (sys_set_object_id(tstate, &PyId__xoptions, xoptions)) {
Eric Snowdae02762017-09-14 00:35:58 -07002274 Py_DECREF(xoptions);
2275 return NULL;
2276 }
2277 Py_DECREF(xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002278 }
2279 return xoptions;
2280}
2281
Victor Stinnere1b29952018-10-30 14:31:42 +01002282static int
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002283_PySys_AddXOptionWithError(const wchar_t *s)
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002284{
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002285 PyObject *name = NULL, *value = NULL;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002286
Victor Stinner838f2642019-06-13 22:41:23 +02002287 PyThreadState *tstate = _PyThreadState_GET();
2288 PyObject *opts = get_xoptions(tstate);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002289 if (opts == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002290 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002291 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002292
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002293 const wchar_t *name_end = wcschr(s, L'=');
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002294 if (!name_end) {
2295 name = PyUnicode_FromWideChar(s, -1);
2296 value = Py_True;
2297 Py_INCREF(value);
2298 }
2299 else {
2300 name = PyUnicode_FromWideChar(s, name_end - s);
2301 value = PyUnicode_FromWideChar(name_end + 1, -1);
2302 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002303 if (name == NULL || value == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002304 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002305 }
2306 if (PyDict_SetItem(opts, name, value) < 0) {
2307 goto error;
2308 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002309 Py_DECREF(name);
2310 Py_DECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002311 return 0;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002312
2313error:
2314 Py_XDECREF(name);
2315 Py_XDECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002316 return -1;
2317}
2318
2319void
2320PySys_AddXOption(const wchar_t *s)
2321{
Victor Stinner50b48572018-11-01 01:51:40 +01002322 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002323 if (tstate == NULL) {
2324 _append_preinit_entry(&_preinit_xoptions, s);
2325 return;
2326 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002327 if (_PySys_AddXOptionWithError(s) < 0) {
2328 /* No return value, therefore clear error state if possible */
Victor Stinner838f2642019-06-13 22:41:23 +02002329 if (tstate) {
2330 _PyErr_Clear(tstate);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002331 }
Victor Stinner0cae6092016-11-11 01:43:56 +01002332 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002333}
2334
2335PyObject *
2336PySys_GetXOptions(void)
2337{
Victor Stinner838f2642019-06-13 22:41:23 +02002338 PyThreadState *tstate = _PyThreadState_GET();
2339 return get_xoptions(tstate);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002340}
2341
Guido van Rossum40552d01998-08-06 03:34:39 +00002342/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
2343 Two literals concatenated works just fine. If you have a K&R compiler
2344 or other abomination that however *does* understand longer strings,
2345 get rid of the !!! comment in the middle and the quotes that surround it. */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002346PyDoc_VAR(sys_doc) =
2347PyDoc_STR(
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002348"This module provides access to some objects used or maintained by the\n\
2349interpreter and to functions that interact strongly with the interpreter.\n\
2350\n\
2351Dynamic objects:\n\
2352\n\
2353argv -- command line arguments; argv[0] is the script pathname if known\n\
2354path -- module search path; path[0] is the script directory, else ''\n\
2355modules -- dictionary of loaded modules\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002356\n\
2357displayhook -- called to show results in an interactive session\n\
2358excepthook -- called to handle any uncaught exception other than SystemExit\n\
2359 To customize printing in an interactive session or to install a custom\n\
2360 top-level exception handler, assign other functions to replace these.\n\
2361\n\
Benjamin Peterson06157a42008-07-15 00:28:36 +00002362stdin -- standard input file object; used by input()\n\
Georg Brandl88fc6642007-02-09 21:28:07 +00002363stdout -- standard output file object; used by print()\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002364stderr -- standard error object; used for error messages\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002365 By assigning other file objects (or objects that behave like files)\n\
2366 to these, it is possible to redirect all of the interpreter's I/O.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002367\n\
2368last_type -- type of last uncaught exception\n\
2369last_value -- value of last uncaught exception\n\
2370last_traceback -- traceback of last uncaught exception\n\
2371 These three are only available in an interactive session after a\n\
2372 traceback has been printed.\n\
Guido van Rossuma71b5f41999-01-14 19:07:00 +00002373"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002374)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002375/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002376PyDoc_STR(
Guido van Rossuma71b5f41999-01-14 19:07:00 +00002377"\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002378Static objects:\n\
2379\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002380builtin_module_names -- tuple of module names built into this interpreter\n\
2381copyright -- copyright notice pertaining to this interpreter\n\
2382exec_prefix -- prefix used to find the machine-specific Python library\n\
Petri Lehtinen4b0eab62012-02-02 21:23:15 +02002383executable -- absolute path of the executable binary of the Python interpreter\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002384float_info -- a struct sequence with information about the float implementation.\n\
2385float_repr_style -- string indicating the style of repr() output for floats\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +01002386hash_info -- a struct sequence with information about the hash algorithm.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002387hexversion -- version information encoded as a single integer\n\
Barry Warsaw409da152012-06-03 16:18:47 -04002388implementation -- Python implementation information.\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00002389int_info -- a struct sequence with information about the int implementation.\n\
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00002390maxsize -- the largest supported length of containers.\n\
Serhiy Storchakad3faf432015-01-18 11:28:37 +02002391maxunicode -- the value of the largest Unicode code point\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002392platform -- platform identifier\n\
2393prefix -- prefix used to find the Python library\n\
2394thread_info -- a struct sequence with information about the thread implementation.\n\
Fred Drake801c08d2000-04-13 15:29:10 +00002395version -- the version of this interpreter as a string\n\
Eric Smith0e5b5622009-02-06 01:32:42 +00002396version_info -- version information as a named tuple\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002397"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002398)
Steve Dowercc16be82016-09-08 10:35:16 -07002399#ifdef MS_COREDLL
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002400/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002401PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002402"dllhandle -- [Windows only] integer handle of the Python DLL\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002403winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002404"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002405)
Steve Dowercc16be82016-09-08 10:35:16 -07002406#endif /* MS_COREDLL */
2407#ifdef MS_WINDOWS
2408/* concatenating string here */
2409PyDoc_STR(
oldkaa0735f2018-02-02 16:52:55 +08002410"_enablelegacywindowsfsencoding -- [Windows only]\n\
Steve Dowercc16be82016-09-08 10:35:16 -07002411"
2412)
2413#endif
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002414PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002415"__stdin__ -- the original stdin; don't touch!\n\
2416__stdout__ -- the original stdout; don't touch!\n\
2417__stderr__ -- the original stderr; don't touch!\n\
2418__displayhook__ -- the original displayhook; don't touch!\n\
2419__excepthook__ -- the original excepthook; don't touch!\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002420\n\
2421Functions:\n\
2422\n\
Georg Brandl1a3284e2007-12-02 09:40:06 +00002423displayhook() -- print an object to the screen, and save it in builtins._\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002424excepthook() -- print an exception and its traceback to sys.stderr\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002425exc_info() -- return thread-safe information about the current exception\n\
2426exit() -- exit the interpreter by raising SystemExit\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002427getdlopenflags() -- returns flags to be used for dlopen() calls\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002428getprofile() -- get the global profiling function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002429getrefcount() -- return the reference count for an object (plus one :-)\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002430getrecursionlimit() -- return the max recursion depth for the interpreter\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002431getsizeof() -- return the size of an object in bytes\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002432gettrace() -- get the global debug tracing function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002433setcheckinterval() -- control how often the interpreter checks for events\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002434setdlopenflags() -- set the flags to be used for dlopen() calls\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002435setprofile() -- set the global profiling function\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002436setrecursionlimit() -- set the max recursion depth for the interpreter\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002437settrace() -- set the global debug tracing function\n\
Fred Drakeccede592000-08-14 20:59:57 +00002438"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002439)
Fred Drakeccede592000-08-14 20:59:57 +00002440/* end of sys_doc */ ;
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002441
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002442
2443PyDoc_STRVAR(flags__doc__,
2444"sys.flags\n\
2445\n\
2446Flags provided through command line arguments or environment vars.");
2447
2448static PyTypeObject FlagsType;
2449
2450static PyStructSequence_Field flags_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002451 {"debug", "-d"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002452 {"inspect", "-i"},
2453 {"interactive", "-i"},
2454 {"optimize", "-O or -OO"},
2455 {"dont_write_bytecode", "-B"},
2456 {"no_user_site", "-s"},
2457 {"no_site", "-S"},
2458 {"ignore_environment", "-E"},
2459 {"verbose", "-v"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002460 /* {"unbuffered", "-u"}, */
2461 /* {"skip_first", "-x"}, */
Georg Brandl8aa7e992010-12-28 18:30:18 +00002462 {"bytes_warning", "-b"},
2463 {"quiet", "-q"},
Georg Brandl09a7c722012-02-20 21:31:46 +01002464 {"hash_randomization", "-R"},
Christian Heimesad73a9c2013-08-10 16:36:18 +02002465 {"isolated", "-I"},
Victor Stinner5e3806f2017-11-30 11:40:24 +01002466 {"dev_mode", "-X dev"},
Victor Stinner91106cd2017-12-13 12:29:09 +01002467 {"utf8_mode", "-X utf8"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002468 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002469};
2470
2471static PyStructSequence_Desc flags_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002472 "sys.flags", /* name */
2473 flags__doc__, /* doc */
2474 flags_fields, /* fields */
Victor Stinner91106cd2017-12-13 12:29:09 +01002475 15
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002476};
2477
2478static PyObject*
Victor Stinner838f2642019-06-13 22:41:23 +02002479make_flags(_PyRuntimeState *runtime, PyThreadState *tstate)
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002480{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002481 int pos = 0;
2482 PyObject *seq;
Victor Stinner331a6a52019-05-27 16:39:22 +02002483 const PyPreConfig *preconfig = &runtime->preconfig;
Victor Stinner838f2642019-06-13 22:41:23 +02002484 const PyConfig *config = &tstate->interp->config;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002486 seq = PyStructSequence_New(&FlagsType);
2487 if (seq == NULL)
2488 return NULL;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002489
2490#define SetFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002491 PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002492
Victor Stinnerfbca9082018-08-30 00:50:45 +02002493 SetFlag(config->parser_debug);
2494 SetFlag(config->inspect);
2495 SetFlag(config->interactive);
2496 SetFlag(config->optimization_level);
2497 SetFlag(!config->write_bytecode);
2498 SetFlag(!config->user_site_directory);
2499 SetFlag(!config->site_import);
Victor Stinner20004952019-03-26 02:31:11 +01002500 SetFlag(!config->use_environment);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002501 SetFlag(config->verbose);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002502 /* SetFlag(saw_unbuffered_flag); */
2503 /* SetFlag(skipfirstline); */
Victor Stinnerfbca9082018-08-30 00:50:45 +02002504 SetFlag(config->bytes_warning);
2505 SetFlag(config->quiet);
2506 SetFlag(config->use_hash_seed == 0 || config->hash_seed != 0);
Victor Stinner20004952019-03-26 02:31:11 +01002507 SetFlag(config->isolated);
2508 PyStructSequence_SET_ITEM(seq, pos++, PyBool_FromLong(config->dev_mode));
2509 SetFlag(preconfig->utf8_mode);
Victor Stinner91106cd2017-12-13 12:29:09 +01002510#undef SetFlag
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002511
Victor Stinner838f2642019-06-13 22:41:23 +02002512 if (_PyErr_Occurred(tstate)) {
Serhiy Storchaka87a854d2013-12-17 14:59:42 +02002513 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002514 return NULL;
2515 }
2516 return seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002517}
2518
Eric Smith0e5b5622009-02-06 01:32:42 +00002519PyDoc_STRVAR(version_info__doc__,
2520"sys.version_info\n\
2521\n\
2522Version information as a named tuple.");
2523
2524static PyTypeObject VersionInfoType;
2525
2526static PyStructSequence_Field version_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002527 {"major", "Major release number"},
2528 {"minor", "Minor release number"},
2529 {"micro", "Patch release number"},
Ned Deilyda4887a2016-11-04 17:03:34 -04002530 {"releaselevel", "'alpha', 'beta', 'candidate', or 'final'"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002531 {"serial", "Serial release number"},
2532 {0}
Eric Smith0e5b5622009-02-06 01:32:42 +00002533};
2534
2535static PyStructSequence_Desc version_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002536 "sys.version_info", /* name */
2537 version_info__doc__, /* doc */
2538 version_info_fields, /* fields */
2539 5
Eric Smith0e5b5622009-02-06 01:32:42 +00002540};
2541
2542static PyObject *
Victor Stinner838f2642019-06-13 22:41:23 +02002543make_version_info(PyThreadState *tstate)
Eric Smith0e5b5622009-02-06 01:32:42 +00002544{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002545 PyObject *version_info;
2546 char *s;
2547 int pos = 0;
Eric Smith0e5b5622009-02-06 01:32:42 +00002548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002549 version_info = PyStructSequence_New(&VersionInfoType);
2550 if (version_info == NULL) {
2551 return NULL;
2552 }
Eric Smith0e5b5622009-02-06 01:32:42 +00002553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002554 /*
2555 * These release level checks are mutually exclusive and cover
2556 * the field, so don't get too fancy with the pre-processor!
2557 */
Eric Smith0e5b5622009-02-06 01:32:42 +00002558#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002559 s = "alpha";
Eric Smith0e5b5622009-02-06 01:32:42 +00002560#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002561 s = "beta";
Eric Smith0e5b5622009-02-06 01:32:42 +00002562#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002563 s = "candidate";
Eric Smith0e5b5622009-02-06 01:32:42 +00002564#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002565 s = "final";
Eric Smith0e5b5622009-02-06 01:32:42 +00002566#endif
2567
2568#define SetIntItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002569 PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002570#define SetStrItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002571 PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002573 SetIntItem(PY_MAJOR_VERSION);
2574 SetIntItem(PY_MINOR_VERSION);
2575 SetIntItem(PY_MICRO_VERSION);
2576 SetStrItem(s);
2577 SetIntItem(PY_RELEASE_SERIAL);
Eric Smith0e5b5622009-02-06 01:32:42 +00002578#undef SetIntItem
2579#undef SetStrItem
2580
Victor Stinner838f2642019-06-13 22:41:23 +02002581 if (_PyErr_Occurred(tstate)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002582 Py_CLEAR(version_info);
2583 return NULL;
2584 }
2585 return version_info;
Eric Smith0e5b5622009-02-06 01:32:42 +00002586}
2587
Brett Cannon3adc7b72012-07-09 14:22:12 -04002588/* sys.implementation values */
2589#define NAME "cpython"
2590const char *_PySys_ImplName = NAME;
Victor Stinnercf01b682015-11-05 11:21:38 +01002591#define MAJOR Py_STRINGIFY(PY_MAJOR_VERSION)
2592#define MINOR Py_STRINGIFY(PY_MINOR_VERSION)
Ned Deily529ea5d2014-06-30 23:31:14 -07002593#define TAG NAME "-" MAJOR MINOR
Brett Cannon3adc7b72012-07-09 14:22:12 -04002594const char *_PySys_ImplCacheTag = TAG;
2595#undef NAME
Brett Cannon3adc7b72012-07-09 14:22:12 -04002596#undef MAJOR
2597#undef MINOR
2598#undef TAG
2599
Barry Warsaw409da152012-06-03 16:18:47 -04002600static PyObject *
2601make_impl_info(PyObject *version_info)
2602{
2603 int res;
2604 PyObject *impl_info, *value, *ns;
2605
2606 impl_info = PyDict_New();
2607 if (impl_info == NULL)
2608 return NULL;
2609
2610 /* populate the dict */
2611
Brett Cannon3adc7b72012-07-09 14:22:12 -04002612 value = PyUnicode_FromString(_PySys_ImplName);
Barry Warsaw409da152012-06-03 16:18:47 -04002613 if (value == NULL)
2614 goto error;
2615 res = PyDict_SetItemString(impl_info, "name", value);
2616 Py_DECREF(value);
2617 if (res < 0)
2618 goto error;
2619
Brett Cannon3adc7b72012-07-09 14:22:12 -04002620 value = PyUnicode_FromString(_PySys_ImplCacheTag);
Barry Warsaw409da152012-06-03 16:18:47 -04002621 if (value == NULL)
2622 goto error;
2623 res = PyDict_SetItemString(impl_info, "cache_tag", value);
2624 Py_DECREF(value);
2625 if (res < 0)
2626 goto error;
Barry Warsaw409da152012-06-03 16:18:47 -04002627
2628 res = PyDict_SetItemString(impl_info, "version", version_info);
2629 if (res < 0)
2630 goto error;
2631
2632 value = PyLong_FromLong(PY_VERSION_HEX);
2633 if (value == NULL)
2634 goto error;
2635 res = PyDict_SetItemString(impl_info, "hexversion", value);
2636 Py_DECREF(value);
2637 if (res < 0)
2638 goto error;
2639
doko@ubuntu.com55532312016-06-14 08:55:19 +02002640#ifdef MULTIARCH
2641 value = PyUnicode_FromString(MULTIARCH);
2642 if (value == NULL)
2643 goto error;
2644 res = PyDict_SetItemString(impl_info, "_multiarch", value);
2645 Py_DECREF(value);
2646 if (res < 0)
2647 goto error;
2648#endif
2649
Barry Warsaw409da152012-06-03 16:18:47 -04002650 /* dict ready */
2651
2652 ns = _PyNamespace_New(impl_info);
2653 Py_DECREF(impl_info);
2654 return ns;
2655
2656error:
2657 Py_CLEAR(impl_info);
2658 return NULL;
2659}
2660
Martin v. Löwis1a214512008-06-11 05:26:20 +00002661static struct PyModuleDef sysmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002662 PyModuleDef_HEAD_INIT,
2663 "sys",
2664 sys_doc,
2665 -1, /* multiple "initialization" just copies the module dict. */
2666 sys_methods,
2667 NULL,
2668 NULL,
2669 NULL,
2670 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002671};
2672
Eric Snow6b4be192017-05-22 21:36:03 -07002673/* Updating the sys namespace, returning NULL pointer on error */
Victor Stinner8fea2522013-10-27 17:15:42 +01002674#define SET_SYS_FROM_STRING_BORROW(key, value) \
Victor Stinner58049602013-07-22 22:40:00 +02002675 do { \
Victor Stinner58049602013-07-22 22:40:00 +02002676 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002677 if (v == NULL) { \
2678 goto err_occurred; \
2679 } \
Victor Stinner58049602013-07-22 22:40:00 +02002680 res = PyDict_SetItemString(sysdict, key, v); \
2681 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002682 goto err_occurred; \
Victor Stinner8fea2522013-10-27 17:15:42 +01002683 } \
2684 } while (0)
2685#define SET_SYS_FROM_STRING(key, value) \
2686 do { \
Victor Stinner8fea2522013-10-27 17:15:42 +01002687 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002688 if (v == NULL) { \
2689 goto err_occurred; \
2690 } \
Victor Stinner8fea2522013-10-27 17:15:42 +01002691 res = PyDict_SetItemString(sysdict, key, v); \
2692 Py_DECREF(v); \
2693 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002694 goto err_occurred; \
Victor Stinner58049602013-07-22 22:40:00 +02002695 } \
2696 } while (0)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002697
Victor Stinner331a6a52019-05-27 16:39:22 +02002698static PyStatus
Victor Stinner838f2642019-06-13 22:41:23 +02002699_PySys_InitCore(_PyRuntimeState *runtime, PyThreadState *tstate,
Victor Stinner0fd2c302019-06-04 03:15:09 +02002700 PyObject *sysdict)
Eric Snow6b4be192017-05-22 21:36:03 -07002701{
Victor Stinnerab672812019-01-23 15:04:40 +01002702 PyObject *version_info;
Eric Snow6b4be192017-05-22 21:36:03 -07002703 int res;
2704
Nick Coghland6009512014-11-20 21:39:37 +10002705 /* stdin/stdout/stderr are set in pylifecycle.c */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002706
Victor Stinner8fea2522013-10-27 17:15:42 +01002707 SET_SYS_FROM_STRING_BORROW("__displayhook__",
2708 PyDict_GetItemString(sysdict, "displayhook"));
2709 SET_SYS_FROM_STRING_BORROW("__excepthook__",
2710 PyDict_GetItemString(sysdict, "excepthook"));
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04002711 SET_SYS_FROM_STRING_BORROW(
2712 "__breakpointhook__",
2713 PyDict_GetItemString(sysdict, "breakpointhook"));
Victor Stinneref9d9b62019-05-22 11:28:22 +02002714 SET_SYS_FROM_STRING_BORROW("__unraisablehook__",
2715 PyDict_GetItemString(sysdict, "unraisablehook"));
2716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002717 SET_SYS_FROM_STRING("version",
2718 PyUnicode_FromString(Py_GetVersion()));
2719 SET_SYS_FROM_STRING("hexversion",
2720 PyLong_FromLong(PY_VERSION_HEX));
Ned Deily5c4b0d02017-03-04 00:19:55 -05002721 SET_SYS_FROM_STRING("_git",
2722 Py_BuildValue("(szz)", "CPython", _Py_gitidentifier(),
2723 _Py_gitversion()));
INADA Naoki6b42eb12017-06-29 15:31:38 +09002724 SET_SYS_FROM_STRING("_framework", PyUnicode_FromString(_PYTHONFRAMEWORK));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002725 SET_SYS_FROM_STRING("api_version",
2726 PyLong_FromLong(PYTHON_API_VERSION));
2727 SET_SYS_FROM_STRING("copyright",
2728 PyUnicode_FromString(Py_GetCopyright()));
2729 SET_SYS_FROM_STRING("platform",
2730 PyUnicode_FromString(Py_GetPlatform()));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002731 SET_SYS_FROM_STRING("maxsize",
2732 PyLong_FromSsize_t(PY_SSIZE_T_MAX));
2733 SET_SYS_FROM_STRING("float_info",
2734 PyFloat_GetInfo());
2735 SET_SYS_FROM_STRING("int_info",
2736 PyLong_GetInfo());
Mark Dickinsondc787d22010-05-23 13:33:13 +00002737 /* initialize hash_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002738 if (Hash_InfoType.tp_name == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002739 if (PyStructSequence_InitType2(&Hash_InfoType, &hash_info_desc) < 0) {
2740 goto type_init_failed;
2741 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002742 }
Mark Dickinsondc787d22010-05-23 13:33:13 +00002743 SET_SYS_FROM_STRING("hash_info",
Victor Stinner838f2642019-06-13 22:41:23 +02002744 get_hash_info(tstate));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002745 SET_SYS_FROM_STRING("maxunicode",
Ezio Melotti48a2f8f2011-09-29 00:18:19 +03002746 PyLong_FromLong(0x10FFFF));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002747 SET_SYS_FROM_STRING("builtin_module_names",
2748 list_builtin_module_names());
Christian Heimes743e0cd2012-10-17 23:52:17 +02002749#if PY_BIG_ENDIAN
2750 SET_SYS_FROM_STRING("byteorder",
2751 PyUnicode_FromString("big"));
2752#else
2753 SET_SYS_FROM_STRING("byteorder",
2754 PyUnicode_FromString("little"));
2755#endif
Fred Drake099325e2000-08-14 15:47:03 +00002756
Guido van Rossum8b9ea871996-08-23 18:14:47 +00002757#ifdef MS_COREDLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002758 SET_SYS_FROM_STRING("dllhandle",
2759 PyLong_FromVoidPtr(PyWin_DLLhModule));
2760 SET_SYS_FROM_STRING("winver",
2761 PyUnicode_FromString(PyWin_DLLVersionString));
Guido van Rossumc606fe11996-04-09 02:37:57 +00002762#endif
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00002763#ifdef ABIFLAGS
2764 SET_SYS_FROM_STRING("abiflags",
2765 PyUnicode_FromString(ABIFLAGS));
2766#endif
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002768 /* version_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002769 if (VersionInfoType.tp_name == NULL) {
2770 if (PyStructSequence_InitType2(&VersionInfoType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002771 &version_info_desc) < 0) {
2772 goto type_init_failed;
2773 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002774 }
Victor Stinner838f2642019-06-13 22:41:23 +02002775 version_info = make_version_info(tstate);
Barry Warsaw409da152012-06-03 16:18:47 -04002776 SET_SYS_FROM_STRING("version_info", version_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002777 /* prevent user from creating new instances */
2778 VersionInfoType.tp_init = NULL;
2779 VersionInfoType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002780 res = PyDict_DelItemString(VersionInfoType.tp_dict, "__new__");
Victor Stinner838f2642019-06-13 22:41:23 +02002781 if (res < 0 && _PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
2782 _PyErr_Clear(tstate);
2783 }
Eric Smith0e5b5622009-02-06 01:32:42 +00002784
Barry Warsaw409da152012-06-03 16:18:47 -04002785 /* implementation */
2786 SET_SYS_FROM_STRING("implementation", make_impl_info(version_info));
2787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002788 /* flags */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002789 if (FlagsType.tp_name == 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002790 if (PyStructSequence_InitType2(&FlagsType, &flags_desc) < 0) {
2791 goto type_init_failed;
2792 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002793 }
Victor Stinner43125222019-04-24 18:23:53 +02002794 /* Set flags to their default values (updated by _PySys_InitMain()) */
Victor Stinner838f2642019-06-13 22:41:23 +02002795 SET_SYS_FROM_STRING("flags", make_flags(runtime, tstate));
Eric Smithf7bb5782010-01-27 00:44:57 +00002796
2797#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002798 /* getwindowsversion */
2799 if (WindowsVersionType.tp_name == 0)
Victor Stinner1c8f0592013-07-22 22:24:54 +02002800 if (PyStructSequence_InitType2(&WindowsVersionType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002801 &windows_version_desc) < 0) {
2802 goto type_init_failed;
2803 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002804 /* prevent user from creating new instances */
2805 WindowsVersionType.tp_init = NULL;
2806 WindowsVersionType.tp_new = NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02002807 assert(!_PyErr_Occurred(tstate));
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002808 res = PyDict_DelItemString(WindowsVersionType.tp_dict, "__new__");
Victor Stinner838f2642019-06-13 22:41:23 +02002809 if (res < 0 && _PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
2810 _PyErr_Clear(tstate);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002811 }
Eric Smithf7bb5782010-01-27 00:44:57 +00002812#endif
2813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002814 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002815#ifndef PY_NO_SHORT_FLOAT_REPR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002816 SET_SYS_FROM_STRING("float_repr_style",
2817 PyUnicode_FromString("short"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002818#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002819 SET_SYS_FROM_STRING("float_repr_style",
2820 PyUnicode_FromString("legacy"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002821#endif
2822
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002823 SET_SYS_FROM_STRING("thread_info", PyThread_GetInfo());
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002824
Yury Selivanoveb636452016-09-08 22:01:51 -07002825 /* initialize asyncgen_hooks */
2826 if (AsyncGenHooksType.tp_name == NULL) {
2827 if (PyStructSequence_InitType2(
2828 &AsyncGenHooksType, &asyncgen_hooks_desc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002829 goto type_init_failed;
Yury Selivanoveb636452016-09-08 22:01:51 -07002830 }
2831 }
2832
Victor Stinner838f2642019-06-13 22:41:23 +02002833 if (_PyErr_Occurred(tstate)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002834 goto err_occurred;
2835 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002836 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002837
2838type_init_failed:
Victor Stinner331a6a52019-05-27 16:39:22 +02002839 return _PyStatus_ERR("failed to initialize a type");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002840
2841err_occurred:
Victor Stinner331a6a52019-05-27 16:39:22 +02002842 return _PyStatus_ERR("can't initialize sys module");
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002843}
2844
Eric Snow6b4be192017-05-22 21:36:03 -07002845#undef SET_SYS_FROM_STRING
Eric Snow6b4be192017-05-22 21:36:03 -07002846
2847/* Updating the sys namespace, returning integer error codes */
Eric Snow6b4be192017-05-22 21:36:03 -07002848#define SET_SYS_FROM_STRING_INT_RESULT(key, value) \
2849 do { \
2850 PyObject *v = (value); \
2851 if (v == NULL) \
2852 return -1; \
2853 res = PyDict_SetItemString(sysdict, key, v); \
2854 Py_DECREF(v); \
2855 if (res < 0) { \
2856 return res; \
2857 } \
2858 } while (0)
2859
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002860
2861static int
2862sys_add_xoption(PyObject *opts, const wchar_t *s)
2863{
2864 PyObject *name, *value;
2865
2866 const wchar_t *name_end = wcschr(s, L'=');
2867 if (!name_end) {
2868 name = PyUnicode_FromWideChar(s, -1);
2869 value = Py_True;
2870 Py_INCREF(value);
2871 }
2872 else {
2873 name = PyUnicode_FromWideChar(s, name_end - s);
2874 value = PyUnicode_FromWideChar(name_end + 1, -1);
2875 }
2876 if (name == NULL || value == NULL) {
2877 goto error;
2878 }
2879 if (PyDict_SetItem(opts, name, value) < 0) {
2880 goto error;
2881 }
2882 Py_DECREF(name);
2883 Py_DECREF(value);
2884 return 0;
2885
2886error:
2887 Py_XDECREF(name);
2888 Py_XDECREF(value);
2889 return -1;
2890}
2891
2892
2893static PyObject*
Victor Stinner331a6a52019-05-27 16:39:22 +02002894sys_create_xoptions_dict(const PyConfig *config)
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002895{
2896 Py_ssize_t nxoption = config->xoptions.length;
2897 wchar_t * const * xoptions = config->xoptions.items;
2898 PyObject *dict = PyDict_New();
2899 if (dict == NULL) {
2900 return NULL;
2901 }
2902
2903 for (Py_ssize_t i=0; i < nxoption; i++) {
2904 const wchar_t *option = xoptions[i];
2905 if (sys_add_xoption(dict, option) < 0) {
2906 Py_DECREF(dict);
2907 return NULL;
2908 }
2909 }
2910
2911 return dict;
2912}
2913
2914
Eric Snow6b4be192017-05-22 21:36:03 -07002915int
Victor Stinner838f2642019-06-13 22:41:23 +02002916_PySys_InitMain(_PyRuntimeState *runtime, PyThreadState *tstate)
Eric Snow6b4be192017-05-22 21:36:03 -07002917{
Victor Stinner838f2642019-06-13 22:41:23 +02002918 PyObject *sysdict = tstate->interp->sysdict;
2919 const PyConfig *config = &tstate->interp->config;
Eric Snow6b4be192017-05-22 21:36:03 -07002920 int res;
2921
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002922#define COPY_LIST(KEY, VALUE) \
Victor Stinner37cd9822018-11-16 11:55:35 +01002923 do { \
Victor Stinner331a6a52019-05-27 16:39:22 +02002924 PyObject *list = _PyWideStringList_AsList(&(VALUE)); \
Victor Stinner37cd9822018-11-16 11:55:35 +01002925 if (list == NULL) { \
2926 return -1; \
2927 } \
2928 SET_SYS_FROM_STRING_BORROW(KEY, list); \
2929 Py_DECREF(list); \
2930 } while (0)
2931
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002932#define SET_SYS_FROM_WSTR(KEY, VALUE) \
2933 do { \
2934 PyObject *str = PyUnicode_FromWideChar(VALUE, -1); \
2935 if (str == NULL) { \
2936 return -1; \
2937 } \
2938 SET_SYS_FROM_STRING_BORROW(KEY, str); \
2939 Py_DECREF(str); \
2940 } while (0)
Victor Stinner37cd9822018-11-16 11:55:35 +01002941
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002942 COPY_LIST("path", config->module_search_paths);
2943
2944 SET_SYS_FROM_WSTR("executable", config->executable);
2945 SET_SYS_FROM_WSTR("prefix", config->prefix);
2946 SET_SYS_FROM_WSTR("base_prefix", config->base_prefix);
2947 SET_SYS_FROM_WSTR("exec_prefix", config->exec_prefix);
2948 SET_SYS_FROM_WSTR("base_exec_prefix", config->base_exec_prefix);
Victor Stinner41264f12017-12-15 02:05:29 +01002949
Carl Meyerb193fa92018-06-15 22:40:56 -06002950 if (config->pycache_prefix != NULL) {
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002951 SET_SYS_FROM_WSTR("pycache_prefix", config->pycache_prefix);
Carl Meyerb193fa92018-06-15 22:40:56 -06002952 } else {
2953 PyDict_SetItemString(sysdict, "pycache_prefix", Py_None);
2954 }
2955
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002956 COPY_LIST("argv", config->argv);
2957 COPY_LIST("warnoptions", config->warnoptions);
2958
2959 PyObject *xoptions = sys_create_xoptions_dict(config);
2960 if (xoptions == NULL) {
2961 return -1;
Victor Stinner41264f12017-12-15 02:05:29 +01002962 }
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002963 SET_SYS_FROM_STRING_BORROW("_xoptions", xoptions);
Pablo Galindo34ef64f2019-03-27 12:43:47 +00002964 Py_DECREF(xoptions);
Victor Stinner41264f12017-12-15 02:05:29 +01002965
Victor Stinner37cd9822018-11-16 11:55:35 +01002966#undef COPY_LIST
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002967#undef SET_SYS_FROM_WSTR
Victor Stinner37cd9822018-11-16 11:55:35 +01002968
Eric Snow6b4be192017-05-22 21:36:03 -07002969 /* Set flags to their final values */
Victor Stinner838f2642019-06-13 22:41:23 +02002970 SET_SYS_FROM_STRING_INT_RESULT("flags", make_flags(runtime, tstate));
Eric Snow6b4be192017-05-22 21:36:03 -07002971 /* prevent user from creating new instances */
2972 FlagsType.tp_init = NULL;
2973 FlagsType.tp_new = NULL;
2974 res = PyDict_DelItemString(FlagsType.tp_dict, "__new__");
2975 if (res < 0) {
Victor Stinner838f2642019-06-13 22:41:23 +02002976 if (!_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
Eric Snow6b4be192017-05-22 21:36:03 -07002977 return res;
2978 }
Victor Stinner838f2642019-06-13 22:41:23 +02002979 _PyErr_Clear(tstate);
Eric Snow6b4be192017-05-22 21:36:03 -07002980 }
2981
2982 SET_SYS_FROM_STRING_INT_RESULT("dont_write_bytecode",
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002983 PyBool_FromLong(!config->write_bytecode));
Eric Snow6b4be192017-05-22 21:36:03 -07002984
Victor Stinner838f2642019-06-13 22:41:23 +02002985 if (get_warnoptions(tstate) == NULL) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002986 return -1;
Victor Stinner838f2642019-06-13 22:41:23 +02002987 }
Victor Stinner865de272017-06-08 13:27:47 +02002988
Victor Stinner838f2642019-06-13 22:41:23 +02002989 if (get_xoptions(tstate) == NULL)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002990 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002991
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002992 /* Transfer any sys.warnoptions and sys._xoptions set directly
2993 * by an embedding application from the linked list to the module. */
Victor Stinner838f2642019-06-13 22:41:23 +02002994 if (sys_read_preinit_options(tstate) != 0)
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002995 return -1;
2996
Victor Stinner838f2642019-06-13 22:41:23 +02002997 if (_PyErr_Occurred(tstate)) {
2998 goto err_occurred;
2999 }
3000
Eric Snow6b4be192017-05-22 21:36:03 -07003001 return 0;
Victor Stinner41264f12017-12-15 02:05:29 +01003002
3003err_occurred:
3004 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07003005}
3006
Victor Stinner41264f12017-12-15 02:05:29 +01003007#undef SET_SYS_FROM_STRING_BORROW
Eric Snow6b4be192017-05-22 21:36:03 -07003008#undef SET_SYS_FROM_STRING_INT_RESULT
Eric Snow6b4be192017-05-22 21:36:03 -07003009
Victor Stinnerab672812019-01-23 15:04:40 +01003010
3011/* Set up a preliminary stderr printer until we have enough
3012 infrastructure for the io module in place.
3013
3014 Use UTF-8/surrogateescape and ignore EAGAIN errors. */
Victor Stinner331a6a52019-05-27 16:39:22 +02003015PyStatus
Victor Stinnerab672812019-01-23 15:04:40 +01003016_PySys_SetPreliminaryStderr(PyObject *sysdict)
3017{
3018 PyObject *pstderr = PyFile_NewStdPrinter(fileno(stderr));
3019 if (pstderr == NULL) {
3020 goto error;
3021 }
3022 if (_PyDict_SetItemId(sysdict, &PyId_stderr, pstderr) < 0) {
3023 goto error;
3024 }
3025 if (PyDict_SetItemString(sysdict, "__stderr__", pstderr) < 0) {
3026 goto error;
3027 }
3028 Py_DECREF(pstderr);
Victor Stinner331a6a52019-05-27 16:39:22 +02003029 return _PyStatus_OK();
Victor Stinnerab672812019-01-23 15:04:40 +01003030
3031error:
3032 Py_XDECREF(pstderr);
Victor Stinner331a6a52019-05-27 16:39:22 +02003033 return _PyStatus_ERR("can't set preliminary stderr");
Victor Stinnerab672812019-01-23 15:04:40 +01003034}
3035
3036
3037/* Create sys module without all attributes: _PySys_InitMain() should be called
3038 later to add remaining attributes. */
Victor Stinner331a6a52019-05-27 16:39:22 +02003039PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +02003040_PySys_Create(_PyRuntimeState *runtime, PyThreadState *tstate,
Victor Stinner0fd2c302019-06-04 03:15:09 +02003041 PyObject **sysmod_p)
Victor Stinnerab672812019-01-23 15:04:40 +01003042{
Victor Stinnerb45d2592019-06-20 00:05:23 +02003043 PyInterpreterState *interp = tstate->interp;
Victor Stinner838f2642019-06-13 22:41:23 +02003044
Victor Stinnerab672812019-01-23 15:04:40 +01003045 PyObject *modules = PyDict_New();
3046 if (modules == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02003047 return _PyStatus_ERR("can't make modules dictionary");
Victor Stinnerab672812019-01-23 15:04:40 +01003048 }
3049 interp->modules = modules;
3050
3051 PyObject *sysmod = _PyModule_CreateInitialized(&sysmodule, PYTHON_API_VERSION);
3052 if (sysmod == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02003053 return _PyStatus_ERR("failed to create a module object");
Victor Stinnerab672812019-01-23 15:04:40 +01003054 }
3055
3056 PyObject *sysdict = PyModule_GetDict(sysmod);
3057 if (sysdict == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02003058 return _PyStatus_ERR("can't initialize sys dict");
Victor Stinnerab672812019-01-23 15:04:40 +01003059 }
3060 Py_INCREF(sysdict);
3061 interp->sysdict = sysdict;
3062
3063 if (PyDict_SetItemString(sysdict, "modules", interp->modules) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +02003064 return _PyStatus_ERR("can't initialize sys module");
Victor Stinnerab672812019-01-23 15:04:40 +01003065 }
3066
Victor Stinner331a6a52019-05-27 16:39:22 +02003067 PyStatus status = _PySys_SetPreliminaryStderr(sysdict);
3068 if (_PyStatus_EXCEPTION(status)) {
3069 return status;
Victor Stinnerab672812019-01-23 15:04:40 +01003070 }
3071
Victor Stinner838f2642019-06-13 22:41:23 +02003072 status = _PySys_InitCore(runtime, tstate, sysdict);
Victor Stinner331a6a52019-05-27 16:39:22 +02003073 if (_PyStatus_EXCEPTION(status)) {
3074 return status;
Victor Stinnerab672812019-01-23 15:04:40 +01003075 }
3076
3077 _PyImport_FixupBuiltin(sysmod, "sys", interp->modules);
3078
3079 *sysmod_p = sysmod;
Victor Stinner331a6a52019-05-27 16:39:22 +02003080 return _PyStatus_OK();
Victor Stinnerab672812019-01-23 15:04:40 +01003081}
3082
3083
Guido van Rossum65bf9f21997-04-29 18:33:38 +00003084static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00003085makepathobject(const wchar_t *path, wchar_t delim)
Guido van Rossum5b3138b1990-11-18 17:41:40 +00003086{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003087 int i, n;
3088 const wchar_t *p;
3089 PyObject *v, *w;
Tim Peters216b78b2006-01-06 02:40:53 +00003090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003091 n = 1;
3092 p = path;
3093 while ((p = wcschr(p, delim)) != NULL) {
3094 n++;
3095 p++;
3096 }
3097 v = PyList_New(n);
3098 if (v == NULL)
3099 return NULL;
3100 for (i = 0; ; i++) {
3101 p = wcschr(path, delim);
3102 if (p == NULL)
3103 p = path + wcslen(path); /* End of string */
3104 w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
3105 if (w == NULL) {
3106 Py_DECREF(v);
3107 return NULL;
3108 }
Zackery Spytz99d56b52018-12-08 07:16:55 -07003109 PyList_SET_ITEM(v, i, w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003110 if (*p == '\0')
3111 break;
3112 path = p+1;
3113 }
3114 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003115}
3116
3117void
Martin v. Löwis790465f2008-04-05 20:41:37 +00003118PySys_SetPath(const wchar_t *path)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003119{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003120 PyObject *v;
3121 if ((v = makepathobject(path, DELIM)) == NULL)
3122 Py_FatalError("can't create sys.path");
Victor Stinner838f2642019-06-13 22:41:23 +02003123 PyThreadState *tstate = _PyThreadState_GET();
3124 if (sys_set_object_id(tstate, &PyId_path, v) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003125 Py_FatalError("can't assign sys.path");
Victor Stinner838f2642019-06-13 22:41:23 +02003126 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003127 Py_DECREF(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00003128}
3129
Guido van Rossum65bf9f21997-04-29 18:33:38 +00003130static PyObject *
Victor Stinner74f65682019-03-15 15:08:05 +01003131make_sys_argv(int argc, wchar_t * const * argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00003132{
Victor Stinner74f65682019-03-15 15:08:05 +01003133 PyObject *list = PyList_New(argc);
3134 if (list == NULL) {
3135 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003136 }
Victor Stinner74f65682019-03-15 15:08:05 +01003137
3138 for (Py_ssize_t i = 0; i < argc; i++) {
3139 PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
3140 if (v == NULL) {
3141 Py_DECREF(list);
3142 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003143 }
Victor Stinner74f65682019-03-15 15:08:05 +01003144 PyList_SET_ITEM(list, i, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003145 }
Victor Stinner74f65682019-03-15 15:08:05 +01003146 return list;
Guido van Rossum3f5da241990-12-20 15:06:42 +00003147}
3148
Victor Stinner11a247d2017-12-13 21:05:57 +01003149void
3150PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
Victor Stinnerd5dda982017-12-13 17:31:16 +01003151{
Victor Stinner838f2642019-06-13 22:41:23 +02003152 PyThreadState *tstate = _PyThreadState_GET();
3153
Victor Stinner74f65682019-03-15 15:08:05 +01003154 if (argc < 1 || argv == NULL) {
3155 /* Ensure at least one (empty) argument is seen */
3156 wchar_t* empty_argv[1] = {L""};
3157 argv = empty_argv;
3158 argc = 1;
3159 }
3160
3161 PyObject *av = make_sys_argv(argc, argv);
Victor Stinnerd5dda982017-12-13 17:31:16 +01003162 if (av == NULL) {
Victor Stinner11a247d2017-12-13 21:05:57 +01003163 Py_FatalError("no mem for sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01003164 }
Victor Stinner838f2642019-06-13 22:41:23 +02003165 if (sys_set_object(tstate, "argv", av) != 0) {
Victor Stinnerd5dda982017-12-13 17:31:16 +01003166 Py_DECREF(av);
Victor Stinner11a247d2017-12-13 21:05:57 +01003167 Py_FatalError("can't assign sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01003168 }
3169 Py_DECREF(av);
3170
3171 if (updatepath) {
3172 /* If argv[0] is not '-c' nor '-m', prepend argv[0] to sys.path.
3173 If argv[0] is a symlink, use the real path. */
Victor Stinner331a6a52019-05-27 16:39:22 +02003174 const PyWideStringList argv_list = {.length = argc, .items = argv};
Victor Stinnerdcf61712019-03-19 16:09:27 +01003175 PyObject *path0 = NULL;
3176 if (_PyPathConfig_ComputeSysPath0(&argv_list, &path0)) {
3177 if (path0 == NULL) {
3178 Py_FatalError("can't compute path0 from argv");
Victor Stinner11a247d2017-12-13 21:05:57 +01003179 }
Victor Stinnerdcf61712019-03-19 16:09:27 +01003180
Victor Stinner838f2642019-06-13 22:41:23 +02003181 PyObject *sys_path = sys_get_object_id(tstate, &PyId_path);
Victor Stinnerdcf61712019-03-19 16:09:27 +01003182 if (sys_path != NULL) {
3183 if (PyList_Insert(sys_path, 0, path0) < 0) {
3184 Py_DECREF(path0);
3185 Py_FatalError("can't prepend path0 to sys.path");
3186 }
3187 }
3188 Py_DECREF(path0);
Victor Stinner11a247d2017-12-13 21:05:57 +01003189 }
Victor Stinnerd5dda982017-12-13 17:31:16 +01003190 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003191}
Guido van Rossuma890e681998-05-12 14:59:24 +00003192
Antoine Pitrouf978fac2010-05-21 17:25:34 +00003193void
3194PySys_SetArgv(int argc, wchar_t **argv)
3195{
Christian Heimesad73a9c2013-08-10 16:36:18 +02003196 PySys_SetArgvEx(argc, argv, Py_IsolatedFlag == 0);
Antoine Pitrouf978fac2010-05-21 17:25:34 +00003197}
3198
Victor Stinner14284c22010-04-23 12:02:30 +00003199/* Reimplementation of PyFile_WriteString() no calling indirectly
3200 PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
3201
3202static int
Victor Stinner79766632010-08-16 17:36:42 +00003203sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
Victor Stinner14284c22010-04-23 12:02:30 +00003204{
Victor Stinnerc3ccaae2016-08-20 01:24:22 +02003205 PyObject *writer = NULL, *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003206 int err;
Victor Stinner14284c22010-04-23 12:02:30 +00003207
Victor Stinnerecccc4f2010-06-08 20:46:00 +00003208 if (file == NULL)
3209 return -1;
3210
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003211 writer = _PyObject_GetAttrId(file, &PyId_write);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003212 if (writer == NULL)
3213 goto error;
Victor Stinner14284c22010-04-23 12:02:30 +00003214
Victor Stinner7bfb42d2016-12-05 17:04:32 +01003215 result = PyObject_CallFunctionObjArgs(writer, unicode, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003216 if (result == NULL) {
3217 goto error;
3218 } else {
3219 err = 0;
3220 goto finally;
3221 }
Victor Stinner14284c22010-04-23 12:02:30 +00003222
3223error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003224 err = -1;
Victor Stinner14284c22010-04-23 12:02:30 +00003225finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003226 Py_XDECREF(writer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003227 Py_XDECREF(result);
3228 return err;
Victor Stinner14284c22010-04-23 12:02:30 +00003229}
3230
Victor Stinner79766632010-08-16 17:36:42 +00003231static int
3232sys_pyfile_write(const char *text, PyObject *file)
3233{
3234 PyObject *unicode = NULL;
3235 int err;
3236
3237 if (file == NULL)
3238 return -1;
3239
3240 unicode = PyUnicode_FromString(text);
3241 if (unicode == NULL)
3242 return -1;
3243
3244 err = sys_pyfile_write_unicode(unicode, file);
3245 Py_DECREF(unicode);
3246 return err;
3247}
Guido van Rossuma890e681998-05-12 14:59:24 +00003248
3249/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
3250 Adapted from code submitted by Just van Rossum.
3251
3252 PySys_WriteStdout(format, ...)
3253 PySys_WriteStderr(format, ...)
3254
3255 The first function writes to sys.stdout; the second to sys.stderr. When
3256 there is a problem, they write to the real (C level) stdout or stderr;
Guido van Rossum8442af31998-10-12 18:22:10 +00003257 no exceptions are raised.
Guido van Rossuma890e681998-05-12 14:59:24 +00003258
Victor Stinner14284c22010-04-23 12:02:30 +00003259 PyErr_CheckSignals() is not called to avoid the execution of the Python
Victor Stinner79766632010-08-16 17:36:42 +00003260 signal handlers: they may raise a new exception whereas sys_write()
3261 ignores all exceptions.
Victor Stinner14284c22010-04-23 12:02:30 +00003262
Guido van Rossuma890e681998-05-12 14:59:24 +00003263 Both take a printf-style format string as their first argument followed
3264 by a variable length argument list determined by the format string.
3265
3266 *** WARNING ***
3267
3268 The format should limit the total size of the formatted output string to
3269 1000 bytes. In particular, this means that no unrestricted "%s" formats
3270 should occur; these should be limited using "%.<N>s where <N> is a
3271 decimal number calculated so that <N> plus the maximum size of other
3272 formatted text does not exceed 1000 bytes. Also watch out for "%f",
3273 which can print hundreds of digits for very large numbers.
3274
3275 */
3276
3277static void
Victor Stinner09054372013-11-06 22:41:44 +01003278sys_write(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Guido van Rossuma890e681998-05-12 14:59:24 +00003279{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003280 PyObject *file;
3281 PyObject *error_type, *error_value, *error_traceback;
3282 char buffer[1001];
3283 int written;
Victor Stinner838f2642019-06-13 22:41:23 +02003284 PyThreadState *tstate = _PyThreadState_GET();
Guido van Rossuma890e681998-05-12 14:59:24 +00003285
Victor Stinner838f2642019-06-13 22:41:23 +02003286 _PyErr_Fetch(tstate, &error_type, &error_value, &error_traceback);
3287 file = sys_get_object_id(tstate, key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003288 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
3289 if (sys_pyfile_write(buffer, file) != 0) {
Victor Stinner838f2642019-06-13 22:41:23 +02003290 _PyErr_Clear(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003291 fputs(buffer, fp);
3292 }
3293 if (written < 0 || (size_t)written >= sizeof(buffer)) {
3294 const char *truncated = "... truncated";
Victor Stinner79766632010-08-16 17:36:42 +00003295 if (sys_pyfile_write(truncated, file) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003296 fputs(truncated, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003297 }
Victor Stinner838f2642019-06-13 22:41:23 +02003298 _PyErr_Restore(tstate, error_type, error_value, error_traceback);
Guido van Rossuma890e681998-05-12 14:59:24 +00003299}
3300
3301void
Guido van Rossuma890e681998-05-12 14:59:24 +00003302PySys_WriteStdout(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00003303{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003304 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00003305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003306 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003307 sys_write(&PyId_stdout, stdout, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003308 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00003309}
3310
3311void
Guido van Rossuma890e681998-05-12 14:59:24 +00003312PySys_WriteStderr(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00003313{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003314 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00003315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003316 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003317 sys_write(&PyId_stderr, stderr, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00003318 va_end(va);
3319}
3320
3321static void
Victor Stinner09054372013-11-06 22:41:44 +01003322sys_format(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Victor Stinner79766632010-08-16 17:36:42 +00003323{
3324 PyObject *file, *message;
3325 PyObject *error_type, *error_value, *error_traceback;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02003326 const char *utf8;
Victor Stinner838f2642019-06-13 22:41:23 +02003327 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner79766632010-08-16 17:36:42 +00003328
Victor Stinner838f2642019-06-13 22:41:23 +02003329 _PyErr_Fetch(tstate, &error_type, &error_value, &error_traceback);
3330 file = sys_get_object_id(tstate, key);
Victor Stinner79766632010-08-16 17:36:42 +00003331 message = PyUnicode_FromFormatV(format, va);
3332 if (message != NULL) {
3333 if (sys_pyfile_write_unicode(message, file) != 0) {
Victor Stinner838f2642019-06-13 22:41:23 +02003334 _PyErr_Clear(tstate);
Serhiy Storchaka06515832016-11-20 09:13:07 +02003335 utf8 = PyUnicode_AsUTF8(message);
Victor Stinner79766632010-08-16 17:36:42 +00003336 if (utf8 != NULL)
3337 fputs(utf8, fp);
3338 }
3339 Py_DECREF(message);
3340 }
Victor Stinner838f2642019-06-13 22:41:23 +02003341 _PyErr_Restore(tstate, error_type, error_value, error_traceback);
Victor Stinner79766632010-08-16 17:36:42 +00003342}
3343
3344void
3345PySys_FormatStdout(const char *format, ...)
3346{
3347 va_list va;
3348
3349 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003350 sys_format(&PyId_stdout, stdout, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00003351 va_end(va);
3352}
3353
3354void
3355PySys_FormatStderr(const char *format, ...)
3356{
3357 va_list va;
3358
3359 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003360 sys_format(&PyId_stderr, stderr, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003361 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00003362}