blob: 222630c1693df0080932834788a093c455be5001 [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{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000335 PyObject *args = PyTuple_New(3);
336 PyObject *whatstr;
337 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 if (args == NULL)
340 return NULL;
341 Py_INCREF(frame);
342 whatstr = whatstrings[what];
343 Py_INCREF(whatstr);
344 if (arg == NULL)
345 arg = Py_None;
346 Py_INCREF(arg);
347 PyTuple_SET_ITEM(args, 0, (PyObject *)frame);
348 PyTuple_SET_ITEM(args, 1, whatstr);
349 PyTuple_SET_ITEM(args, 2, arg);
Fred Drake5755ce62001-06-27 19:19:46 +0000350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000351 /* call the Python-level function */
352 PyFrame_FastToLocals(frame);
353 result = PyEval_CallObject(callback, args);
354 PyFrame_LocalsToFast(frame, 1);
355 if (result == NULL)
356 PyTraceBack_Here(frame);
Fred Drake5755ce62001-06-27 19:19:46 +0000357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000358 /* cleanup */
359 Py_DECREF(args);
360 return result;
Fred Drake5755ce62001-06-27 19:19:46 +0000361}
362
363static int
364profile_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000365 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000366{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 PyThreadState *tstate = frame->f_tstate;
368 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 if (arg == NULL)
371 arg = Py_None;
372 result = call_trampoline(tstate, self, frame, what, arg);
373 if (result == NULL) {
374 PyEval_SetProfile(NULL, NULL);
375 return -1;
376 }
377 Py_DECREF(result);
378 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000379}
380
381static int
382trace_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000384{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000385 PyThreadState *tstate = frame->f_tstate;
386 PyObject *callback;
387 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389 if (what == PyTrace_CALL)
390 callback = self;
391 else
392 callback = frame->f_trace;
393 if (callback == NULL)
394 return 0;
395 result = call_trampoline(tstate, callback, frame, what, arg);
396 if (result == NULL) {
397 PyEval_SetTrace(NULL, NULL);
398 Py_XDECREF(frame->f_trace);
399 frame->f_trace = NULL;
400 return -1;
401 }
402 if (result != Py_None) {
403 PyObject *temp = frame->f_trace;
404 frame->f_trace = NULL;
405 Py_XDECREF(temp);
406 frame->f_trace = result;
407 }
408 else {
409 Py_DECREF(result);
410 }
411 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000412}
Fred Draked0838392001-06-16 21:02:31 +0000413
Fred Drake8b4d01d2000-05-09 19:57:01 +0000414static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000415sys_settrace(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000416{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 if (trace_init() == -1)
418 return NULL;
419 if (args == Py_None)
420 PyEval_SetTrace(NULL, NULL);
421 else
422 PyEval_SetTrace(trace_trampoline, args);
423 Py_INCREF(Py_None);
424 return Py_None;
Guido van Rossume2437a11992-03-23 18:20:18 +0000425}
426
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000427PyDoc_STRVAR(settrace_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000428"settrace(function)\n\
429\n\
430Set the global debug tracing function. It will be called on each\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000431function call. See the debugger chapter in the library manual."
432);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000433
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000434static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000435sys_gettrace(PyObject *self, PyObject *args)
436{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000437 PyThreadState *tstate = PyThreadState_GET();
438 PyObject *temp = tstate->c_traceobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000440 if (temp == NULL)
441 temp = Py_None;
442 Py_INCREF(temp);
443 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000444}
445
446PyDoc_STRVAR(gettrace_doc,
447"gettrace()\n\
448\n\
449Return the global debug tracing function set with sys.settrace.\n\
450See the debugger chapter in the library manual."
451);
452
453static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000454sys_setprofile(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000455{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 if (trace_init() == -1)
457 return NULL;
458 if (args == Py_None)
459 PyEval_SetProfile(NULL, NULL);
460 else
461 PyEval_SetProfile(profile_trampoline, args);
462 Py_INCREF(Py_None);
463 return Py_None;
Guido van Rossume2437a11992-03-23 18:20:18 +0000464}
465
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000466PyDoc_STRVAR(setprofile_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000467"setprofile(function)\n\
468\n\
469Set the profiling function. It will be called on each function call\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000470and return. See the profiler chapter in the library manual."
471);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000472
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000473static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000474sys_getprofile(PyObject *self, PyObject *args)
475{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 PyThreadState *tstate = PyThreadState_GET();
477 PyObject *temp = tstate->c_profileobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 if (temp == NULL)
480 temp = Py_None;
481 Py_INCREF(temp);
482 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000483}
484
485PyDoc_STRVAR(getprofile_doc,
486"getprofile()\n\
487\n\
488Return the profiling function set with sys.setprofile.\n\
489See the profiler chapter in the library manual."
490);
491
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000492static int _check_interval = 100;
493
Christian Heimes9bd667a2008-01-20 15:14:11 +0000494static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000495sys_setcheckinterval(PyObject *self, PyObject *args)
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000496{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 if (PyErr_WarnEx(PyExc_DeprecationWarning,
498 "sys.getcheckinterval() and sys.setcheckinterval() "
499 "are deprecated. Use sys.setswitchinterval() "
500 "instead.", 1) < 0)
501 return NULL;
502 if (!PyArg_ParseTuple(args, "i:setcheckinterval", &_check_interval))
503 return NULL;
504 Py_INCREF(Py_None);
505 return Py_None;
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000506}
507
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000508PyDoc_STRVAR(setcheckinterval_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000509"setcheckinterval(n)\n\
510\n\
511Tell the Python interpreter to check for asynchronous events every\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000512n instructions. This also affects how often thread switches occur."
513);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000514
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000515static PyObject *
Tim Peterse5e065b2003-07-06 18:36:54 +0000516sys_getcheckinterval(PyObject *self, PyObject *args)
517{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 if (PyErr_WarnEx(PyExc_DeprecationWarning,
519 "sys.getcheckinterval() and sys.setcheckinterval() "
520 "are deprecated. Use sys.getswitchinterval() "
521 "instead.", 1) < 0)
522 return NULL;
523 return PyLong_FromLong(_check_interval);
Tim Peterse5e065b2003-07-06 18:36:54 +0000524}
525
526PyDoc_STRVAR(getcheckinterval_doc,
527"getcheckinterval() -> current check interval; see setcheckinterval()."
528);
529
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000530#ifdef WITH_THREAD
531static PyObject *
532sys_setswitchinterval(PyObject *self, PyObject *args)
533{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 double d;
535 if (!PyArg_ParseTuple(args, "d:setswitchinterval", &d))
536 return NULL;
537 if (d <= 0.0) {
538 PyErr_SetString(PyExc_ValueError,
539 "switch interval must be strictly positive");
540 return NULL;
541 }
542 _PyEval_SetSwitchInterval((unsigned long) (1e6 * d));
543 Py_INCREF(Py_None);
544 return Py_None;
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000545}
546
547PyDoc_STRVAR(setswitchinterval_doc,
548"setswitchinterval(n)\n\
549\n\
550Set the ideal thread switching delay inside the Python interpreter\n\
551The actual frequency of switching threads can be lower if the\n\
552interpreter executes long sequences of uninterruptible code\n\
553(this is implementation-specific and workload-dependent).\n\
554\n\
555The parameter must represent the desired switching delay in seconds\n\
556A typical value is 0.005 (5 milliseconds)."
557);
558
559static PyObject *
560sys_getswitchinterval(PyObject *self, PyObject *args)
561{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 return PyFloat_FromDouble(1e-6 * _PyEval_GetSwitchInterval());
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000563}
564
565PyDoc_STRVAR(getswitchinterval_doc,
566"getswitchinterval() -> current thread switch interval; see setswitchinterval()."
567);
568
569#endif /* WITH_THREAD */
570
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000571#ifdef WITH_TSC
572static PyObject *
573sys_settscdump(PyObject *self, PyObject *args)
574{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 int bool;
576 PyThreadState *tstate = PyThreadState_Get();
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 if (!PyArg_ParseTuple(args, "i:settscdump", &bool))
579 return NULL;
580 if (bool)
581 tstate->interp->tscdump = 1;
582 else
583 tstate->interp->tscdump = 0;
584 Py_INCREF(Py_None);
585 return Py_None;
Tim Peters216b78b2006-01-06 02:40:53 +0000586
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000587}
588
Tim Peters216b78b2006-01-06 02:40:53 +0000589PyDoc_STRVAR(settscdump_doc,
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000590"settscdump(bool)\n\
591\n\
592If true, tell the Python interpreter to dump VM measurements to\n\
593stderr. If false, turn off dump. The measurements are based on the\n\
Michael W. Hudson800ba232004-08-12 18:19:17 +0000594processor's time-stamp counter."
Tim Peters216b78b2006-01-06 02:40:53 +0000595);
Neal Norwitz0f5aed42004-06-13 20:32:17 +0000596#endif /* TSC */
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000597
Tim Peterse5e065b2003-07-06 18:36:54 +0000598static PyObject *
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000599sys_setrecursionlimit(PyObject *self, PyObject *args)
600{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 int new_limit;
602 if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit))
603 return NULL;
604 if (new_limit <= 0) {
605 PyErr_SetString(PyExc_ValueError,
606 "recursion limit must be positive");
607 return NULL;
608 }
609 Py_SetRecursionLimit(new_limit);
610 Py_INCREF(Py_None);
611 return Py_None;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000612}
613
Mark Dickinsondc787d22010-05-23 13:33:13 +0000614static PyTypeObject Hash_InfoType;
615
616PyDoc_STRVAR(hash_info_doc,
617"hash_info\n\
618\n\
619A struct sequence providing parameters used for computing\n\
620numeric hashes. The attributes are read only.");
621
622static PyStructSequence_Field hash_info_fields[] = {
623 {"width", "width of the type used for hashing, in bits"},
624 {"modulus", "prime number giving the modulus on which the hash "
625 "function is based"},
626 {"inf", "value to be used for hash of a positive infinity"},
627 {"nan", "value to be used for hash of a nan"},
628 {"imag", "multiplier used for the imaginary part of a complex number"},
629 {NULL, NULL}
630};
631
632static PyStructSequence_Desc hash_info_desc = {
633 "sys.hash_info",
634 hash_info_doc,
635 hash_info_fields,
636 5,
637};
638
Matthias Klosed885e952010-07-06 10:53:30 +0000639static PyObject *
Mark Dickinsondc787d22010-05-23 13:33:13 +0000640get_hash_info(void)
641{
642 PyObject *hash_info;
643 int field = 0;
644 hash_info = PyStructSequence_New(&Hash_InfoType);
645 if (hash_info == NULL)
646 return NULL;
647 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000648 PyLong_FromLong(8*sizeof(Py_hash_t)));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000649 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000650 PyLong_FromSsize_t(_PyHASH_MODULUS));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000651 PyStructSequence_SET_ITEM(hash_info, field++,
652 PyLong_FromLong(_PyHASH_INF));
653 PyStructSequence_SET_ITEM(hash_info, field++,
654 PyLong_FromLong(_PyHASH_NAN));
655 PyStructSequence_SET_ITEM(hash_info, field++,
656 PyLong_FromLong(_PyHASH_IMAG));
657 if (PyErr_Occurred()) {
658 Py_CLEAR(hash_info);
659 return NULL;
660 }
661 return hash_info;
662}
663
664
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000665PyDoc_STRVAR(setrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000666"setrecursionlimit(n)\n\
667\n\
668Set the maximum depth of the Python interpreter stack to n. This\n\
669limit prevents infinite recursion from causing an overflow of the C\n\
670stack and crashing Python. The highest possible limit is platform-\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000671dependent."
672);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000673
674static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000675sys_getrecursionlimit(PyObject *self)
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000676{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 return PyLong_FromLong(Py_GetRecursionLimit());
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000678}
679
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000680PyDoc_STRVAR(getrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000681"getrecursionlimit()\n\
682\n\
683Return the current value of the recursion limit, the maximum depth\n\
684of the Python interpreter stack. This limit prevents infinite\n\
Jack Jansene739a0d2002-06-26 20:39:20 +0000685recursion from causing an overflow of the C stack and crashing Python."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000686);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000687
Mark Hammond8696ebc2002-10-08 02:44:31 +0000688#ifdef MS_WINDOWS
689PyDoc_STRVAR(getwindowsversion_doc,
690"getwindowsversion()\n\
691\n\
Eric Smithf7bb5782010-01-27 00:44:57 +0000692Return information about the running version of Windows as a named tuple.\n\
693The members are named: major, minor, build, platform, service_pack,\n\
694service_pack_major, service_pack_minor, suite_mask, and product_type. For\n\
Ezio Melotti4969f702011-03-15 05:59:46 +0200695backward compatibility, only the first 5 items are available by indexing.\n\
Eric Smithf7bb5782010-01-27 00:44:57 +0000696All elements are numbers, except service_pack which is a string. Platform\n\
697may be 0 for win32s, 1 for Windows 9x/ME, 2 for Windows NT/2000/XP/Vista/7,\n\
6983 for Windows CE. Product_type may be 1 for a workstation, 2 for a domain\n\
699controller, 3 for a server."
Mark Hammond8696ebc2002-10-08 02:44:31 +0000700);
701
Eric Smithf7bb5782010-01-27 00:44:57 +0000702static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};
703
704static PyStructSequence_Field windows_version_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 {"major", "Major version number"},
706 {"minor", "Minor version number"},
707 {"build", "Build number"},
708 {"platform", "Operating system platform"},
709 {"service_pack", "Latest Service Pack installed on the system"},
710 {"service_pack_major", "Service Pack major version number"},
711 {"service_pack_minor", "Service Pack minor version number"},
712 {"suite_mask", "Bit mask identifying available product suites"},
713 {"product_type", "System product type"},
714 {0}
Eric Smithf7bb5782010-01-27 00:44:57 +0000715};
716
717static PyStructSequence_Desc windows_version_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 "sys.getwindowsversion", /* name */
719 getwindowsversion_doc, /* doc */
720 windows_version_fields, /* fields */
721 5 /* For backward compatibility,
722 only the first 5 items are accessible
723 via indexing, the rest are name only */
Eric Smithf7bb5782010-01-27 00:44:57 +0000724};
725
Mark Hammond8696ebc2002-10-08 02:44:31 +0000726static PyObject *
727sys_getwindowsversion(PyObject *self)
728{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000729 PyObject *version;
730 int pos = 0;
731 OSVERSIONINFOEX ver;
732 ver.dwOSVersionInfoSize = sizeof(ver);
733 if (!GetVersionEx((OSVERSIONINFO*) &ver))
734 return PyErr_SetFromWindowsErr(0);
Eric Smithf7bb5782010-01-27 00:44:57 +0000735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 version = PyStructSequence_New(&WindowsVersionType);
737 if (version == NULL)
738 return NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +0000739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion));
741 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion));
742 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber));
743 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId));
744 PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromString(ver.szCSDVersion));
745 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor));
746 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor));
747 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask));
748 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType));
Eric Smithf7bb5782010-01-27 00:44:57 +0000749
Serhiy Storchaka48d761e2013-12-17 15:11:24 +0200750 if (PyErr_Occurred()) {
751 Py_DECREF(version);
752 return NULL;
753 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000754 return version;
Mark Hammond8696ebc2002-10-08 02:44:31 +0000755}
756
757#endif /* MS_WINDOWS */
758
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000759#ifdef HAVE_DLOPEN
760static PyObject *
761sys_setdlopenflags(PyObject *self, PyObject *args)
762{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000763 int new_val;
764 PyThreadState *tstate = PyThreadState_GET();
765 if (!PyArg_ParseTuple(args, "i:setdlopenflags", &new_val))
766 return NULL;
767 if (!tstate)
768 return NULL;
769 tstate->interp->dlopenflags = new_val;
770 Py_INCREF(Py_None);
771 return Py_None;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000772}
773
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000774PyDoc_STRVAR(setdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000775"setdlopenflags(n) -> None\n\
776\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000777Set the flags used by the interpreter for dlopen calls, such as when the\n\
778interpreter loads extension modules. Among other things, this will enable\n\
779a lazy resolving of symbols when importing a module, if called as\n\
780sys.setdlopenflags(0). To share symbols across extension modules, call as\n\
781sys.setdlopenflags(ctypes.RTLD_GLOBAL). Symbolic names for the flag modules\n\
Victor Stinnerf4afa432011-10-31 11:48:09 +0100782can be found in the os module (RTLD_xxx constants, e.g. os.RTLD_LAZY).");
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000783
784static PyObject *
785sys_getdlopenflags(PyObject *self, PyObject *args)
786{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 PyThreadState *tstate = PyThreadState_GET();
788 if (!tstate)
789 return NULL;
790 return PyLong_FromLong(tstate->interp->dlopenflags);
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000791}
792
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000793PyDoc_STRVAR(getdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000794"getdlopenflags() -> int\n\
795\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000796Return the current value of the flags that are used for dlopen calls.\n\
797The flag constants are defined in the ctypes and DLFCN modules.");
798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799#endif /* HAVE_DLOPEN */
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000800
Guido van Rossum14b4adb1992-09-03 20:25:30 +0000801#ifdef USE_MALLOPT
802/* Link with -lmalloc (or -lmpc) on an SGI */
803#include <malloc.h>
804
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000805static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000806sys_mdebug(PyObject *self, PyObject *args)
Guido van Rossum14b4adb1992-09-03 20:25:30 +0000807{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 int flag;
809 if (!PyArg_ParseTuple(args, "i:mdebug", &flag))
810 return NULL;
811 mallopt(M_DEBUG, flag);
812 Py_INCREF(Py_None);
813 return Py_None;
Guido van Rossum14b4adb1992-09-03 20:25:30 +0000814}
815#endif /* USE_MALLOPT */
816
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000817static PyObject *
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000818sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000819{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 PyObject *res = NULL;
Benjamin Petersonce798522012-01-22 11:24:29 -0500821 static PyObject *gc_head_size = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000822 static char *kwlist[] = {"object", "default", 0};
823 PyObject *o, *dflt = NULL;
824 PyObject *method;
Benjamin Petersonce798522012-01-22 11:24:29 -0500825 _Py_IDENTIFIER(__sizeof__);
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000826
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000827 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
828 kwlist, &o, &dflt))
829 return NULL;
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 /* Initialize static variable for GC head size */
832 if (gc_head_size == NULL) {
833 gc_head_size = PyLong_FromSsize_t(sizeof(PyGC_Head));
834 if (gc_head_size == NULL)
835 return NULL;
836 }
Benjamin Petersona5758c02009-05-09 18:15:04 +0000837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 /* Make sure the type is initialized. float gets initialized late */
839 if (PyType_Ready(Py_TYPE(o)) < 0)
840 return NULL;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000841
Benjamin Petersonce798522012-01-22 11:24:29 -0500842 method = _PyObject_LookupSpecial(o, &PyId___sizeof__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000843 if (method == NULL) {
844 if (!PyErr_Occurred())
845 PyErr_Format(PyExc_TypeError,
846 "Type %.100s doesn't define __sizeof__",
847 Py_TYPE(o)->tp_name);
848 }
849 else {
850 res = PyObject_CallFunctionObjArgs(method, NULL);
851 Py_DECREF(method);
852 }
853
854 /* Has a default value been given */
855 if ((res == NULL) && (dflt != NULL) &&
856 PyErr_ExceptionMatches(PyExc_TypeError))
857 {
858 PyErr_Clear();
859 Py_INCREF(dflt);
860 return dflt;
861 }
862 else if (res == NULL)
863 return res;
864
865 /* add gc_head size */
866 if (PyObject_IS_GC(o)) {
867 PyObject *tmp = res;
868 res = PyNumber_Add(tmp, gc_head_size);
869 Py_DECREF(tmp);
870 }
871 return res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000872}
873
874PyDoc_STRVAR(getsizeof_doc,
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000875"getsizeof(object, default) -> int\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000876\n\
877Return the size of object in bytes.");
878
879static PyObject *
Fred Drakea7688822001-10-24 20:47:48 +0000880sys_getrefcount(PyObject *self, PyObject *arg)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000881{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 return PyLong_FromSsize_t(arg->ob_refcnt);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000883}
884
Tim Peters4be93d02002-07-07 19:59:50 +0000885#ifdef Py_REF_DEBUG
Mark Hammond440d8982000-06-20 08:12:48 +0000886static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000887sys_gettotalrefcount(PyObject *self)
Mark Hammond440d8982000-06-20 08:12:48 +0000888{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 return PyLong_FromSsize_t(_Py_GetRefTotal());
Mark Hammond440d8982000-06-20 08:12:48 +0000890}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000891#endif /* Py_REF_DEBUG */
Mark Hammond440d8982000-06-20 08:12:48 +0000892
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000893PyDoc_STRVAR(getrefcount_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000894"getrefcount(object) -> integer\n\
895\n\
Fred Drakeba3ff1b2002-06-20 21:36:19 +0000896Return the reference count of object. The count returned is generally\n\
897one higher than you might expect, because it includes the (temporary)\n\
898reference as an argument to getrefcount()."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000899);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000900
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000901#ifdef COUNT_ALLOCS
902static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000903sys_getcounts(PyObject *self)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000904{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 extern PyObject *get_counts(void);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 return get_counts();
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000908}
909#endif
910
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000911PyDoc_STRVAR(getframe_doc,
Barry Warsawb6a54d22000-12-06 21:47:46 +0000912"_getframe([depth]) -> frameobject\n\
913\n\
914Return a frame object from the call stack. If optional integer depth is\n\
915given, return the frame object that many calls below the top of the stack.\n\
916If that is deeper than the call stack, ValueError is raised. The default\n\
917for depth is zero, returning the frame at the top of the call stack.\n\
918\n\
919This function should be used for internal and specialized\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000920purposes only."
921);
Barry Warsawb6a54d22000-12-06 21:47:46 +0000922
923static PyObject *
924sys_getframe(PyObject *self, PyObject *args)
925{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 PyFrameObject *f = PyThreadState_GET()->frame;
927 int depth = -1;
Barry Warsawb6a54d22000-12-06 21:47:46 +0000928
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 if (!PyArg_ParseTuple(args, "|i:_getframe", &depth))
930 return NULL;
Barry Warsawb6a54d22000-12-06 21:47:46 +0000931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 while (depth > 0 && f != NULL) {
933 f = f->f_back;
934 --depth;
935 }
936 if (f == NULL) {
937 PyErr_SetString(PyExc_ValueError,
938 "call stack is not deep enough");
939 return NULL;
940 }
941 Py_INCREF(f);
942 return (PyObject*)f;
Barry Warsawb6a54d22000-12-06 21:47:46 +0000943}
944
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000945PyDoc_STRVAR(current_frames_doc,
946"_current_frames() -> dictionary\n\
947\n\
948Return a dictionary mapping each current thread T's thread id to T's\n\
949current stack frame.\n\
950\n\
951This function should be used for specialized purposes only."
952);
953
954static PyObject *
955sys_current_frames(PyObject *self, PyObject *noargs)
956{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 return _PyThread_CurrentFrames();
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000958}
959
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000960PyDoc_STRVAR(call_tracing_doc,
961"call_tracing(func, args) -> object\n\
962\n\
963Call func(*args), while tracing is enabled. The tracing state is\n\
964saved, and restored afterwards. This is intended to be called from\n\
965a debugger from a checkpoint, to recursively debug some other code."
966);
967
968static PyObject *
969sys_call_tracing(PyObject *self, PyObject *args)
970{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 PyObject *func, *funcargs;
972 if (!PyArg_ParseTuple(args, "OO!:call_tracing", &func, &PyTuple_Type, &funcargs))
973 return NULL;
974 return _PyEval_CallTracing(func, funcargs);
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000975}
976
Jeremy Hylton985eba52003-02-05 23:13:00 +0000977PyDoc_STRVAR(callstats_doc,
978"callstats() -> tuple of integers\n\
979\n\
980Return a tuple of function call statistics, if CALL_PROFILE was defined\n\
981when Python was built. Otherwise, return None.\n\
982\n\
983When enabled, this function returns detailed, implementation-specific\n\
984details about the number of function calls executed. The return value is\n\
985a 11-tuple where the entries in the tuple are counts of:\n\
9860. all function calls\n\
9871. calls to PyFunction_Type objects\n\
9882. PyFunction calls that do not create an argument tuple\n\
9893. PyFunction calls that do not create an argument tuple\n\
990 and bypass PyEval_EvalCodeEx()\n\
9914. PyMethod calls\n\
9925. PyMethod calls on bound methods\n\
9936. PyType calls\n\
9947. PyCFunction calls\n\
9958. generator calls\n\
9969. All other calls\n\
99710. Number of stack pops performed by call_function()"
998);
Barry Warsawb6a54d22000-12-06 21:47:46 +0000999
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001000#ifdef __cplusplus
1001extern "C" {
1002#endif
1003
David Malcolm49526f42012-06-22 14:55:41 -04001004static PyObject *
1005sys_debugmallocstats(PyObject *self, PyObject *args)
1006{
1007#ifdef WITH_PYMALLOC
1008 _PyObject_DebugMallocStats(stderr);
1009 fputc('\n', stderr);
1010#endif
1011 _PyObject_DebugTypeStats(stderr);
1012
1013 Py_RETURN_NONE;
1014}
1015PyDoc_STRVAR(debugmallocstats_doc,
1016"_debugmallocstats()\n\
1017\n\
1018Print summary info to stderr about the state of\n\
1019pymalloc's structures.\n\
1020\n\
1021In Py_DEBUG mode, also perform some expensive internal consistency\n\
1022checks.\n\
1023");
1024
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001025#ifdef Py_TRACE_REFS
Guido van Rossumded690f1996-05-24 20:48:31 +00001026/* Defined in objects.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001027extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001028#endif
Guido van Rossumded690f1996-05-24 20:48:31 +00001029
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001030#ifdef DYNAMIC_EXECUTION_PROFILE
1031/* Defined in ceval.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001032extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001033#endif
1034
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001035#ifdef __cplusplus
1036}
1037#endif
1038
Christian Heimes15ebc882008-02-04 18:48:49 +00001039static PyObject *
1040sys_clear_type_cache(PyObject* self, PyObject* args)
1041{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 PyType_ClearCache();
1043 Py_RETURN_NONE;
Christian Heimes15ebc882008-02-04 18:48:49 +00001044}
1045
1046PyDoc_STRVAR(sys_clear_type_cache__doc__,
1047"_clear_type_cache() -> None\n\
1048Clear the internal type lookup cache.");
1049
1050
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001051static PyMethodDef sys_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 /* Might as well keep this in alphabetic order */
1053 {"callstats", (PyCFunction)PyEval_GetCallStats, METH_NOARGS,
1054 callstats_doc},
1055 {"_clear_type_cache", sys_clear_type_cache, METH_NOARGS,
1056 sys_clear_type_cache__doc__},
1057 {"_current_frames", sys_current_frames, METH_NOARGS,
1058 current_frames_doc},
1059 {"displayhook", sys_displayhook, METH_O, displayhook_doc},
1060 {"exc_info", sys_exc_info, METH_NOARGS, exc_info_doc},
1061 {"excepthook", sys_excepthook, METH_VARARGS, excepthook_doc},
1062 {"exit", sys_exit, METH_VARARGS, exit_doc},
1063 {"getdefaultencoding", (PyCFunction)sys_getdefaultencoding,
1064 METH_NOARGS, getdefaultencoding_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001065#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001066 {"getdlopenflags", (PyCFunction)sys_getdlopenflags, METH_NOARGS,
1067 getdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001068#endif
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001069#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 {"getcounts", (PyCFunction)sys_getcounts, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001071#endif
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001072#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001074#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 {"getfilesystemencoding", (PyCFunction)sys_getfilesystemencoding,
1076 METH_NOARGS, getfilesystemencoding_doc},
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001077#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 {"getobjects", _Py_GetObjects, METH_VARARGS},
Tim Peters4be93d02002-07-07 19:59:50 +00001079#endif
1080#ifdef Py_REF_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 {"gettotalrefcount", (PyCFunction)sys_gettotalrefcount, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001082#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 {"getrefcount", (PyCFunction)sys_getrefcount, METH_O, getrefcount_doc},
1084 {"getrecursionlimit", (PyCFunction)sys_getrecursionlimit, METH_NOARGS,
1085 getrecursionlimit_doc},
1086 {"getsizeof", (PyCFunction)sys_getsizeof,
1087 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
1088 {"_getframe", sys_getframe, METH_VARARGS, getframe_doc},
Mark Hammond8696ebc2002-10-08 02:44:31 +00001089#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001090 {"getwindowsversion", (PyCFunction)sys_getwindowsversion, METH_NOARGS,
1091 getwindowsversion_doc},
Mark Hammond8696ebc2002-10-08 02:44:31 +00001092#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093 {"intern", sys_intern, METH_VARARGS, intern_doc},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001094#ifdef USE_MALLOPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 {"mdebug", sys_mdebug, METH_VARARGS},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001096#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 {"setcheckinterval", sys_setcheckinterval, METH_VARARGS,
1098 setcheckinterval_doc},
1099 {"getcheckinterval", sys_getcheckinterval, METH_NOARGS,
1100 getcheckinterval_doc},
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001101#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 {"setswitchinterval", sys_setswitchinterval, METH_VARARGS,
1103 setswitchinterval_doc},
1104 {"getswitchinterval", sys_getswitchinterval, METH_NOARGS,
1105 getswitchinterval_doc},
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001106#endif
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001107#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001108 {"setdlopenflags", sys_setdlopenflags, METH_VARARGS,
1109 setdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001110#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 {"setprofile", sys_setprofile, METH_O, setprofile_doc},
1112 {"getprofile", sys_getprofile, METH_NOARGS, getprofile_doc},
1113 {"setrecursionlimit", sys_setrecursionlimit, METH_VARARGS,
1114 setrecursionlimit_doc},
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00001115#ifdef WITH_TSC
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 {"settscdump", sys_settscdump, METH_VARARGS, settscdump_doc},
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00001117#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 {"settrace", sys_settrace, METH_O, settrace_doc},
1119 {"gettrace", sys_gettrace, METH_NOARGS, gettrace_doc},
1120 {"call_tracing", sys_call_tracing, METH_VARARGS, call_tracing_doc},
David Malcolm49526f42012-06-22 14:55:41 -04001121 {"_debugmallocstats", sys_debugmallocstats, METH_VARARGS,
1122 debugmallocstats_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 {NULL, NULL} /* sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +00001124};
1125
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001126static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001127list_builtin_module_names(void)
Guido van Rossum34679b71993-01-26 13:33:44 +00001128{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001129 PyObject *list = PyList_New(0);
1130 int i;
1131 if (list == NULL)
1132 return NULL;
1133 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1134 PyObject *name = PyUnicode_FromString(
1135 PyImport_Inittab[i].name);
1136 if (name == NULL)
1137 break;
1138 PyList_Append(list, name);
1139 Py_DECREF(name);
1140 }
1141 if (PyList_Sort(list) != 0) {
1142 Py_DECREF(list);
1143 list = NULL;
1144 }
1145 if (list) {
1146 PyObject *v = PyList_AsTuple(list);
1147 Py_DECREF(list);
1148 list = v;
1149 }
1150 return list;
Guido van Rossum34679b71993-01-26 13:33:44 +00001151}
1152
Guido van Rossum23fff912000-12-15 22:02:05 +00001153static PyObject *warnoptions = NULL;
1154
1155void
1156PySys_ResetWarnOptions(void)
1157{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001158 if (warnoptions == NULL || !PyList_Check(warnoptions))
1159 return;
1160 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
Guido van Rossum23fff912000-12-15 22:02:05 +00001161}
1162
1163void
Victor Stinner9ca9c252010-05-19 16:53:30 +00001164PySys_AddWarnOptionUnicode(PyObject *unicode)
Guido van Rossum23fff912000-12-15 22:02:05 +00001165{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
1167 Py_XDECREF(warnoptions);
1168 warnoptions = PyList_New(0);
1169 if (warnoptions == NULL)
1170 return;
1171 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00001172 PyList_Append(warnoptions, unicode);
1173}
1174
1175void
1176PySys_AddWarnOption(const wchar_t *s)
1177{
1178 PyObject *unicode;
1179 unicode = PyUnicode_FromWideChar(s, -1);
1180 if (unicode == NULL)
1181 return;
1182 PySys_AddWarnOptionUnicode(unicode);
1183 Py_DECREF(unicode);
Guido van Rossum23fff912000-12-15 22:02:05 +00001184}
1185
Christian Heimes33fe8092008-04-13 13:53:33 +00001186int
1187PySys_HasWarnOptions(void)
1188{
1189 return (warnoptions != NULL && (PyList_Size(warnoptions) > 0)) ? 1 : 0;
1190}
1191
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001192static PyObject *xoptions = NULL;
1193
1194static PyObject *
1195get_xoptions(void)
1196{
1197 if (xoptions == NULL || !PyDict_Check(xoptions)) {
1198 Py_XDECREF(xoptions);
1199 xoptions = PyDict_New();
1200 }
1201 return xoptions;
1202}
1203
1204void
1205PySys_AddXOption(const wchar_t *s)
1206{
1207 PyObject *opts;
1208 PyObject *name = NULL, *value = NULL;
1209 const wchar_t *name_end;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001210
1211 opts = get_xoptions();
1212 if (opts == NULL)
1213 goto error;
1214
1215 name_end = wcschr(s, L'=');
1216 if (!name_end) {
1217 name = PyUnicode_FromWideChar(s, -1);
1218 value = Py_True;
1219 Py_INCREF(value);
1220 }
1221 else {
1222 name = PyUnicode_FromWideChar(s, name_end - s);
1223 value = PyUnicode_FromWideChar(name_end + 1, -1);
1224 }
1225 if (name == NULL || value == NULL)
1226 goto error;
Brett Cannonb94767f2011-02-22 20:15:44 +00001227 PyDict_SetItem(opts, name, value);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001228 Py_DECREF(name);
1229 Py_DECREF(value);
1230 return;
1231
1232error:
1233 Py_XDECREF(name);
1234 Py_XDECREF(value);
1235 /* No return value, therefore clear error state if possible */
1236 if (_Py_atomic_load_relaxed(&_PyThreadState_Current))
1237 PyErr_Clear();
1238}
1239
1240PyObject *
1241PySys_GetXOptions(void)
1242{
1243 return get_xoptions();
1244}
1245
Guido van Rossum40552d01998-08-06 03:34:39 +00001246/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
1247 Two literals concatenated works just fine. If you have a K&R compiler
1248 or other abomination that however *does* understand longer strings,
1249 get rid of the !!! comment in the middle and the quotes that surround it. */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001250PyDoc_VAR(sys_doc) =
1251PyDoc_STR(
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001252"This module provides access to some objects used or maintained by the\n\
1253interpreter and to functions that interact strongly with the interpreter.\n\
1254\n\
1255Dynamic objects:\n\
1256\n\
1257argv -- command line arguments; argv[0] is the script pathname if known\n\
1258path -- module search path; path[0] is the script directory, else ''\n\
1259modules -- dictionary of loaded modules\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001260\n\
1261displayhook -- called to show results in an interactive session\n\
1262excepthook -- called to handle any uncaught exception other than SystemExit\n\
1263 To customize printing in an interactive session or to install a custom\n\
1264 top-level exception handler, assign other functions to replace these.\n\
1265\n\
Benjamin Peterson06157a42008-07-15 00:28:36 +00001266stdin -- standard input file object; used by input()\n\
Georg Brandl88fc6642007-02-09 21:28:07 +00001267stdout -- standard output file object; used by print()\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001268stderr -- standard error object; used for error messages\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001269 By assigning other file objects (or objects that behave like files)\n\
1270 to these, it is possible to redirect all of the interpreter's I/O.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001271\n\
1272last_type -- type of last uncaught exception\n\
1273last_value -- value of last uncaught exception\n\
1274last_traceback -- traceback of last uncaught exception\n\
1275 These three are only available in an interactive session after a\n\
1276 traceback has been printed.\n\
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001277"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001278)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001279/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001280PyDoc_STR(
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001281"\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001282Static objects:\n\
1283\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001284builtin_module_names -- tuple of module names built into this interpreter\n\
1285copyright -- copyright notice pertaining to this interpreter\n\
1286exec_prefix -- prefix used to find the machine-specific Python library\n\
Petri Lehtinen4b0eab62012-02-02 21:23:15 +02001287executable -- absolute path of the executable binary of the Python interpreter\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001288float_info -- a struct sequence with information about the float implementation.\n\
1289float_repr_style -- string indicating the style of repr() output for floats\n\
1290hexversion -- version information encoded as a single integer\n\
Barry Warsaw409da152012-06-03 16:18:47 -04001291implementation -- Python implementation information.\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00001292int_info -- a struct sequence with information about the int implementation.\n\
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00001293maxsize -- the largest supported length of containers.\n\
Ezio Melotti48a2f8f2011-09-29 00:18:19 +03001294maxunicode -- the value of the largest Unicode codepoint\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001295platform -- platform identifier\n\
1296prefix -- prefix used to find the Python library\n\
1297thread_info -- a struct sequence with information about the thread implementation.\n\
Fred Drake801c08d2000-04-13 15:29:10 +00001298version -- the version of this interpreter as a string\n\
Eric Smith0e5b5622009-02-06 01:32:42 +00001299version_info -- version information as a named tuple\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001300"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001301)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001302#ifdef MS_WINDOWS
1303/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001304PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001305"dllhandle -- [Windows only] integer handle of the Python DLL\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001306winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001307"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001308)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001309#endif /* MS_WINDOWS */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001310PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001311"__stdin__ -- the original stdin; don't touch!\n\
1312__stdout__ -- the original stdout; don't touch!\n\
1313__stderr__ -- the original stderr; don't touch!\n\
1314__displayhook__ -- the original displayhook; don't touch!\n\
1315__excepthook__ -- the original excepthook; don't touch!\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001316\n\
1317Functions:\n\
1318\n\
Georg Brandl1a3284e2007-12-02 09:40:06 +00001319displayhook() -- print an object to the screen, and save it in builtins._\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001320excepthook() -- print an exception and its traceback to sys.stderr\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001321exc_info() -- return thread-safe information about the current exception\n\
1322exit() -- exit the interpreter by raising SystemExit\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001323getdlopenflags() -- returns flags to be used for dlopen() calls\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00001324getprofile() -- get the global profiling function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001325getrefcount() -- return the reference count for an object (plus one :-)\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001326getrecursionlimit() -- return the max recursion depth for the interpreter\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001327getsizeof() -- return the size of an object in bytes\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00001328gettrace() -- get the global debug tracing function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001329setcheckinterval() -- control how often the interpreter checks for events\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001330setdlopenflags() -- set the flags to be used for dlopen() calls\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001331setprofile() -- set the global profiling function\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001332setrecursionlimit() -- set the max recursion depth for the interpreter\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001333settrace() -- set the global debug tracing function\n\
Fred Drakeccede592000-08-14 20:59:57 +00001334"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001335)
Fred Drakeccede592000-08-14 20:59:57 +00001336/* end of sys_doc */ ;
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001337
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001338
1339PyDoc_STRVAR(flags__doc__,
1340"sys.flags\n\
1341\n\
1342Flags provided through command line arguments or environment vars.");
1343
1344static PyTypeObject FlagsType;
1345
1346static PyStructSequence_Field flags_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 {"debug", "-d"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348 {"inspect", "-i"},
1349 {"interactive", "-i"},
1350 {"optimize", "-O or -OO"},
1351 {"dont_write_bytecode", "-B"},
1352 {"no_user_site", "-s"},
1353 {"no_site", "-S"},
1354 {"ignore_environment", "-E"},
1355 {"verbose", "-v"},
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001356#ifdef RISCOS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001357 {"riscos_wimp", "???"},
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001358#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 /* {"unbuffered", "-u"}, */
1360 /* {"skip_first", "-x"}, */
Georg Brandl8aa7e992010-12-28 18:30:18 +00001361 {"bytes_warning", "-b"},
1362 {"quiet", "-q"},
Georg Brandl09a7c722012-02-20 21:31:46 +01001363 {"hash_randomization", "-R"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001364 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001365};
1366
1367static PyStructSequence_Desc flags_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 "sys.flags", /* name */
1369 flags__doc__, /* doc */
1370 flags_fields, /* fields */
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001371#ifdef RISCOS
Georg Brandl09a7c722012-02-20 21:31:46 +01001372 13
Éric Araujobe3bd572011-03-26 01:55:15 +01001373#else
Georg Brandl2fb477c2012-02-21 00:33:36 +01001374 12
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001375#endif
1376};
1377
1378static PyObject*
1379make_flags(void)
1380{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001381 int pos = 0;
1382 PyObject *seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001384 seq = PyStructSequence_New(&FlagsType);
1385 if (seq == NULL)
1386 return NULL;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001387
1388#define SetFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001391 SetFlag(Py_DebugFlag);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001392 SetFlag(Py_InspectFlag);
1393 SetFlag(Py_InteractiveFlag);
1394 SetFlag(Py_OptimizeFlag);
1395 SetFlag(Py_DontWriteBytecodeFlag);
1396 SetFlag(Py_NoUserSiteDirectory);
1397 SetFlag(Py_NoSiteFlag);
1398 SetFlag(Py_IgnoreEnvironmentFlag);
1399 SetFlag(Py_VerboseFlag);
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001400#ifdef RISCOS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001401 SetFlag(Py_RISCOSWimpFlag);
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001402#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 /* SetFlag(saw_unbuffered_flag); */
1404 /* SetFlag(skipfirstline); */
Christian Heimes33fe8092008-04-13 13:53:33 +00001405 SetFlag(Py_BytesWarningFlag);
Georg Brandl8aa7e992010-12-28 18:30:18 +00001406 SetFlag(Py_QuietFlag);
Georg Brandl2daf6ae2012-02-20 19:54:16 +01001407 SetFlag(Py_HashRandomizationFlag);
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001408#undef SetFlag
1409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 if (PyErr_Occurred()) {
Serhiy Storchaka87a854d2013-12-17 14:59:42 +02001411 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 return NULL;
1413 }
1414 return seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001415}
1416
Eric Smith0e5b5622009-02-06 01:32:42 +00001417PyDoc_STRVAR(version_info__doc__,
1418"sys.version_info\n\
1419\n\
1420Version information as a named tuple.");
1421
1422static PyTypeObject VersionInfoType;
1423
1424static PyStructSequence_Field version_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 {"major", "Major release number"},
1426 {"minor", "Minor release number"},
1427 {"micro", "Patch release number"},
1428 {"releaselevel", "'alpha', 'beta', 'candidate', or 'release'"},
1429 {"serial", "Serial release number"},
1430 {0}
Eric Smith0e5b5622009-02-06 01:32:42 +00001431};
1432
1433static PyStructSequence_Desc version_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001434 "sys.version_info", /* name */
1435 version_info__doc__, /* doc */
1436 version_info_fields, /* fields */
1437 5
Eric Smith0e5b5622009-02-06 01:32:42 +00001438};
1439
1440static PyObject *
1441make_version_info(void)
1442{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001443 PyObject *version_info;
1444 char *s;
1445 int pos = 0;
Eric Smith0e5b5622009-02-06 01:32:42 +00001446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001447 version_info = PyStructSequence_New(&VersionInfoType);
1448 if (version_info == NULL) {
1449 return NULL;
1450 }
Eric Smith0e5b5622009-02-06 01:32:42 +00001451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001452 /*
1453 * These release level checks are mutually exclusive and cover
1454 * the field, so don't get too fancy with the pre-processor!
1455 */
Eric Smith0e5b5622009-02-06 01:32:42 +00001456#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001457 s = "alpha";
Eric Smith0e5b5622009-02-06 01:32:42 +00001458#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001459 s = "beta";
Eric Smith0e5b5622009-02-06 01:32:42 +00001460#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001461 s = "candidate";
Eric Smith0e5b5622009-02-06 01:32:42 +00001462#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001463 s = "final";
Eric Smith0e5b5622009-02-06 01:32:42 +00001464#endif
1465
1466#define SetIntItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001467 PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00001468#define SetStrItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001469 PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00001470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001471 SetIntItem(PY_MAJOR_VERSION);
1472 SetIntItem(PY_MINOR_VERSION);
1473 SetIntItem(PY_MICRO_VERSION);
1474 SetStrItem(s);
1475 SetIntItem(PY_RELEASE_SERIAL);
Eric Smith0e5b5622009-02-06 01:32:42 +00001476#undef SetIntItem
1477#undef SetStrItem
1478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001479 if (PyErr_Occurred()) {
1480 Py_CLEAR(version_info);
1481 return NULL;
1482 }
1483 return version_info;
Eric Smith0e5b5622009-02-06 01:32:42 +00001484}
1485
Brett Cannon3adc7b72012-07-09 14:22:12 -04001486/* sys.implementation values */
1487#define NAME "cpython"
1488const char *_PySys_ImplName = NAME;
1489#define QUOTE(arg) #arg
1490#define STRIFY(name) QUOTE(name)
1491#define MAJOR STRIFY(PY_MAJOR_VERSION)
1492#define MINOR STRIFY(PY_MINOR_VERSION)
1493#define TAG NAME "-" MAJOR MINOR;
1494const char *_PySys_ImplCacheTag = TAG;
1495#undef NAME
1496#undef QUOTE
1497#undef STRIFY
1498#undef MAJOR
1499#undef MINOR
1500#undef TAG
1501
Barry Warsaw409da152012-06-03 16:18:47 -04001502static PyObject *
1503make_impl_info(PyObject *version_info)
1504{
1505 int res;
1506 PyObject *impl_info, *value, *ns;
1507
1508 impl_info = PyDict_New();
1509 if (impl_info == NULL)
1510 return NULL;
1511
1512 /* populate the dict */
1513
Brett Cannon3adc7b72012-07-09 14:22:12 -04001514 value = PyUnicode_FromString(_PySys_ImplName);
Barry Warsaw409da152012-06-03 16:18:47 -04001515 if (value == NULL)
1516 goto error;
1517 res = PyDict_SetItemString(impl_info, "name", value);
1518 Py_DECREF(value);
1519 if (res < 0)
1520 goto error;
1521
Brett Cannon3adc7b72012-07-09 14:22:12 -04001522 value = PyUnicode_FromString(_PySys_ImplCacheTag);
Barry Warsaw409da152012-06-03 16:18:47 -04001523 if (value == NULL)
1524 goto error;
1525 res = PyDict_SetItemString(impl_info, "cache_tag", value);
1526 Py_DECREF(value);
1527 if (res < 0)
1528 goto error;
Barry Warsaw409da152012-06-03 16:18:47 -04001529
1530 res = PyDict_SetItemString(impl_info, "version", version_info);
1531 if (res < 0)
1532 goto error;
1533
1534 value = PyLong_FromLong(PY_VERSION_HEX);
1535 if (value == NULL)
1536 goto error;
1537 res = PyDict_SetItemString(impl_info, "hexversion", value);
1538 Py_DECREF(value);
1539 if (res < 0)
1540 goto error;
1541
1542 /* dict ready */
1543
1544 ns = _PyNamespace_New(impl_info);
1545 Py_DECREF(impl_info);
1546 return ns;
1547
1548error:
1549 Py_CLEAR(impl_info);
1550 return NULL;
1551}
1552
Martin v. Löwis1a214512008-06-11 05:26:20 +00001553static struct PyModuleDef sysmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001554 PyModuleDef_HEAD_INIT,
1555 "sys",
1556 sys_doc,
1557 -1, /* multiple "initialization" just copies the module dict. */
1558 sys_methods,
1559 NULL,
1560 NULL,
1561 NULL,
1562 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001563};
1564
Guido van Rossum25ce5661997-08-02 03:10:38 +00001565PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001566_PySys_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001567{
Barry Warsaw409da152012-06-03 16:18:47 -04001568 PyObject *m, *v, *sysdict, *version_info;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001569 char *s;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001571 m = PyModule_Create(&sysmodule);
1572 if (m == NULL)
1573 return NULL;
1574 sysdict = PyModule_GetDict(m);
1575#define SET_SYS_FROM_STRING(key, value) \
1576 v = value; \
1577 if (v != NULL) \
1578 PyDict_SetItemString(sysdict, key, v); \
1579 Py_XDECREF(v)
Guido van Rossum25ce5661997-08-02 03:10:38 +00001580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001581 /* Check that stdin is not a directory
1582 Using shell redirection, you can redirect stdin to a directory,
1583 crashing the Python interpreter. Catch this common mistake here
1584 and output a useful error message. Note that under MS Windows,
1585 the shell already prevents that. */
Martin v. Löwisec59d042009-01-12 07:59:10 +00001586#if !defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001587 {
1588 struct stat sb;
1589 if (fstat(fileno(stdin), &sb) == 0 &&
1590 S_ISDIR(sb.st_mode)) {
1591 /* There's nothing more we can do. */
1592 /* Py_FatalError() will core dump, so just exit. */
1593 PySys_WriteStderr("Python error: <stdin> is a directory, cannot continue\n");
1594 exit(EXIT_FAILURE);
1595 }
1596 }
Martin v. Löwisec59d042009-01-12 07:59:10 +00001597#endif
Neal Norwitz11bd1192005-10-03 00:54:56 +00001598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001599 /* stdin/stdout/stderr are now set by pythonrun.c */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 PyDict_SetItemString(sysdict, "__displayhook__",
1602 PyDict_GetItemString(sysdict, "displayhook"));
1603 PyDict_SetItemString(sysdict, "__excepthook__",
1604 PyDict_GetItemString(sysdict, "excepthook"));
1605 SET_SYS_FROM_STRING("version",
1606 PyUnicode_FromString(Py_GetVersion()));
1607 SET_SYS_FROM_STRING("hexversion",
1608 PyLong_FromLong(PY_VERSION_HEX));
Georg Brandl1ca2e792011-03-05 20:51:24 +01001609 SET_SYS_FROM_STRING("_mercurial",
1610 Py_BuildValue("(szz)", "CPython", _Py_hgidentifier(),
1611 _Py_hgversion()));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001612 SET_SYS_FROM_STRING("dont_write_bytecode",
1613 PyBool_FromLong(Py_DontWriteBytecodeFlag));
1614 SET_SYS_FROM_STRING("api_version",
1615 PyLong_FromLong(PYTHON_API_VERSION));
1616 SET_SYS_FROM_STRING("copyright",
1617 PyUnicode_FromString(Py_GetCopyright()));
1618 SET_SYS_FROM_STRING("platform",
1619 PyUnicode_FromString(Py_GetPlatform()));
1620 SET_SYS_FROM_STRING("executable",
1621 PyUnicode_FromWideChar(
1622 Py_GetProgramFullPath(), -1));
1623 SET_SYS_FROM_STRING("prefix",
1624 PyUnicode_FromWideChar(Py_GetPrefix(), -1));
1625 SET_SYS_FROM_STRING("exec_prefix",
1626 PyUnicode_FromWideChar(Py_GetExecPrefix(), -1));
Vinay Sajip7ded1f02012-05-26 03:45:29 +01001627 SET_SYS_FROM_STRING("base_prefix",
1628 PyUnicode_FromWideChar(Py_GetPrefix(), -1));
1629 SET_SYS_FROM_STRING("base_exec_prefix",
1630 PyUnicode_FromWideChar(Py_GetExecPrefix(), -1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001631 SET_SYS_FROM_STRING("maxsize",
1632 PyLong_FromSsize_t(PY_SSIZE_T_MAX));
1633 SET_SYS_FROM_STRING("float_info",
1634 PyFloat_GetInfo());
1635 SET_SYS_FROM_STRING("int_info",
1636 PyLong_GetInfo());
Mark Dickinsondc787d22010-05-23 13:33:13 +00001637 /* initialize hash_info */
1638 if (Hash_InfoType.tp_name == 0)
1639 PyStructSequence_InitType(&Hash_InfoType, &hash_info_desc);
1640 SET_SYS_FROM_STRING("hash_info",
1641 get_hash_info());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001642 SET_SYS_FROM_STRING("maxunicode",
Ezio Melotti48a2f8f2011-09-29 00:18:19 +03001643 PyLong_FromLong(0x10FFFF));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001644 SET_SYS_FROM_STRING("builtin_module_names",
1645 list_builtin_module_names());
1646 {
1647 /* Assumes that longs are at least 2 bytes long.
1648 Should be safe! */
1649 unsigned long number = 1;
1650 char *value;
Fred Drake099325e2000-08-14 15:47:03 +00001651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 s = (char *) &number;
1653 if (s[0] == 0)
1654 value = "big";
1655 else
1656 value = "little";
1657 SET_SYS_FROM_STRING("byteorder",
1658 PyUnicode_FromString(value));
1659 }
Guido van Rossum8b9ea871996-08-23 18:14:47 +00001660#ifdef MS_COREDLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001661 SET_SYS_FROM_STRING("dllhandle",
1662 PyLong_FromVoidPtr(PyWin_DLLhModule));
1663 SET_SYS_FROM_STRING("winver",
1664 PyUnicode_FromString(PyWin_DLLVersionString));
Guido van Rossumc606fe11996-04-09 02:37:57 +00001665#endif
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00001666#ifdef ABIFLAGS
1667 SET_SYS_FROM_STRING("abiflags",
1668 PyUnicode_FromString(ABIFLAGS));
1669#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001670 if (warnoptions == NULL) {
1671 warnoptions = PyList_New(0);
1672 }
1673 else {
1674 Py_INCREF(warnoptions);
1675 }
1676 if (warnoptions != NULL) {
1677 PyDict_SetItemString(sysdict, "warnoptions", warnoptions);
1678 }
Tim Peters216b78b2006-01-06 02:40:53 +00001679
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001680 v = get_xoptions();
1681 if (v != NULL) {
1682 PyDict_SetItemString(sysdict, "_xoptions", v);
1683 }
1684
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 /* version_info */
1686 if (VersionInfoType.tp_name == 0)
1687 PyStructSequence_InitType(&VersionInfoType, &version_info_desc);
Barry Warsaw409da152012-06-03 16:18:47 -04001688 version_info = make_version_info();
1689 SET_SYS_FROM_STRING("version_info", version_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001690 /* prevent user from creating new instances */
1691 VersionInfoType.tp_init = NULL;
1692 VersionInfoType.tp_new = NULL;
Eric Smith0e5b5622009-02-06 01:32:42 +00001693
Barry Warsaw409da152012-06-03 16:18:47 -04001694 /* implementation */
1695 SET_SYS_FROM_STRING("implementation", make_impl_info(version_info));
1696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001697 /* flags */
1698 if (FlagsType.tp_name == 0)
1699 PyStructSequence_InitType(&FlagsType, &flags_desc);
1700 SET_SYS_FROM_STRING("flags", make_flags());
1701 /* prevent user from creating new instances */
1702 FlagsType.tp_init = NULL;
1703 FlagsType.tp_new = NULL;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001704
Eric Smithf7bb5782010-01-27 00:44:57 +00001705
1706#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001707 /* getwindowsversion */
1708 if (WindowsVersionType.tp_name == 0)
1709 PyStructSequence_InitType(&WindowsVersionType, &windows_version_desc);
1710 /* prevent user from creating new instances */
1711 WindowsVersionType.tp_init = NULL;
1712 WindowsVersionType.tp_new = NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +00001713#endif
1714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001715 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00001716#ifndef PY_NO_SHORT_FLOAT_REPR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001717 SET_SYS_FROM_STRING("float_repr_style",
1718 PyUnicode_FromString("short"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00001719#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001720 SET_SYS_FROM_STRING("float_repr_style",
1721 PyUnicode_FromString("legacy"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00001722#endif
1723
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001724#ifdef WITH_THREAD
1725 SET_SYS_FROM_STRING("thread_info", PyThread_GetInfo());
1726#endif
1727
Christian Heimes7b3ce6a2008-01-31 14:31:45 +00001728#undef SET_SYS_FROM_STRING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 if (PyErr_Occurred())
1730 return NULL;
1731 return m;
Guido van Rossum5b3138b1990-11-18 17:41:40 +00001732}
1733
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001734static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00001735makepathobject(const wchar_t *path, wchar_t delim)
Guido van Rossum5b3138b1990-11-18 17:41:40 +00001736{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001737 int i, n;
1738 const wchar_t *p;
1739 PyObject *v, *w;
Tim Peters216b78b2006-01-06 02:40:53 +00001740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001741 n = 1;
1742 p = path;
1743 while ((p = wcschr(p, delim)) != NULL) {
1744 n++;
1745 p++;
1746 }
1747 v = PyList_New(n);
1748 if (v == NULL)
1749 return NULL;
1750 for (i = 0; ; i++) {
1751 p = wcschr(path, delim);
1752 if (p == NULL)
1753 p = path + wcslen(path); /* End of string */
1754 w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
1755 if (w == NULL) {
1756 Py_DECREF(v);
1757 return NULL;
1758 }
1759 PyList_SetItem(v, i, w);
1760 if (*p == '\0')
1761 break;
1762 path = p+1;
1763 }
1764 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001765}
1766
1767void
Martin v. Löwis790465f2008-04-05 20:41:37 +00001768PySys_SetPath(const wchar_t *path)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001769{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001770 PyObject *v;
1771 if ((v = makepathobject(path, DELIM)) == NULL)
1772 Py_FatalError("can't create sys.path");
1773 if (PySys_SetObject("path", v) != 0)
1774 Py_FatalError("can't assign sys.path");
1775 Py_DECREF(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001776}
1777
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001778static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00001779makeargvobject(int argc, wchar_t **argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001780{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001781 PyObject *av;
1782 if (argc <= 0 || argv == NULL) {
1783 /* Ensure at least one (empty) argument is seen */
1784 static wchar_t *empty_argv[1] = {L""};
1785 argv = empty_argv;
1786 argc = 1;
1787 }
1788 av = PyList_New(argc);
1789 if (av != NULL) {
1790 int i;
1791 for (i = 0; i < argc; i++) {
Martin v. Löwisc16f3bd2003-05-03 09:14:54 +00001792#ifdef __VMS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001793 PyObject *v;
Martin v. Löwisc16f3bd2003-05-03 09:14:54 +00001794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001795 /* argv[0] is the script pathname if known */
1796 if (i == 0) {
1797 char* fn = decc$translate_vms(argv[0]);
1798 if ((fn == (char *)0) || fn == (char *)-1)
1799 v = PyUnicode_FromString(argv[0]);
1800 else
1801 v = PyUnicode_FromString(
1802 decc$translate_vms(argv[0]));
1803 } else
1804 v = PyUnicode_FromString(argv[i]);
Martin v. Löwisc16f3bd2003-05-03 09:14:54 +00001805#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001806 PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
Martin v. Löwisc16f3bd2003-05-03 09:14:54 +00001807#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001808 if (v == NULL) {
1809 Py_DECREF(av);
1810 av = NULL;
1811 break;
1812 }
1813 PyList_SetItem(av, i, v);
1814 }
1815 }
1816 return av;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001817}
1818
Nick Coghland26c18a2010-08-17 13:06:11 +00001819#define _HAVE_SCRIPT_ARGUMENT(argc, argv) \
1820 (argc > 0 && argv0 != NULL && \
1821 wcscmp(argv0, L"-c") != 0 && wcscmp(argv0, L"-m") != 0)
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001822
1823static void
1824sys_update_path(int argc, wchar_t **argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001825{
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001826 wchar_t *argv0;
1827 wchar_t *p = NULL;
1828 Py_ssize_t n = 0;
1829 PyObject *a;
1830 PyObject *path;
1831#ifdef HAVE_READLINK
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001832 wchar_t link[MAXPATHLEN+1];
1833 wchar_t argv0copy[2*MAXPATHLEN+1];
1834 int nr = 0;
1835#endif
Guido van Rossum162e38c2003-02-19 15:25:10 +00001836#if defined(HAVE_REALPATH)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001837 wchar_t fullpath[MAXPATHLEN];
Martin v. Löwisec59d042009-01-12 07:59:10 +00001838#elif defined(MS_WINDOWS) && !defined(MS_WINCE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001839 wchar_t fullpath[MAX_PATH];
Thomas Heller27bb71e2003-01-08 14:33:48 +00001840#endif
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001841
1842 path = PySys_GetObject("path");
1843 if (path == NULL)
1844 return;
1845
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001846 argv0 = argv[0];
1847
1848#ifdef HAVE_READLINK
1849 if (_HAVE_SCRIPT_ARGUMENT(argc, argv))
1850 nr = _Py_wreadlink(argv0, link, MAXPATHLEN);
1851 if (nr > 0) {
1852 /* It's a symlink */
1853 link[nr] = '\0';
1854 if (link[0] == SEP)
1855 argv0 = link; /* Link to absolute path */
1856 else if (wcschr(link, SEP) == NULL)
1857 ; /* Link without path */
1858 else {
1859 /* Must join(dirname(argv0), link) */
1860 wchar_t *q = wcsrchr(argv0, SEP);
1861 if (q == NULL)
1862 argv0 = link; /* argv0 without path */
1863 else {
Christian Heimes60a60672013-07-22 12:53:32 +02001864 /* Must make a copy, argv0copy has room for 2 * MAXPATHLEN */
1865 wcsncpy(argv0copy, argv0, MAXPATHLEN);
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001866 q = wcsrchr(argv0copy, SEP);
Christian Heimes60a60672013-07-22 12:53:32 +02001867 wcsncpy(q+1, link, MAXPATHLEN);
1868 q[MAXPATHLEN + 1] = L'\0';
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001869 argv0 = argv0copy;
1870 }
1871 }
1872 }
1873#endif /* HAVE_READLINK */
1874#if SEP == '\\' /* Special case for MS filename syntax */
1875 if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) {
1876 wchar_t *q;
1877#if defined(MS_WINDOWS) && !defined(MS_WINCE)
1878 /* This code here replaces the first element in argv with the full
1879 path that it represents. Under CE, there are no relative paths so
1880 the argument must be the full path anyway. */
1881 wchar_t *ptemp;
1882 if (GetFullPathNameW(argv0,
Victor Stinner63941882011-09-29 00:42:28 +02001883 Py_ARRAY_LENGTH(fullpath),
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001884 fullpath,
1885 &ptemp)) {
1886 argv0 = fullpath;
1887 }
1888#endif
1889 p = wcsrchr(argv0, SEP);
1890 /* Test for alternate separator */
1891 q = wcsrchr(p ? p : argv0, '/');
1892 if (q != NULL)
1893 p = q;
1894 if (p != NULL) {
1895 n = p + 1 - argv0;
1896 if (n > 1 && p[-1] != ':')
1897 n--; /* Drop trailing separator */
1898 }
1899 }
1900#else /* All other filename syntaxes */
1901 if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) {
1902#if defined(HAVE_REALPATH)
Victor Stinner23847142013-11-15 17:33:43 +01001903 if (_Py_wrealpath(argv0, fullpath, Py_ARRAY_LENGTH(fullpath))) {
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001904 argv0 = fullpath;
1905 }
1906#endif
1907 p = wcsrchr(argv0, SEP);
1908 }
1909 if (p != NULL) {
1910 n = p + 1 - argv0;
1911#if SEP == '/' /* Special case for Unix filename syntax */
1912 if (n > 1)
1913 n--; /* Drop trailing separator */
1914#endif /* Unix */
1915 }
1916#endif /* All others */
1917 a = PyUnicode_FromWideChar(argv0, n);
1918 if (a == NULL)
1919 Py_FatalError("no mem for sys.path insertion");
1920 if (PyList_Insert(path, 0, a) < 0)
1921 Py_FatalError("sys.path.insert(0) failed");
1922 Py_DECREF(a);
1923}
1924
1925void
1926PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
1927{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001928 PyObject *av = makeargvobject(argc, argv);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001929 if (av == NULL)
1930 Py_FatalError("no mem for sys.argv");
1931 if (PySys_SetObject("argv", av) != 0)
1932 Py_FatalError("can't assign sys.argv");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001933 Py_DECREF(av);
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001934 if (updatepath)
1935 sys_update_path(argc, argv);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001936}
Guido van Rossuma890e681998-05-12 14:59:24 +00001937
Antoine Pitrouf978fac2010-05-21 17:25:34 +00001938void
1939PySys_SetArgv(int argc, wchar_t **argv)
1940{
1941 PySys_SetArgvEx(argc, argv, 1);
1942}
1943
Victor Stinner14284c22010-04-23 12:02:30 +00001944/* Reimplementation of PyFile_WriteString() no calling indirectly
1945 PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
1946
1947static int
Victor Stinner79766632010-08-16 17:36:42 +00001948sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
Victor Stinner14284c22010-04-23 12:02:30 +00001949{
Victor Stinner79766632010-08-16 17:36:42 +00001950 PyObject *writer = NULL, *args = NULL, *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001951 int err;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001952 _Py_IDENTIFIER(write);
Victor Stinner14284c22010-04-23 12:02:30 +00001953
Victor Stinnerecccc4f2010-06-08 20:46:00 +00001954 if (file == NULL)
1955 return -1;
1956
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001957 writer = _PyObject_GetAttrId(file, &PyId_write);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001958 if (writer == NULL)
1959 goto error;
Victor Stinner14284c22010-04-23 12:02:30 +00001960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001961 args = PyTuple_Pack(1, unicode);
1962 if (args == NULL)
1963 goto error;
Victor Stinner14284c22010-04-23 12:02:30 +00001964
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001965 result = PyEval_CallObject(writer, args);
1966 if (result == NULL) {
1967 goto error;
1968 } else {
1969 err = 0;
1970 goto finally;
1971 }
Victor Stinner14284c22010-04-23 12:02:30 +00001972
1973error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001974 err = -1;
Victor Stinner14284c22010-04-23 12:02:30 +00001975finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001976 Py_XDECREF(writer);
1977 Py_XDECREF(args);
1978 Py_XDECREF(result);
1979 return err;
Victor Stinner14284c22010-04-23 12:02:30 +00001980}
1981
Victor Stinner79766632010-08-16 17:36:42 +00001982static int
1983sys_pyfile_write(const char *text, PyObject *file)
1984{
1985 PyObject *unicode = NULL;
1986 int err;
1987
1988 if (file == NULL)
1989 return -1;
1990
1991 unicode = PyUnicode_FromString(text);
1992 if (unicode == NULL)
1993 return -1;
1994
1995 err = sys_pyfile_write_unicode(unicode, file);
1996 Py_DECREF(unicode);
1997 return err;
1998}
Guido van Rossuma890e681998-05-12 14:59:24 +00001999
2000/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
2001 Adapted from code submitted by Just van Rossum.
2002
2003 PySys_WriteStdout(format, ...)
2004 PySys_WriteStderr(format, ...)
2005
2006 The first function writes to sys.stdout; the second to sys.stderr. When
2007 there is a problem, they write to the real (C level) stdout or stderr;
Guido van Rossum8442af31998-10-12 18:22:10 +00002008 no exceptions are raised.
Guido van Rossuma890e681998-05-12 14:59:24 +00002009
Victor Stinner14284c22010-04-23 12:02:30 +00002010 PyErr_CheckSignals() is not called to avoid the execution of the Python
Victor Stinner79766632010-08-16 17:36:42 +00002011 signal handlers: they may raise a new exception whereas sys_write()
2012 ignores all exceptions.
Victor Stinner14284c22010-04-23 12:02:30 +00002013
Guido van Rossuma890e681998-05-12 14:59:24 +00002014 Both take a printf-style format string as their first argument followed
2015 by a variable length argument list determined by the format string.
2016
2017 *** WARNING ***
2018
2019 The format should limit the total size of the formatted output string to
2020 1000 bytes. In particular, this means that no unrestricted "%s" formats
2021 should occur; these should be limited using "%.<N>s where <N> is a
2022 decimal number calculated so that <N> plus the maximum size of other
2023 formatted text does not exceed 1000 bytes. Also watch out for "%f",
2024 which can print hundreds of digits for very large numbers.
2025
2026 */
2027
2028static void
Victor Stinner79766632010-08-16 17:36:42 +00002029sys_write(char *name, FILE *fp, const char *format, va_list va)
Guido van Rossuma890e681998-05-12 14:59:24 +00002030{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002031 PyObject *file;
2032 PyObject *error_type, *error_value, *error_traceback;
2033 char buffer[1001];
2034 int written;
Guido van Rossuma890e681998-05-12 14:59:24 +00002035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002036 PyErr_Fetch(&error_type, &error_value, &error_traceback);
2037 file = PySys_GetObject(name);
2038 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
2039 if (sys_pyfile_write(buffer, file) != 0) {
2040 PyErr_Clear();
2041 fputs(buffer, fp);
2042 }
2043 if (written < 0 || (size_t)written >= sizeof(buffer)) {
2044 const char *truncated = "... truncated";
Victor Stinner79766632010-08-16 17:36:42 +00002045 if (sys_pyfile_write(truncated, file) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002046 fputs(truncated, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002047 }
2048 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossuma890e681998-05-12 14:59:24 +00002049}
2050
2051void
Guido van Rossuma890e681998-05-12 14:59:24 +00002052PySys_WriteStdout(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002053{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002054 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002056 va_start(va, format);
Victor Stinner79766632010-08-16 17:36:42 +00002057 sys_write("stdout", stdout, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002058 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002059}
2060
2061void
Guido van Rossuma890e681998-05-12 14:59:24 +00002062PySys_WriteStderr(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002063{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 va_start(va, format);
Victor Stinner79766632010-08-16 17:36:42 +00002067 sys_write("stderr", stderr, format, va);
2068 va_end(va);
2069}
2070
2071static void
2072sys_format(char *name, FILE *fp, const char *format, va_list va)
2073{
2074 PyObject *file, *message;
2075 PyObject *error_type, *error_value, *error_traceback;
2076 char *utf8;
2077
2078 PyErr_Fetch(&error_type, &error_value, &error_traceback);
2079 file = PySys_GetObject(name);
2080 message = PyUnicode_FromFormatV(format, va);
2081 if (message != NULL) {
2082 if (sys_pyfile_write_unicode(message, file) != 0) {
2083 PyErr_Clear();
2084 utf8 = _PyUnicode_AsString(message);
2085 if (utf8 != NULL)
2086 fputs(utf8, fp);
2087 }
2088 Py_DECREF(message);
2089 }
2090 PyErr_Restore(error_type, error_value, error_traceback);
2091}
2092
2093void
2094PySys_FormatStdout(const char *format, ...)
2095{
2096 va_list va;
2097
2098 va_start(va, format);
2099 sys_format("stdout", stdout, format, va);
2100 va_end(va);
2101}
2102
2103void
2104PySys_FormatStderr(const char *format, ...)
2105{
2106 va_list va;
2107
2108 va_start(va, format);
2109 sys_format("stderr", stderr, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002111}