blob: f0aceada5f096f846ce0866103aef088086ce608 [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;
82
83 stdout_encoding = PyObject_GetAttrString(outf, "encoding");
84 if (stdout_encoding == NULL)
85 goto error;
86 stdout_encoding_str = _PyUnicode_AsString(stdout_encoding);
87 if (stdout_encoding_str == NULL)
88 goto error;
89
90 repr_str = PyObject_Repr(o);
91 if (repr_str == NULL)
92 goto error;
93 encoded = PyUnicode_AsEncodedString(repr_str,
94 stdout_encoding_str,
95 "backslashreplace");
96 Py_DECREF(repr_str);
97 if (encoded == NULL)
98 goto error;
99
100 buffer = PyObject_GetAttrString(outf, "buffer");
101 if (buffer) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200102 _Py_identifier(write);
103 result = _PyObject_CallMethodId(buffer, &PyId_write, "(O)", encoded);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000104 Py_DECREF(buffer);
105 Py_DECREF(encoded);
106 if (result == NULL)
107 goto error;
108 Py_DECREF(result);
109 }
110 else {
111 PyErr_Clear();
112 escaped_str = PyUnicode_FromEncodedObject(encoded,
113 stdout_encoding_str,
114 "strict");
115 Py_DECREF(encoded);
116 if (PyFile_WriteObject(escaped_str, outf, Py_PRINT_RAW) != 0) {
117 Py_DECREF(escaped_str);
118 goto error;
119 }
120 Py_DECREF(escaped_str);
121 }
122 ret = 0;
123 goto finally;
124
125error:
126 ret = -1;
127finally:
128 Py_XDECREF(stdout_encoding);
129 return ret;
130}
131
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000132static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000133sys_displayhook(PyObject *self, PyObject *o)
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000134{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 PyObject *outf;
136 PyInterpreterState *interp = PyThreadState_GET()->interp;
137 PyObject *modules = interp->modules;
138 PyObject *builtins = PyDict_GetItemString(modules, "builtins");
Victor Stinner13d49ee2010-12-04 17:24:33 +0000139 int err;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000141 if (builtins == NULL) {
142 PyErr_SetString(PyExc_RuntimeError, "lost builtins module");
143 return NULL;
144 }
Moshe Zadka03897ea2001-07-23 13:32:43 +0000145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000146 /* Print value except if None */
147 /* After printing, also assign to '_' */
148 /* Before, set '_' to None to avoid recursion */
149 if (o == Py_None) {
150 Py_INCREF(Py_None);
151 return Py_None;
152 }
153 if (PyObject_SetAttrString(builtins, "_", Py_None) != 0)
154 return NULL;
155 outf = PySys_GetObject("stdout");
156 if (outf == NULL || outf == Py_None) {
157 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
158 return NULL;
159 }
Victor Stinner13d49ee2010-12-04 17:24:33 +0000160 if (PyFile_WriteObject(o, outf, 0) != 0) {
161 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
162 /* repr(o) is not encodable to sys.stdout.encoding with
163 * sys.stdout.errors error handler (which is probably 'strict') */
164 PyErr_Clear();
165 err = sys_displayhook_unencodable(outf, o);
166 if (err)
167 return NULL;
168 }
169 else {
170 return NULL;
171 }
172 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000173 if (PyFile_WriteString("\n", outf) != 0)
174 return NULL;
175 if (PyObject_SetAttrString(builtins, "_", o) != 0)
176 return NULL;
177 Py_INCREF(Py_None);
178 return Py_None;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000179}
180
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000181PyDoc_STRVAR(displayhook_doc,
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000182"displayhook(object) -> None\n"
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000183"\n"
Florent Xicluna5749e852010-03-03 11:54:54 +0000184"Print an object to sys.stdout and also save it in builtins._\n"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000185);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000186
187static PyObject *
188sys_excepthook(PyObject* self, PyObject* args)
189{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000190 PyObject *exc, *value, *tb;
191 if (!PyArg_UnpackTuple(args, "excepthook", 3, 3, &exc, &value, &tb))
192 return NULL;
193 PyErr_Display(exc, value, tb);
194 Py_INCREF(Py_None);
195 return Py_None;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000196}
197
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000198PyDoc_STRVAR(excepthook_doc,
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000199"excepthook(exctype, value, traceback) -> None\n"
200"\n"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000201"Handle an exception by displaying it with a traceback on sys.stderr.\n"
202);
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000203
204static PyObject *
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000205sys_exc_info(PyObject *self, PyObject *noargs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000206{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000207 PyThreadState *tstate;
208 tstate = PyThreadState_GET();
209 return Py_BuildValue(
210 "(OOO)",
211 tstate->exc_type != NULL ? tstate->exc_type : Py_None,
212 tstate->exc_value != NULL ? tstate->exc_value : Py_None,
213 tstate->exc_traceback != NULL ?
214 tstate->exc_traceback : Py_None);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000215}
216
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000217PyDoc_STRVAR(exc_info_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000218"exc_info() -> (type, value, traceback)\n\
219\n\
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000220Return information about the most recent exception caught by an except\n\
221clause in the current stack frame or in an older stack frame."
222);
223
224static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000225sys_exit(PyObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000226{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 PyObject *exit_code = 0;
228 if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code))
229 return NULL;
230 /* Raise SystemExit so callers may catch it or clean up. */
231 PyErr_SetObject(PyExc_SystemExit, exit_code);
232 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000233}
234
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000235PyDoc_STRVAR(exit_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000236"exit([status])\n\
237\n\
238Exit the interpreter by raising SystemExit(status).\n\
239If the status is omitted or None, it defaults to zero (i.e., success).\n\
Neil Schemenauer0f2103f2002-03-23 20:46:35 +0000240If the status is numeric, it will be used as the system exit status.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000241If it is another kind of object, it will be printed and the system\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000242exit status will be one (i.e., failure)."
243);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000244
Martin v. Löwis107b7da2001-11-09 20:59:39 +0000245
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000246static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000247sys_getdefaultencoding(PyObject *self)
Fred Drake8b4d01d2000-05-09 19:57:01 +0000248{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 return PyUnicode_FromString(PyUnicode_GetDefaultEncoding());
Fred Drake8b4d01d2000-05-09 19:57:01 +0000250}
251
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000252PyDoc_STRVAR(getdefaultencoding_doc,
Marc-André Lemburg99964b82000-06-07 09:13:41 +0000253"getdefaultencoding() -> string\n\
Fred Drake8b4d01d2000-05-09 19:57:01 +0000254\n\
255Return the current default string encoding used by the Unicode \n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000256implementation."
257);
Fred Drake8b4d01d2000-05-09 19:57:01 +0000258
259static PyObject *
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000260sys_getfilesystemencoding(PyObject *self)
261{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 if (Py_FileSystemDefaultEncoding)
263 return PyUnicode_FromString(Py_FileSystemDefaultEncoding);
Victor Stinner27181ac2011-03-31 13:39:03 +0200264 PyErr_SetString(PyExc_RuntimeError,
265 "filesystem encoding is not initialized");
266 return NULL;
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000267}
268
269PyDoc_STRVAR(getfilesystemencoding_doc,
270"getfilesystemencoding() -> string\n\
271\n\
272Return the encoding used to convert Unicode filenames in\n\
273operating system filenames."
274);
275
Martin v. Löwis04dc25c2008-10-03 16:09:28 +0000276static PyObject *
Georg Brandl66a796e2006-12-19 20:50:34 +0000277sys_intern(PyObject *self, PyObject *args)
278{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000279 PyObject *s;
280 if (!PyArg_ParseTuple(args, "U:intern", &s))
281 return NULL;
282 if (PyUnicode_CheckExact(s)) {
283 Py_INCREF(s);
284 PyUnicode_InternInPlace(&s);
285 return s;
286 }
287 else {
288 PyErr_Format(PyExc_TypeError,
289 "can't intern %.400s", s->ob_type->tp_name);
290 return NULL;
291 }
Georg Brandl66a796e2006-12-19 20:50:34 +0000292}
293
294PyDoc_STRVAR(intern_doc,
295"intern(string) -> string\n\
296\n\
297``Intern'' the given string. This enters the string in the (global)\n\
298table of interned strings whose purpose is to speed up dictionary lookups.\n\
299Return the string itself or the previously interned string object with the\n\
300same value.");
301
302
Fred Drake5755ce62001-06-27 19:19:46 +0000303/*
304 * Cached interned string objects used for calling the profile and
305 * trace functions. Initialized by trace_init().
306 */
Nicholas Bastinc69ebe82004-03-24 21:57:10 +0000307static PyObject *whatstrings[7] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL};
Fred Drake5755ce62001-06-27 19:19:46 +0000308
309static int
310trace_init(void)
311{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000312 static char *whatnames[7] = {"call", "exception", "line", "return",
313 "c_call", "c_exception", "c_return"};
314 PyObject *name;
315 int i;
316 for (i = 0; i < 7; ++i) {
317 if (whatstrings[i] == NULL) {
318 name = PyUnicode_InternFromString(whatnames[i]);
319 if (name == NULL)
320 return -1;
321 whatstrings[i] = name;
322 }
323 }
324 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000325}
326
327
328static PyObject *
329call_trampoline(PyThreadState *tstate, PyObject* callback,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 PyFrameObject *frame, int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000331{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332 PyObject *args = PyTuple_New(3);
333 PyObject *whatstr;
334 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336 if (args == NULL)
337 return NULL;
338 Py_INCREF(frame);
339 whatstr = whatstrings[what];
340 Py_INCREF(whatstr);
341 if (arg == NULL)
342 arg = Py_None;
343 Py_INCREF(arg);
344 PyTuple_SET_ITEM(args, 0, (PyObject *)frame);
345 PyTuple_SET_ITEM(args, 1, whatstr);
346 PyTuple_SET_ITEM(args, 2, arg);
Fred Drake5755ce62001-06-27 19:19:46 +0000347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000348 /* call the Python-level function */
349 PyFrame_FastToLocals(frame);
350 result = PyEval_CallObject(callback, args);
351 PyFrame_LocalsToFast(frame, 1);
352 if (result == NULL)
353 PyTraceBack_Here(frame);
Fred Drake5755ce62001-06-27 19:19:46 +0000354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000355 /* cleanup */
356 Py_DECREF(args);
357 return result;
Fred Drake5755ce62001-06-27 19:19:46 +0000358}
359
360static int
361profile_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000362 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000363{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364 PyThreadState *tstate = frame->f_tstate;
365 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 if (arg == NULL)
368 arg = Py_None;
369 result = call_trampoline(tstate, self, frame, what, arg);
370 if (result == NULL) {
371 PyEval_SetProfile(NULL, NULL);
372 return -1;
373 }
374 Py_DECREF(result);
375 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000376}
377
378static int
379trace_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000381{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 PyThreadState *tstate = frame->f_tstate;
383 PyObject *callback;
384 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000386 if (what == PyTrace_CALL)
387 callback = self;
388 else
389 callback = frame->f_trace;
390 if (callback == NULL)
391 return 0;
392 result = call_trampoline(tstate, callback, frame, what, arg);
393 if (result == NULL) {
394 PyEval_SetTrace(NULL, NULL);
395 Py_XDECREF(frame->f_trace);
396 frame->f_trace = NULL;
397 return -1;
398 }
399 if (result != Py_None) {
400 PyObject *temp = frame->f_trace;
401 frame->f_trace = NULL;
402 Py_XDECREF(temp);
403 frame->f_trace = result;
404 }
405 else {
406 Py_DECREF(result);
407 }
408 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000409}
Fred Draked0838392001-06-16 21:02:31 +0000410
Fred Drake8b4d01d2000-05-09 19:57:01 +0000411static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000412sys_settrace(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000413{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 if (trace_init() == -1)
415 return NULL;
416 if (args == Py_None)
417 PyEval_SetTrace(NULL, NULL);
418 else
419 PyEval_SetTrace(trace_trampoline, args);
420 Py_INCREF(Py_None);
421 return Py_None;
Guido van Rossume2437a11992-03-23 18:20:18 +0000422}
423
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000424PyDoc_STRVAR(settrace_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000425"settrace(function)\n\
426\n\
427Set the global debug tracing function. It will be called on each\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000428function call. See the debugger chapter in the library manual."
429);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000430
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000431static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000432sys_gettrace(PyObject *self, PyObject *args)
433{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 PyThreadState *tstate = PyThreadState_GET();
435 PyObject *temp = tstate->c_traceobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000437 if (temp == NULL)
438 temp = Py_None;
439 Py_INCREF(temp);
440 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000441}
442
443PyDoc_STRVAR(gettrace_doc,
444"gettrace()\n\
445\n\
446Return the global debug tracing function set with sys.settrace.\n\
447See the debugger chapter in the library manual."
448);
449
450static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000451sys_setprofile(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000452{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 if (trace_init() == -1)
454 return NULL;
455 if (args == Py_None)
456 PyEval_SetProfile(NULL, NULL);
457 else
458 PyEval_SetProfile(profile_trampoline, args);
459 Py_INCREF(Py_None);
460 return Py_None;
Guido van Rossume2437a11992-03-23 18:20:18 +0000461}
462
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000463PyDoc_STRVAR(setprofile_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000464"setprofile(function)\n\
465\n\
466Set the profiling function. It will be called on each function call\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000467and return. See the profiler chapter in the library manual."
468);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000469
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000470static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000471sys_getprofile(PyObject *self, PyObject *args)
472{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 PyThreadState *tstate = PyThreadState_GET();
474 PyObject *temp = tstate->c_profileobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 if (temp == NULL)
477 temp = Py_None;
478 Py_INCREF(temp);
479 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000480}
481
482PyDoc_STRVAR(getprofile_doc,
483"getprofile()\n\
484\n\
485Return the profiling function set with sys.setprofile.\n\
486See the profiler chapter in the library manual."
487);
488
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000489static int _check_interval = 100;
490
Christian Heimes9bd667a2008-01-20 15:14:11 +0000491static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000492sys_setcheckinterval(PyObject *self, PyObject *args)
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000493{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 if (PyErr_WarnEx(PyExc_DeprecationWarning,
495 "sys.getcheckinterval() and sys.setcheckinterval() "
496 "are deprecated. Use sys.setswitchinterval() "
497 "instead.", 1) < 0)
498 return NULL;
499 if (!PyArg_ParseTuple(args, "i:setcheckinterval", &_check_interval))
500 return NULL;
501 Py_INCREF(Py_None);
502 return Py_None;
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000503}
504
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000505PyDoc_STRVAR(setcheckinterval_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000506"setcheckinterval(n)\n\
507\n\
508Tell the Python interpreter to check for asynchronous events every\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000509n instructions. This also affects how often thread switches occur."
510);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000511
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000512static PyObject *
Tim Peterse5e065b2003-07-06 18:36:54 +0000513sys_getcheckinterval(PyObject *self, PyObject *args)
514{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 if (PyErr_WarnEx(PyExc_DeprecationWarning,
516 "sys.getcheckinterval() and sys.setcheckinterval() "
517 "are deprecated. Use sys.getswitchinterval() "
518 "instead.", 1) < 0)
519 return NULL;
520 return PyLong_FromLong(_check_interval);
Tim Peterse5e065b2003-07-06 18:36:54 +0000521}
522
523PyDoc_STRVAR(getcheckinterval_doc,
524"getcheckinterval() -> current check interval; see setcheckinterval()."
525);
526
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000527#ifdef WITH_THREAD
528static PyObject *
529sys_setswitchinterval(PyObject *self, PyObject *args)
530{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 double d;
532 if (!PyArg_ParseTuple(args, "d:setswitchinterval", &d))
533 return NULL;
534 if (d <= 0.0) {
535 PyErr_SetString(PyExc_ValueError,
536 "switch interval must be strictly positive");
537 return NULL;
538 }
539 _PyEval_SetSwitchInterval((unsigned long) (1e6 * d));
540 Py_INCREF(Py_None);
541 return Py_None;
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000542}
543
544PyDoc_STRVAR(setswitchinterval_doc,
545"setswitchinterval(n)\n\
546\n\
547Set the ideal thread switching delay inside the Python interpreter\n\
548The actual frequency of switching threads can be lower if the\n\
549interpreter executes long sequences of uninterruptible code\n\
550(this is implementation-specific and workload-dependent).\n\
551\n\
552The parameter must represent the desired switching delay in seconds\n\
553A typical value is 0.005 (5 milliseconds)."
554);
555
556static PyObject *
557sys_getswitchinterval(PyObject *self, PyObject *args)
558{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 return PyFloat_FromDouble(1e-6 * _PyEval_GetSwitchInterval());
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000560}
561
562PyDoc_STRVAR(getswitchinterval_doc,
563"getswitchinterval() -> current thread switch interval; see setswitchinterval()."
564);
565
566#endif /* WITH_THREAD */
567
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000568#ifdef WITH_TSC
569static PyObject *
570sys_settscdump(PyObject *self, PyObject *args)
571{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000572 int bool;
573 PyThreadState *tstate = PyThreadState_Get();
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 if (!PyArg_ParseTuple(args, "i:settscdump", &bool))
576 return NULL;
577 if (bool)
578 tstate->interp->tscdump = 1;
579 else
580 tstate->interp->tscdump = 0;
581 Py_INCREF(Py_None);
582 return Py_None;
Tim Peters216b78b2006-01-06 02:40:53 +0000583
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000584}
585
Tim Peters216b78b2006-01-06 02:40:53 +0000586PyDoc_STRVAR(settscdump_doc,
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000587"settscdump(bool)\n\
588\n\
589If true, tell the Python interpreter to dump VM measurements to\n\
590stderr. If false, turn off dump. The measurements are based on the\n\
Michael W. Hudson800ba232004-08-12 18:19:17 +0000591processor's time-stamp counter."
Tim Peters216b78b2006-01-06 02:40:53 +0000592);
Neal Norwitz0f5aed42004-06-13 20:32:17 +0000593#endif /* TSC */
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000594
Tim Peterse5e065b2003-07-06 18:36:54 +0000595static PyObject *
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000596sys_setrecursionlimit(PyObject *self, PyObject *args)
597{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 int new_limit;
599 if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit))
600 return NULL;
601 if (new_limit <= 0) {
602 PyErr_SetString(PyExc_ValueError,
603 "recursion limit must be positive");
604 return NULL;
605 }
606 Py_SetRecursionLimit(new_limit);
607 Py_INCREF(Py_None);
608 return Py_None;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000609}
610
Mark Dickinsondc787d22010-05-23 13:33:13 +0000611static PyTypeObject Hash_InfoType;
612
613PyDoc_STRVAR(hash_info_doc,
614"hash_info\n\
615\n\
616A struct sequence providing parameters used for computing\n\
617numeric hashes. The attributes are read only.");
618
619static PyStructSequence_Field hash_info_fields[] = {
620 {"width", "width of the type used for hashing, in bits"},
621 {"modulus", "prime number giving the modulus on which the hash "
622 "function is based"},
623 {"inf", "value to be used for hash of a positive infinity"},
624 {"nan", "value to be used for hash of a nan"},
625 {"imag", "multiplier used for the imaginary part of a complex number"},
626 {NULL, NULL}
627};
628
629static PyStructSequence_Desc hash_info_desc = {
630 "sys.hash_info",
631 hash_info_doc,
632 hash_info_fields,
633 5,
634};
635
Matthias Klosed885e952010-07-06 10:53:30 +0000636static PyObject *
Mark Dickinsondc787d22010-05-23 13:33:13 +0000637get_hash_info(void)
638{
639 PyObject *hash_info;
640 int field = 0;
641 hash_info = PyStructSequence_New(&Hash_InfoType);
642 if (hash_info == NULL)
643 return NULL;
644 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000645 PyLong_FromLong(8*sizeof(Py_hash_t)));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000646 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000647 PyLong_FromSsize_t(_PyHASH_MODULUS));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000648 PyStructSequence_SET_ITEM(hash_info, field++,
649 PyLong_FromLong(_PyHASH_INF));
650 PyStructSequence_SET_ITEM(hash_info, field++,
651 PyLong_FromLong(_PyHASH_NAN));
652 PyStructSequence_SET_ITEM(hash_info, field++,
653 PyLong_FromLong(_PyHASH_IMAG));
654 if (PyErr_Occurred()) {
655 Py_CLEAR(hash_info);
656 return NULL;
657 }
658 return hash_info;
659}
660
661
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000662PyDoc_STRVAR(setrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000663"setrecursionlimit(n)\n\
664\n\
665Set the maximum depth of the Python interpreter stack to n. This\n\
666limit prevents infinite recursion from causing an overflow of the C\n\
667stack and crashing Python. The highest possible limit is platform-\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000668dependent."
669);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000670
671static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000672sys_getrecursionlimit(PyObject *self)
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000673{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 return PyLong_FromLong(Py_GetRecursionLimit());
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000675}
676
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000677PyDoc_STRVAR(getrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000678"getrecursionlimit()\n\
679\n\
680Return the current value of the recursion limit, the maximum depth\n\
681of the Python interpreter stack. This limit prevents infinite\n\
Jack Jansene739a0d2002-06-26 20:39:20 +0000682recursion from causing an overflow of the C stack and crashing Python."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000683);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000684
Mark Hammond8696ebc2002-10-08 02:44:31 +0000685#ifdef MS_WINDOWS
686PyDoc_STRVAR(getwindowsversion_doc,
687"getwindowsversion()\n\
688\n\
Eric Smithf7bb5782010-01-27 00:44:57 +0000689Return information about the running version of Windows as a named tuple.\n\
690The members are named: major, minor, build, platform, service_pack,\n\
691service_pack_major, service_pack_minor, suite_mask, and product_type. For\n\
Ezio Melotti4969f702011-03-15 05:59:46 +0200692backward compatibility, only the first 5 items are available by indexing.\n\
Eric Smithf7bb5782010-01-27 00:44:57 +0000693All elements are numbers, except service_pack which is a string. Platform\n\
694may be 0 for win32s, 1 for Windows 9x/ME, 2 for Windows NT/2000/XP/Vista/7,\n\
6953 for Windows CE. Product_type may be 1 for a workstation, 2 for a domain\n\
696controller, 3 for a server."
Mark Hammond8696ebc2002-10-08 02:44:31 +0000697);
698
Eric Smithf7bb5782010-01-27 00:44:57 +0000699static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};
700
701static PyStructSequence_Field windows_version_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 {"major", "Major version number"},
703 {"minor", "Minor version number"},
704 {"build", "Build number"},
705 {"platform", "Operating system platform"},
706 {"service_pack", "Latest Service Pack installed on the system"},
707 {"service_pack_major", "Service Pack major version number"},
708 {"service_pack_minor", "Service Pack minor version number"},
709 {"suite_mask", "Bit mask identifying available product suites"},
710 {"product_type", "System product type"},
711 {0}
Eric Smithf7bb5782010-01-27 00:44:57 +0000712};
713
714static PyStructSequence_Desc windows_version_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 "sys.getwindowsversion", /* name */
716 getwindowsversion_doc, /* doc */
717 windows_version_fields, /* fields */
718 5 /* For backward compatibility,
719 only the first 5 items are accessible
720 via indexing, the rest are name only */
Eric Smithf7bb5782010-01-27 00:44:57 +0000721};
722
Mark Hammond8696ebc2002-10-08 02:44:31 +0000723static PyObject *
724sys_getwindowsversion(PyObject *self)
725{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 PyObject *version;
727 int pos = 0;
728 OSVERSIONINFOEX ver;
729 ver.dwOSVersionInfoSize = sizeof(ver);
730 if (!GetVersionEx((OSVERSIONINFO*) &ver))
731 return PyErr_SetFromWindowsErr(0);
Eric Smithf7bb5782010-01-27 00:44:57 +0000732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000733 version = PyStructSequence_New(&WindowsVersionType);
734 if (version == NULL)
735 return NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +0000736
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion));
738 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion));
739 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber));
740 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId));
741 PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromString(ver.szCSDVersion));
742 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor));
743 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor));
744 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask));
745 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType));
Eric Smithf7bb5782010-01-27 00:44:57 +0000746
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000747 return version;
Mark Hammond8696ebc2002-10-08 02:44:31 +0000748}
749
750#endif /* MS_WINDOWS */
751
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000752#ifdef HAVE_DLOPEN
753static PyObject *
754sys_setdlopenflags(PyObject *self, PyObject *args)
755{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 int new_val;
757 PyThreadState *tstate = PyThreadState_GET();
758 if (!PyArg_ParseTuple(args, "i:setdlopenflags", &new_val))
759 return NULL;
760 if (!tstate)
761 return NULL;
762 tstate->interp->dlopenflags = new_val;
763 Py_INCREF(Py_None);
764 return Py_None;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000765}
766
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000767PyDoc_STRVAR(setdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000768"setdlopenflags(n) -> None\n\
769\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000770Set the flags used by the interpreter for dlopen calls, such as when the\n\
771interpreter loads extension modules. Among other things, this will enable\n\
772a lazy resolving of symbols when importing a module, if called as\n\
773sys.setdlopenflags(0). To share symbols across extension modules, call as\n\
774sys.setdlopenflags(ctypes.RTLD_GLOBAL). Symbolic names for the flag modules\n\
775can be either found in the ctypes module, or in the DLFCN module. If DLFCN\n\
776is not available, it can be generated from /usr/include/dlfcn.h using the\n\
777h2py script.");
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000778
779static PyObject *
780sys_getdlopenflags(PyObject *self, PyObject *args)
781{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 PyThreadState *tstate = PyThreadState_GET();
783 if (!tstate)
784 return NULL;
785 return PyLong_FromLong(tstate->interp->dlopenflags);
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000786}
787
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000788PyDoc_STRVAR(getdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000789"getdlopenflags() -> int\n\
790\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000791Return the current value of the flags that are used for dlopen calls.\n\
792The flag constants are defined in the ctypes and DLFCN modules.");
793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794#endif /* HAVE_DLOPEN */
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000795
Guido van Rossum14b4adb1992-09-03 20:25:30 +0000796#ifdef USE_MALLOPT
797/* Link with -lmalloc (or -lmpc) on an SGI */
798#include <malloc.h>
799
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000800static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000801sys_mdebug(PyObject *self, PyObject *args)
Guido van Rossum14b4adb1992-09-03 20:25:30 +0000802{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 int flag;
804 if (!PyArg_ParseTuple(args, "i:mdebug", &flag))
805 return NULL;
806 mallopt(M_DEBUG, flag);
807 Py_INCREF(Py_None);
808 return Py_None;
Guido van Rossum14b4adb1992-09-03 20:25:30 +0000809}
810#endif /* USE_MALLOPT */
811
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000812static PyObject *
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000813sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000814{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 PyObject *res = NULL;
816 static PyObject *str__sizeof__ = NULL, *gc_head_size = NULL;
817 static char *kwlist[] = {"object", "default", 0};
818 PyObject *o, *dflt = NULL;
819 PyObject *method;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000820
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
822 kwlist, &o, &dflt))
823 return NULL;
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000825 /* Initialize static variable for GC head size */
826 if (gc_head_size == NULL) {
827 gc_head_size = PyLong_FromSsize_t(sizeof(PyGC_Head));
828 if (gc_head_size == NULL)
829 return NULL;
830 }
Benjamin Petersona5758c02009-05-09 18:15:04 +0000831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000832 /* Make sure the type is initialized. float gets initialized late */
833 if (PyType_Ready(Py_TYPE(o)) < 0)
834 return NULL;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 method = _PyObject_LookupSpecial(o, "__sizeof__",
837 &str__sizeof__);
838 if (method == NULL) {
839 if (!PyErr_Occurred())
840 PyErr_Format(PyExc_TypeError,
841 "Type %.100s doesn't define __sizeof__",
842 Py_TYPE(o)->tp_name);
843 }
844 else {
845 res = PyObject_CallFunctionObjArgs(method, NULL);
846 Py_DECREF(method);
847 }
848
849 /* Has a default value been given */
850 if ((res == NULL) && (dflt != NULL) &&
851 PyErr_ExceptionMatches(PyExc_TypeError))
852 {
853 PyErr_Clear();
854 Py_INCREF(dflt);
855 return dflt;
856 }
857 else if (res == NULL)
858 return res;
859
860 /* add gc_head size */
861 if (PyObject_IS_GC(o)) {
862 PyObject *tmp = res;
863 res = PyNumber_Add(tmp, gc_head_size);
864 Py_DECREF(tmp);
865 }
866 return res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000867}
868
869PyDoc_STRVAR(getsizeof_doc,
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000870"getsizeof(object, default) -> int\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000871\n\
872Return the size of object in bytes.");
873
874static PyObject *
Fred Drakea7688822001-10-24 20:47:48 +0000875sys_getrefcount(PyObject *self, PyObject *arg)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000876{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 return PyLong_FromSsize_t(arg->ob_refcnt);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000878}
879
Tim Peters4be93d02002-07-07 19:59:50 +0000880#ifdef Py_REF_DEBUG
Mark Hammond440d8982000-06-20 08:12:48 +0000881static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000882sys_gettotalrefcount(PyObject *self)
Mark Hammond440d8982000-06-20 08:12:48 +0000883{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 return PyLong_FromSsize_t(_Py_GetRefTotal());
Mark Hammond440d8982000-06-20 08:12:48 +0000885}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000886#endif /* Py_REF_DEBUG */
Mark Hammond440d8982000-06-20 08:12:48 +0000887
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000888PyDoc_STRVAR(getrefcount_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000889"getrefcount(object) -> integer\n\
890\n\
Fred Drakeba3ff1b2002-06-20 21:36:19 +0000891Return the reference count of object. The count returned is generally\n\
892one higher than you might expect, because it includes the (temporary)\n\
893reference as an argument to getrefcount()."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000894);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000895
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000896#ifdef COUNT_ALLOCS
897static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000898sys_getcounts(PyObject *self)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000899{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 extern PyObject *get_counts(void);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 return get_counts();
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000903}
904#endif
905
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000906PyDoc_STRVAR(getframe_doc,
Barry Warsawb6a54d22000-12-06 21:47:46 +0000907"_getframe([depth]) -> frameobject\n\
908\n\
909Return a frame object from the call stack. If optional integer depth is\n\
910given, return the frame object that many calls below the top of the stack.\n\
911If that is deeper than the call stack, ValueError is raised. The default\n\
912for depth is zero, returning the frame at the top of the call stack.\n\
913\n\
914This function should be used for internal and specialized\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000915purposes only."
916);
Barry Warsawb6a54d22000-12-06 21:47:46 +0000917
918static PyObject *
919sys_getframe(PyObject *self, PyObject *args)
920{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 PyFrameObject *f = PyThreadState_GET()->frame;
922 int depth = -1;
Barry Warsawb6a54d22000-12-06 21:47:46 +0000923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 if (!PyArg_ParseTuple(args, "|i:_getframe", &depth))
925 return NULL;
Barry Warsawb6a54d22000-12-06 21:47:46 +0000926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 while (depth > 0 && f != NULL) {
928 f = f->f_back;
929 --depth;
930 }
931 if (f == NULL) {
932 PyErr_SetString(PyExc_ValueError,
933 "call stack is not deep enough");
934 return NULL;
935 }
936 Py_INCREF(f);
937 return (PyObject*)f;
Barry Warsawb6a54d22000-12-06 21:47:46 +0000938}
939
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000940PyDoc_STRVAR(current_frames_doc,
941"_current_frames() -> dictionary\n\
942\n\
943Return a dictionary mapping each current thread T's thread id to T's\n\
944current stack frame.\n\
945\n\
946This function should be used for specialized purposes only."
947);
948
949static PyObject *
950sys_current_frames(PyObject *self, PyObject *noargs)
951{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 return _PyThread_CurrentFrames();
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000953}
954
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000955PyDoc_STRVAR(call_tracing_doc,
956"call_tracing(func, args) -> object\n\
957\n\
958Call func(*args), while tracing is enabled. The tracing state is\n\
959saved, and restored afterwards. This is intended to be called from\n\
960a debugger from a checkpoint, to recursively debug some other code."
961);
962
963static PyObject *
964sys_call_tracing(PyObject *self, PyObject *args)
965{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 PyObject *func, *funcargs;
967 if (!PyArg_ParseTuple(args, "OO!:call_tracing", &func, &PyTuple_Type, &funcargs))
968 return NULL;
969 return _PyEval_CallTracing(func, funcargs);
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000970}
971
Jeremy Hylton985eba52003-02-05 23:13:00 +0000972PyDoc_STRVAR(callstats_doc,
973"callstats() -> tuple of integers\n\
974\n\
975Return a tuple of function call statistics, if CALL_PROFILE was defined\n\
976when Python was built. Otherwise, return None.\n\
977\n\
978When enabled, this function returns detailed, implementation-specific\n\
979details about the number of function calls executed. The return value is\n\
980a 11-tuple where the entries in the tuple are counts of:\n\
9810. all function calls\n\
9821. calls to PyFunction_Type objects\n\
9832. PyFunction calls that do not create an argument tuple\n\
9843. PyFunction calls that do not create an argument tuple\n\
985 and bypass PyEval_EvalCodeEx()\n\
9864. PyMethod calls\n\
9875. PyMethod calls on bound methods\n\
9886. PyType calls\n\
9897. PyCFunction calls\n\
9908. generator calls\n\
9919. All other calls\n\
99210. Number of stack pops performed by call_function()"
993);
Barry Warsawb6a54d22000-12-06 21:47:46 +0000994
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000995#ifdef __cplusplus
996extern "C" {
997#endif
998
Guido van Rossum7f3f2c11996-05-23 22:45:41 +0000999#ifdef Py_TRACE_REFS
Guido van Rossumded690f1996-05-24 20:48:31 +00001000/* Defined in objects.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001001extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001002#endif
Guido van Rossumded690f1996-05-24 20:48:31 +00001003
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001004#ifdef DYNAMIC_EXECUTION_PROFILE
1005/* Defined in ceval.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001006extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001007#endif
1008
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001009#ifdef __cplusplus
1010}
1011#endif
1012
Christian Heimes15ebc882008-02-04 18:48:49 +00001013static PyObject *
1014sys_clear_type_cache(PyObject* self, PyObject* args)
1015{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 PyType_ClearCache();
1017 Py_RETURN_NONE;
Christian Heimes15ebc882008-02-04 18:48:49 +00001018}
1019
1020PyDoc_STRVAR(sys_clear_type_cache__doc__,
1021"_clear_type_cache() -> None\n\
1022Clear the internal type lookup cache.");
1023
1024
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001025static PyMethodDef sys_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001026 /* Might as well keep this in alphabetic order */
1027 {"callstats", (PyCFunction)PyEval_GetCallStats, METH_NOARGS,
1028 callstats_doc},
1029 {"_clear_type_cache", sys_clear_type_cache, METH_NOARGS,
1030 sys_clear_type_cache__doc__},
1031 {"_current_frames", sys_current_frames, METH_NOARGS,
1032 current_frames_doc},
1033 {"displayhook", sys_displayhook, METH_O, displayhook_doc},
1034 {"exc_info", sys_exc_info, METH_NOARGS, exc_info_doc},
1035 {"excepthook", sys_excepthook, METH_VARARGS, excepthook_doc},
1036 {"exit", sys_exit, METH_VARARGS, exit_doc},
1037 {"getdefaultencoding", (PyCFunction)sys_getdefaultencoding,
1038 METH_NOARGS, getdefaultencoding_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001039#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 {"getdlopenflags", (PyCFunction)sys_getdlopenflags, METH_NOARGS,
1041 getdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001042#endif
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001043#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 {"getcounts", (PyCFunction)sys_getcounts, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001045#endif
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001046#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001048#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 {"getfilesystemencoding", (PyCFunction)sys_getfilesystemencoding,
1050 METH_NOARGS, getfilesystemencoding_doc},
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001051#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 {"getobjects", _Py_GetObjects, METH_VARARGS},
Tim Peters4be93d02002-07-07 19:59:50 +00001053#endif
1054#ifdef Py_REF_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 {"gettotalrefcount", (PyCFunction)sys_gettotalrefcount, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001056#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 {"getrefcount", (PyCFunction)sys_getrefcount, METH_O, getrefcount_doc},
1058 {"getrecursionlimit", (PyCFunction)sys_getrecursionlimit, METH_NOARGS,
1059 getrecursionlimit_doc},
1060 {"getsizeof", (PyCFunction)sys_getsizeof,
1061 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
1062 {"_getframe", sys_getframe, METH_VARARGS, getframe_doc},
Mark Hammond8696ebc2002-10-08 02:44:31 +00001063#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 {"getwindowsversion", (PyCFunction)sys_getwindowsversion, METH_NOARGS,
1065 getwindowsversion_doc},
Mark Hammond8696ebc2002-10-08 02:44:31 +00001066#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 {"intern", sys_intern, METH_VARARGS, intern_doc},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001068#ifdef USE_MALLOPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 {"mdebug", sys_mdebug, METH_VARARGS},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001070#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 {"setcheckinterval", sys_setcheckinterval, METH_VARARGS,
1072 setcheckinterval_doc},
1073 {"getcheckinterval", sys_getcheckinterval, METH_NOARGS,
1074 getcheckinterval_doc},
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001075#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 {"setswitchinterval", sys_setswitchinterval, METH_VARARGS,
1077 setswitchinterval_doc},
1078 {"getswitchinterval", sys_getswitchinterval, METH_NOARGS,
1079 getswitchinterval_doc},
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001080#endif
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001081#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 {"setdlopenflags", sys_setdlopenflags, METH_VARARGS,
1083 setdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001084#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 {"setprofile", sys_setprofile, METH_O, setprofile_doc},
1086 {"getprofile", sys_getprofile, METH_NOARGS, getprofile_doc},
1087 {"setrecursionlimit", sys_setrecursionlimit, METH_VARARGS,
1088 setrecursionlimit_doc},
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00001089#ifdef WITH_TSC
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001090 {"settscdump", sys_settscdump, METH_VARARGS, settscdump_doc},
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00001091#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 {"settrace", sys_settrace, METH_O, settrace_doc},
1093 {"gettrace", sys_gettrace, METH_NOARGS, gettrace_doc},
1094 {"call_tracing", sys_call_tracing, METH_VARARGS, call_tracing_doc},
1095 {NULL, NULL} /* sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +00001096};
1097
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001098static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001099list_builtin_module_names(void)
Guido van Rossum34679b71993-01-26 13:33:44 +00001100{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 PyObject *list = PyList_New(0);
1102 int i;
1103 if (list == NULL)
1104 return NULL;
1105 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1106 PyObject *name = PyUnicode_FromString(
1107 PyImport_Inittab[i].name);
1108 if (name == NULL)
1109 break;
1110 PyList_Append(list, name);
1111 Py_DECREF(name);
1112 }
1113 if (PyList_Sort(list) != 0) {
1114 Py_DECREF(list);
1115 list = NULL;
1116 }
1117 if (list) {
1118 PyObject *v = PyList_AsTuple(list);
1119 Py_DECREF(list);
1120 list = v;
1121 }
1122 return list;
Guido van Rossum34679b71993-01-26 13:33:44 +00001123}
1124
Guido van Rossum23fff912000-12-15 22:02:05 +00001125static PyObject *warnoptions = NULL;
1126
1127void
1128PySys_ResetWarnOptions(void)
1129{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 if (warnoptions == NULL || !PyList_Check(warnoptions))
1131 return;
1132 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
Guido van Rossum23fff912000-12-15 22:02:05 +00001133}
1134
1135void
Victor Stinner9ca9c252010-05-19 16:53:30 +00001136PySys_AddWarnOptionUnicode(PyObject *unicode)
Guido van Rossum23fff912000-12-15 22:02:05 +00001137{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001138 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
1139 Py_XDECREF(warnoptions);
1140 warnoptions = PyList_New(0);
1141 if (warnoptions == NULL)
1142 return;
1143 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00001144 PyList_Append(warnoptions, unicode);
1145}
1146
1147void
1148PySys_AddWarnOption(const wchar_t *s)
1149{
1150 PyObject *unicode;
1151 unicode = PyUnicode_FromWideChar(s, -1);
1152 if (unicode == NULL)
1153 return;
1154 PySys_AddWarnOptionUnicode(unicode);
1155 Py_DECREF(unicode);
Guido van Rossum23fff912000-12-15 22:02:05 +00001156}
1157
Christian Heimes33fe8092008-04-13 13:53:33 +00001158int
1159PySys_HasWarnOptions(void)
1160{
1161 return (warnoptions != NULL && (PyList_Size(warnoptions) > 0)) ? 1 : 0;
1162}
1163
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001164static PyObject *xoptions = NULL;
1165
1166static PyObject *
1167get_xoptions(void)
1168{
1169 if (xoptions == NULL || !PyDict_Check(xoptions)) {
1170 Py_XDECREF(xoptions);
1171 xoptions = PyDict_New();
1172 }
1173 return xoptions;
1174}
1175
1176void
1177PySys_AddXOption(const wchar_t *s)
1178{
1179 PyObject *opts;
1180 PyObject *name = NULL, *value = NULL;
1181 const wchar_t *name_end;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001182
1183 opts = get_xoptions();
1184 if (opts == NULL)
1185 goto error;
1186
1187 name_end = wcschr(s, L'=');
1188 if (!name_end) {
1189 name = PyUnicode_FromWideChar(s, -1);
1190 value = Py_True;
1191 Py_INCREF(value);
1192 }
1193 else {
1194 name = PyUnicode_FromWideChar(s, name_end - s);
1195 value = PyUnicode_FromWideChar(name_end + 1, -1);
1196 }
1197 if (name == NULL || value == NULL)
1198 goto error;
Brett Cannonb94767f2011-02-22 20:15:44 +00001199 PyDict_SetItem(opts, name, value);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001200 Py_DECREF(name);
1201 Py_DECREF(value);
1202 return;
1203
1204error:
1205 Py_XDECREF(name);
1206 Py_XDECREF(value);
1207 /* No return value, therefore clear error state if possible */
1208 if (_Py_atomic_load_relaxed(&_PyThreadState_Current))
1209 PyErr_Clear();
1210}
1211
1212PyObject *
1213PySys_GetXOptions(void)
1214{
1215 return get_xoptions();
1216}
1217
Guido van Rossum40552d01998-08-06 03:34:39 +00001218/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
1219 Two literals concatenated works just fine. If you have a K&R compiler
1220 or other abomination that however *does* understand longer strings,
1221 get rid of the !!! comment in the middle and the quotes that surround it. */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001222PyDoc_VAR(sys_doc) =
1223PyDoc_STR(
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001224"This module provides access to some objects used or maintained by the\n\
1225interpreter and to functions that interact strongly with the interpreter.\n\
1226\n\
1227Dynamic objects:\n\
1228\n\
1229argv -- command line arguments; argv[0] is the script pathname if known\n\
1230path -- module search path; path[0] is the script directory, else ''\n\
1231modules -- dictionary of loaded modules\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001232\n\
1233displayhook -- called to show results in an interactive session\n\
1234excepthook -- called to handle any uncaught exception other than SystemExit\n\
1235 To customize printing in an interactive session or to install a custom\n\
1236 top-level exception handler, assign other functions to replace these.\n\
1237\n\
Benjamin Peterson06157a42008-07-15 00:28:36 +00001238stdin -- standard input file object; used by input()\n\
Georg Brandl88fc6642007-02-09 21:28:07 +00001239stdout -- standard output file object; used by print()\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001240stderr -- standard error object; used for error messages\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001241 By assigning other file objects (or objects that behave like files)\n\
1242 to these, it is possible to redirect all of the interpreter's I/O.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001243\n\
1244last_type -- type of last uncaught exception\n\
1245last_value -- value of last uncaught exception\n\
1246last_traceback -- traceback of last uncaught exception\n\
1247 These three are only available in an interactive session after a\n\
1248 traceback has been printed.\n\
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001249"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001250)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001251/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001252PyDoc_STR(
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001253"\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001254Static objects:\n\
1255\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001256builtin_module_names -- tuple of module names built into this interpreter\n\
1257copyright -- copyright notice pertaining to this interpreter\n\
1258exec_prefix -- prefix used to find the machine-specific Python library\n\
1259executable -- pathname of this Python interpreter\n\
1260float_info -- a struct sequence with information about the float implementation.\n\
1261float_repr_style -- string indicating the style of repr() output for floats\n\
1262hexversion -- version information encoded as a single integer\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00001263int_info -- a struct sequence with information about the int implementation.\n\
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00001264maxsize -- the largest supported length of containers.\n\
Ezio Melotti48a2f8f2011-09-29 00:18:19 +03001265maxunicode -- the value of the largest Unicode codepoint\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001266platform -- platform identifier\n\
1267prefix -- prefix used to find the Python library\n\
1268thread_info -- a struct sequence with information about the thread implementation.\n\
Fred Drake801c08d2000-04-13 15:29:10 +00001269version -- the version of this interpreter as a string\n\
Eric Smith0e5b5622009-02-06 01:32:42 +00001270version_info -- version information as a named tuple\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001271"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001272)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001273#ifdef MS_WINDOWS
1274/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001275PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001276"dllhandle -- [Windows only] integer handle of the Python DLL\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001277winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001278"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001279)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001280#endif /* MS_WINDOWS */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001281PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001282"__stdin__ -- the original stdin; don't touch!\n\
1283__stdout__ -- the original stdout; don't touch!\n\
1284__stderr__ -- the original stderr; don't touch!\n\
1285__displayhook__ -- the original displayhook; don't touch!\n\
1286__excepthook__ -- the original excepthook; don't touch!\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001287\n\
1288Functions:\n\
1289\n\
Georg Brandl1a3284e2007-12-02 09:40:06 +00001290displayhook() -- print an object to the screen, and save it in builtins._\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001291excepthook() -- print an exception and its traceback to sys.stderr\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001292exc_info() -- return thread-safe information about the current exception\n\
1293exit() -- exit the interpreter by raising SystemExit\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001294getdlopenflags() -- returns flags to be used for dlopen() calls\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00001295getprofile() -- get the global profiling function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001296getrefcount() -- return the reference count for an object (plus one :-)\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001297getrecursionlimit() -- return the max recursion depth for the interpreter\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001298getsizeof() -- return the size of an object in bytes\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00001299gettrace() -- get the global debug tracing function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001300setcheckinterval() -- control how often the interpreter checks for events\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001301setdlopenflags() -- set the flags to be used for dlopen() calls\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001302setprofile() -- set the global profiling function\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001303setrecursionlimit() -- set the max recursion depth for the interpreter\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001304settrace() -- set the global debug tracing function\n\
Fred Drakeccede592000-08-14 20:59:57 +00001305"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001306)
Fred Drakeccede592000-08-14 20:59:57 +00001307/* end of sys_doc */ ;
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001308
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001309
1310PyDoc_STRVAR(flags__doc__,
1311"sys.flags\n\
1312\n\
1313Flags provided through command line arguments or environment vars.");
1314
1315static PyTypeObject FlagsType;
1316
1317static PyStructSequence_Field flags_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001318 {"debug", "-d"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 {"inspect", "-i"},
1320 {"interactive", "-i"},
1321 {"optimize", "-O or -OO"},
1322 {"dont_write_bytecode", "-B"},
1323 {"no_user_site", "-s"},
1324 {"no_site", "-S"},
1325 {"ignore_environment", "-E"},
1326 {"verbose", "-v"},
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001327#ifdef RISCOS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328 {"riscos_wimp", "???"},
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001329#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 /* {"unbuffered", "-u"}, */
1331 /* {"skip_first", "-x"}, */
Georg Brandl8aa7e992010-12-28 18:30:18 +00001332 {"bytes_warning", "-b"},
1333 {"quiet", "-q"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001335};
1336
1337static PyStructSequence_Desc flags_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001338 "sys.flags", /* name */
1339 flags__doc__, /* doc */
1340 flags_fields, /* fields */
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001341#ifdef RISCOS
Raymond Hettinger90e8f8c2011-01-05 20:08:25 +00001342 12
Éric Araujobe3bd572011-03-26 01:55:15 +01001343#else
1344 11
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001345#endif
1346};
1347
1348static PyObject*
1349make_flags(void)
1350{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 int pos = 0;
1352 PyObject *seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001354 seq = PyStructSequence_New(&FlagsType);
1355 if (seq == NULL)
1356 return NULL;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001357
1358#define SetFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001361 SetFlag(Py_DebugFlag);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 SetFlag(Py_InspectFlag);
1363 SetFlag(Py_InteractiveFlag);
1364 SetFlag(Py_OptimizeFlag);
1365 SetFlag(Py_DontWriteBytecodeFlag);
1366 SetFlag(Py_NoUserSiteDirectory);
1367 SetFlag(Py_NoSiteFlag);
1368 SetFlag(Py_IgnoreEnvironmentFlag);
1369 SetFlag(Py_VerboseFlag);
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001370#ifdef RISCOS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001371 SetFlag(Py_RISCOSWimpFlag);
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001372#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001373 /* SetFlag(saw_unbuffered_flag); */
1374 /* SetFlag(skipfirstline); */
Christian Heimes33fe8092008-04-13 13:53:33 +00001375 SetFlag(Py_BytesWarningFlag);
Georg Brandl8aa7e992010-12-28 18:30:18 +00001376 SetFlag(Py_QuietFlag);
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001377#undef SetFlag
1378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001379 if (PyErr_Occurred()) {
1380 return NULL;
1381 }
1382 return seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001383}
1384
Eric Smith0e5b5622009-02-06 01:32:42 +00001385PyDoc_STRVAR(version_info__doc__,
1386"sys.version_info\n\
1387\n\
1388Version information as a named tuple.");
1389
1390static PyTypeObject VersionInfoType;
1391
1392static PyStructSequence_Field version_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001393 {"major", "Major release number"},
1394 {"minor", "Minor release number"},
1395 {"micro", "Patch release number"},
1396 {"releaselevel", "'alpha', 'beta', 'candidate', or 'release'"},
1397 {"serial", "Serial release number"},
1398 {0}
Eric Smith0e5b5622009-02-06 01:32:42 +00001399};
1400
1401static PyStructSequence_Desc version_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001402 "sys.version_info", /* name */
1403 version_info__doc__, /* doc */
1404 version_info_fields, /* fields */
1405 5
Eric Smith0e5b5622009-02-06 01:32:42 +00001406};
1407
1408static PyObject *
1409make_version_info(void)
1410{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001411 PyObject *version_info;
1412 char *s;
1413 int pos = 0;
Eric Smith0e5b5622009-02-06 01:32:42 +00001414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 version_info = PyStructSequence_New(&VersionInfoType);
1416 if (version_info == NULL) {
1417 return NULL;
1418 }
Eric Smith0e5b5622009-02-06 01:32:42 +00001419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001420 /*
1421 * These release level checks are mutually exclusive and cover
1422 * the field, so don't get too fancy with the pre-processor!
1423 */
Eric Smith0e5b5622009-02-06 01:32:42 +00001424#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 s = "alpha";
Eric Smith0e5b5622009-02-06 01:32:42 +00001426#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001427 s = "beta";
Eric Smith0e5b5622009-02-06 01:32:42 +00001428#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001429 s = "candidate";
Eric Smith0e5b5622009-02-06 01:32:42 +00001430#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 s = "final";
Eric Smith0e5b5622009-02-06 01:32:42 +00001432#endif
1433
1434#define SetIntItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001435 PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00001436#define SetStrItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001437 PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00001438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001439 SetIntItem(PY_MAJOR_VERSION);
1440 SetIntItem(PY_MINOR_VERSION);
1441 SetIntItem(PY_MICRO_VERSION);
1442 SetStrItem(s);
1443 SetIntItem(PY_RELEASE_SERIAL);
Eric Smith0e5b5622009-02-06 01:32:42 +00001444#undef SetIntItem
1445#undef SetStrItem
1446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001447 if (PyErr_Occurred()) {
1448 Py_CLEAR(version_info);
1449 return NULL;
1450 }
1451 return version_info;
Eric Smith0e5b5622009-02-06 01:32:42 +00001452}
1453
Martin v. Löwis1a214512008-06-11 05:26:20 +00001454static struct PyModuleDef sysmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001455 PyModuleDef_HEAD_INIT,
1456 "sys",
1457 sys_doc,
1458 -1, /* multiple "initialization" just copies the module dict. */
1459 sys_methods,
1460 NULL,
1461 NULL,
1462 NULL,
1463 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001464};
1465
Guido van Rossum25ce5661997-08-02 03:10:38 +00001466PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001467_PySys_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001468{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001469 PyObject *m, *v, *sysdict;
1470 char *s;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 m = PyModule_Create(&sysmodule);
1473 if (m == NULL)
1474 return NULL;
1475 sysdict = PyModule_GetDict(m);
1476#define SET_SYS_FROM_STRING(key, value) \
1477 v = value; \
1478 if (v != NULL) \
1479 PyDict_SetItemString(sysdict, key, v); \
1480 Py_XDECREF(v)
Guido van Rossum25ce5661997-08-02 03:10:38 +00001481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001482 /* Check that stdin is not a directory
1483 Using shell redirection, you can redirect stdin to a directory,
1484 crashing the Python interpreter. Catch this common mistake here
1485 and output a useful error message. Note that under MS Windows,
1486 the shell already prevents that. */
Martin v. Löwisec59d042009-01-12 07:59:10 +00001487#if !defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001488 {
1489 struct stat sb;
1490 if (fstat(fileno(stdin), &sb) == 0 &&
1491 S_ISDIR(sb.st_mode)) {
1492 /* There's nothing more we can do. */
1493 /* Py_FatalError() will core dump, so just exit. */
1494 PySys_WriteStderr("Python error: <stdin> is a directory, cannot continue\n");
1495 exit(EXIT_FAILURE);
1496 }
1497 }
Martin v. Löwisec59d042009-01-12 07:59:10 +00001498#endif
Neal Norwitz11bd1192005-10-03 00:54:56 +00001499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001500 /* stdin/stdout/stderr are now set by pythonrun.c */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001502 PyDict_SetItemString(sysdict, "__displayhook__",
1503 PyDict_GetItemString(sysdict, "displayhook"));
1504 PyDict_SetItemString(sysdict, "__excepthook__",
1505 PyDict_GetItemString(sysdict, "excepthook"));
1506 SET_SYS_FROM_STRING("version",
1507 PyUnicode_FromString(Py_GetVersion()));
1508 SET_SYS_FROM_STRING("hexversion",
1509 PyLong_FromLong(PY_VERSION_HEX));
Georg Brandl1ca2e792011-03-05 20:51:24 +01001510 SET_SYS_FROM_STRING("_mercurial",
1511 Py_BuildValue("(szz)", "CPython", _Py_hgidentifier(),
1512 _Py_hgversion()));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001513 SET_SYS_FROM_STRING("dont_write_bytecode",
1514 PyBool_FromLong(Py_DontWriteBytecodeFlag));
1515 SET_SYS_FROM_STRING("api_version",
1516 PyLong_FromLong(PYTHON_API_VERSION));
1517 SET_SYS_FROM_STRING("copyright",
1518 PyUnicode_FromString(Py_GetCopyright()));
1519 SET_SYS_FROM_STRING("platform",
1520 PyUnicode_FromString(Py_GetPlatform()));
1521 SET_SYS_FROM_STRING("executable",
1522 PyUnicode_FromWideChar(
1523 Py_GetProgramFullPath(), -1));
1524 SET_SYS_FROM_STRING("prefix",
1525 PyUnicode_FromWideChar(Py_GetPrefix(), -1));
1526 SET_SYS_FROM_STRING("exec_prefix",
1527 PyUnicode_FromWideChar(Py_GetExecPrefix(), -1));
1528 SET_SYS_FROM_STRING("maxsize",
1529 PyLong_FromSsize_t(PY_SSIZE_T_MAX));
1530 SET_SYS_FROM_STRING("float_info",
1531 PyFloat_GetInfo());
1532 SET_SYS_FROM_STRING("int_info",
1533 PyLong_GetInfo());
Mark Dickinsondc787d22010-05-23 13:33:13 +00001534 /* initialize hash_info */
1535 if (Hash_InfoType.tp_name == 0)
1536 PyStructSequence_InitType(&Hash_InfoType, &hash_info_desc);
1537 SET_SYS_FROM_STRING("hash_info",
1538 get_hash_info());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001539 SET_SYS_FROM_STRING("maxunicode",
Ezio Melotti48a2f8f2011-09-29 00:18:19 +03001540 PyLong_FromLong(0x10FFFF));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001541 SET_SYS_FROM_STRING("builtin_module_names",
1542 list_builtin_module_names());
1543 {
1544 /* Assumes that longs are at least 2 bytes long.
1545 Should be safe! */
1546 unsigned long number = 1;
1547 char *value;
Fred Drake099325e2000-08-14 15:47:03 +00001548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001549 s = (char *) &number;
1550 if (s[0] == 0)
1551 value = "big";
1552 else
1553 value = "little";
1554 SET_SYS_FROM_STRING("byteorder",
1555 PyUnicode_FromString(value));
1556 }
Guido van Rossum8b9ea871996-08-23 18:14:47 +00001557#ifdef MS_COREDLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 SET_SYS_FROM_STRING("dllhandle",
1559 PyLong_FromVoidPtr(PyWin_DLLhModule));
1560 SET_SYS_FROM_STRING("winver",
1561 PyUnicode_FromString(PyWin_DLLVersionString));
Guido van Rossumc606fe11996-04-09 02:37:57 +00001562#endif
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00001563#ifdef ABIFLAGS
1564 SET_SYS_FROM_STRING("abiflags",
1565 PyUnicode_FromString(ABIFLAGS));
1566#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001567 if (warnoptions == NULL) {
1568 warnoptions = PyList_New(0);
1569 }
1570 else {
1571 Py_INCREF(warnoptions);
1572 }
1573 if (warnoptions != NULL) {
1574 PyDict_SetItemString(sysdict, "warnoptions", warnoptions);
1575 }
Tim Peters216b78b2006-01-06 02:40:53 +00001576
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001577 v = get_xoptions();
1578 if (v != NULL) {
1579 PyDict_SetItemString(sysdict, "_xoptions", v);
1580 }
1581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001582 /* version_info */
1583 if (VersionInfoType.tp_name == 0)
1584 PyStructSequence_InitType(&VersionInfoType, &version_info_desc);
1585 SET_SYS_FROM_STRING("version_info", make_version_info());
1586 /* prevent user from creating new instances */
1587 VersionInfoType.tp_init = NULL;
1588 VersionInfoType.tp_new = NULL;
Eric Smith0e5b5622009-02-06 01:32:42 +00001589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001590 /* flags */
1591 if (FlagsType.tp_name == 0)
1592 PyStructSequence_InitType(&FlagsType, &flags_desc);
1593 SET_SYS_FROM_STRING("flags", make_flags());
1594 /* prevent user from creating new instances */
1595 FlagsType.tp_init = NULL;
1596 FlagsType.tp_new = NULL;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001597
Eric Smithf7bb5782010-01-27 00:44:57 +00001598
1599#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 /* getwindowsversion */
1601 if (WindowsVersionType.tp_name == 0)
1602 PyStructSequence_InitType(&WindowsVersionType, &windows_version_desc);
1603 /* prevent user from creating new instances */
1604 WindowsVersionType.tp_init = NULL;
1605 WindowsVersionType.tp_new = NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +00001606#endif
1607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001608 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00001609#ifndef PY_NO_SHORT_FLOAT_REPR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001610 SET_SYS_FROM_STRING("float_repr_style",
1611 PyUnicode_FromString("short"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00001612#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 SET_SYS_FROM_STRING("float_repr_style",
1614 PyUnicode_FromString("legacy"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00001615#endif
1616
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001617#ifdef WITH_THREAD
1618 SET_SYS_FROM_STRING("thread_info", PyThread_GetInfo());
1619#endif
1620
Christian Heimes7b3ce6a2008-01-31 14:31:45 +00001621#undef SET_SYS_FROM_STRING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 if (PyErr_Occurred())
1623 return NULL;
1624 return m;
Guido van Rossum5b3138b1990-11-18 17:41:40 +00001625}
1626
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001627static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00001628makepathobject(const wchar_t *path, wchar_t delim)
Guido van Rossum5b3138b1990-11-18 17:41:40 +00001629{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001630 int i, n;
1631 const wchar_t *p;
1632 PyObject *v, *w;
Tim Peters216b78b2006-01-06 02:40:53 +00001633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001634 n = 1;
1635 p = path;
1636 while ((p = wcschr(p, delim)) != NULL) {
1637 n++;
1638 p++;
1639 }
1640 v = PyList_New(n);
1641 if (v == NULL)
1642 return NULL;
1643 for (i = 0; ; i++) {
1644 p = wcschr(path, delim);
1645 if (p == NULL)
1646 p = path + wcslen(path); /* End of string */
1647 w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
1648 if (w == NULL) {
1649 Py_DECREF(v);
1650 return NULL;
1651 }
1652 PyList_SetItem(v, i, w);
1653 if (*p == '\0')
1654 break;
1655 path = p+1;
1656 }
1657 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001658}
1659
1660void
Martin v. Löwis790465f2008-04-05 20:41:37 +00001661PySys_SetPath(const wchar_t *path)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001662{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001663 PyObject *v;
1664 if ((v = makepathobject(path, DELIM)) == NULL)
1665 Py_FatalError("can't create sys.path");
1666 if (PySys_SetObject("path", v) != 0)
1667 Py_FatalError("can't assign sys.path");
1668 Py_DECREF(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001669}
1670
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001671static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00001672makeargvobject(int argc, wchar_t **argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001673{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001674 PyObject *av;
1675 if (argc <= 0 || argv == NULL) {
1676 /* Ensure at least one (empty) argument is seen */
1677 static wchar_t *empty_argv[1] = {L""};
1678 argv = empty_argv;
1679 argc = 1;
1680 }
1681 av = PyList_New(argc);
1682 if (av != NULL) {
1683 int i;
1684 for (i = 0; i < argc; i++) {
Martin v. Löwisc16f3bd2003-05-03 09:14:54 +00001685#ifdef __VMS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001686 PyObject *v;
Martin v. Löwisc16f3bd2003-05-03 09:14:54 +00001687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001688 /* argv[0] is the script pathname if known */
1689 if (i == 0) {
1690 char* fn = decc$translate_vms(argv[0]);
1691 if ((fn == (char *)0) || fn == (char *)-1)
1692 v = PyUnicode_FromString(argv[0]);
1693 else
1694 v = PyUnicode_FromString(
1695 decc$translate_vms(argv[0]));
1696 } else
1697 v = PyUnicode_FromString(argv[i]);
Martin v. Löwisc16f3bd2003-05-03 09:14:54 +00001698#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001699 PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
Martin v. Löwisc16f3bd2003-05-03 09:14:54 +00001700#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 if (v == NULL) {
1702 Py_DECREF(av);
1703 av = NULL;
1704 break;
1705 }
1706 PyList_SetItem(av, i, v);
1707 }
1708 }
1709 return av;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001710}
1711
Nick Coghland26c18a2010-08-17 13:06:11 +00001712#define _HAVE_SCRIPT_ARGUMENT(argc, argv) \
1713 (argc > 0 && argv0 != NULL && \
1714 wcscmp(argv0, L"-c") != 0 && wcscmp(argv0, L"-m") != 0)
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001715
1716static void
1717sys_update_path(int argc, wchar_t **argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001718{
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001719 wchar_t *argv0;
1720 wchar_t *p = NULL;
1721 Py_ssize_t n = 0;
1722 PyObject *a;
1723 PyObject *path;
1724#ifdef HAVE_READLINK
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001725 wchar_t link[MAXPATHLEN+1];
1726 wchar_t argv0copy[2*MAXPATHLEN+1];
1727 int nr = 0;
1728#endif
Guido van Rossum162e38c2003-02-19 15:25:10 +00001729#if defined(HAVE_REALPATH)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001730 wchar_t fullpath[MAXPATHLEN];
Martin v. Löwisec59d042009-01-12 07:59:10 +00001731#elif defined(MS_WINDOWS) && !defined(MS_WINCE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001732 wchar_t fullpath[MAX_PATH];
Thomas Heller27bb71e2003-01-08 14:33:48 +00001733#endif
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001734
1735 path = PySys_GetObject("path");
1736 if (path == NULL)
1737 return;
1738
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001739 argv0 = argv[0];
1740
1741#ifdef HAVE_READLINK
1742 if (_HAVE_SCRIPT_ARGUMENT(argc, argv))
1743 nr = _Py_wreadlink(argv0, link, MAXPATHLEN);
1744 if (nr > 0) {
1745 /* It's a symlink */
1746 link[nr] = '\0';
1747 if (link[0] == SEP)
1748 argv0 = link; /* Link to absolute path */
1749 else if (wcschr(link, SEP) == NULL)
1750 ; /* Link without path */
1751 else {
1752 /* Must join(dirname(argv0), link) */
1753 wchar_t *q = wcsrchr(argv0, SEP);
1754 if (q == NULL)
1755 argv0 = link; /* argv0 without path */
1756 else {
1757 /* Must make a copy */
1758 wcscpy(argv0copy, argv0);
1759 q = wcsrchr(argv0copy, SEP);
1760 wcscpy(q+1, link);
1761 argv0 = argv0copy;
1762 }
1763 }
1764 }
1765#endif /* HAVE_READLINK */
1766#if SEP == '\\' /* Special case for MS filename syntax */
1767 if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) {
1768 wchar_t *q;
1769#if defined(MS_WINDOWS) && !defined(MS_WINCE)
1770 /* This code here replaces the first element in argv with the full
1771 path that it represents. Under CE, there are no relative paths so
1772 the argument must be the full path anyway. */
1773 wchar_t *ptemp;
1774 if (GetFullPathNameW(argv0,
Victor Stinner63941882011-09-29 00:42:28 +02001775 Py_ARRAY_LENGTH(fullpath),
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001776 fullpath,
1777 &ptemp)) {
1778 argv0 = fullpath;
1779 }
1780#endif
1781 p = wcsrchr(argv0, SEP);
1782 /* Test for alternate separator */
1783 q = wcsrchr(p ? p : argv0, '/');
1784 if (q != NULL)
1785 p = q;
1786 if (p != NULL) {
1787 n = p + 1 - argv0;
1788 if (n > 1 && p[-1] != ':')
1789 n--; /* Drop trailing separator */
1790 }
1791 }
1792#else /* All other filename syntaxes */
1793 if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) {
1794#if defined(HAVE_REALPATH)
Victor Stinner015f4d82010-10-07 22:29:53 +00001795 if (_Py_wrealpath(argv0, fullpath, PATH_MAX)) {
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001796 argv0 = fullpath;
1797 }
1798#endif
1799 p = wcsrchr(argv0, SEP);
1800 }
1801 if (p != NULL) {
1802 n = p + 1 - argv0;
1803#if SEP == '/' /* Special case for Unix filename syntax */
1804 if (n > 1)
1805 n--; /* Drop trailing separator */
1806#endif /* Unix */
1807 }
1808#endif /* All others */
1809 a = PyUnicode_FromWideChar(argv0, n);
1810 if (a == NULL)
1811 Py_FatalError("no mem for sys.path insertion");
1812 if (PyList_Insert(path, 0, a) < 0)
1813 Py_FatalError("sys.path.insert(0) failed");
1814 Py_DECREF(a);
1815}
1816
1817void
1818PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
1819{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001820 PyObject *av = makeargvobject(argc, argv);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001821 if (av == NULL)
1822 Py_FatalError("no mem for sys.argv");
1823 if (PySys_SetObject("argv", av) != 0)
1824 Py_FatalError("can't assign sys.argv");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001825 Py_DECREF(av);
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001826 if (updatepath)
1827 sys_update_path(argc, argv);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001828}
Guido van Rossuma890e681998-05-12 14:59:24 +00001829
Antoine Pitrouf978fac2010-05-21 17:25:34 +00001830void
1831PySys_SetArgv(int argc, wchar_t **argv)
1832{
1833 PySys_SetArgvEx(argc, argv, 1);
1834}
1835
Victor Stinner14284c22010-04-23 12:02:30 +00001836/* Reimplementation of PyFile_WriteString() no calling indirectly
1837 PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
1838
1839static int
Victor Stinner79766632010-08-16 17:36:42 +00001840sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
Victor Stinner14284c22010-04-23 12:02:30 +00001841{
Victor Stinner79766632010-08-16 17:36:42 +00001842 PyObject *writer = NULL, *args = NULL, *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001843 int err;
Victor Stinner14284c22010-04-23 12:02:30 +00001844
Victor Stinnerecccc4f2010-06-08 20:46:00 +00001845 if (file == NULL)
1846 return -1;
1847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 writer = PyObject_GetAttrString(file, "write");
1849 if (writer == NULL)
1850 goto error;
Victor Stinner14284c22010-04-23 12:02:30 +00001851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001852 args = PyTuple_Pack(1, unicode);
1853 if (args == NULL)
1854 goto error;
Victor Stinner14284c22010-04-23 12:02:30 +00001855
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001856 result = PyEval_CallObject(writer, args);
1857 if (result == NULL) {
1858 goto error;
1859 } else {
1860 err = 0;
1861 goto finally;
1862 }
Victor Stinner14284c22010-04-23 12:02:30 +00001863
1864error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 err = -1;
Victor Stinner14284c22010-04-23 12:02:30 +00001866finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001867 Py_XDECREF(writer);
1868 Py_XDECREF(args);
1869 Py_XDECREF(result);
1870 return err;
Victor Stinner14284c22010-04-23 12:02:30 +00001871}
1872
Victor Stinner79766632010-08-16 17:36:42 +00001873static int
1874sys_pyfile_write(const char *text, PyObject *file)
1875{
1876 PyObject *unicode = NULL;
1877 int err;
1878
1879 if (file == NULL)
1880 return -1;
1881
1882 unicode = PyUnicode_FromString(text);
1883 if (unicode == NULL)
1884 return -1;
1885
1886 err = sys_pyfile_write_unicode(unicode, file);
1887 Py_DECREF(unicode);
1888 return err;
1889}
Guido van Rossuma890e681998-05-12 14:59:24 +00001890
1891/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
1892 Adapted from code submitted by Just van Rossum.
1893
1894 PySys_WriteStdout(format, ...)
1895 PySys_WriteStderr(format, ...)
1896
1897 The first function writes to sys.stdout; the second to sys.stderr. When
1898 there is a problem, they write to the real (C level) stdout or stderr;
Guido van Rossum8442af31998-10-12 18:22:10 +00001899 no exceptions are raised.
Guido van Rossuma890e681998-05-12 14:59:24 +00001900
Victor Stinner14284c22010-04-23 12:02:30 +00001901 PyErr_CheckSignals() is not called to avoid the execution of the Python
Victor Stinner79766632010-08-16 17:36:42 +00001902 signal handlers: they may raise a new exception whereas sys_write()
1903 ignores all exceptions.
Victor Stinner14284c22010-04-23 12:02:30 +00001904
Guido van Rossuma890e681998-05-12 14:59:24 +00001905 Both take a printf-style format string as their first argument followed
1906 by a variable length argument list determined by the format string.
1907
1908 *** WARNING ***
1909
1910 The format should limit the total size of the formatted output string to
1911 1000 bytes. In particular, this means that no unrestricted "%s" formats
1912 should occur; these should be limited using "%.<N>s where <N> is a
1913 decimal number calculated so that <N> plus the maximum size of other
1914 formatted text does not exceed 1000 bytes. Also watch out for "%f",
1915 which can print hundreds of digits for very large numbers.
1916
1917 */
1918
1919static void
Victor Stinner79766632010-08-16 17:36:42 +00001920sys_write(char *name, FILE *fp, const char *format, va_list va)
Guido van Rossuma890e681998-05-12 14:59:24 +00001921{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001922 PyObject *file;
1923 PyObject *error_type, *error_value, *error_traceback;
1924 char buffer[1001];
1925 int written;
Guido van Rossuma890e681998-05-12 14:59:24 +00001926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001927 PyErr_Fetch(&error_type, &error_value, &error_traceback);
1928 file = PySys_GetObject(name);
1929 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
1930 if (sys_pyfile_write(buffer, file) != 0) {
1931 PyErr_Clear();
1932 fputs(buffer, fp);
1933 }
1934 if (written < 0 || (size_t)written >= sizeof(buffer)) {
1935 const char *truncated = "... truncated";
Victor Stinner79766632010-08-16 17:36:42 +00001936 if (sys_pyfile_write(truncated, file) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001937 fputs(truncated, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001938 }
1939 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossuma890e681998-05-12 14:59:24 +00001940}
1941
1942void
Guido van Rossuma890e681998-05-12 14:59:24 +00001943PySys_WriteStdout(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00001944{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00001946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001947 va_start(va, format);
Victor Stinner79766632010-08-16 17:36:42 +00001948 sys_write("stdout", stdout, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001949 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00001950}
1951
1952void
Guido van Rossuma890e681998-05-12 14:59:24 +00001953PySys_WriteStderr(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00001954{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001955 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00001956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001957 va_start(va, format);
Victor Stinner79766632010-08-16 17:36:42 +00001958 sys_write("stderr", stderr, format, va);
1959 va_end(va);
1960}
1961
1962static void
1963sys_format(char *name, FILE *fp, const char *format, va_list va)
1964{
1965 PyObject *file, *message;
1966 PyObject *error_type, *error_value, *error_traceback;
1967 char *utf8;
1968
1969 PyErr_Fetch(&error_type, &error_value, &error_traceback);
1970 file = PySys_GetObject(name);
1971 message = PyUnicode_FromFormatV(format, va);
1972 if (message != NULL) {
1973 if (sys_pyfile_write_unicode(message, file) != 0) {
1974 PyErr_Clear();
1975 utf8 = _PyUnicode_AsString(message);
1976 if (utf8 != NULL)
1977 fputs(utf8, fp);
1978 }
1979 Py_DECREF(message);
1980 }
1981 PyErr_Restore(error_type, error_value, error_traceback);
1982}
1983
1984void
1985PySys_FormatStdout(const char *format, ...)
1986{
1987 va_list va;
1988
1989 va_start(va, format);
1990 sys_format("stdout", stdout, format, va);
1991 va_end(va);
1992}
1993
1994void
1995PySys_FormatStderr(const char *format, ...)
1996{
1997 va_list va;
1998
1999 va_start(va, format);
2000 sys_format("stderr", stderr, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002001 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002002}