blob: 97ce0594b55e0e8abc4ba80949ad6a3a0366af12 [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 Stinnerd5c355c2011-04-30 14:53:09 +020020#include "pythread.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000021
Guido van Rossume2437a11992-03-23 18:20:18 +000022#include "osdefs.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +000023
Mark Hammond8696ebc2002-10-08 02:44:31 +000024#ifdef MS_WINDOWS
25#define WIN32_LEAN_AND_MEAN
Amaury Forgeot d'Arc06cfe952007-11-10 13:55:44 +000026#include <windows.h>
Mark Hammond8696ebc2002-10-08 02:44:31 +000027#endif /* MS_WINDOWS */
28
Guido van Rossum9b38a141996-09-11 23:12:24 +000029#ifdef MS_COREDLL
Guido van Rossumc606fe11996-04-09 02:37:57 +000030extern void *PyWin_DLLhModule;
Guido van Rossum6c1e5f21997-09-29 23:34:23 +000031/* A string loaded from the DLL at startup: */
32extern const char *PyWin_DLLVersionString;
Guido van Rossumc606fe11996-04-09 02:37:57 +000033#endif
34
Martin v. Löwisc16f3bd2003-05-03 09:14:54 +000035#ifdef __VMS
36#include <unixlib.h>
37#endif
38
Martin v. Löwis5467d4c2003-05-10 07:10:12 +000039#ifdef HAVE_LANGINFO_H
40#include <locale.h>
41#include <langinfo.h>
42#endif
43
Guido van Rossum65bf9f21997-04-29 18:33:38 +000044PyObject *
Neal Norwitzf3081322007-08-25 00:32:45 +000045PySys_GetObject(const char *name)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000046{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000047 PyThreadState *tstate = PyThreadState_GET();
48 PyObject *sd = tstate->interp->sysdict;
49 if (sd == NULL)
50 return NULL;
51 return PyDict_GetItemString(sd, name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000052}
53
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000054int
Neal Norwitzf3081322007-08-25 00:32:45 +000055PySys_SetObject(const char *name, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000056{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000057 PyThreadState *tstate = PyThreadState_GET();
58 PyObject *sd = tstate->interp->sysdict;
59 if (v == NULL) {
60 if (PyDict_GetItemString(sd, name) == NULL)
61 return 0;
62 else
63 return PyDict_DelItemString(sd, name);
64 }
65 else
66 return PyDict_SetItemString(sd, name, v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000067}
68
Victor Stinner13d49ee2010-12-04 17:24:33 +000069/* Write repr(o) to sys.stdout using sys.stdout.encoding and 'backslashreplace'
70 error handler. If sys.stdout has a buffer attribute, use
71 sys.stdout.buffer.write(encoded), otherwise redecode the string and use
72 sys.stdout.write(redecoded).
73
74 Helper function for sys_displayhook(). */
75static int
76sys_displayhook_unencodable(PyObject *outf, PyObject *o)
77{
78 PyObject *stdout_encoding = NULL;
79 PyObject *encoded, *escaped_str, *repr_str, *buffer, *result;
80 char *stdout_encoding_str;
81 int ret;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020082 _Py_IDENTIFIER(encoding);
83 _Py_IDENTIFIER(buffer);
Victor Stinner13d49ee2010-12-04 17:24:33 +000084
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +020085 stdout_encoding = _PyObject_GetAttrId(outf, &PyId_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +000086 if (stdout_encoding == NULL)
87 goto error;
88 stdout_encoding_str = _PyUnicode_AsString(stdout_encoding);
89 if (stdout_encoding_str == NULL)
90 goto error;
91
92 repr_str = PyObject_Repr(o);
93 if (repr_str == NULL)
94 goto error;
95 encoded = PyUnicode_AsEncodedString(repr_str,
96 stdout_encoding_str,
97 "backslashreplace");
98 Py_DECREF(repr_str);
99 if (encoded == NULL)
100 goto error;
101
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200102 buffer = _PyObject_GetAttrId(outf, &PyId_buffer);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000103 if (buffer) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200104 _Py_IDENTIFIER(write);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200105 result = _PyObject_CallMethodId(buffer, &PyId_write, "(O)", encoded);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000106 Py_DECREF(buffer);
107 Py_DECREF(encoded);
108 if (result == NULL)
109 goto error;
110 Py_DECREF(result);
111 }
112 else {
113 PyErr_Clear();
114 escaped_str = PyUnicode_FromEncodedObject(encoded,
115 stdout_encoding_str,
116 "strict");
117 Py_DECREF(encoded);
118 if (PyFile_WriteObject(escaped_str, outf, Py_PRINT_RAW) != 0) {
119 Py_DECREF(escaped_str);
120 goto error;
121 }
122 Py_DECREF(escaped_str);
123 }
124 ret = 0;
125 goto finally;
126
127error:
128 ret = -1;
129finally:
130 Py_XDECREF(stdout_encoding);
131 return ret;
132}
133
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000134static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000135sys_displayhook(PyObject *self, PyObject *o)
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000136{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000137 PyObject *outf;
138 PyInterpreterState *interp = PyThreadState_GET()->interp;
139 PyObject *modules = interp->modules;
140 PyObject *builtins = PyDict_GetItemString(modules, "builtins");
Victor Stinner13d49ee2010-12-04 17:24:33 +0000141 int err;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200142 _Py_IDENTIFIER(_);
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000144 if (builtins == NULL) {
145 PyErr_SetString(PyExc_RuntimeError, "lost builtins module");
146 return NULL;
147 }
Moshe Zadka03897ea2001-07-23 13:32:43 +0000148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149 /* Print value except if None */
150 /* After printing, also assign to '_' */
151 /* Before, set '_' to None to avoid recursion */
152 if (o == Py_None) {
153 Py_INCREF(Py_None);
154 return Py_None;
155 }
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200156 if (_PyObject_SetAttrId(builtins, &PyId__, Py_None) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000157 return NULL;
158 outf = PySys_GetObject("stdout");
159 if (outf == NULL || outf == Py_None) {
160 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
161 return NULL;
162 }
Victor Stinner13d49ee2010-12-04 17:24:33 +0000163 if (PyFile_WriteObject(o, outf, 0) != 0) {
164 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
165 /* repr(o) is not encodable to sys.stdout.encoding with
166 * sys.stdout.errors error handler (which is probably 'strict') */
167 PyErr_Clear();
168 err = sys_displayhook_unencodable(outf, o);
169 if (err)
170 return NULL;
171 }
172 else {
173 return NULL;
174 }
175 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 if (PyFile_WriteString("\n", outf) != 0)
177 return NULL;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200178 if (_PyObject_SetAttrId(builtins, &PyId__, o) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000179 return NULL;
180 Py_INCREF(Py_None);
181 return Py_None;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000182}
183
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000184PyDoc_STRVAR(displayhook_doc,
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000185"displayhook(object) -> None\n"
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000186"\n"
Florent Xicluna5749e852010-03-03 11:54:54 +0000187"Print an object to sys.stdout and also save it in builtins._\n"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000188);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000189
190static PyObject *
191sys_excepthook(PyObject* self, PyObject* args)
192{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000193 PyObject *exc, *value, *tb;
194 if (!PyArg_UnpackTuple(args, "excepthook", 3, 3, &exc, &value, &tb))
195 return NULL;
196 PyErr_Display(exc, value, tb);
197 Py_INCREF(Py_None);
198 return Py_None;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000199}
200
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000201PyDoc_STRVAR(excepthook_doc,
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000202"excepthook(exctype, value, traceback) -> None\n"
203"\n"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000204"Handle an exception by displaying it with a traceback on sys.stderr.\n"
205);
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000206
207static PyObject *
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000208sys_exc_info(PyObject *self, PyObject *noargs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000209{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000210 PyThreadState *tstate;
211 tstate = PyThreadState_GET();
212 return Py_BuildValue(
213 "(OOO)",
214 tstate->exc_type != NULL ? tstate->exc_type : Py_None,
215 tstate->exc_value != NULL ? tstate->exc_value : Py_None,
216 tstate->exc_traceback != NULL ?
217 tstate->exc_traceback : Py_None);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000218}
219
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000220PyDoc_STRVAR(exc_info_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000221"exc_info() -> (type, value, traceback)\n\
222\n\
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000223Return information about the most recent exception caught by an except\n\
224clause in the current stack frame or in an older stack frame."
225);
226
227static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000228sys_exit(PyObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000229{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000230 PyObject *exit_code = 0;
231 if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code))
232 return NULL;
233 /* Raise SystemExit so callers may catch it or clean up. */
234 PyErr_SetObject(PyExc_SystemExit, exit_code);
235 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000236}
237
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000238PyDoc_STRVAR(exit_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000239"exit([status])\n\
240\n\
241Exit the interpreter by raising SystemExit(status).\n\
242If the status is omitted or None, it defaults to zero (i.e., success).\n\
Ezio Melotti4af4d272013-08-26 14:00:39 +0300243If the status is an integer, it will be used as the system exit status.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000244If it is another kind of object, it will be printed and the system\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000245exit status will be one (i.e., failure)."
246);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000247
Martin v. Löwis107b7da2001-11-09 20:59:39 +0000248
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000249static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000250sys_getdefaultencoding(PyObject *self)
Fred Drake8b4d01d2000-05-09 19:57:01 +0000251{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 return PyUnicode_FromString(PyUnicode_GetDefaultEncoding());
Fred Drake8b4d01d2000-05-09 19:57:01 +0000253}
254
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000255PyDoc_STRVAR(getdefaultencoding_doc,
Marc-André Lemburg99964b82000-06-07 09:13:41 +0000256"getdefaultencoding() -> string\n\
Fred Drake8b4d01d2000-05-09 19:57:01 +0000257\n\
258Return the current default string encoding used by the Unicode \n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000259implementation."
260);
Fred Drake8b4d01d2000-05-09 19:57:01 +0000261
262static PyObject *
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000263sys_getfilesystemencoding(PyObject *self)
264{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000265 if (Py_FileSystemDefaultEncoding)
266 return PyUnicode_FromString(Py_FileSystemDefaultEncoding);
Victor Stinner27181ac2011-03-31 13:39:03 +0200267 PyErr_SetString(PyExc_RuntimeError,
268 "filesystem encoding is not initialized");
269 return NULL;
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000270}
271
272PyDoc_STRVAR(getfilesystemencoding_doc,
273"getfilesystemencoding() -> string\n\
274\n\
275Return the encoding used to convert Unicode filenames in\n\
276operating system filenames."
277);
278
Martin v. Löwis04dc25c2008-10-03 16:09:28 +0000279static PyObject *
Georg Brandl66a796e2006-12-19 20:50:34 +0000280sys_intern(PyObject *self, PyObject *args)
281{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 PyObject *s;
283 if (!PyArg_ParseTuple(args, "U:intern", &s))
284 return NULL;
285 if (PyUnicode_CheckExact(s)) {
286 Py_INCREF(s);
287 PyUnicode_InternInPlace(&s);
288 return s;
289 }
290 else {
291 PyErr_Format(PyExc_TypeError,
292 "can't intern %.400s", s->ob_type->tp_name);
293 return NULL;
294 }
Georg Brandl66a796e2006-12-19 20:50:34 +0000295}
296
297PyDoc_STRVAR(intern_doc,
298"intern(string) -> string\n\
299\n\
300``Intern'' the given string. This enters the string in the (global)\n\
301table of interned strings whose purpose is to speed up dictionary lookups.\n\
302Return the string itself or the previously interned string object with the\n\
303same value.");
304
305
Fred Drake5755ce62001-06-27 19:19:46 +0000306/*
307 * Cached interned string objects used for calling the profile and
308 * trace functions. Initialized by trace_init().
309 */
Nicholas Bastinc69ebe82004-03-24 21:57:10 +0000310static PyObject *whatstrings[7] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL};
Fred Drake5755ce62001-06-27 19:19:46 +0000311
312static int
313trace_init(void)
314{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000315 static char *whatnames[7] = {"call", "exception", "line", "return",
316 "c_call", "c_exception", "c_return"};
317 PyObject *name;
318 int i;
319 for (i = 0; i < 7; ++i) {
320 if (whatstrings[i] == NULL) {
321 name = PyUnicode_InternFromString(whatnames[i]);
322 if (name == NULL)
323 return -1;
324 whatstrings[i] = name;
325 }
326 }
327 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000328}
329
330
331static PyObject *
332call_trampoline(PyThreadState *tstate, PyObject* callback,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 PyFrameObject *frame, int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000334{
Victor Stinner41bb43a2013-10-29 01:19:37 +0100335 PyObject *args;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336 PyObject *whatstr;
337 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000338
Victor Stinner41bb43a2013-10-29 01:19:37 +0100339 args = PyTuple_New(3);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000340 if (args == NULL)
341 return NULL;
Victor Stinner41bb43a2013-10-29 01:19:37 +0100342 if (PyFrame_FastToLocalsWithError(frame) < 0)
343 return NULL;
344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000345 Py_INCREF(frame);
346 whatstr = whatstrings[what];
347 Py_INCREF(whatstr);
348 if (arg == NULL)
349 arg = Py_None;
350 Py_INCREF(arg);
351 PyTuple_SET_ITEM(args, 0, (PyObject *)frame);
352 PyTuple_SET_ITEM(args, 1, whatstr);
353 PyTuple_SET_ITEM(args, 2, arg);
Fred Drake5755ce62001-06-27 19:19:46 +0000354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000355 /* call the Python-level function */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000356 result = PyEval_CallObject(callback, args);
357 PyFrame_LocalsToFast(frame, 1);
358 if (result == NULL)
359 PyTraceBack_Here(frame);
Fred Drake5755ce62001-06-27 19:19:46 +0000360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000361 /* cleanup */
362 Py_DECREF(args);
363 return result;
Fred Drake5755ce62001-06-27 19:19:46 +0000364}
365
366static int
367profile_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000369{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 PyThreadState *tstate = frame->f_tstate;
371 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000373 if (arg == NULL)
374 arg = Py_None;
375 result = call_trampoline(tstate, self, frame, what, arg);
376 if (result == NULL) {
377 PyEval_SetProfile(NULL, NULL);
378 return -1;
379 }
380 Py_DECREF(result);
381 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000382}
383
384static int
385trace_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000386 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000387{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000388 PyThreadState *tstate = frame->f_tstate;
389 PyObject *callback;
390 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 if (what == PyTrace_CALL)
393 callback = self;
394 else
395 callback = frame->f_trace;
396 if (callback == NULL)
397 return 0;
398 result = call_trampoline(tstate, callback, frame, what, arg);
399 if (result == NULL) {
400 PyEval_SetTrace(NULL, NULL);
401 Py_XDECREF(frame->f_trace);
402 frame->f_trace = NULL;
403 return -1;
404 }
405 if (result != Py_None) {
406 PyObject *temp = frame->f_trace;
407 frame->f_trace = NULL;
408 Py_XDECREF(temp);
409 frame->f_trace = result;
410 }
411 else {
412 Py_DECREF(result);
413 }
414 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000415}
Fred Draked0838392001-06-16 21:02:31 +0000416
Fred Drake8b4d01d2000-05-09 19:57:01 +0000417static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000418sys_settrace(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000419{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 if (trace_init() == -1)
421 return NULL;
422 if (args == Py_None)
423 PyEval_SetTrace(NULL, NULL);
424 else
425 PyEval_SetTrace(trace_trampoline, args);
426 Py_INCREF(Py_None);
427 return Py_None;
Guido van Rossume2437a11992-03-23 18:20:18 +0000428}
429
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000430PyDoc_STRVAR(settrace_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000431"settrace(function)\n\
432\n\
433Set the global debug tracing function. It will be called on each\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000434function call. See the debugger chapter in the library manual."
435);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000436
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000437static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000438sys_gettrace(PyObject *self, PyObject *args)
439{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000440 PyThreadState *tstate = PyThreadState_GET();
441 PyObject *temp = tstate->c_traceobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 if (temp == NULL)
444 temp = Py_None;
445 Py_INCREF(temp);
446 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000447}
448
449PyDoc_STRVAR(gettrace_doc,
450"gettrace()\n\
451\n\
452Return the global debug tracing function set with sys.settrace.\n\
453See the debugger chapter in the library manual."
454);
455
456static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000457sys_setprofile(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000458{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 if (trace_init() == -1)
460 return NULL;
461 if (args == Py_None)
462 PyEval_SetProfile(NULL, NULL);
463 else
464 PyEval_SetProfile(profile_trampoline, args);
465 Py_INCREF(Py_None);
466 return Py_None;
Guido van Rossume2437a11992-03-23 18:20:18 +0000467}
468
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000469PyDoc_STRVAR(setprofile_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000470"setprofile(function)\n\
471\n\
472Set the profiling function. It will be called on each function call\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000473and return. See the profiler chapter in the library manual."
474);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000475
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000476static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000477sys_getprofile(PyObject *self, PyObject *args)
478{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 PyThreadState *tstate = PyThreadState_GET();
480 PyObject *temp = tstate->c_profileobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 if (temp == NULL)
483 temp = Py_None;
484 Py_INCREF(temp);
485 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000486}
487
488PyDoc_STRVAR(getprofile_doc,
489"getprofile()\n\
490\n\
491Return the profiling function set with sys.setprofile.\n\
492See the profiler chapter in the library manual."
493);
494
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000495static int _check_interval = 100;
496
Christian Heimes9bd667a2008-01-20 15:14:11 +0000497static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000498sys_setcheckinterval(PyObject *self, PyObject *args)
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000499{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 if (PyErr_WarnEx(PyExc_DeprecationWarning,
501 "sys.getcheckinterval() and sys.setcheckinterval() "
502 "are deprecated. Use sys.setswitchinterval() "
503 "instead.", 1) < 0)
504 return NULL;
505 if (!PyArg_ParseTuple(args, "i:setcheckinterval", &_check_interval))
506 return NULL;
507 Py_INCREF(Py_None);
508 return Py_None;
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000509}
510
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000511PyDoc_STRVAR(setcheckinterval_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000512"setcheckinterval(n)\n\
513\n\
514Tell the Python interpreter to check for asynchronous events every\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000515n instructions. This also affects how often thread switches occur."
516);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000517
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000518static PyObject *
Tim Peterse5e065b2003-07-06 18:36:54 +0000519sys_getcheckinterval(PyObject *self, PyObject *args)
520{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 if (PyErr_WarnEx(PyExc_DeprecationWarning,
522 "sys.getcheckinterval() and sys.setcheckinterval() "
523 "are deprecated. Use sys.getswitchinterval() "
524 "instead.", 1) < 0)
525 return NULL;
526 return PyLong_FromLong(_check_interval);
Tim Peterse5e065b2003-07-06 18:36:54 +0000527}
528
529PyDoc_STRVAR(getcheckinterval_doc,
530"getcheckinterval() -> current check interval; see setcheckinterval()."
531);
532
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000533#ifdef WITH_THREAD
534static PyObject *
535sys_setswitchinterval(PyObject *self, PyObject *args)
536{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 double d;
538 if (!PyArg_ParseTuple(args, "d:setswitchinterval", &d))
539 return NULL;
540 if (d <= 0.0) {
541 PyErr_SetString(PyExc_ValueError,
542 "switch interval must be strictly positive");
543 return NULL;
544 }
545 _PyEval_SetSwitchInterval((unsigned long) (1e6 * d));
546 Py_INCREF(Py_None);
547 return Py_None;
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000548}
549
550PyDoc_STRVAR(setswitchinterval_doc,
551"setswitchinterval(n)\n\
552\n\
553Set the ideal thread switching delay inside the Python interpreter\n\
554The actual frequency of switching threads can be lower if the\n\
555interpreter executes long sequences of uninterruptible code\n\
556(this is implementation-specific and workload-dependent).\n\
557\n\
558The parameter must represent the desired switching delay in seconds\n\
559A typical value is 0.005 (5 milliseconds)."
560);
561
562static PyObject *
563sys_getswitchinterval(PyObject *self, PyObject *args)
564{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 return PyFloat_FromDouble(1e-6 * _PyEval_GetSwitchInterval());
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000566}
567
568PyDoc_STRVAR(getswitchinterval_doc,
569"getswitchinterval() -> current thread switch interval; see setswitchinterval()."
570);
571
572#endif /* WITH_THREAD */
573
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000574#ifdef WITH_TSC
575static PyObject *
576sys_settscdump(PyObject *self, PyObject *args)
577{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 int bool;
579 PyThreadState *tstate = PyThreadState_Get();
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 if (!PyArg_ParseTuple(args, "i:settscdump", &bool))
582 return NULL;
583 if (bool)
584 tstate->interp->tscdump = 1;
585 else
586 tstate->interp->tscdump = 0;
587 Py_INCREF(Py_None);
588 return Py_None;
Tim Peters216b78b2006-01-06 02:40:53 +0000589
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000590}
591
Tim Peters216b78b2006-01-06 02:40:53 +0000592PyDoc_STRVAR(settscdump_doc,
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000593"settscdump(bool)\n\
594\n\
595If true, tell the Python interpreter to dump VM measurements to\n\
596stderr. If false, turn off dump. The measurements are based on the\n\
Michael W. Hudson800ba232004-08-12 18:19:17 +0000597processor's time-stamp counter."
Tim Peters216b78b2006-01-06 02:40:53 +0000598);
Neal Norwitz0f5aed42004-06-13 20:32:17 +0000599#endif /* TSC */
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000600
Tim Peterse5e065b2003-07-06 18:36:54 +0000601static PyObject *
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000602sys_setrecursionlimit(PyObject *self, PyObject *args)
603{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000604 int new_limit;
605 if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit))
606 return NULL;
607 if (new_limit <= 0) {
608 PyErr_SetString(PyExc_ValueError,
609 "recursion limit must be positive");
610 return NULL;
611 }
612 Py_SetRecursionLimit(new_limit);
613 Py_INCREF(Py_None);
614 return Py_None;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000615}
616
Mark Dickinsondc787d22010-05-23 13:33:13 +0000617static PyTypeObject Hash_InfoType;
618
619PyDoc_STRVAR(hash_info_doc,
620"hash_info\n\
621\n\
622A struct sequence providing parameters used for computing\n\
623numeric hashes. The attributes are read only.");
624
625static PyStructSequence_Field hash_info_fields[] = {
626 {"width", "width of the type used for hashing, in bits"},
627 {"modulus", "prime number giving the modulus on which the hash "
628 "function is based"},
629 {"inf", "value to be used for hash of a positive infinity"},
630 {"nan", "value to be used for hash of a nan"},
631 {"imag", "multiplier used for the imaginary part of a complex number"},
632 {NULL, NULL}
633};
634
635static PyStructSequence_Desc hash_info_desc = {
636 "sys.hash_info",
637 hash_info_doc,
638 hash_info_fields,
639 5,
640};
641
Matthias Klosed885e952010-07-06 10:53:30 +0000642static PyObject *
Mark Dickinsondc787d22010-05-23 13:33:13 +0000643get_hash_info(void)
644{
645 PyObject *hash_info;
646 int field = 0;
647 hash_info = PyStructSequence_New(&Hash_InfoType);
648 if (hash_info == NULL)
649 return NULL;
650 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000651 PyLong_FromLong(8*sizeof(Py_hash_t)));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000652 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000653 PyLong_FromSsize_t(_PyHASH_MODULUS));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000654 PyStructSequence_SET_ITEM(hash_info, field++,
655 PyLong_FromLong(_PyHASH_INF));
656 PyStructSequence_SET_ITEM(hash_info, field++,
657 PyLong_FromLong(_PyHASH_NAN));
658 PyStructSequence_SET_ITEM(hash_info, field++,
659 PyLong_FromLong(_PyHASH_IMAG));
660 if (PyErr_Occurred()) {
661 Py_CLEAR(hash_info);
662 return NULL;
663 }
664 return hash_info;
665}
666
667
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000668PyDoc_STRVAR(setrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000669"setrecursionlimit(n)\n\
670\n\
671Set the maximum depth of the Python interpreter stack to n. This\n\
672limit prevents infinite recursion from causing an overflow of the C\n\
673stack and crashing Python. The highest possible limit is platform-\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000674dependent."
675);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000676
677static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000678sys_getrecursionlimit(PyObject *self)
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000679{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000680 return PyLong_FromLong(Py_GetRecursionLimit());
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000681}
682
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000683PyDoc_STRVAR(getrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000684"getrecursionlimit()\n\
685\n\
686Return the current value of the recursion limit, the maximum depth\n\
687of the Python interpreter stack. This limit prevents infinite\n\
Jack Jansene739a0d2002-06-26 20:39:20 +0000688recursion from causing an overflow of the C stack and crashing Python."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000689);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000690
Mark Hammond8696ebc2002-10-08 02:44:31 +0000691#ifdef MS_WINDOWS
692PyDoc_STRVAR(getwindowsversion_doc,
693"getwindowsversion()\n\
694\n\
Eric Smithf7bb5782010-01-27 00:44:57 +0000695Return information about the running version of Windows as a named tuple.\n\
696The members are named: major, minor, build, platform, service_pack,\n\
697service_pack_major, service_pack_minor, suite_mask, and product_type. For\n\
Ezio Melotti4969f702011-03-15 05:59:46 +0200698backward compatibility, only the first 5 items are available by indexing.\n\
Eric Smithf7bb5782010-01-27 00:44:57 +0000699All elements are numbers, except service_pack which is a string. Platform\n\
700may be 0 for win32s, 1 for Windows 9x/ME, 2 for Windows NT/2000/XP/Vista/7,\n\
7013 for Windows CE. Product_type may be 1 for a workstation, 2 for a domain\n\
702controller, 3 for a server."
Mark Hammond8696ebc2002-10-08 02:44:31 +0000703);
704
Eric Smithf7bb5782010-01-27 00:44:57 +0000705static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};
706
707static PyStructSequence_Field windows_version_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 {"major", "Major version number"},
709 {"minor", "Minor version number"},
710 {"build", "Build number"},
711 {"platform", "Operating system platform"},
712 {"service_pack", "Latest Service Pack installed on the system"},
713 {"service_pack_major", "Service Pack major version number"},
714 {"service_pack_minor", "Service Pack minor version number"},
715 {"suite_mask", "Bit mask identifying available product suites"},
716 {"product_type", "System product type"},
717 {0}
Eric Smithf7bb5782010-01-27 00:44:57 +0000718};
719
720static PyStructSequence_Desc windows_version_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000721 "sys.getwindowsversion", /* name */
722 getwindowsversion_doc, /* doc */
723 windows_version_fields, /* fields */
724 5 /* For backward compatibility,
725 only the first 5 items are accessible
726 via indexing, the rest are name only */
Eric Smithf7bb5782010-01-27 00:44:57 +0000727};
728
Mark Hammond8696ebc2002-10-08 02:44:31 +0000729static PyObject *
730sys_getwindowsversion(PyObject *self)
731{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 PyObject *version;
733 int pos = 0;
734 OSVERSIONINFOEX ver;
735 ver.dwOSVersionInfoSize = sizeof(ver);
736 if (!GetVersionEx((OSVERSIONINFO*) &ver))
737 return PyErr_SetFromWindowsErr(0);
Eric Smithf7bb5782010-01-27 00:44:57 +0000738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 version = PyStructSequence_New(&WindowsVersionType);
740 if (version == NULL)
741 return NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +0000742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion));
744 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion));
745 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber));
746 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId));
747 PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromString(ver.szCSDVersion));
748 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor));
749 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor));
750 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask));
751 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType));
Eric Smithf7bb5782010-01-27 00:44:57 +0000752
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000753 return version;
Mark Hammond8696ebc2002-10-08 02:44:31 +0000754}
755
756#endif /* MS_WINDOWS */
757
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000758#ifdef HAVE_DLOPEN
759static PyObject *
760sys_setdlopenflags(PyObject *self, PyObject *args)
761{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 int new_val;
763 PyThreadState *tstate = PyThreadState_GET();
764 if (!PyArg_ParseTuple(args, "i:setdlopenflags", &new_val))
765 return NULL;
766 if (!tstate)
767 return NULL;
768 tstate->interp->dlopenflags = new_val;
769 Py_INCREF(Py_None);
770 return Py_None;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000771}
772
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000773PyDoc_STRVAR(setdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000774"setdlopenflags(n) -> None\n\
775\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000776Set the flags used by the interpreter for dlopen calls, such as when the\n\
777interpreter loads extension modules. Among other things, this will enable\n\
778a lazy resolving of symbols when importing a module, if called as\n\
779sys.setdlopenflags(0). To share symbols across extension modules, call as\n\
Andrew Kuchlingc61b9132013-06-21 10:58:41 -0400780sys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag modules\n\
Victor Stinnerf4afa432011-10-31 11:48:09 +0100781can be found in the os module (RTLD_xxx constants, e.g. os.RTLD_LAZY).");
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000782
783static PyObject *
784sys_getdlopenflags(PyObject *self, PyObject *args)
785{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 PyThreadState *tstate = PyThreadState_GET();
787 if (!tstate)
788 return NULL;
789 return PyLong_FromLong(tstate->interp->dlopenflags);
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000790}
791
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000792PyDoc_STRVAR(getdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000793"getdlopenflags() -> int\n\
794\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000795Return the current value of the flags that are used for dlopen calls.\n\
Andrew Kuchlingc61b9132013-06-21 10:58:41 -0400796The flag constants are defined in the os module.");
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798#endif /* HAVE_DLOPEN */
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000799
Guido van Rossum14b4adb1992-09-03 20:25:30 +0000800#ifdef USE_MALLOPT
801/* Link with -lmalloc (or -lmpc) on an SGI */
802#include <malloc.h>
803
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000804static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000805sys_mdebug(PyObject *self, PyObject *args)
Guido van Rossum14b4adb1992-09-03 20:25:30 +0000806{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 int flag;
808 if (!PyArg_ParseTuple(args, "i:mdebug", &flag))
809 return NULL;
810 mallopt(M_DEBUG, flag);
811 Py_INCREF(Py_None);
812 return Py_None;
Guido van Rossum14b4adb1992-09-03 20:25:30 +0000813}
814#endif /* USE_MALLOPT */
815
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000816static PyObject *
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000817sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000818{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 PyObject *res = NULL;
Benjamin Petersonce798522012-01-22 11:24:29 -0500820 static PyObject *gc_head_size = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 static char *kwlist[] = {"object", "default", 0};
822 PyObject *o, *dflt = NULL;
823 PyObject *method;
Benjamin Petersonce798522012-01-22 11:24:29 -0500824 _Py_IDENTIFIER(__sizeof__);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
827 kwlist, &o, &dflt))
828 return NULL;
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 /* Initialize static variable for GC head size */
831 if (gc_head_size == NULL) {
832 gc_head_size = PyLong_FromSsize_t(sizeof(PyGC_Head));
833 if (gc_head_size == NULL)
834 return NULL;
835 }
Benjamin Petersona5758c02009-05-09 18:15:04 +0000836
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837 /* Make sure the type is initialized. float gets initialized late */
838 if (PyType_Ready(Py_TYPE(o)) < 0)
839 return NULL;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000840
Benjamin Petersonce798522012-01-22 11:24:29 -0500841 method = _PyObject_LookupSpecial(o, &PyId___sizeof__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000842 if (method == NULL) {
843 if (!PyErr_Occurred())
844 PyErr_Format(PyExc_TypeError,
845 "Type %.100s doesn't define __sizeof__",
846 Py_TYPE(o)->tp_name);
847 }
848 else {
849 res = PyObject_CallFunctionObjArgs(method, NULL);
850 Py_DECREF(method);
851 }
852
853 /* Has a default value been given */
854 if ((res == NULL) && (dflt != NULL) &&
855 PyErr_ExceptionMatches(PyExc_TypeError))
856 {
857 PyErr_Clear();
858 Py_INCREF(dflt);
859 return dflt;
860 }
861 else if (res == NULL)
862 return res;
863
864 /* add gc_head size */
865 if (PyObject_IS_GC(o)) {
866 PyObject *tmp = res;
867 res = PyNumber_Add(tmp, gc_head_size);
868 Py_DECREF(tmp);
869 }
870 return res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000871}
872
873PyDoc_STRVAR(getsizeof_doc,
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000874"getsizeof(object, default) -> int\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000875\n\
876Return the size of object in bytes.");
877
878static PyObject *
Fred Drakea7688822001-10-24 20:47:48 +0000879sys_getrefcount(PyObject *self, PyObject *arg)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000880{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 return PyLong_FromSsize_t(arg->ob_refcnt);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000882}
883
Tim Peters4be93d02002-07-07 19:59:50 +0000884#ifdef Py_REF_DEBUG
Mark Hammond440d8982000-06-20 08:12:48 +0000885static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000886sys_gettotalrefcount(PyObject *self)
Mark Hammond440d8982000-06-20 08:12:48 +0000887{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 return PyLong_FromSsize_t(_Py_GetRefTotal());
Mark Hammond440d8982000-06-20 08:12:48 +0000889}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000890#endif /* Py_REF_DEBUG */
Mark Hammond440d8982000-06-20 08:12:48 +0000891
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000892PyDoc_STRVAR(getrefcount_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000893"getrefcount(object) -> integer\n\
894\n\
Fred Drakeba3ff1b2002-06-20 21:36:19 +0000895Return the reference count of object. The count returned is generally\n\
896one higher than you might expect, because it includes the (temporary)\n\
897reference as an argument to getrefcount()."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000898);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000899
Antoine Pitrouf9d0b122012-12-09 14:28:26 +0100900static PyObject *
901sys_getallocatedblocks(PyObject *self)
902{
903 return PyLong_FromSsize_t(_Py_GetAllocatedBlocks());
904}
905
906PyDoc_STRVAR(getallocatedblocks_doc,
907"getallocatedblocks() -> integer\n\
908\n\
909Return the number of memory blocks currently allocated, regardless of their\n\
910size."
911);
912
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000913#ifdef COUNT_ALLOCS
914static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000915sys_getcounts(PyObject *self)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000916{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 extern PyObject *get_counts(void);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 return get_counts();
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000920}
921#endif
922
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000923PyDoc_STRVAR(getframe_doc,
Barry Warsawb6a54d22000-12-06 21:47:46 +0000924"_getframe([depth]) -> frameobject\n\
925\n\
926Return a frame object from the call stack. If optional integer depth is\n\
927given, return the frame object that many calls below the top of the stack.\n\
928If that is deeper than the call stack, ValueError is raised. The default\n\
929for depth is zero, returning the frame at the top of the call stack.\n\
930\n\
931This function should be used for internal and specialized\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000932purposes only."
933);
Barry Warsawb6a54d22000-12-06 21:47:46 +0000934
935static PyObject *
936sys_getframe(PyObject *self, PyObject *args)
937{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 PyFrameObject *f = PyThreadState_GET()->frame;
939 int depth = -1;
Barry Warsawb6a54d22000-12-06 21:47:46 +0000940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 if (!PyArg_ParseTuple(args, "|i:_getframe", &depth))
942 return NULL;
Barry Warsawb6a54d22000-12-06 21:47:46 +0000943
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 while (depth > 0 && f != NULL) {
945 f = f->f_back;
946 --depth;
947 }
948 if (f == NULL) {
949 PyErr_SetString(PyExc_ValueError,
950 "call stack is not deep enough");
951 return NULL;
952 }
953 Py_INCREF(f);
954 return (PyObject*)f;
Barry Warsawb6a54d22000-12-06 21:47:46 +0000955}
956
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000957PyDoc_STRVAR(current_frames_doc,
958"_current_frames() -> dictionary\n\
959\n\
960Return a dictionary mapping each current thread T's thread id to T's\n\
961current stack frame.\n\
962\n\
963This function should be used for specialized purposes only."
964);
965
966static PyObject *
967sys_current_frames(PyObject *self, PyObject *noargs)
968{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 return _PyThread_CurrentFrames();
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000970}
971
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000972PyDoc_STRVAR(call_tracing_doc,
973"call_tracing(func, args) -> object\n\
974\n\
975Call func(*args), while tracing is enabled. The tracing state is\n\
976saved, and restored afterwards. This is intended to be called from\n\
977a debugger from a checkpoint, to recursively debug some other code."
978);
979
980static PyObject *
981sys_call_tracing(PyObject *self, PyObject *args)
982{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 PyObject *func, *funcargs;
984 if (!PyArg_ParseTuple(args, "OO!:call_tracing", &func, &PyTuple_Type, &funcargs))
985 return NULL;
986 return _PyEval_CallTracing(func, funcargs);
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000987}
988
Jeremy Hylton985eba52003-02-05 23:13:00 +0000989PyDoc_STRVAR(callstats_doc,
990"callstats() -> tuple of integers\n\
991\n\
992Return a tuple of function call statistics, if CALL_PROFILE was defined\n\
993when Python was built. Otherwise, return None.\n\
994\n\
995When enabled, this function returns detailed, implementation-specific\n\
996details about the number of function calls executed. The return value is\n\
997a 11-tuple where the entries in the tuple are counts of:\n\
9980. all function calls\n\
9991. calls to PyFunction_Type objects\n\
10002. PyFunction calls that do not create an argument tuple\n\
10013. PyFunction calls that do not create an argument tuple\n\
1002 and bypass PyEval_EvalCodeEx()\n\
10034. PyMethod calls\n\
10045. PyMethod calls on bound methods\n\
10056. PyType calls\n\
10067. PyCFunction calls\n\
10078. generator calls\n\
10089. All other calls\n\
100910. Number of stack pops performed by call_function()"
1010);
Barry Warsawb6a54d22000-12-06 21:47:46 +00001011
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001012#ifdef __cplusplus
1013extern "C" {
1014#endif
1015
David Malcolm49526f42012-06-22 14:55:41 -04001016static PyObject *
1017sys_debugmallocstats(PyObject *self, PyObject *args)
1018{
1019#ifdef WITH_PYMALLOC
1020 _PyObject_DebugMallocStats(stderr);
1021 fputc('\n', stderr);
1022#endif
1023 _PyObject_DebugTypeStats(stderr);
1024
1025 Py_RETURN_NONE;
1026}
1027PyDoc_STRVAR(debugmallocstats_doc,
1028"_debugmallocstats()\n\
1029\n\
1030Print summary info to stderr about the state of\n\
1031pymalloc's structures.\n\
1032\n\
1033In Py_DEBUG mode, also perform some expensive internal consistency\n\
1034checks.\n\
1035");
1036
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001037#ifdef Py_TRACE_REFS
Guido van Rossumded690f1996-05-24 20:48:31 +00001038/* Defined in objects.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001039extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001040#endif
Guido van Rossumded690f1996-05-24 20:48:31 +00001041
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001042#ifdef DYNAMIC_EXECUTION_PROFILE
1043/* Defined in ceval.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001044extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001045#endif
1046
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001047#ifdef __cplusplus
1048}
1049#endif
1050
Christian Heimes15ebc882008-02-04 18:48:49 +00001051static PyObject *
1052sys_clear_type_cache(PyObject* self, PyObject* args)
1053{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 PyType_ClearCache();
1055 Py_RETURN_NONE;
Christian Heimes15ebc882008-02-04 18:48:49 +00001056}
1057
1058PyDoc_STRVAR(sys_clear_type_cache__doc__,
1059"_clear_type_cache() -> None\n\
1060Clear the internal type lookup cache.");
1061
1062
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001063static PyMethodDef sys_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 /* Might as well keep this in alphabetic order */
1065 {"callstats", (PyCFunction)PyEval_GetCallStats, METH_NOARGS,
1066 callstats_doc},
1067 {"_clear_type_cache", sys_clear_type_cache, METH_NOARGS,
1068 sys_clear_type_cache__doc__},
1069 {"_current_frames", sys_current_frames, METH_NOARGS,
1070 current_frames_doc},
1071 {"displayhook", sys_displayhook, METH_O, displayhook_doc},
1072 {"exc_info", sys_exc_info, METH_NOARGS, exc_info_doc},
1073 {"excepthook", sys_excepthook, METH_VARARGS, excepthook_doc},
1074 {"exit", sys_exit, METH_VARARGS, exit_doc},
1075 {"getdefaultencoding", (PyCFunction)sys_getdefaultencoding,
1076 METH_NOARGS, getdefaultencoding_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001077#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 {"getdlopenflags", (PyCFunction)sys_getdlopenflags, METH_NOARGS,
1079 getdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001080#endif
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001081 {"getallocatedblocks", (PyCFunction)sys_getallocatedblocks, METH_NOARGS,
1082 getallocatedblocks_doc},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001083#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 {"getcounts", (PyCFunction)sys_getcounts, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001085#endif
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001086#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001088#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 {"getfilesystemencoding", (PyCFunction)sys_getfilesystemencoding,
1090 METH_NOARGS, getfilesystemencoding_doc},
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001091#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 {"getobjects", _Py_GetObjects, METH_VARARGS},
Tim Peters4be93d02002-07-07 19:59:50 +00001093#endif
1094#ifdef Py_REF_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 {"gettotalrefcount", (PyCFunction)sys_gettotalrefcount, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001096#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 {"getrefcount", (PyCFunction)sys_getrefcount, METH_O, getrefcount_doc},
1098 {"getrecursionlimit", (PyCFunction)sys_getrecursionlimit, METH_NOARGS,
1099 getrecursionlimit_doc},
1100 {"getsizeof", (PyCFunction)sys_getsizeof,
1101 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
1102 {"_getframe", sys_getframe, METH_VARARGS, getframe_doc},
Mark Hammond8696ebc2002-10-08 02:44:31 +00001103#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 {"getwindowsversion", (PyCFunction)sys_getwindowsversion, METH_NOARGS,
1105 getwindowsversion_doc},
Mark Hammond8696ebc2002-10-08 02:44:31 +00001106#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001107 {"intern", sys_intern, METH_VARARGS, intern_doc},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001108#ifdef USE_MALLOPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 {"mdebug", sys_mdebug, METH_VARARGS},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001110#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 {"setcheckinterval", sys_setcheckinterval, METH_VARARGS,
1112 setcheckinterval_doc},
1113 {"getcheckinterval", sys_getcheckinterval, METH_NOARGS,
1114 getcheckinterval_doc},
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001115#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 {"setswitchinterval", sys_setswitchinterval, METH_VARARGS,
1117 setswitchinterval_doc},
1118 {"getswitchinterval", sys_getswitchinterval, METH_NOARGS,
1119 getswitchinterval_doc},
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001120#endif
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001121#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 {"setdlopenflags", sys_setdlopenflags, METH_VARARGS,
1123 setdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001124#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 {"setprofile", sys_setprofile, METH_O, setprofile_doc},
1126 {"getprofile", sys_getprofile, METH_NOARGS, getprofile_doc},
1127 {"setrecursionlimit", sys_setrecursionlimit, METH_VARARGS,
1128 setrecursionlimit_doc},
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00001129#ifdef WITH_TSC
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 {"settscdump", sys_settscdump, METH_VARARGS, settscdump_doc},
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00001131#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 {"settrace", sys_settrace, METH_O, settrace_doc},
1133 {"gettrace", sys_gettrace, METH_NOARGS, gettrace_doc},
1134 {"call_tracing", sys_call_tracing, METH_VARARGS, call_tracing_doc},
David Malcolm49526f42012-06-22 14:55:41 -04001135 {"_debugmallocstats", sys_debugmallocstats, METH_VARARGS,
1136 debugmallocstats_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001137 {NULL, NULL} /* sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +00001138};
1139
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001140static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001141list_builtin_module_names(void)
Guido van Rossum34679b71993-01-26 13:33:44 +00001142{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 PyObject *list = PyList_New(0);
1144 int i;
1145 if (list == NULL)
1146 return NULL;
1147 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1148 PyObject *name = PyUnicode_FromString(
1149 PyImport_Inittab[i].name);
1150 if (name == NULL)
1151 break;
1152 PyList_Append(list, name);
1153 Py_DECREF(name);
1154 }
1155 if (PyList_Sort(list) != 0) {
1156 Py_DECREF(list);
1157 list = NULL;
1158 }
1159 if (list) {
1160 PyObject *v = PyList_AsTuple(list);
1161 Py_DECREF(list);
1162 list = v;
1163 }
1164 return list;
Guido van Rossum34679b71993-01-26 13:33:44 +00001165}
1166
Guido van Rossum23fff912000-12-15 22:02:05 +00001167static PyObject *warnoptions = NULL;
1168
1169void
1170PySys_ResetWarnOptions(void)
1171{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001172 if (warnoptions == NULL || !PyList_Check(warnoptions))
1173 return;
1174 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
Guido van Rossum23fff912000-12-15 22:02:05 +00001175}
1176
1177void
Victor Stinner9ca9c252010-05-19 16:53:30 +00001178PySys_AddWarnOptionUnicode(PyObject *unicode)
Guido van Rossum23fff912000-12-15 22:02:05 +00001179{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001180 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
1181 Py_XDECREF(warnoptions);
1182 warnoptions = PyList_New(0);
1183 if (warnoptions == NULL)
1184 return;
1185 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00001186 PyList_Append(warnoptions, unicode);
1187}
1188
1189void
1190PySys_AddWarnOption(const wchar_t *s)
1191{
1192 PyObject *unicode;
1193 unicode = PyUnicode_FromWideChar(s, -1);
1194 if (unicode == NULL)
1195 return;
1196 PySys_AddWarnOptionUnicode(unicode);
1197 Py_DECREF(unicode);
Guido van Rossum23fff912000-12-15 22:02:05 +00001198}
1199
Christian Heimes33fe8092008-04-13 13:53:33 +00001200int
1201PySys_HasWarnOptions(void)
1202{
1203 return (warnoptions != NULL && (PyList_Size(warnoptions) > 0)) ? 1 : 0;
1204}
1205
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001206static PyObject *xoptions = NULL;
1207
1208static PyObject *
1209get_xoptions(void)
1210{
1211 if (xoptions == NULL || !PyDict_Check(xoptions)) {
1212 Py_XDECREF(xoptions);
1213 xoptions = PyDict_New();
1214 }
1215 return xoptions;
1216}
1217
1218void
1219PySys_AddXOption(const wchar_t *s)
1220{
1221 PyObject *opts;
1222 PyObject *name = NULL, *value = NULL;
1223 const wchar_t *name_end;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001224
1225 opts = get_xoptions();
1226 if (opts == NULL)
1227 goto error;
1228
1229 name_end = wcschr(s, L'=');
1230 if (!name_end) {
1231 name = PyUnicode_FromWideChar(s, -1);
1232 value = Py_True;
1233 Py_INCREF(value);
1234 }
1235 else {
1236 name = PyUnicode_FromWideChar(s, name_end - s);
1237 value = PyUnicode_FromWideChar(name_end + 1, -1);
1238 }
1239 if (name == NULL || value == NULL)
1240 goto error;
Brett Cannonb94767f2011-02-22 20:15:44 +00001241 PyDict_SetItem(opts, name, value);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001242 Py_DECREF(name);
1243 Py_DECREF(value);
1244 return;
1245
1246error:
1247 Py_XDECREF(name);
1248 Py_XDECREF(value);
1249 /* No return value, therefore clear error state if possible */
1250 if (_Py_atomic_load_relaxed(&_PyThreadState_Current))
1251 PyErr_Clear();
1252}
1253
1254PyObject *
1255PySys_GetXOptions(void)
1256{
1257 return get_xoptions();
1258}
1259
Guido van Rossum40552d01998-08-06 03:34:39 +00001260/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
1261 Two literals concatenated works just fine. If you have a K&R compiler
1262 or other abomination that however *does* understand longer strings,
1263 get rid of the !!! comment in the middle and the quotes that surround it. */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001264PyDoc_VAR(sys_doc) =
1265PyDoc_STR(
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001266"This module provides access to some objects used or maintained by the\n\
1267interpreter and to functions that interact strongly with the interpreter.\n\
1268\n\
1269Dynamic objects:\n\
1270\n\
1271argv -- command line arguments; argv[0] is the script pathname if known\n\
1272path -- module search path; path[0] is the script directory, else ''\n\
1273modules -- dictionary of loaded modules\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001274\n\
1275displayhook -- called to show results in an interactive session\n\
1276excepthook -- called to handle any uncaught exception other than SystemExit\n\
1277 To customize printing in an interactive session or to install a custom\n\
1278 top-level exception handler, assign other functions to replace these.\n\
1279\n\
Benjamin Peterson06157a42008-07-15 00:28:36 +00001280stdin -- standard input file object; used by input()\n\
Georg Brandl88fc6642007-02-09 21:28:07 +00001281stdout -- standard output file object; used by print()\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001282stderr -- standard error object; used for error messages\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001283 By assigning other file objects (or objects that behave like files)\n\
1284 to these, it is possible to redirect all of the interpreter's I/O.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001285\n\
1286last_type -- type of last uncaught exception\n\
1287last_value -- value of last uncaught exception\n\
1288last_traceback -- traceback of last uncaught exception\n\
1289 These three are only available in an interactive session after a\n\
1290 traceback has been printed.\n\
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001291"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001292)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001293/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001294PyDoc_STR(
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001295"\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001296Static objects:\n\
1297\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001298builtin_module_names -- tuple of module names built into this interpreter\n\
1299copyright -- copyright notice pertaining to this interpreter\n\
1300exec_prefix -- prefix used to find the machine-specific Python library\n\
Petri Lehtinen4b0eab62012-02-02 21:23:15 +02001301executable -- absolute path of the executable binary of the Python interpreter\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001302float_info -- a struct sequence with information about the float implementation.\n\
1303float_repr_style -- string indicating the style of repr() output for floats\n\
1304hexversion -- version information encoded as a single integer\n\
Barry Warsaw409da152012-06-03 16:18:47 -04001305implementation -- Python implementation information.\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00001306int_info -- a struct sequence with information about the int implementation.\n\
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00001307maxsize -- the largest supported length of containers.\n\
Ezio Melotti48a2f8f2011-09-29 00:18:19 +03001308maxunicode -- the value of the largest Unicode codepoint\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001309platform -- platform identifier\n\
1310prefix -- prefix used to find the Python library\n\
1311thread_info -- a struct sequence with information about the thread implementation.\n\
Fred Drake801c08d2000-04-13 15:29:10 +00001312version -- the version of this interpreter as a string\n\
Eric Smith0e5b5622009-02-06 01:32:42 +00001313version_info -- version information as a named tuple\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001314"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001315)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001316#ifdef MS_WINDOWS
1317/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001318PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001319"dllhandle -- [Windows only] integer handle of the Python DLL\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001320winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001321"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001322)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001323#endif /* MS_WINDOWS */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001324PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001325"__stdin__ -- the original stdin; don't touch!\n\
1326__stdout__ -- the original stdout; don't touch!\n\
1327__stderr__ -- the original stderr; don't touch!\n\
1328__displayhook__ -- the original displayhook; don't touch!\n\
1329__excepthook__ -- the original excepthook; don't touch!\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001330\n\
1331Functions:\n\
1332\n\
Georg Brandl1a3284e2007-12-02 09:40:06 +00001333displayhook() -- print an object to the screen, and save it in builtins._\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001334excepthook() -- print an exception and its traceback to sys.stderr\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001335exc_info() -- return thread-safe information about the current exception\n\
1336exit() -- exit the interpreter by raising SystemExit\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001337getdlopenflags() -- returns flags to be used for dlopen() calls\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00001338getprofile() -- get the global profiling function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001339getrefcount() -- return the reference count for an object (plus one :-)\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001340getrecursionlimit() -- return the max recursion depth for the interpreter\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001341getsizeof() -- return the size of an object in bytes\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00001342gettrace() -- get the global debug tracing function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001343setcheckinterval() -- control how often the interpreter checks for events\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001344setdlopenflags() -- set the flags to be used for dlopen() calls\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001345setprofile() -- set the global profiling function\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001346setrecursionlimit() -- set the max recursion depth for the interpreter\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001347settrace() -- set the global debug tracing function\n\
Fred Drakeccede592000-08-14 20:59:57 +00001348"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001349)
Fred Drakeccede592000-08-14 20:59:57 +00001350/* end of sys_doc */ ;
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001351
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001352
1353PyDoc_STRVAR(flags__doc__,
1354"sys.flags\n\
1355\n\
1356Flags provided through command line arguments or environment vars.");
1357
1358static PyTypeObject FlagsType;
1359
1360static PyStructSequence_Field flags_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001361 {"debug", "-d"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 {"inspect", "-i"},
1363 {"interactive", "-i"},
1364 {"optimize", "-O or -OO"},
1365 {"dont_write_bytecode", "-B"},
1366 {"no_user_site", "-s"},
1367 {"no_site", "-S"},
1368 {"ignore_environment", "-E"},
1369 {"verbose", "-v"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 /* {"unbuffered", "-u"}, */
1371 /* {"skip_first", "-x"}, */
Georg Brandl8aa7e992010-12-28 18:30:18 +00001372 {"bytes_warning", "-b"},
1373 {"quiet", "-q"},
Georg Brandl09a7c722012-02-20 21:31:46 +01001374 {"hash_randomization", "-R"},
Christian Heimesad73a9c2013-08-10 16:36:18 +02001375 {"isolated", "-I"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001376 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001377};
1378
1379static PyStructSequence_Desc flags_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001380 "sys.flags", /* name */
1381 flags__doc__, /* doc */
1382 flags_fields, /* fields */
Christian Heimesad73a9c2013-08-10 16:36:18 +02001383 13
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001384};
1385
1386static PyObject*
1387make_flags(void)
1388{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 int pos = 0;
1390 PyObject *seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001392 seq = PyStructSequence_New(&FlagsType);
1393 if (seq == NULL)
1394 return NULL;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001395
1396#define SetFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397 PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001399 SetFlag(Py_DebugFlag);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001400 SetFlag(Py_InspectFlag);
1401 SetFlag(Py_InteractiveFlag);
1402 SetFlag(Py_OptimizeFlag);
1403 SetFlag(Py_DontWriteBytecodeFlag);
1404 SetFlag(Py_NoUserSiteDirectory);
1405 SetFlag(Py_NoSiteFlag);
1406 SetFlag(Py_IgnoreEnvironmentFlag);
1407 SetFlag(Py_VerboseFlag);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 /* SetFlag(saw_unbuffered_flag); */
1409 /* SetFlag(skipfirstline); */
Christian Heimes33fe8092008-04-13 13:53:33 +00001410 SetFlag(Py_BytesWarningFlag);
Georg Brandl8aa7e992010-12-28 18:30:18 +00001411 SetFlag(Py_QuietFlag);
Georg Brandl2daf6ae2012-02-20 19:54:16 +01001412 SetFlag(Py_HashRandomizationFlag);
Christian Heimesad73a9c2013-08-10 16:36:18 +02001413 SetFlag(Py_IsolatedFlag);
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001414#undef SetFlag
1415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001416 if (PyErr_Occurred()) {
1417 return NULL;
1418 }
1419 return seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001420}
1421
Eric Smith0e5b5622009-02-06 01:32:42 +00001422PyDoc_STRVAR(version_info__doc__,
1423"sys.version_info\n\
1424\n\
1425Version information as a named tuple.");
1426
1427static PyTypeObject VersionInfoType;
1428
1429static PyStructSequence_Field version_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001430 {"major", "Major release number"},
1431 {"minor", "Minor release number"},
1432 {"micro", "Patch release number"},
1433 {"releaselevel", "'alpha', 'beta', 'candidate', or 'release'"},
1434 {"serial", "Serial release number"},
1435 {0}
Eric Smith0e5b5622009-02-06 01:32:42 +00001436};
1437
1438static PyStructSequence_Desc version_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001439 "sys.version_info", /* name */
1440 version_info__doc__, /* doc */
1441 version_info_fields, /* fields */
1442 5
Eric Smith0e5b5622009-02-06 01:32:42 +00001443};
1444
1445static PyObject *
1446make_version_info(void)
1447{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 PyObject *version_info;
1449 char *s;
1450 int pos = 0;
Eric Smith0e5b5622009-02-06 01:32:42 +00001451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001452 version_info = PyStructSequence_New(&VersionInfoType);
1453 if (version_info == NULL) {
1454 return NULL;
1455 }
Eric Smith0e5b5622009-02-06 01:32:42 +00001456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001457 /*
1458 * These release level checks are mutually exclusive and cover
1459 * the field, so don't get too fancy with the pre-processor!
1460 */
Eric Smith0e5b5622009-02-06 01:32:42 +00001461#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001462 s = "alpha";
Eric Smith0e5b5622009-02-06 01:32:42 +00001463#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001464 s = "beta";
Eric Smith0e5b5622009-02-06 01:32:42 +00001465#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001466 s = "candidate";
Eric Smith0e5b5622009-02-06 01:32:42 +00001467#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 s = "final";
Eric Smith0e5b5622009-02-06 01:32:42 +00001469#endif
1470
1471#define SetIntItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00001473#define SetStrItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001474 PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00001475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001476 SetIntItem(PY_MAJOR_VERSION);
1477 SetIntItem(PY_MINOR_VERSION);
1478 SetIntItem(PY_MICRO_VERSION);
1479 SetStrItem(s);
1480 SetIntItem(PY_RELEASE_SERIAL);
Eric Smith0e5b5622009-02-06 01:32:42 +00001481#undef SetIntItem
1482#undef SetStrItem
1483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001484 if (PyErr_Occurred()) {
1485 Py_CLEAR(version_info);
1486 return NULL;
1487 }
1488 return version_info;
Eric Smith0e5b5622009-02-06 01:32:42 +00001489}
1490
Brett Cannon3adc7b72012-07-09 14:22:12 -04001491/* sys.implementation values */
1492#define NAME "cpython"
1493const char *_PySys_ImplName = NAME;
1494#define QUOTE(arg) #arg
1495#define STRIFY(name) QUOTE(name)
1496#define MAJOR STRIFY(PY_MAJOR_VERSION)
1497#define MINOR STRIFY(PY_MINOR_VERSION)
1498#define TAG NAME "-" MAJOR MINOR;
1499const char *_PySys_ImplCacheTag = TAG;
1500#undef NAME
1501#undef QUOTE
1502#undef STRIFY
1503#undef MAJOR
1504#undef MINOR
1505#undef TAG
1506
Barry Warsaw409da152012-06-03 16:18:47 -04001507static PyObject *
1508make_impl_info(PyObject *version_info)
1509{
1510 int res;
1511 PyObject *impl_info, *value, *ns;
1512
1513 impl_info = PyDict_New();
1514 if (impl_info == NULL)
1515 return NULL;
1516
1517 /* populate the dict */
1518
Brett Cannon3adc7b72012-07-09 14:22:12 -04001519 value = PyUnicode_FromString(_PySys_ImplName);
Barry Warsaw409da152012-06-03 16:18:47 -04001520 if (value == NULL)
1521 goto error;
1522 res = PyDict_SetItemString(impl_info, "name", value);
1523 Py_DECREF(value);
1524 if (res < 0)
1525 goto error;
1526
Brett Cannon3adc7b72012-07-09 14:22:12 -04001527 value = PyUnicode_FromString(_PySys_ImplCacheTag);
Barry Warsaw409da152012-06-03 16:18:47 -04001528 if (value == NULL)
1529 goto error;
1530 res = PyDict_SetItemString(impl_info, "cache_tag", value);
1531 Py_DECREF(value);
1532 if (res < 0)
1533 goto error;
Barry Warsaw409da152012-06-03 16:18:47 -04001534
1535 res = PyDict_SetItemString(impl_info, "version", version_info);
1536 if (res < 0)
1537 goto error;
1538
1539 value = PyLong_FromLong(PY_VERSION_HEX);
1540 if (value == NULL)
1541 goto error;
1542 res = PyDict_SetItemString(impl_info, "hexversion", value);
1543 Py_DECREF(value);
1544 if (res < 0)
1545 goto error;
1546
1547 /* dict ready */
1548
1549 ns = _PyNamespace_New(impl_info);
1550 Py_DECREF(impl_info);
1551 return ns;
1552
1553error:
1554 Py_CLEAR(impl_info);
1555 return NULL;
1556}
1557
Martin v. Löwis1a214512008-06-11 05:26:20 +00001558static struct PyModuleDef sysmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 PyModuleDef_HEAD_INIT,
1560 "sys",
1561 sys_doc,
1562 -1, /* multiple "initialization" just copies the module dict. */
1563 sys_methods,
1564 NULL,
1565 NULL,
1566 NULL,
1567 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001568};
1569
Guido van Rossum25ce5661997-08-02 03:10:38 +00001570PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001571_PySys_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001572{
Victor Stinner58049602013-07-22 22:40:00 +02001573 PyObject *m, *sysdict, *version_info;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001575 m = PyModule_Create(&sysmodule);
1576 if (m == NULL)
1577 return NULL;
1578 sysdict = PyModule_GetDict(m);
Victor Stinner8fea2522013-10-27 17:15:42 +01001579#define SET_SYS_FROM_STRING_BORROW(key, value) \
Victor Stinner58049602013-07-22 22:40:00 +02001580 do { \
1581 int res; \
1582 PyObject *v = (value); \
1583 if (v == NULL) \
1584 return NULL; \
1585 res = PyDict_SetItemString(sysdict, key, v); \
1586 if (res < 0) { \
Victor Stinner8fea2522013-10-27 17:15:42 +01001587 return NULL; \
1588 } \
1589 } while (0)
1590#define SET_SYS_FROM_STRING(key, value) \
1591 do { \
1592 int res; \
1593 PyObject *v = (value); \
1594 if (v == NULL) \
1595 return NULL; \
1596 res = PyDict_SetItemString(sysdict, key, v); \
1597 Py_DECREF(v); \
1598 if (res < 0) { \
Victor Stinner58049602013-07-22 22:40:00 +02001599 return NULL; \
1600 } \
1601 } while (0)
Guido van Rossum25ce5661997-08-02 03:10:38 +00001602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 /* Check that stdin is not a directory
1604 Using shell redirection, you can redirect stdin to a directory,
1605 crashing the Python interpreter. Catch this common mistake here
1606 and output a useful error message. Note that under MS Windows,
1607 the shell already prevents that. */
Martin v. Löwisec59d042009-01-12 07:59:10 +00001608#if !defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 {
1610 struct stat sb;
1611 if (fstat(fileno(stdin), &sb) == 0 &&
1612 S_ISDIR(sb.st_mode)) {
1613 /* There's nothing more we can do. */
1614 /* Py_FatalError() will core dump, so just exit. */
1615 PySys_WriteStderr("Python error: <stdin> is a directory, cannot continue\n");
1616 exit(EXIT_FAILURE);
1617 }
1618 }
Martin v. Löwisec59d042009-01-12 07:59:10 +00001619#endif
Neal Norwitz11bd1192005-10-03 00:54:56 +00001620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001621 /* stdin/stdout/stderr are now set by pythonrun.c */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001622
Victor Stinner8fea2522013-10-27 17:15:42 +01001623 SET_SYS_FROM_STRING_BORROW("__displayhook__",
1624 PyDict_GetItemString(sysdict, "displayhook"));
1625 SET_SYS_FROM_STRING_BORROW("__excepthook__",
1626 PyDict_GetItemString(sysdict, "excepthook"));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001627 SET_SYS_FROM_STRING("version",
1628 PyUnicode_FromString(Py_GetVersion()));
1629 SET_SYS_FROM_STRING("hexversion",
1630 PyLong_FromLong(PY_VERSION_HEX));
Georg Brandl1ca2e792011-03-05 20:51:24 +01001631 SET_SYS_FROM_STRING("_mercurial",
1632 Py_BuildValue("(szz)", "CPython", _Py_hgidentifier(),
1633 _Py_hgversion()));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001634 SET_SYS_FROM_STRING("dont_write_bytecode",
1635 PyBool_FromLong(Py_DontWriteBytecodeFlag));
1636 SET_SYS_FROM_STRING("api_version",
1637 PyLong_FromLong(PYTHON_API_VERSION));
1638 SET_SYS_FROM_STRING("copyright",
1639 PyUnicode_FromString(Py_GetCopyright()));
1640 SET_SYS_FROM_STRING("platform",
1641 PyUnicode_FromString(Py_GetPlatform()));
1642 SET_SYS_FROM_STRING("executable",
1643 PyUnicode_FromWideChar(
1644 Py_GetProgramFullPath(), -1));
1645 SET_SYS_FROM_STRING("prefix",
1646 PyUnicode_FromWideChar(Py_GetPrefix(), -1));
1647 SET_SYS_FROM_STRING("exec_prefix",
1648 PyUnicode_FromWideChar(Py_GetExecPrefix(), -1));
Vinay Sajip7ded1f02012-05-26 03:45:29 +01001649 SET_SYS_FROM_STRING("base_prefix",
1650 PyUnicode_FromWideChar(Py_GetPrefix(), -1));
1651 SET_SYS_FROM_STRING("base_exec_prefix",
1652 PyUnicode_FromWideChar(Py_GetExecPrefix(), -1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001653 SET_SYS_FROM_STRING("maxsize",
1654 PyLong_FromSsize_t(PY_SSIZE_T_MAX));
1655 SET_SYS_FROM_STRING("float_info",
1656 PyFloat_GetInfo());
1657 SET_SYS_FROM_STRING("int_info",
1658 PyLong_GetInfo());
Mark Dickinsondc787d22010-05-23 13:33:13 +00001659 /* initialize hash_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02001660 if (Hash_InfoType.tp_name == NULL) {
1661 if (PyStructSequence_InitType2(&Hash_InfoType, &hash_info_desc) < 0)
1662 return NULL;
1663 }
Mark Dickinsondc787d22010-05-23 13:33:13 +00001664 SET_SYS_FROM_STRING("hash_info",
1665 get_hash_info());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001666 SET_SYS_FROM_STRING("maxunicode",
Ezio Melotti48a2f8f2011-09-29 00:18:19 +03001667 PyLong_FromLong(0x10FFFF));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001668 SET_SYS_FROM_STRING("builtin_module_names",
1669 list_builtin_module_names());
Christian Heimes743e0cd2012-10-17 23:52:17 +02001670#if PY_BIG_ENDIAN
1671 SET_SYS_FROM_STRING("byteorder",
1672 PyUnicode_FromString("big"));
1673#else
1674 SET_SYS_FROM_STRING("byteorder",
1675 PyUnicode_FromString("little"));
1676#endif
Fred Drake099325e2000-08-14 15:47:03 +00001677
Guido van Rossum8b9ea871996-08-23 18:14:47 +00001678#ifdef MS_COREDLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001679 SET_SYS_FROM_STRING("dllhandle",
1680 PyLong_FromVoidPtr(PyWin_DLLhModule));
1681 SET_SYS_FROM_STRING("winver",
1682 PyUnicode_FromString(PyWin_DLLVersionString));
Guido van Rossumc606fe11996-04-09 02:37:57 +00001683#endif
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00001684#ifdef ABIFLAGS
1685 SET_SYS_FROM_STRING("abiflags",
1686 PyUnicode_FromString(ABIFLAGS));
1687#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001688 if (warnoptions == NULL) {
1689 warnoptions = PyList_New(0);
Victor Stinner58049602013-07-22 22:40:00 +02001690 if (warnoptions == NULL)
1691 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001692 }
1693 else {
1694 Py_INCREF(warnoptions);
1695 }
Victor Stinner8fea2522013-10-27 17:15:42 +01001696 SET_SYS_FROM_STRING_BORROW("warnoptions", warnoptions);
Tim Peters216b78b2006-01-06 02:40:53 +00001697
Victor Stinner8fea2522013-10-27 17:15:42 +01001698 SET_SYS_FROM_STRING_BORROW("_xoptions", get_xoptions());
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001700 /* version_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02001701 if (VersionInfoType.tp_name == NULL) {
1702 if (PyStructSequence_InitType2(&VersionInfoType,
1703 &version_info_desc) < 0)
1704 return NULL;
1705 }
Barry Warsaw409da152012-06-03 16:18:47 -04001706 version_info = make_version_info();
1707 SET_SYS_FROM_STRING("version_info", version_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001708 /* prevent user from creating new instances */
1709 VersionInfoType.tp_init = NULL;
1710 VersionInfoType.tp_new = NULL;
Eric Smith0e5b5622009-02-06 01:32:42 +00001711
Barry Warsaw409da152012-06-03 16:18:47 -04001712 /* implementation */
1713 SET_SYS_FROM_STRING("implementation", make_impl_info(version_info));
1714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001715 /* flags */
Victor Stinner1c8f0592013-07-22 22:24:54 +02001716 if (FlagsType.tp_name == 0) {
1717 if (PyStructSequence_InitType2(&FlagsType, &flags_desc) < 0)
1718 return NULL;
1719 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001720 SET_SYS_FROM_STRING("flags", make_flags());
1721 /* prevent user from creating new instances */
1722 FlagsType.tp_init = NULL;
1723 FlagsType.tp_new = NULL;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001724
Eric Smithf7bb5782010-01-27 00:44:57 +00001725
1726#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001727 /* getwindowsversion */
1728 if (WindowsVersionType.tp_name == 0)
Victor Stinner1c8f0592013-07-22 22:24:54 +02001729 if (PyStructSequence_InitType2(&WindowsVersionType,
1730 &windows_version_desc) < 0)
1731 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001732 /* prevent user from creating new instances */
1733 WindowsVersionType.tp_init = NULL;
1734 WindowsVersionType.tp_new = NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +00001735#endif
1736
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001737 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00001738#ifndef PY_NO_SHORT_FLOAT_REPR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001739 SET_SYS_FROM_STRING("float_repr_style",
1740 PyUnicode_FromString("short"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00001741#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001742 SET_SYS_FROM_STRING("float_repr_style",
1743 PyUnicode_FromString("legacy"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00001744#endif
1745
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001746#ifdef WITH_THREAD
1747 SET_SYS_FROM_STRING("thread_info", PyThread_GetInfo());
1748#endif
1749
Christian Heimes7b3ce6a2008-01-31 14:31:45 +00001750#undef SET_SYS_FROM_STRING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001751 if (PyErr_Occurred())
1752 return NULL;
1753 return m;
Guido van Rossum5b3138b1990-11-18 17:41:40 +00001754}
1755
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001756static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00001757makepathobject(const wchar_t *path, wchar_t delim)
Guido van Rossum5b3138b1990-11-18 17:41:40 +00001758{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 int i, n;
1760 const wchar_t *p;
1761 PyObject *v, *w;
Tim Peters216b78b2006-01-06 02:40:53 +00001762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001763 n = 1;
1764 p = path;
1765 while ((p = wcschr(p, delim)) != NULL) {
1766 n++;
1767 p++;
1768 }
1769 v = PyList_New(n);
1770 if (v == NULL)
1771 return NULL;
1772 for (i = 0; ; i++) {
1773 p = wcschr(path, delim);
1774 if (p == NULL)
1775 p = path + wcslen(path); /* End of string */
1776 w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
1777 if (w == NULL) {
1778 Py_DECREF(v);
1779 return NULL;
1780 }
1781 PyList_SetItem(v, i, w);
1782 if (*p == '\0')
1783 break;
1784 path = p+1;
1785 }
1786 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001787}
1788
1789void
Martin v. Löwis790465f2008-04-05 20:41:37 +00001790PySys_SetPath(const wchar_t *path)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001791{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 PyObject *v;
1793 if ((v = makepathobject(path, DELIM)) == NULL)
1794 Py_FatalError("can't create sys.path");
1795 if (PySys_SetObject("path", v) != 0)
1796 Py_FatalError("can't assign sys.path");
1797 Py_DECREF(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001798}
1799
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001800static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00001801makeargvobject(int argc, wchar_t **argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001802{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001803 PyObject *av;
1804 if (argc <= 0 || argv == NULL) {
1805 /* Ensure at least one (empty) argument is seen */
1806 static wchar_t *empty_argv[1] = {L""};
1807 argv = empty_argv;
1808 argc = 1;
1809 }
1810 av = PyList_New(argc);
1811 if (av != NULL) {
1812 int i;
1813 for (i = 0; i < argc; i++) {
Martin v. Löwisc16f3bd2003-05-03 09:14:54 +00001814#ifdef __VMS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001815 PyObject *v;
Martin v. Löwisc16f3bd2003-05-03 09:14:54 +00001816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001817 /* argv[0] is the script pathname if known */
1818 if (i == 0) {
1819 char* fn = decc$translate_vms(argv[0]);
1820 if ((fn == (char *)0) || fn == (char *)-1)
1821 v = PyUnicode_FromString(argv[0]);
1822 else
1823 v = PyUnicode_FromString(
1824 decc$translate_vms(argv[0]));
1825 } else
1826 v = PyUnicode_FromString(argv[i]);
Martin v. Löwisc16f3bd2003-05-03 09:14:54 +00001827#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001828 PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
Martin v. Löwisc16f3bd2003-05-03 09:14:54 +00001829#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001830 if (v == NULL) {
1831 Py_DECREF(av);
1832 av = NULL;
1833 break;
1834 }
1835 PyList_SetItem(av, i, v);
1836 }
1837 }
1838 return av;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001839}
1840
Nick Coghland26c18a2010-08-17 13:06:11 +00001841#define _HAVE_SCRIPT_ARGUMENT(argc, argv) \
1842 (argc > 0 && argv0 != NULL && \
1843 wcscmp(argv0, L"-c") != 0 && wcscmp(argv0, L"-m") != 0)
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001844
1845static void
1846sys_update_path(int argc, wchar_t **argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001847{
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001848 wchar_t *argv0;
1849 wchar_t *p = NULL;
1850 Py_ssize_t n = 0;
1851 PyObject *a;
1852 PyObject *path;
1853#ifdef HAVE_READLINK
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001854 wchar_t link[MAXPATHLEN+1];
1855 wchar_t argv0copy[2*MAXPATHLEN+1];
1856 int nr = 0;
1857#endif
Guido van Rossum162e38c2003-02-19 15:25:10 +00001858#if defined(HAVE_REALPATH)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001859 wchar_t fullpath[MAXPATHLEN];
Martin v. Löwisec59d042009-01-12 07:59:10 +00001860#elif defined(MS_WINDOWS) && !defined(MS_WINCE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861 wchar_t fullpath[MAX_PATH];
Thomas Heller27bb71e2003-01-08 14:33:48 +00001862#endif
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001863
1864 path = PySys_GetObject("path");
1865 if (path == NULL)
1866 return;
1867
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001868 argv0 = argv[0];
1869
1870#ifdef HAVE_READLINK
1871 if (_HAVE_SCRIPT_ARGUMENT(argc, argv))
1872 nr = _Py_wreadlink(argv0, link, MAXPATHLEN);
1873 if (nr > 0) {
1874 /* It's a symlink */
1875 link[nr] = '\0';
1876 if (link[0] == SEP)
1877 argv0 = link; /* Link to absolute path */
1878 else if (wcschr(link, SEP) == NULL)
1879 ; /* Link without path */
1880 else {
1881 /* Must join(dirname(argv0), link) */
1882 wchar_t *q = wcsrchr(argv0, SEP);
1883 if (q == NULL)
1884 argv0 = link; /* argv0 without path */
1885 else {
Christian Heimes60a60672013-07-22 12:53:32 +02001886 /* Must make a copy, argv0copy has room for 2 * MAXPATHLEN */
1887 wcsncpy(argv0copy, argv0, MAXPATHLEN);
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001888 q = wcsrchr(argv0copy, SEP);
Christian Heimes60a60672013-07-22 12:53:32 +02001889 wcsncpy(q+1, link, MAXPATHLEN);
1890 q[MAXPATHLEN + 1] = L'\0';
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001891 argv0 = argv0copy;
1892 }
1893 }
1894 }
1895#endif /* HAVE_READLINK */
1896#if SEP == '\\' /* Special case for MS filename syntax */
1897 if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) {
1898 wchar_t *q;
1899#if defined(MS_WINDOWS) && !defined(MS_WINCE)
1900 /* This code here replaces the first element in argv with the full
1901 path that it represents. Under CE, there are no relative paths so
1902 the argument must be the full path anyway. */
1903 wchar_t *ptemp;
1904 if (GetFullPathNameW(argv0,
Victor Stinner63941882011-09-29 00:42:28 +02001905 Py_ARRAY_LENGTH(fullpath),
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001906 fullpath,
1907 &ptemp)) {
1908 argv0 = fullpath;
1909 }
1910#endif
1911 p = wcsrchr(argv0, SEP);
1912 /* Test for alternate separator */
1913 q = wcsrchr(p ? p : argv0, '/');
1914 if (q != NULL)
1915 p = q;
1916 if (p != NULL) {
1917 n = p + 1 - argv0;
1918 if (n > 1 && p[-1] != ':')
1919 n--; /* Drop trailing separator */
1920 }
1921 }
1922#else /* All other filename syntaxes */
1923 if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) {
1924#if defined(HAVE_REALPATH)
Victor Stinner015f4d82010-10-07 22:29:53 +00001925 if (_Py_wrealpath(argv0, fullpath, PATH_MAX)) {
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001926 argv0 = fullpath;
1927 }
1928#endif
1929 p = wcsrchr(argv0, SEP);
1930 }
1931 if (p != NULL) {
1932 n = p + 1 - argv0;
1933#if SEP == '/' /* Special case for Unix filename syntax */
1934 if (n > 1)
1935 n--; /* Drop trailing separator */
1936#endif /* Unix */
1937 }
1938#endif /* All others */
1939 a = PyUnicode_FromWideChar(argv0, n);
1940 if (a == NULL)
1941 Py_FatalError("no mem for sys.path insertion");
1942 if (PyList_Insert(path, 0, a) < 0)
1943 Py_FatalError("sys.path.insert(0) failed");
1944 Py_DECREF(a);
1945}
1946
1947void
1948PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
1949{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001950 PyObject *av = makeargvobject(argc, argv);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001951 if (av == NULL)
1952 Py_FatalError("no mem for sys.argv");
1953 if (PySys_SetObject("argv", av) != 0)
1954 Py_FatalError("can't assign sys.argv");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001955 Py_DECREF(av);
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001956 if (updatepath)
1957 sys_update_path(argc, argv);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001958}
Guido van Rossuma890e681998-05-12 14:59:24 +00001959
Antoine Pitrouf978fac2010-05-21 17:25:34 +00001960void
1961PySys_SetArgv(int argc, wchar_t **argv)
1962{
Christian Heimesad73a9c2013-08-10 16:36:18 +02001963 PySys_SetArgvEx(argc, argv, Py_IsolatedFlag == 0);
Antoine Pitrouf978fac2010-05-21 17:25:34 +00001964}
1965
Victor Stinner14284c22010-04-23 12:02:30 +00001966/* Reimplementation of PyFile_WriteString() no calling indirectly
1967 PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
1968
1969static int
Victor Stinner79766632010-08-16 17:36:42 +00001970sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
Victor Stinner14284c22010-04-23 12:02:30 +00001971{
Victor Stinner79766632010-08-16 17:36:42 +00001972 PyObject *writer = NULL, *args = NULL, *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001973 int err;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001974 _Py_IDENTIFIER(write);
Victor Stinner14284c22010-04-23 12:02:30 +00001975
Victor Stinnerecccc4f2010-06-08 20:46:00 +00001976 if (file == NULL)
1977 return -1;
1978
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001979 writer = _PyObject_GetAttrId(file, &PyId_write);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001980 if (writer == NULL)
1981 goto error;
Victor Stinner14284c22010-04-23 12:02:30 +00001982
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001983 args = PyTuple_Pack(1, unicode);
1984 if (args == NULL)
1985 goto error;
Victor Stinner14284c22010-04-23 12:02:30 +00001986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001987 result = PyEval_CallObject(writer, args);
1988 if (result == NULL) {
1989 goto error;
1990 } else {
1991 err = 0;
1992 goto finally;
1993 }
Victor Stinner14284c22010-04-23 12:02:30 +00001994
1995error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001996 err = -1;
Victor Stinner14284c22010-04-23 12:02:30 +00001997finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 Py_XDECREF(writer);
1999 Py_XDECREF(args);
2000 Py_XDECREF(result);
2001 return err;
Victor Stinner14284c22010-04-23 12:02:30 +00002002}
2003
Victor Stinner79766632010-08-16 17:36:42 +00002004static int
2005sys_pyfile_write(const char *text, PyObject *file)
2006{
2007 PyObject *unicode = NULL;
2008 int err;
2009
2010 if (file == NULL)
2011 return -1;
2012
2013 unicode = PyUnicode_FromString(text);
2014 if (unicode == NULL)
2015 return -1;
2016
2017 err = sys_pyfile_write_unicode(unicode, file);
2018 Py_DECREF(unicode);
2019 return err;
2020}
Guido van Rossuma890e681998-05-12 14:59:24 +00002021
2022/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
2023 Adapted from code submitted by Just van Rossum.
2024
2025 PySys_WriteStdout(format, ...)
2026 PySys_WriteStderr(format, ...)
2027
2028 The first function writes to sys.stdout; the second to sys.stderr. When
2029 there is a problem, they write to the real (C level) stdout or stderr;
Guido van Rossum8442af31998-10-12 18:22:10 +00002030 no exceptions are raised.
Guido van Rossuma890e681998-05-12 14:59:24 +00002031
Victor Stinner14284c22010-04-23 12:02:30 +00002032 PyErr_CheckSignals() is not called to avoid the execution of the Python
Victor Stinner79766632010-08-16 17:36:42 +00002033 signal handlers: they may raise a new exception whereas sys_write()
2034 ignores all exceptions.
Victor Stinner14284c22010-04-23 12:02:30 +00002035
Guido van Rossuma890e681998-05-12 14:59:24 +00002036 Both take a printf-style format string as their first argument followed
2037 by a variable length argument list determined by the format string.
2038
2039 *** WARNING ***
2040
2041 The format should limit the total size of the formatted output string to
2042 1000 bytes. In particular, this means that no unrestricted "%s" formats
2043 should occur; these should be limited using "%.<N>s where <N> is a
2044 decimal number calculated so that <N> plus the maximum size of other
2045 formatted text does not exceed 1000 bytes. Also watch out for "%f",
2046 which can print hundreds of digits for very large numbers.
2047
2048 */
2049
2050static void
Victor Stinner79766632010-08-16 17:36:42 +00002051sys_write(char *name, FILE *fp, const char *format, va_list va)
Guido van Rossuma890e681998-05-12 14:59:24 +00002052{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002053 PyObject *file;
2054 PyObject *error_type, *error_value, *error_traceback;
2055 char buffer[1001];
2056 int written;
Guido van Rossuma890e681998-05-12 14:59:24 +00002057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002058 PyErr_Fetch(&error_type, &error_value, &error_traceback);
2059 file = PySys_GetObject(name);
2060 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
2061 if (sys_pyfile_write(buffer, file) != 0) {
2062 PyErr_Clear();
2063 fputs(buffer, fp);
2064 }
2065 if (written < 0 || (size_t)written >= sizeof(buffer)) {
2066 const char *truncated = "... truncated";
Victor Stinner79766632010-08-16 17:36:42 +00002067 if (sys_pyfile_write(truncated, file) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002068 fputs(truncated, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002069 }
2070 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossuma890e681998-05-12 14:59:24 +00002071}
2072
2073void
Guido van Rossuma890e681998-05-12 14:59:24 +00002074PySys_WriteStdout(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002075{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002076 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002078 va_start(va, format);
Victor Stinner79766632010-08-16 17:36:42 +00002079 sys_write("stdout", stdout, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002080 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002081}
2082
2083void
Guido van Rossuma890e681998-05-12 14:59:24 +00002084PySys_WriteStderr(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002085{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002086 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002088 va_start(va, format);
Victor Stinner79766632010-08-16 17:36:42 +00002089 sys_write("stderr", stderr, format, va);
2090 va_end(va);
2091}
2092
2093static void
2094sys_format(char *name, FILE *fp, const char *format, va_list va)
2095{
2096 PyObject *file, *message;
2097 PyObject *error_type, *error_value, *error_traceback;
2098 char *utf8;
2099
2100 PyErr_Fetch(&error_type, &error_value, &error_traceback);
2101 file = PySys_GetObject(name);
2102 message = PyUnicode_FromFormatV(format, va);
2103 if (message != NULL) {
2104 if (sys_pyfile_write_unicode(message, file) != 0) {
2105 PyErr_Clear();
2106 utf8 = _PyUnicode_AsString(message);
2107 if (utf8 != NULL)
2108 fputs(utf8, fp);
2109 }
2110 Py_DECREF(message);
2111 }
2112 PyErr_Restore(error_type, error_value, error_traceback);
2113}
2114
2115void
2116PySys_FormatStdout(const char *format, ...)
2117{
2118 va_list va;
2119
2120 va_start(va, format);
2121 sys_format("stdout", stdout, format, va);
2122 va_end(va);
2123}
2124
2125void
2126PySys_FormatStderr(const char *format, ...)
2127{
2128 va_list va;
2129
2130 va_start(va, format);
2131 sys_format("stderr", stderr, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002132 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002133}