blob: 3e5ecfe3f621c365175beed4eaa7513c1e22f308 [file] [log] [blame]
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001
2/* Python interpreter top-level routines, including init/exit */
3
Guido van Rossum82598051997-03-05 00:20:32 +00004#include "Python.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +00005
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006#include "Python-ast.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +00007#include "grammar.h"
8#include "node.h"
Fred Drake85f36392000-07-11 17:53:00 +00009#include "token.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000010#include "parsetok.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000011#include "errcode.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000012#include "code.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000013#include "compile.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000014#include "symtable.h"
Neal Norwitzadb69fc2005-12-17 20:54:49 +000015#include "pyarena.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000016#include "ast.h"
Guido van Rossumff4949e1992-08-05 19:58:53 +000017#include "eval.h"
Guido van Rossumfdef2711994-09-14 13:31:04 +000018#include "marshal.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000019
Martin v. Löwis0e8bd7e2006-06-10 12:23:46 +000020#ifdef HAVE_SIGNAL_H
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000021#include <signal.h>
Martin v. Löwis0e8bd7e2006-06-10 12:23:46 +000022#endif
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000023
Martin v. Löwis73d538b2003-03-05 15:13:47 +000024#ifdef HAVE_LANGINFO_H
25#include <locale.h>
26#include <langinfo.h>
27#endif
28
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000029#ifdef MS_WINDOWS
Guido van Rossuma44823b1995-03-14 15:01:17 +000030#undef BYTE
31#include "windows.h"
32#endif
33
Neal Norwitz4281cef2006-03-04 19:58:13 +000034#ifndef Py_REF_DEBUG
Tim Peters62e97f02006-03-28 21:44:32 +000035#define PRINT_TOTAL_REFS()
Neal Norwitz4281cef2006-03-04 19:58:13 +000036#else /* Py_REF_DEBUG */
Tim Peters62e97f02006-03-28 21:44:32 +000037#define PRINT_TOTAL_REFS() fprintf(stderr, \
38 "[%" PY_FORMAT_SIZE_T "d refs]\n", \
Armin Rigoe1709372006-04-12 17:06:05 +000039 _Py_GetRefTotal())
Neal Norwitz4281cef2006-03-04 19:58:13 +000040#endif
41
Anthony Baxterac6bd462006-04-13 02:06:09 +000042#ifdef __cplusplus
43extern "C" {
44#endif
45
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000046extern char *Py_GetPath(void);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000047
Guido van Rossum82598051997-03-05 00:20:32 +000048extern grammar _PyParser_Grammar; /* From graminit.c */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000049
Guido van Rossumb73cc041993-11-01 16:28:59 +000050/* Forward */
Tim Petersdbd9ba62000-07-09 03:09:57 +000051static void initmain(void);
52static void initsite(void);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000053static PyObject *run_mod(mod_ty, const char *, PyObject *, PyObject *,
Neal Norwitzadb69fc2005-12-17 20:54:49 +000054 PyCompilerFlags *, PyArena *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000055static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
Jeremy Hyltonbc320242001-03-22 02:47:58 +000056 PyCompilerFlags *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000057static void err_input(perrdetail *);
58static void initsigs(void);
59static void call_sys_exitfunc(void);
60static void call_ll_exitfuncs(void);
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000061extern void _PyUnicode_Init(void);
62extern void _PyUnicode_Fini(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +000063
Mark Hammond8d98d2c2003-04-19 15:41:53 +000064#ifdef WITH_THREAD
65extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
66extern void _PyGILState_Fini(void);
67#endif /* WITH_THREAD */
68
Guido van Rossum82598051997-03-05 00:20:32 +000069int Py_DebugFlag; /* Needed by parser.c */
70int Py_VerboseFlag; /* Needed by import.c */
Guido van Rossum7433b121997-02-14 19:45:36 +000071int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Georg Brandl49aafc92007-03-07 00:34:46 +000072int Py_InspectFlag; /* Needed to determine whether to exit at SystemError */
Guido van Rossumdcc0c131997-08-29 22:32:42 +000073int Py_NoSiteFlag; /* Suppress 'import site' */
Barry Warsaw3ce09642000-05-02 19:18:59 +000074int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +000075int Py_FrozenFlag; /* Needed by getpath.c */
Guido van Rossumb16d1972000-05-01 17:55:15 +000076int Py_UnicodeFlag = 0; /* Needed by compile.c */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +000077int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Tim Peters3caca232001-12-06 06:23:26 +000078/* _XXX Py_QnewFlag should go away in 2.3. It's true iff -Qnew is passed,
79 on the command line, and is used in 2.2 by ceval.c to make all "/" divisions
80 true divisions (which they will be in 2.3). */
81int _Py_QnewFlag = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +000082
Mark Hammonda43fd0c2003-02-19 00:33:33 +000083/* Reference to 'warnings' module, to avoid importing it
Mark Hammondedd07732003-07-15 23:03:55 +000084 on the fly when the import lock may be held. See 683658/771097
Mark Hammonda43fd0c2003-02-19 00:33:33 +000085*/
Mark Hammondedd07732003-07-15 23:03:55 +000086static PyObject *warnings_module = NULL;
87
88/* Returns a borrowed reference to the 'warnings' module, or NULL.
89 If the module is returned, it is guaranteed to have been obtained
90 without acquiring the import lock
91*/
Martin v. Löwisa2c17c52003-08-09 09:47:11 +000092PyObject *PyModule_GetWarningsModule(void)
Mark Hammondedd07732003-07-15 23:03:55 +000093{
94 PyObject *typ, *val, *tb;
95 PyObject *all_modules;
96 /* If we managed to get the module at init time, just use it */
97 if (warnings_module)
98 return warnings_module;
99 /* If it wasn't available at init time, it may be available
100 now in sys.modules (common scenario is frozen apps: import
101 at init time fails, but the frozen init code sets up sys.path
102 correctly, then does an implicit import of warnings for us
103 */
104 /* Save and restore any exceptions */
105 PyErr_Fetch(&typ, &val, &tb);
106
Mark Hammond5f4e8ca2003-07-16 01:54:38 +0000107 all_modules = PySys_GetObject("modules");
Mark Hammondedd07732003-07-15 23:03:55 +0000108 if (all_modules) {
109 warnings_module = PyDict_GetItemString(all_modules, "warnings");
110 /* We keep a ref in the global */
111 Py_XINCREF(warnings_module);
112 }
113 PyErr_Restore(typ, val, tb);
114 return warnings_module;
115}
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000116
Guido van Rossum25ce5661997-08-02 03:10:38 +0000117static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000118
Thomas Wouters7e474022000-07-16 12:04:32 +0000119/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000120
121int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000122Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000123{
124 return initialized;
125}
126
Guido van Rossum25ce5661997-08-02 03:10:38 +0000127/* Global initializations. Can be undone by Py_Finalize(). Don't
128 call this twice without an intervening Py_Finalize() call. When
129 initializations fail, a fatal error is issued and the function does
130 not return. On return, the first thread and interpreter state have
131 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000132
Guido van Rossum25ce5661997-08-02 03:10:38 +0000133 Locking: you must hold the interpreter lock while calling this.
134 (If the lock has not yet been initialized, that's equivalent to
135 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000136
Guido van Rossum25ce5661997-08-02 03:10:38 +0000137*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000138
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000139static int
140add_flag(int flag, const char *envs)
141{
142 int env = atoi(envs);
143 if (flag < env)
144 flag = env;
145 if (flag < 1)
146 flag = 1;
147 return flag;
148}
149
Guido van Rossuma027efa1997-05-05 20:56:21 +0000150void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000151Py_InitializeEx(int install_sigs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000152{
Guido van Rossuma027efa1997-05-05 20:56:21 +0000153 PyInterpreterState *interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000154 PyThreadState *tstate;
155 PyObject *bimod, *sysmod;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000156 char *p;
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000157#if defined(Py_USING_UNICODE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
158 char *codeset;
159 char *saved_locale;
160 PyObject *sys_stream, *sys_isatty;
161#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +0000162 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000163
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000164 if (initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +0000165 return;
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000166 initialized = 1;
Tim Petersd08e3822003-04-17 15:24:21 +0000167
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000168 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000169 Py_DebugFlag = add_flag(Py_DebugFlag, p);
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000170 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000171 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000172 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000173 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000174
Guido van Rossuma027efa1997-05-05 20:56:21 +0000175 interp = PyInterpreterState_New();
176 if (interp == NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000177 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000178
Guido van Rossuma027efa1997-05-05 20:56:21 +0000179 tstate = PyThreadState_New(interp);
180 if (tstate == NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000181 Py_FatalError("Py_Initialize: can't make first thread");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000182 (void) PyThreadState_Swap(tstate);
183
Guido van Rossum70d893a2001-08-16 08:21:42 +0000184 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000185
Neal Norwitzb2501f42002-12-31 03:42:13 +0000186 if (!_PyFrame_Init())
Neal Norwitzc91ed402002-12-30 22:29:22 +0000187 Py_FatalError("Py_Initialize: can't init frames");
188
Neal Norwitzb2501f42002-12-31 03:42:13 +0000189 if (!_PyInt_Init())
Neal Norwitzc91ed402002-12-30 22:29:22 +0000190 Py_FatalError("Py_Initialize: can't init ints");
191
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000192 _PyFloat_Init();
193
Guido van Rossum25ce5661997-08-02 03:10:38 +0000194 interp->modules = PyDict_New();
195 if (interp->modules == NULL)
196 Py_FatalError("Py_Initialize: can't make modules dictionary");
Collin Winter276887b2007-03-12 16:11:39 +0000197 interp->modules_reloading = PyDict_New();
198 if (interp->modules_reloading == NULL)
199 Py_FatalError("Py_Initialize: can't make modules_reloading dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000200
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000201#ifdef Py_USING_UNICODE
Guido van Rossumc94044c2000-03-10 23:03:54 +0000202 /* Init Unicode implementation; relies on the codec registry */
203 _PyUnicode_Init();
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000204#endif
Guido van Rossumc94044c2000-03-10 23:03:54 +0000205
Barry Warsawf242aa02000-05-25 23:09:49 +0000206 bimod = _PyBuiltin_Init();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000207 if (bimod == NULL)
208 Py_FatalError("Py_Initialize: can't initialize __builtin__");
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000209 interp->builtins = PyModule_GetDict(bimod);
Neal Norwitz0f7dbf72006-08-12 03:17:41 +0000210 if (interp->builtins == NULL)
211 Py_FatalError("Py_Initialize: can't initialize builtins dict");
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000212 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000213
214 sysmod = _PySys_Init();
215 if (sysmod == NULL)
216 Py_FatalError("Py_Initialize: can't initialize sys");
217 interp->sysdict = PyModule_GetDict(sysmod);
Neal Norwitz0f7dbf72006-08-12 03:17:41 +0000218 if (interp->sysdict == NULL)
219 Py_FatalError("Py_Initialize: can't initialize sys dict");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000220 Py_INCREF(interp->sysdict);
221 _PyImport_FixupExtension("sys", "sys");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000222 PySys_SetPath(Py_GetPath());
Guido van Rossum25ce5661997-08-02 03:10:38 +0000223 PyDict_SetItemString(interp->sysdict, "modules",
224 interp->modules);
225
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000226 _PyImport_Init();
227
Barry Warsawf242aa02000-05-25 23:09:49 +0000228 /* initialize builtin exceptions */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000229 _PyExc_Init();
Barry Warsaw5821bc52001-08-13 23:04:56 +0000230 _PyImport_FixupExtension("exceptions", "exceptions");
Barry Warsawf242aa02000-05-25 23:09:49 +0000231
Barry Warsaw035574d1997-08-29 22:07:17 +0000232 /* phase 2 of builtins */
Barry Warsaw963b8711997-09-18 16:42:02 +0000233 _PyImport_FixupExtension("__builtin__", "__builtin__");
Barry Warsaw035574d1997-08-29 22:07:17 +0000234
Just van Rossum52e14d62002-12-30 22:08:05 +0000235 _PyImportHooks_Init();
236
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000237 if (install_sigs)
238 initsigs(); /* Signal handling stuff, including initintr() */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000239
240 initmain(); /* Module __main__ */
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000241 if (!Py_NoSiteFlag)
242 initsite(); /* Module site */
Just van Rossum5bfba3a2003-02-25 20:25:12 +0000243
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000244 /* auto-thread-state API, if available */
245#ifdef WITH_THREAD
246 _PyGILState_Init(interp, tstate);
247#endif /* WITH_THREAD */
248
Mark Hammondedd07732003-07-15 23:03:55 +0000249 warnings_module = PyImport_ImportModule("warnings");
250 if (!warnings_module)
251 PyErr_Clear();
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000252
253#if defined(Py_USING_UNICODE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
254 /* On Unix, set the file system encoding according to the
255 user's preference, if the CODESET names a well-known
256 Python codec, and Py_FileSystemDefaultEncoding isn't
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000257 initialized by other means. Also set the encoding of
258 stdin and stdout if these are terminals. */
259
Martin v. Löwisf56d0152003-11-13 07:43:21 +0000260 saved_locale = strdup(setlocale(LC_CTYPE, NULL));
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000261 setlocale(LC_CTYPE, "");
262 codeset = nl_langinfo(CODESET);
263 if (codeset && *codeset) {
264 PyObject *enc = PyCodec_Encoder(codeset);
265 if (enc) {
266 codeset = strdup(codeset);
267 Py_DECREF(enc);
268 } else {
269 codeset = NULL;
270 PyErr_Clear();
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000271 }
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000272 } else
273 codeset = NULL;
274 setlocale(LC_CTYPE, saved_locale);
Martin v. Löwisf56d0152003-11-13 07:43:21 +0000275 free(saved_locale);
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000276
277 if (codeset) {
Michael W. Hudson68debc92003-08-11 12:20:24 +0000278 sys_stream = PySys_GetObject("stdin");
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000279 sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
280 if (!sys_isatty)
281 PyErr_Clear();
Thomas Woutersafea5292007-01-23 13:42:00 +0000282 if(sys_isatty && PyObject_IsTrue(sys_isatty) &&
283 PyFile_Check(sys_stream)) {
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000284 if (!PyFile_SetEncoding(sys_stream, codeset))
285 Py_FatalError("Cannot set codeset of stdin");
286 }
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000287 Py_XDECREF(sys_isatty);
288
289 sys_stream = PySys_GetObject("stdout");
290 sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
291 if (!sys_isatty)
292 PyErr_Clear();
Thomas Woutersafea5292007-01-23 13:42:00 +0000293 if(sys_isatty && PyObject_IsTrue(sys_isatty) &&
294 PyFile_Check(sys_stream)) {
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000295 if (!PyFile_SetEncoding(sys_stream, codeset))
296 Py_FatalError("Cannot set codeset of stdout");
297 }
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000298 Py_XDECREF(sys_isatty);
299
Martin v. Löwisea62d252006-04-03 10:56:49 +0000300 sys_stream = PySys_GetObject("stderr");
301 sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
302 if (!sys_isatty)
303 PyErr_Clear();
Thomas Woutersafea5292007-01-23 13:42:00 +0000304 if(sys_isatty && PyObject_IsTrue(sys_isatty) &&
305 PyFile_Check(sys_stream)) {
Martin v. Löwisea62d252006-04-03 10:56:49 +0000306 if (!PyFile_SetEncoding(sys_stream, codeset))
307 Py_FatalError("Cannot set codeset of stderr");
308 }
309 Py_XDECREF(sys_isatty);
310
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000311 if (!Py_FileSystemDefaultEncoding)
312 Py_FileSystemDefaultEncoding = codeset;
313 else
314 free(codeset);
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000315 }
316#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000317}
318
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000319void
320Py_Initialize(void)
321{
322 Py_InitializeEx(1);
323}
324
325
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000326#ifdef COUNT_ALLOCS
Martin v. Löwis45294a92006-04-18 06:24:08 +0000327extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000328#endif
329
Guido van Rossum25ce5661997-08-02 03:10:38 +0000330/* Undo the effect of Py_Initialize().
331
332 Beware: if multiple interpreter and/or thread states exist, these
333 are not wiped out; only the current thread and interpreter state
334 are deleted. But since everything else is deleted, those other
335 interpreter and thread states should no longer be used.
336
337 (XXX We should do better, e.g. wipe out all interpreters and
338 threads.)
339
340 Locking: as above.
341
342*/
343
344void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000345Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000346{
347 PyInterpreterState *interp;
348 PyThreadState *tstate;
349
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000350 if (!initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +0000351 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000352
Tim Peters384fd102001-01-21 03:40:37 +0000353 /* The interpreter is still entirely intact at this point, and the
354 * exit funcs may be relying on that. In particular, if some thread
355 * or exit func is still waiting to do an import, the import machinery
356 * expects Py_IsInitialized() to return true. So don't say the
357 * interpreter is uninitialized until after the exit funcs have run.
358 * Note that Threading.py uses an exit func to do a join on all the
359 * threads created thru it, so this also protects pending imports in
360 * the threads created via Threading.
361 */
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000362 call_sys_exitfunc();
Tim Peters384fd102001-01-21 03:40:37 +0000363 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000364
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000365 /* Get current thread state and interpreter pointer */
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000366 tstate = PyThreadState_GET();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000367 interp = tstate->interp;
368
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000369 /* Disable signal handling */
370 PyOS_FiniInterrupts();
371
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000372 /* drop module references we saved */
Mark Hammondedd07732003-07-15 23:03:55 +0000373 Py_XDECREF(warnings_module);
374 warnings_module = NULL;
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000375
Guido van Rossume13ddc92003-04-17 17:29:22 +0000376 /* Collect garbage. This may call finalizers; it's nice to call these
Tim Peters1d7323e2003-12-01 21:35:27 +0000377 * before all modules are destroyed.
378 * XXX If a __del__ or weakref callback is triggered here, and tries to
379 * XXX import a module, bad things can happen, because Python no
380 * XXX longer believes it's initialized.
381 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
382 * XXX is easy to provoke that way. I've also seen, e.g.,
383 * XXX Exception exceptions.ImportError: 'No module named sha'
384 * XXX in <function callback at 0x008F5718> ignored
385 * XXX but I'm unclear on exactly how that one happens. In any case,
386 * XXX I haven't seen a real-life report of either of these.
Neal Norwitz9589ee22006-03-04 19:01:22 +0000387 */
Guido van Rossume13ddc92003-04-17 17:29:22 +0000388 PyGC_Collect();
Martin v. Löwis45294a92006-04-18 06:24:08 +0000389#ifdef COUNT_ALLOCS
390 /* With COUNT_ALLOCS, it helps to run GC multiple times:
391 each collection might release some types from the type
392 list, so they become garbage. */
393 while (PyGC_Collect() > 0)
394 /* nothing */;
395#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000396
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000397 /* Destroy all modules */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000398 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000399
Guido van Rossume13ddc92003-04-17 17:29:22 +0000400 /* Collect final garbage. This disposes of cycles created by
Tim Peters1d7323e2003-12-01 21:35:27 +0000401 * new-style class definitions, for example.
402 * XXX This is disabled because it caused too many problems. If
403 * XXX a __del__ or weakref callback triggers here, Python code has
404 * XXX a hard time running, because even the sys module has been
405 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
406 * XXX One symptom is a sequence of information-free messages
407 * XXX coming from threads (if a __del__ or callback is invoked,
408 * XXX other threads can execute too, and any exception they encounter
409 * XXX triggers a comedy of errors as subsystem after subsystem
410 * XXX fails to find what it *expects* to find in sys to help report
411 * XXX the exception and consequent unexpected failures). I've also
412 * XXX seen segfaults then, after adding print statements to the
413 * XXX Python code getting called.
414 */
415#if 0
Guido van Rossume13ddc92003-04-17 17:29:22 +0000416 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000417#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000418
Guido van Rossum1707aad1997-12-08 23:43:45 +0000419 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
420 _PyImport_Fini();
421
422 /* Debugging stuff */
423#ifdef COUNT_ALLOCS
Martin v. Löwis45294a92006-04-18 06:24:08 +0000424 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000425#endif
426
Tim Peters62e97f02006-03-28 21:44:32 +0000427 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000428
Tim Peters9cf25ce2003-04-17 15:21:01 +0000429#ifdef Py_TRACE_REFS
430 /* Display all objects still alive -- this can invoke arbitrary
431 * __repr__ overrides, so requires a mostly-intact interpreter.
432 * Alas, a lot of stuff may still be alive now that will be cleaned
433 * up later.
434 */
Tim Peters269b2a62003-04-17 19:52:29 +0000435 if (Py_GETENV("PYTHONDUMPREFS"))
Tim Peters9cf25ce2003-04-17 15:21:01 +0000436 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000437#endif /* Py_TRACE_REFS */
438
Mark Hammond6cb90292003-04-22 11:18:00 +0000439 /* Cleanup auto-thread-state */
440#ifdef WITH_THREAD
441 _PyGILState_Fini();
442#endif /* WITH_THREAD */
443
Guido van Rossumd922fa42003-04-15 14:10:09 +0000444 /* Clear interpreter state */
Barry Warsawf242aa02000-05-25 23:09:49 +0000445 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000446
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000447 /* Now we decref the exception classes. After this point nothing
448 can raise an exception. That's okay, because each Fini() method
449 below has been checked to make sure no exceptions are ever
450 raised.
451 */
452
453 _PyExc_Fini();
454
Guido van Rossumd922fa42003-04-15 14:10:09 +0000455 /* Delete current thread */
Barry Warsawf242aa02000-05-25 23:09:49 +0000456 PyThreadState_Swap(NULL);
457 PyInterpreterState_Delete(interp);
458
Guido van Rossumd922fa42003-04-15 14:10:09 +0000459 /* Sundry finalizers */
Guido van Rossumcc283f51997-08-05 02:22:03 +0000460 PyMethod_Fini();
461 PyFrame_Fini();
462 PyCFunction_Fini();
463 PyTuple_Fini();
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +0000464 PyList_Fini();
Raymond Hettingerd7946662005-08-01 21:39:29 +0000465 PySet_Fini();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000466 PyString_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000467 PyInt_Fini();
468 PyFloat_Fini();
469
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000470#ifdef Py_USING_UNICODE
471 /* Cleanup Unicode implementation */
472 _PyUnicode_Fini();
473#endif
474
Guido van Rossumcc283f51997-08-05 02:22:03 +0000475 /* XXX Still allocated:
476 - various static ad-hoc pointers to interned strings
477 - int and float free list blocks
478 - whatever various modules and libraries allocate
479 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000480
481 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000482
Tim Peters269b2a62003-04-17 19:52:29 +0000483#ifdef Py_TRACE_REFS
484 /* Display addresses (& refcnts) of all objects still alive.
485 * An address can be used to find the repr of the object, printed
486 * above by _Py_PrintReferences.
487 */
488 if (Py_GETENV("PYTHONDUMPREFS"))
489 _Py_PrintReferenceAddresses(stderr);
490#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000491#ifdef PYMALLOC_DEBUG
492 if (Py_GETENV("PYTHONMALLOCSTATS"))
493 _PyObject_DebugMallocStats();
494#endif
495
Guido van Rossumcc283f51997-08-05 02:22:03 +0000496 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000497}
498
499/* Create and initialize a new interpreter and thread, and return the
500 new thread. This requires that Py_Initialize() has been called
501 first.
502
503 Unsuccessful initialization yields a NULL pointer. Note that *no*
504 exception information is available even in this case -- the
505 exception information is held in the thread, and there is no
506 thread.
507
508 Locking: as above.
509
510*/
511
512PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000513Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000514{
515 PyInterpreterState *interp;
516 PyThreadState *tstate, *save_tstate;
517 PyObject *bimod, *sysmod;
518
519 if (!initialized)
520 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
521
522 interp = PyInterpreterState_New();
523 if (interp == NULL)
524 return NULL;
525
526 tstate = PyThreadState_New(interp);
527 if (tstate == NULL) {
528 PyInterpreterState_Delete(interp);
529 return NULL;
530 }
531
532 save_tstate = PyThreadState_Swap(tstate);
533
534 /* XXX The following is lax in error checking */
535
536 interp->modules = PyDict_New();
Collin Winter276887b2007-03-12 16:11:39 +0000537 interp->modules_reloading = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000538
539 bimod = _PyImport_FindExtension("__builtin__", "__builtin__");
540 if (bimod != NULL) {
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000541 interp->builtins = PyModule_GetDict(bimod);
Neal Norwitz0c6ae5b2006-08-21 20:16:24 +0000542 if (interp->builtins == NULL)
543 goto handle_error;
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000544 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000545 }
546 sysmod = _PyImport_FindExtension("sys", "sys");
547 if (bimod != NULL && sysmod != NULL) {
548 interp->sysdict = PyModule_GetDict(sysmod);
Neal Norwitz0c6ae5b2006-08-21 20:16:24 +0000549 if (interp->sysdict == NULL)
550 goto handle_error;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000551 Py_INCREF(interp->sysdict);
552 PySys_SetPath(Py_GetPath());
553 PyDict_SetItemString(interp->sysdict, "modules",
554 interp->modules);
Martin v. Löwisd7ceb222003-01-22 09:00:38 +0000555 _PyImportHooks_Init();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000556 initmain();
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000557 if (!Py_NoSiteFlag)
558 initsite();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000559 }
560
561 if (!PyErr_Occurred())
562 return tstate;
563
Neal Norwitz0c6ae5b2006-08-21 20:16:24 +0000564handle_error:
Guido van Rossum25ce5661997-08-02 03:10:38 +0000565 /* Oops, it didn't work. Undo it all. */
566
567 PyErr_Print();
568 PyThreadState_Clear(tstate);
569 PyThreadState_Swap(save_tstate);
570 PyThreadState_Delete(tstate);
571 PyInterpreterState_Delete(interp);
572
573 return NULL;
574}
575
576/* Delete an interpreter and its last thread. This requires that the
577 given thread state is current, that the thread has no remaining
578 frames, and that it is its interpreter's only remaining thread.
579 It is a fatal error to violate these constraints.
580
581 (Py_Finalize() doesn't have these constraints -- it zaps
582 everything, regardless.)
583
584 Locking: as above.
585
586*/
587
588void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000589Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000590{
591 PyInterpreterState *interp = tstate->interp;
592
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000593 if (tstate != PyThreadState_GET())
Guido van Rossum25ce5661997-08-02 03:10:38 +0000594 Py_FatalError("Py_EndInterpreter: thread is not current");
595 if (tstate->frame != NULL)
596 Py_FatalError("Py_EndInterpreter: thread still has a frame");
597 if (tstate != interp->tstate_head || tstate->next != NULL)
598 Py_FatalError("Py_EndInterpreter: not the last thread");
599
600 PyImport_Cleanup();
601 PyInterpreterState_Clear(interp);
602 PyThreadState_Swap(NULL);
603 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000604}
605
606static char *progname = "python";
607
608void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000609Py_SetProgramName(char *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000610{
611 if (pn && *pn)
612 progname = pn;
613}
614
615char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000616Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000617{
618 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000619}
620
Guido van Rossuma61691e1998-02-06 22:27:24 +0000621static char *default_home = NULL;
622
623void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000624Py_SetPythonHome(char *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000625{
626 default_home = home;
627}
628
629char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000630Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000631{
632 char *home = default_home;
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000633 if (home == NULL && !Py_IgnoreEnvironmentFlag)
634 home = Py_GETENV("PYTHONHOME");
Guido van Rossuma61691e1998-02-06 22:27:24 +0000635 return home;
636}
637
Guido van Rossum6135a871995-01-09 17:53:26 +0000638/* Create __main__ module */
639
640static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000641initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000642{
Guido van Rossum82598051997-03-05 00:20:32 +0000643 PyObject *m, *d;
644 m = PyImport_AddModule("__main__");
Guido van Rossum6135a871995-01-09 17:53:26 +0000645 if (m == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +0000646 Py_FatalError("can't create __main__ module");
647 d = PyModule_GetDict(m);
648 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
Guido van Rossum858cb731997-11-19 16:15:37 +0000649 PyObject *bimod = PyImport_ImportModule("__builtin__");
650 if (bimod == NULL ||
651 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
Guido van Rossum82598051997-03-05 00:20:32 +0000652 Py_FatalError("can't add __builtins__ to __main__");
Barry Warsaw3d05b1a1999-01-29 21:30:22 +0000653 Py_DECREF(bimod);
Guido van Rossum6135a871995-01-09 17:53:26 +0000654 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000655}
656
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000657/* Import the site module (not into __main__ though) */
658
659static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000660initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000661{
662 PyObject *m, *f;
663 m = PyImport_ImportModule("site");
664 if (m == NULL) {
665 f = PySys_GetObject("stderr");
666 if (Py_VerboseFlag) {
667 PyFile_WriteString(
668 "'import site' failed; traceback:\n", f);
669 PyErr_Print();
670 }
671 else {
672 PyFile_WriteString(
673 "'import site' failed; use -v for traceback\n", f);
674 PyErr_Clear();
675 }
676 }
677 else {
678 Py_DECREF(m);
679 }
680}
681
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000682/* Parse input from a file and execute it */
683
684int
Tim Peters5e9d6cf2006-05-28 10:41:29 +0000685PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000686 PyCompilerFlags *flags)
687{
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000688 if (filename == NULL)
689 filename = "???";
Guido van Rossum0df002c2000-08-27 19:21:52 +0000690 if (Py_FdIsInteractive(fp, filename)) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000691 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
Guido van Rossum0df002c2000-08-27 19:21:52 +0000692 if (closeit)
693 fclose(fp);
694 return err;
695 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000696 else
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000697 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000698}
699
700int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000701PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000702{
Guido van Rossum82598051997-03-05 00:20:32 +0000703 PyObject *v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000704 int ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000705 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000706
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000707 if (flags == NULL) {
708 flags = &local_flags;
Tim Peters5ba58662001-07-16 02:29:45 +0000709 local_flags.cf_flags = 0;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000710 }
Guido van Rossum82598051997-03-05 00:20:32 +0000711 v = PySys_GetObject("ps1");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000712 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000713 PySys_SetObject("ps1", v = PyString_FromString(">>> "));
714 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000715 }
Guido van Rossum82598051997-03-05 00:20:32 +0000716 v = PySys_GetObject("ps2");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000717 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000718 PySys_SetObject("ps2", v = PyString_FromString("... "));
719 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000720 }
721 for (;;) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000722 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
Tim Peters62e97f02006-03-28 21:44:32 +0000723 PRINT_TOTAL_REFS();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000724 if (ret == E_EOF)
725 return 0;
726 /*
727 if (ret == E_NOMEM)
728 return -1;
729 */
730 }
731}
732
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000733/* compute parser flags based on compiler flags */
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000734#define PARSER_FLAGS(flags) \
Thomas Wouters34aa7ba2006-02-28 19:02:24 +0000735 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
Neal Norwitzca460d92006-09-06 06:28:06 +0000736 PyPARSE_DONT_IMPLY_DEDENT : 0)) : 0)
737
738#if 0
739/* Keep an example of flags with future keyword support. */
740#define PARSER_FLAGS(flags) \
741 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
Thomas Wouters34aa7ba2006-02-28 19:02:24 +0000742 PyPARSE_DONT_IMPLY_DEDENT : 0) \
Neal Norwitz9589ee22006-03-04 19:01:22 +0000743 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
744 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
Neal Norwitzca460d92006-09-06 06:28:06 +0000745#endif
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000746
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000747int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000748PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000749{
Guido van Rossum82598051997-03-05 00:20:32 +0000750 PyObject *m, *d, *v, *w;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000751 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +0000752 PyArena *arena;
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000753 char *ps1 = "", *ps2 = "";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000754 int errcode = 0;
Tim Petersfe2127d2001-07-16 05:37:24 +0000755
Guido van Rossum82598051997-03-05 00:20:32 +0000756 v = PySys_GetObject("ps1");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000757 if (v != NULL) {
758 v = PyObject_Str(v);
759 if (v == NULL)
760 PyErr_Clear();
761 else if (PyString_Check(v))
762 ps1 = PyString_AsString(v);
763 }
Guido van Rossum82598051997-03-05 00:20:32 +0000764 w = PySys_GetObject("ps2");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000765 if (w != NULL) {
766 w = PyObject_Str(w);
767 if (w == NULL)
768 PyErr_Clear();
769 else if (PyString_Check(w))
770 ps2 = PyString_AsString(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000771 }
Neal Norwitz9589ee22006-03-04 19:01:22 +0000772 arena = PyArena_New();
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000773 if (arena == NULL) {
774 Py_XDECREF(v);
775 Py_XDECREF(w);
776 return -1;
777 }
Tim Peters5e9d6cf2006-05-28 10:41:29 +0000778 mod = PyParser_ASTFromFile(fp, filename,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000779 Py_single_input, ps1, ps2,
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000780 flags, &errcode, arena);
Guido van Rossum82598051997-03-05 00:20:32 +0000781 Py_XDECREF(v);
782 Py_XDECREF(w);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000783 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +0000784 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000785 if (errcode == E_EOF) {
786 PyErr_Clear();
Guido van Rossuma110aa61994-08-29 12:50:44 +0000787 return E_EOF;
788 }
Guido van Rossum82598051997-03-05 00:20:32 +0000789 PyErr_Print();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000790 return -1;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000791 }
Guido van Rossum82598051997-03-05 00:20:32 +0000792 m = PyImport_AddModule("__main__");
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000793 if (m == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +0000794 PyArena_Free(arena);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000795 return -1;
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000796 }
Guido van Rossum82598051997-03-05 00:20:32 +0000797 d = PyModule_GetDict(m);
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000798 v = run_mod(mod, filename, d, d, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +0000799 PyArena_Free(arena);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000800 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000801 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000802 return -1;
803 }
Guido van Rossum82598051997-03-05 00:20:32 +0000804 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000805 if (Py_FlushLine())
806 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000807 return 0;
808}
809
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000810/* Check whether a file maybe a pyc file: Look at the extension,
811 the file type, and, if we may close it, at the first few bytes. */
812
813static int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000814maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000815{
816 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
817 return 1;
818
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000819 /* Only look into the file if we are allowed to close it, since
820 it then should also be seekable. */
821 if (closeit) {
822 /* Read only two bytes of the magic. If the file was opened in
823 text mode, the bytes 3 and 4 of the magic (\r\n) might not
824 be read as they are on disk. */
825 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
826 unsigned char buf[2];
Tim Peters3e876562001-02-11 04:35:39 +0000827 /* Mess: In case of -x, the stream is NOT at its start now,
828 and ungetc() was used to push back the first newline,
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000829 which makes the current stream position formally undefined,
830 and a x-platform nightmare.
831 Unfortunately, we have no direct way to know whether -x
832 was specified. So we use a terrible hack: if the current
833 stream position is not 0, we assume -x was specified, and
834 give up. Bug 132850 on SourceForge spells out the
835 hopelessness of trying anything else (fseek and ftell
836 don't work predictably x-platform for text-mode files).
Tim Peters3e876562001-02-11 04:35:39 +0000837 */
Tim Peters3e876562001-02-11 04:35:39 +0000838 int ispyc = 0;
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000839 if (ftell(fp) == 0) {
840 if (fread(buf, 1, 2, fp) == 2 &&
Tim Petersd08e3822003-04-17 15:24:21 +0000841 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000842 ispyc = 1;
843 rewind(fp);
844 }
Tim Peters3e876562001-02-11 04:35:39 +0000845 return ispyc;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000846 }
847 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +0000848}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000849
Guido van Rossum0df002c2000-08-27 19:21:52 +0000850int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000851PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000852 PyCompilerFlags *flags)
853{
Guido van Rossum82598051997-03-05 00:20:32 +0000854 PyObject *m, *d, *v;
Martin v. Löwis95292d62002-12-11 14:04:59 +0000855 const char *ext;
Georg Brandlaa2321b2007-03-07 00:40:28 +0000856 int set_file_name = 0, ret;
Guido van Rossumfdef2711994-09-14 13:31:04 +0000857
Guido van Rossum82598051997-03-05 00:20:32 +0000858 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000859 if (m == NULL)
860 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000861 d = PyModule_GetDict(m);
Fred Drake8ed02042002-10-17 21:24:58 +0000862 if (PyDict_GetItemString(d, "__file__") == NULL) {
863 PyObject *f = PyString_FromString(filename);
864 if (f == NULL)
865 return -1;
866 if (PyDict_SetItemString(d, "__file__", f) < 0) {
867 Py_DECREF(f);
868 return -1;
869 }
Georg Brandlaa2321b2007-03-07 00:40:28 +0000870 set_file_name = 1;
Fred Drake8ed02042002-10-17 21:24:58 +0000871 Py_DECREF(f);
872 }
Guido van Rossumfdef2711994-09-14 13:31:04 +0000873 ext = filename + strlen(filename) - 4;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000874 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Guido van Rossumfdef2711994-09-14 13:31:04 +0000875 /* Try to run a pyc file. First, re-open in binary */
Guido van Rossum0df002c2000-08-27 19:21:52 +0000876 if (closeit)
877 fclose(fp);
Fred Drake8ed02042002-10-17 21:24:58 +0000878 if ((fp = fopen(filename, "rb")) == NULL) {
Guido van Rossumfdef2711994-09-14 13:31:04 +0000879 fprintf(stderr, "python: Can't reopen .pyc file\n");
Georg Brandlaa2321b2007-03-07 00:40:28 +0000880 ret = -1;
881 goto done;
Guido van Rossumfdef2711994-09-14 13:31:04 +0000882 }
Guido van Rossum2a7f58d1997-04-02 05:28:38 +0000883 /* Turn on optimization if a .pyo file is given */
884 if (strcmp(ext, ".pyo") == 0)
885 Py_OptimizeFlag = 1;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000886 v = run_pyc_file(fp, filename, d, d, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000887 } else {
Tim Petersd08e3822003-04-17 15:24:21 +0000888 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000889 closeit, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000890 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000891 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000892 PyErr_Print();
Georg Brandlaa2321b2007-03-07 00:40:28 +0000893 ret = -1;
894 goto done;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000895 }
Guido van Rossum82598051997-03-05 00:20:32 +0000896 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000897 if (Py_FlushLine())
898 PyErr_Clear();
Georg Brandlaa2321b2007-03-07 00:40:28 +0000899 ret = 0;
900 done:
901 if (set_file_name && PyDict_DelItemString(d, "__file__"))
902 PyErr_Clear();
903 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000904}
905
906int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000907PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +0000908{
Guido van Rossum82598051997-03-05 00:20:32 +0000909 PyObject *m, *d, *v;
910 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000911 if (m == NULL)
912 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000913 d = PyModule_GetDict(m);
Guido van Rossum393661d2001-08-31 17:40:15 +0000914 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000915 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000916 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000917 return -1;
918 }
Guido van Rossum82598051997-03-05 00:20:32 +0000919 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000920 if (Py_FlushLine())
921 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000922 return 0;
923}
924
Barry Warsaw035574d1997-08-29 22:07:17 +0000925static int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000926parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
927 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +0000928{
929 long hold;
930 PyObject *v;
931
932 /* old style errors */
933 if (PyTuple_Check(err))
Neal Norwitz78293352002-04-01 01:41:20 +0000934 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
Neal Norwitz9589ee22006-03-04 19:01:22 +0000935 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +0000936
937 /* new style errors. `err' is an instance */
938
939 if (! (v = PyObject_GetAttrString(err, "msg")))
940 goto finally;
941 *message = v;
942
943 if (!(v = PyObject_GetAttrString(err, "filename")))
944 goto finally;
945 if (v == Py_None)
946 *filename = NULL;
947 else if (! (*filename = PyString_AsString(v)))
948 goto finally;
949
950 Py_DECREF(v);
951 if (!(v = PyObject_GetAttrString(err, "lineno")))
952 goto finally;
953 hold = PyInt_AsLong(v);
954 Py_DECREF(v);
955 v = NULL;
956 if (hold < 0 && PyErr_Occurred())
957 goto finally;
958 *lineno = (int)hold;
959
960 if (!(v = PyObject_GetAttrString(err, "offset")))
961 goto finally;
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000962 if (v == Py_None) {
963 *offset = -1;
964 Py_DECREF(v);
965 v = NULL;
966 } else {
967 hold = PyInt_AsLong(v);
968 Py_DECREF(v);
969 v = NULL;
970 if (hold < 0 && PyErr_Occurred())
971 goto finally;
972 *offset = (int)hold;
973 }
Barry Warsaw035574d1997-08-29 22:07:17 +0000974
975 if (!(v = PyObject_GetAttrString(err, "text")))
976 goto finally;
977 if (v == Py_None)
978 *text = NULL;
979 else if (! (*text = PyString_AsString(v)))
980 goto finally;
981 Py_DECREF(v);
982 return 1;
983
984finally:
985 Py_XDECREF(v);
986 return 0;
987}
988
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000989void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000990PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000991{
Guido van Rossuma61691e1998-02-06 22:27:24 +0000992 PyErr_PrintEx(1);
993}
994
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000995static void
Martin v. Löwis95292d62002-12-11 14:04:59 +0000996print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000997{
998 char *nl;
999 if (offset >= 0) {
1000 if (offset > 0 && offset == (int)strlen(text))
1001 offset--;
1002 for (;;) {
1003 nl = strchr(text, '\n');
1004 if (nl == NULL || nl-text >= offset)
1005 break;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001006 offset -= (int)(nl+1-text);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001007 text = nl+1;
1008 }
1009 while (*text == ' ' || *text == '\t') {
1010 text++;
1011 offset--;
1012 }
1013 }
1014 PyFile_WriteString(" ", f);
1015 PyFile_WriteString(text, f);
1016 if (*text == '\0' || text[strlen(text)-1] != '\n')
1017 PyFile_WriteString("\n", f);
1018 if (offset == -1)
1019 return;
1020 PyFile_WriteString(" ", f);
1021 offset--;
1022 while (offset > 0) {
1023 PyFile_WriteString(" ", f);
1024 offset--;
1025 }
1026 PyFile_WriteString("^\n", f);
1027}
1028
Guido van Rossum66e8e862001-03-23 17:54:43 +00001029static void
1030handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001031{
Neal Norwitz9589ee22006-03-04 19:01:22 +00001032 PyObject *exception, *value, *tb;
1033 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001034
Georg Brandl49aafc92007-03-07 00:34:46 +00001035 if (Py_InspectFlag)
1036 /* Don't exit if -i flag was given. This flag is set to 0
1037 * when entering interactive mode for inspecting. */
1038 return;
1039
Guido van Rossum66e8e862001-03-23 17:54:43 +00001040 PyErr_Fetch(&exception, &value, &tb);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001041 if (Py_FlushLine())
1042 PyErr_Clear();
1043 fflush(stdout);
1044 if (value == NULL || value == Py_None)
Tim Peterscf615b52003-04-19 18:47:02 +00001045 goto done;
Brett Cannonbf364092006-03-01 04:25:17 +00001046 if (PyExceptionInstance_Check(value)) {
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001047 /* The error code should be in the `code' attribute. */
1048 PyObject *code = PyObject_GetAttrString(value, "code");
1049 if (code) {
1050 Py_DECREF(value);
1051 value = code;
1052 if (value == Py_None)
Tim Peterscf615b52003-04-19 18:47:02 +00001053 goto done;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001054 }
1055 /* If we failed to dig out the 'code' attribute,
1056 just let the else clause below print the error. */
1057 }
1058 if (PyInt_Check(value))
Tim Peterscf615b52003-04-19 18:47:02 +00001059 exitcode = (int)PyInt_AsLong(value);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001060 else {
1061 PyObject_Print(value, stderr, Py_PRINT_RAW);
1062 PySys_WriteStderr("\n");
Tim Peterscf615b52003-04-19 18:47:02 +00001063 exitcode = 1;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001064 }
Tim Peterscf615b52003-04-19 18:47:02 +00001065 done:
Neal Norwitz9589ee22006-03-04 19:01:22 +00001066 /* Restore and clear the exception info, in order to properly decref
1067 * the exception, value, and traceback. If we just exit instead,
1068 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1069 * some finalizers from running.
1070 */
Tim Peterscf615b52003-04-19 18:47:02 +00001071 PyErr_Restore(exception, value, tb);
1072 PyErr_Clear();
1073 Py_Exit(exitcode);
1074 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001075}
1076
1077void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001078PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001079{
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001080 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001081
1082 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1083 handle_system_exit();
1084 }
Guido van Rossum82598051997-03-05 00:20:32 +00001085 PyErr_Fetch(&exception, &v, &tb);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001086 if (exception == NULL)
1087 return;
Barry Warsaw035574d1997-08-29 22:07:17 +00001088 PyErr_NormalizeException(&exception, &v, &tb);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001089 if (exception == NULL)
Guido van Rossum296b4751997-05-23 00:19:20 +00001090 return;
Guido van Rossum9d785502006-03-07 18:31:44 +00001091 /* Now we know v != NULL too */
Guido van Rossuma61691e1998-02-06 22:27:24 +00001092 if (set_sys_last_vars) {
1093 PySys_SetObject("last_type", exception);
1094 PySys_SetObject("last_value", v);
1095 PySys_SetObject("last_traceback", tb);
1096 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001097 hook = PySys_GetObject("excepthook");
1098 if (hook) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001099 PyObject *args = PyTuple_Pack(3,
Guido van Rossum9d785502006-03-07 18:31:44 +00001100 exception, v, tb ? tb : Py_None);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001101 PyObject *result = PyEval_CallObject(hook, args);
1102 if (result == NULL) {
1103 PyObject *exception2, *v2, *tb2;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001104 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1105 handle_system_exit();
1106 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001107 PyErr_Fetch(&exception2, &v2, &tb2);
1108 PyErr_NormalizeException(&exception2, &v2, &tb2);
Neal Norwitza5e4f222006-07-17 00:59:04 +00001109 /* It should not be possible for exception2 or v2
1110 to be NULL. However PyErr_Display() can't
1111 tolerate NULLs, so just be safe. */
1112 if (exception2 == NULL) {
1113 exception2 = Py_None;
1114 Py_INCREF(exception2);
1115 }
1116 if (v2 == NULL) {
1117 v2 = Py_None;
1118 Py_INCREF(v2);
1119 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001120 if (Py_FlushLine())
1121 PyErr_Clear();
1122 fflush(stdout);
1123 PySys_WriteStderr("Error in sys.excepthook:\n");
1124 PyErr_Display(exception2, v2, tb2);
1125 PySys_WriteStderr("\nOriginal exception was:\n");
1126 PyErr_Display(exception, v, tb);
Neal Norwitza5e4f222006-07-17 00:59:04 +00001127 Py_DECREF(exception2);
1128 Py_DECREF(v2);
Jeremy Hylton07028582001-12-07 15:35:35 +00001129 Py_XDECREF(tb2);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001130 }
1131 Py_XDECREF(result);
1132 Py_XDECREF(args);
1133 } else {
1134 PySys_WriteStderr("sys.excepthook is missing\n");
1135 PyErr_Display(exception, v, tb);
1136 }
1137 Py_XDECREF(exception);
1138 Py_XDECREF(v);
1139 Py_XDECREF(tb);
1140}
1141
Richard Jones7b9558d2006-05-27 12:29:24 +00001142void
1143PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001144{
1145 int err = 0;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001146 PyObject *f = PySys_GetObject("stderr");
Armin Rigo5d2c6832004-03-22 20:16:58 +00001147 Py_INCREF(value);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001148 if (f == NULL)
1149 fprintf(stderr, "lost sys.stderr\n");
1150 else {
Guido van Rossum0829c751998-02-28 04:31:39 +00001151 if (Py_FlushLine())
1152 PyErr_Clear();
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001153 fflush(stdout);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001154 if (tb && tb != Py_None)
1155 err = PyTraceBack_Print(tb, f);
Barry Warsaw36b8f941997-08-26 18:09:48 +00001156 if (err == 0 &&
Armin Rigo5d2c6832004-03-22 20:16:58 +00001157 PyObject_HasAttrString(value, "print_file_and_line"))
Barry Warsaw36b8f941997-08-26 18:09:48 +00001158 {
Guido van Rossum82598051997-03-05 00:20:32 +00001159 PyObject *message;
Martin v. Löwis95292d62002-12-11 14:04:59 +00001160 const char *filename, *text;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001161 int lineno, offset;
Armin Rigo5d2c6832004-03-22 20:16:58 +00001162 if (!parse_syntax_error(value, &message, &filename,
Barry Warsaw035574d1997-08-29 22:07:17 +00001163 &lineno, &offset, &text))
Guido van Rossum82598051997-03-05 00:20:32 +00001164 PyErr_Clear();
Guido van Rossuma110aa61994-08-29 12:50:44 +00001165 else {
1166 char buf[10];
Guido van Rossum82598051997-03-05 00:20:32 +00001167 PyFile_WriteString(" File \"", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001168 if (filename == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +00001169 PyFile_WriteString("<string>", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001170 else
Guido van Rossum82598051997-03-05 00:20:32 +00001171 PyFile_WriteString(filename, f);
1172 PyFile_WriteString("\", line ", f);
Jeremy Hylton518ab1c2001-11-28 20:42:20 +00001173 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
Guido van Rossum82598051997-03-05 00:20:32 +00001174 PyFile_WriteString(buf, f);
1175 PyFile_WriteString("\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001176 if (text != NULL)
1177 print_error_text(f, offset, text);
Armin Rigo5d2c6832004-03-22 20:16:58 +00001178 Py_DECREF(value);
1179 value = message;
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001180 /* Can't be bothered to check all those
1181 PyFile_WriteString() calls */
1182 if (PyErr_Occurred())
1183 err = -1;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001184 }
1185 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001186 if (err) {
1187 /* Don't do anything else */
1188 }
Brett Cannonbf364092006-03-01 04:25:17 +00001189 else if (PyExceptionClass_Check(exception)) {
Richard Jones7b9558d2006-05-27 12:29:24 +00001190 PyObject* moduleName;
Tim Peters5e9d6cf2006-05-28 10:41:29 +00001191 char* className = PyExceptionClass_Name(exception);
1192 if (className != NULL) {
1193 char *dot = strrchr(className, '.');
1194 if (dot != NULL)
1195 className = dot+1;
1196 }
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001197
Tim Peters5e9d6cf2006-05-28 10:41:29 +00001198 moduleName = PyObject_GetAttrString(exception, "__module__");
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001199 if (moduleName == NULL)
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001200 err = PyFile_WriteString("<unknown>", f);
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001201 else {
1202 char* modstr = PyString_AsString(moduleName);
Tim Petersd08e3822003-04-17 15:24:21 +00001203 if (modstr && strcmp(modstr, "exceptions"))
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001204 {
1205 err = PyFile_WriteString(modstr, f);
1206 err += PyFile_WriteString(".", f);
1207 }
Richard Jones7b9558d2006-05-27 12:29:24 +00001208 Py_DECREF(moduleName);
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001209 }
1210 if (err == 0) {
1211 if (className == NULL)
1212 err = PyFile_WriteString("<unknown>", f);
1213 else
Brett Cannonbf364092006-03-01 04:25:17 +00001214 err = PyFile_WriteString(className, f);
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001215 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001216 }
1217 else
1218 err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
Brett Cannon2e63b732006-03-02 18:34:57 +00001219 if (err == 0 && (value != Py_None)) {
1220 PyObject *s = PyObject_Str(value);
1221 /* only print colon if the str() of the
1222 object is not the empty string
1223 */
1224 if (s == NULL)
1225 err = -1;
1226 else if (!PyString_Check(s) ||
1227 PyString_GET_SIZE(s) != 0)
1228 err = PyFile_WriteString(": ", f);
1229 if (err == 0)
1230 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1231 Py_XDECREF(s);
Guido van Rossum262e1241995-02-07 15:30:45 +00001232 }
Georg Brandl7b9c5552007-03-12 14:30:05 +00001233 /* try to write a newline in any case */
1234 err += PyFile_WriteString("\n", f);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001235 }
Armin Rigo5d2c6832004-03-22 20:16:58 +00001236 Py_DECREF(value);
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001237 /* If an error happened here, don't show it.
1238 XXX This is wrong, but too many callers rely on this behavior. */
1239 if (err != 0)
1240 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001241}
1242
Guido van Rossum82598051997-03-05 00:20:32 +00001243PyObject *
Tim Peters5e9d6cf2006-05-28 10:41:29 +00001244PyRun_StringFlags(const char *str, int start, PyObject *globals,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001245 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001246{
Neal Norwitze92fba02006-03-04 18:52:26 +00001247 PyObject *ret = NULL;
Neal Norwitzd12bd012006-07-21 07:59:47 +00001248 mod_ty mod;
Neal Norwitzb59d08c2006-07-22 16:20:49 +00001249 PyArena *arena = PyArena_New();
Neal Norwitzd12bd012006-07-21 07:59:47 +00001250 if (arena == NULL)
1251 return NULL;
1252
1253 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
Neal Norwitze92fba02006-03-04 18:52:26 +00001254 if (mod != NULL)
1255 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001256 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001257 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001258}
1259
1260PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001261PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001262 PyObject *locals, int closeit, PyCompilerFlags *flags)
1263{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001264 PyObject *ret;
Neal Norwitzd12bd012006-07-21 07:59:47 +00001265 mod_ty mod;
Neal Norwitzb59d08c2006-07-22 16:20:49 +00001266 PyArena *arena = PyArena_New();
Neal Norwitzd12bd012006-07-21 07:59:47 +00001267 if (arena == NULL)
1268 return NULL;
1269
1270 mod = PyParser_ASTFromFile(fp, filename, start, 0, 0,
1271 flags, NULL, arena);
Georg Brandl098cd692007-03-06 12:17:50 +00001272 if (closeit)
1273 fclose(fp);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001274 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001275 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001276 return NULL;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001277 }
Neal Norwitze92fba02006-03-04 18:52:26 +00001278 ret = run_mod(mod, filename, globals, locals, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001279 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001280 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001281}
1282
Guido van Rossum82598051997-03-05 00:20:32 +00001283static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001284run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001285 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001286{
Guido van Rossum82598051997-03-05 00:20:32 +00001287 PyCodeObject *co;
1288 PyObject *v;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001289 co = PyAST_Compile(mod, filename, flags, arena);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001290 if (co == NULL)
1291 return NULL;
Guido van Rossum82598051997-03-05 00:20:32 +00001292 v = PyEval_EvalCode(co, globals, locals);
1293 Py_DECREF(co);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001294 return v;
1295}
1296
Guido van Rossum82598051997-03-05 00:20:32 +00001297static PyObject *
Tim Peters5e9d6cf2006-05-28 10:41:29 +00001298run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001299 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001300{
Guido van Rossum82598051997-03-05 00:20:32 +00001301 PyCodeObject *co;
1302 PyObject *v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001303 long magic;
Fred Drakee8de31c2000-08-31 05:38:39 +00001304 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001305
Guido van Rossum82598051997-03-05 00:20:32 +00001306 magic = PyMarshal_ReadLongFromFile(fp);
1307 if (magic != PyImport_GetMagicNumber()) {
1308 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001309 "Bad magic number in .pyc file");
1310 return NULL;
1311 }
Guido van Rossum82598051997-03-05 00:20:32 +00001312 (void) PyMarshal_ReadLongFromFile(fp);
Tim Petersd9b9ac82001-01-28 00:27:39 +00001313 v = PyMarshal_ReadLastObjectFromFile(fp);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001314 fclose(fp);
Guido van Rossum82598051997-03-05 00:20:32 +00001315 if (v == NULL || !PyCode_Check(v)) {
1316 Py_XDECREF(v);
1317 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001318 "Bad code object in .pyc file");
1319 return NULL;
1320 }
Guido van Rossum82598051997-03-05 00:20:32 +00001321 co = (PyCodeObject *)v;
1322 v = PyEval_EvalCode(co, globals, locals);
Jeremy Hyltonb857ba22001-08-10 21:41:33 +00001323 if (v && flags)
1324 flags->cf_flags |= (co->co_flags & PyCF_MASK);
Guido van Rossum82598051997-03-05 00:20:32 +00001325 Py_DECREF(co);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001326 return v;
1327}
1328
Guido van Rossum82598051997-03-05 00:20:32 +00001329PyObject *
Tim Petersd08e3822003-04-17 15:24:21 +00001330Py_CompileStringFlags(const char *str, const char *filename, int start,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001331 PyCompilerFlags *flags)
1332{
Guido van Rossum82598051997-03-05 00:20:32 +00001333 PyCodeObject *co;
Neal Norwitzb59d08c2006-07-22 16:20:49 +00001334 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001335 PyArena *arena = PyArena_New();
Neal Norwitzb59d08c2006-07-22 16:20:49 +00001336 if (arena == NULL)
1337 return NULL;
1338
1339 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001340 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001341 PyArena_Free(arena);
Guido van Rossum5b722181993-03-30 17:46:03 +00001342 return NULL;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001343 }
Martin v. Löwis2b366e42006-02-26 22:12:35 +00001344 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001345 PyObject *result = PyAST_mod2obj(mod);
1346 PyArena_Free(arena);
1347 return result;
1348 }
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001349 co = PyAST_Compile(mod, filename, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001350 PyArena_Free(arena);
Guido van Rossum82598051997-03-05 00:20:32 +00001351 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001352}
1353
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001354struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001355Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001356{
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001357 struct symtable *st;
Neal Norwitzb59d08c2006-07-22 16:20:49 +00001358 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001359 PyArena *arena = PyArena_New();
Neal Norwitzb59d08c2006-07-22 16:20:49 +00001360 if (arena == NULL)
1361 return NULL;
1362
1363 mod = PyParser_ASTFromString(str, filename, start, NULL, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001364 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001365 PyArena_Free(arena);
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001366 return NULL;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001367 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001368 st = PySymtable_Build(mod, filename, 0);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001369 PyArena_Free(arena);
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001370 return st;
1371}
1372
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001373/* Preferred access to parser is through AST. */
1374mod_ty
Tim Peters5e9d6cf2006-05-28 10:41:29 +00001375PyParser_ASTFromString(const char *s, const char *filename, int start,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001376 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001377{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001378 mod_ty mod;
1379 perrdetail err;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001380 node *n = PyParser_ParseStringFlagsFilename(s, filename,
Tim Peters5e9d6cf2006-05-28 10:41:29 +00001381 &_PyParser_Grammar, start, &err,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001382 PARSER_FLAGS(flags));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001383 if (n) {
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001384 mod = PyAST_FromNode(n, flags, filename, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001385 PyNode_Free(n);
1386 return mod;
1387 }
1388 else {
1389 err_input(&err);
1390 return NULL;
1391 }
1392}
1393
1394mod_ty
Tim Peters5e9d6cf2006-05-28 10:41:29 +00001395PyParser_ASTFromFile(FILE *fp, const char *filename, int start, char *ps1,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001396 char *ps2, PyCompilerFlags *flags, int *errcode,
Neal Norwitz9589ee22006-03-04 19:01:22 +00001397 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001398{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001399 mod_ty mod;
1400 perrdetail err;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001401 node *n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar,
1402 start, ps1, ps2, &err, PARSER_FLAGS(flags));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001403 if (n) {
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001404 mod = PyAST_FromNode(n, flags, filename, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001405 PyNode_Free(n);
1406 return mod;
1407 }
1408 else {
1409 err_input(&err);
1410 if (errcode)
1411 *errcode = err.error;
1412 return NULL;
1413 }
1414}
1415
Guido van Rossuma110aa61994-08-29 12:50:44 +00001416/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001417
Guido van Rossuma110aa61994-08-29 12:50:44 +00001418node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001419PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001420{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001421 perrdetail err;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001422 node *n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar,
1423 start, NULL, NULL, &err, flags);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001424 if (n == NULL)
1425 err_input(&err);
Tim Peters5e9d6cf2006-05-28 10:41:29 +00001426
Guido van Rossuma110aa61994-08-29 12:50:44 +00001427 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001428}
1429
Guido van Rossuma110aa61994-08-29 12:50:44 +00001430/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001431
Guido van Rossuma110aa61994-08-29 12:50:44 +00001432node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001433PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001434{
Tim Petersfe2127d2001-07-16 05:37:24 +00001435 perrdetail err;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001436 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1437 start, &err, flags);
Tim Petersfe2127d2001-07-16 05:37:24 +00001438 if (n == NULL)
1439 err_input(&err);
1440 return n;
1441}
1442
1443node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001444PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Thomas Heller6b17abf2002-07-09 09:23:27 +00001445 int start, int flags)
1446{
Thomas Heller6b17abf2002-07-09 09:23:27 +00001447 perrdetail err;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001448 node *n = PyParser_ParseStringFlagsFilename(str, filename,
1449 &_PyParser_Grammar, start, &err, flags);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001450 if (n == NULL)
1451 err_input(&err);
1452 return n;
1453}
1454
1455node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001456PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001457{
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001458 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001459}
1460
Guido van Rossum66ebd912003-04-17 16:02:26 +00001461/* May want to move a more generalized form of this to parsetok.c or
1462 even parser modules. */
1463
1464void
1465PyParser_SetError(perrdetail *err)
1466{
1467 err_input(err);
1468}
1469
Guido van Rossuma110aa61994-08-29 12:50:44 +00001470/* Set the error appropriate to the given input error code (see errcode.h) */
1471
1472static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001473err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001474{
Fred Drake85f36392000-07-11 17:53:00 +00001475 PyObject *v, *w, *errtype;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001476 PyObject* u = NULL;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001477 char *msg = NULL;
Fred Drake85f36392000-07-11 17:53:00 +00001478 errtype = PyExc_SyntaxError;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001479 switch (err->error) {
1480 case E_SYNTAX:
Fred Drake85f36392000-07-11 17:53:00 +00001481 errtype = PyExc_IndentationError;
1482 if (err->expected == INDENT)
1483 msg = "expected an indented block";
1484 else if (err->token == INDENT)
1485 msg = "unexpected indent";
1486 else if (err->token == DEDENT)
1487 msg = "unexpected unindent";
1488 else {
1489 errtype = PyExc_SyntaxError;
1490 msg = "invalid syntax";
1491 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001492 break;
1493 case E_TOKEN:
1494 msg = "invalid token";
Guido van Rossuma110aa61994-08-29 12:50:44 +00001495 break;
Skip Montanaro118ec702002-08-15 01:20:16 +00001496 case E_EOFS:
1497 msg = "EOF while scanning triple-quoted string";
1498 break;
1499 case E_EOLS:
1500 msg = "EOL while scanning single-quoted string";
1501 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001502 case E_INTR:
Michael W. Hudson30ea2f22004-07-07 17:44:12 +00001503 if (!PyErr_Occurred())
1504 PyErr_SetNone(PyExc_KeyboardInterrupt);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001505 return;
1506 case E_NOMEM:
Guido van Rossum82598051997-03-05 00:20:32 +00001507 PyErr_NoMemory();
Guido van Rossuma110aa61994-08-29 12:50:44 +00001508 return;
1509 case E_EOF:
1510 msg = "unexpected EOF while parsing";
1511 break;
Fred Drake85f36392000-07-11 17:53:00 +00001512 case E_TABSPACE:
1513 errtype = PyExc_TabError;
Guido van Rossum560e8ad1998-04-10 19:43:42 +00001514 msg = "inconsistent use of tabs and spaces in indentation";
1515 break;
Jeremy Hylton94988062000-06-20 19:10:44 +00001516 case E_OVERFLOW:
1517 msg = "expression too long";
1518 break;
Fred Drake85f36392000-07-11 17:53:00 +00001519 case E_DEDENT:
1520 errtype = PyExc_IndentationError;
1521 msg = "unindent does not match any outer indentation level";
1522 break;
1523 case E_TOODEEP:
1524 errtype = PyExc_IndentationError;
1525 msg = "too many levels of indentation";
1526 break;
Martin v. Löwisd35edda2005-08-24 08:39:24 +00001527 case E_DECODE: {
1528 PyObject *type, *value, *tb;
1529 PyErr_Fetch(&type, &value, &tb);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001530 if (value != NULL) {
Martin v. Löwisd35edda2005-08-24 08:39:24 +00001531 u = PyObject_Str(value);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001532 if (u != NULL) {
1533 msg = PyString_AsString(u);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001534 }
1535 }
Martin v. Löwisc2632a52004-07-21 05:35:02 +00001536 if (msg == NULL)
1537 msg = "unknown decode error";
Neal Norwitzdb83eb32005-12-18 05:29:30 +00001538 Py_XDECREF(type);
1539 Py_XDECREF(value);
Neal Norwitz40d37812005-10-02 01:48:49 +00001540 Py_XDECREF(tb);
Martin v. Löwisc2632a52004-07-21 05:35:02 +00001541 break;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001542 }
Martin v. Löwis4bf108d2005-03-03 11:45:45 +00001543 case E_LINECONT:
1544 msg = "unexpected character after line continuation character";
1545 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001546 default:
1547 fprintf(stderr, "error=%d\n", err->error);
1548 msg = "unknown parsing error";
1549 break;
1550 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001551 v = Py_BuildValue("(ziiz)", err->filename,
1552 err->lineno, err->offset, err->text);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001553 if (err->text != NULL) {
Tim Petersc9d78aa2006-03-26 23:27:58 +00001554 PyObject_FREE(err->text);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001555 err->text = NULL;
1556 }
1557 w = NULL;
1558 if (v != NULL)
1559 w = Py_BuildValue("(sO)", msg, v);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001560 Py_XDECREF(u);
Guido van Rossum41318302001-03-23 04:01:07 +00001561 Py_XDECREF(v);
Fred Drake85f36392000-07-11 17:53:00 +00001562 PyErr_SetObject(errtype, w);
Guido van Rossum82598051997-03-05 00:20:32 +00001563 Py_XDECREF(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001564}
1565
1566/* Print fatal error message and abort */
1567
1568void
Tim Peters7c321a82002-07-09 02:57:01 +00001569Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001570{
Guido van Rossum83dd6c31994-09-29 09:38:33 +00001571 fprintf(stderr, "Fatal Python error: %s\n", msg);
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001572#ifdef MS_WINDOWS
Guido van Rossum23c94461997-05-22 20:21:30 +00001573 OutputDebugString("Fatal Python error: ");
Guido van Rossuma44823b1995-03-14 15:01:17 +00001574 OutputDebugString(msg);
1575 OutputDebugString("\n");
Guido van Rossum0ba35361998-08-13 13:33:16 +00001576#ifdef _DEBUG
1577 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00001578#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001579#endif /* MS_WINDOWS */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001580 abort();
1581}
1582
1583/* Clean up and exit */
1584
Guido van Rossuma110aa61994-08-29 12:50:44 +00001585#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00001586#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00001587#endif
1588
Guido van Rossum2dcfc961998-10-01 16:01:57 +00001589#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001590static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00001591static int nexitfuncs = 0;
1592
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001593int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00001594{
1595 if (nexitfuncs >= NEXITFUNCS)
1596 return -1;
1597 exitfuncs[nexitfuncs++] = func;
1598 return 0;
1599}
1600
Guido van Rossumcc283f51997-08-05 02:22:03 +00001601static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001602call_sys_exitfunc(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001603{
Guido van Rossum82598051997-03-05 00:20:32 +00001604 PyObject *exitfunc = PySys_GetObject("exitfunc");
Guido van Rossum59bff391992-09-03 20:28:00 +00001605
1606 if (exitfunc) {
Fred Drake6a12d8d2001-03-23 17:34:02 +00001607 PyObject *res;
Guido van Rossum82598051997-03-05 00:20:32 +00001608 Py_INCREF(exitfunc);
1609 PySys_SetObject("exitfunc", (PyObject *)NULL);
1610 res = PyEval_CallObject(exitfunc, (PyObject *)NULL);
Guido van Rossum59bff391992-09-03 20:28:00 +00001611 if (res == NULL) {
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001612 if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
1613 PySys_WriteStderr("Error in sys.exitfunc:\n");
1614 }
Guido van Rossum82598051997-03-05 00:20:32 +00001615 PyErr_Print();
Guido van Rossum59bff391992-09-03 20:28:00 +00001616 }
Guido van Rossum82598051997-03-05 00:20:32 +00001617 Py_DECREF(exitfunc);
Guido van Rossum59bff391992-09-03 20:28:00 +00001618 }
1619
Guido van Rossum0829c751998-02-28 04:31:39 +00001620 if (Py_FlushLine())
1621 PyErr_Clear();
Guido van Rossumcc283f51997-08-05 02:22:03 +00001622}
Guido van Rossum1662dd51994-09-07 14:38:28 +00001623
Guido van Rossumcc283f51997-08-05 02:22:03 +00001624static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001625call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00001626{
Guido van Rossum1662dd51994-09-07 14:38:28 +00001627 while (nexitfuncs > 0)
1628 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00001629
1630 fflush(stdout);
1631 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001632}
1633
1634void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001635Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001636{
Guido van Rossumcc283f51997-08-05 02:22:03 +00001637 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001638
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001639 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001640}
1641
Guido van Rossumf1dc5661993-07-05 10:31:29 +00001642static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001643initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001644{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001645#ifdef SIGPIPE
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001646 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001647#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00001648#ifdef SIGXFZ
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001649 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00001650#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00001651#ifdef SIGXFSZ
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001652 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00001653#endif
Guido van Rossum82598051997-03-05 00:20:32 +00001654 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001655}
1656
Guido van Rossum7433b121997-02-14 19:45:36 +00001657
1658/*
1659 * The file descriptor fd is considered ``interactive'' if either
1660 * a) isatty(fd) is TRUE, or
1661 * b) the -i flag was given, and the filename associated with
1662 * the descriptor is NULL or "<stdin>" or "???".
1663 */
1664int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001665Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00001666{
1667 if (isatty((int)fileno(fp)))
1668 return 1;
1669 if (!Py_InteractiveFlag)
1670 return 0;
1671 return (filename == NULL) ||
1672 (strcmp(filename, "<stdin>") == 0) ||
1673 (strcmp(filename, "???") == 0);
1674}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001675
1676
Tim Petersd08e3822003-04-17 15:24:21 +00001677#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001678#if defined(WIN32) && defined(_MSC_VER)
1679
1680/* Stack checking for Microsoft C */
1681
1682#include <malloc.h>
1683#include <excpt.h>
1684
Fred Drakee8de31c2000-08-31 05:38:39 +00001685/*
1686 * Return non-zero when we run out of memory on the stack; zero otherwise.
1687 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001688int
Fred Drake399739f2000-08-31 05:52:44 +00001689PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001690{
1691 __try {
Tim Peters92e4dd82002-10-05 01:47:34 +00001692 /* alloca throws a stack overflow exception if there's
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001693 not enough space left on the stack */
Tim Peters92e4dd82002-10-05 01:47:34 +00001694 alloca(PYOS_STACK_MARGIN * sizeof(void*));
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001695 return 0;
1696 } __except (EXCEPTION_EXECUTE_HANDLER) {
1697 /* just ignore all errors */
1698 }
1699 return 1;
1700}
1701
1702#endif /* WIN32 && _MSC_VER */
1703
1704/* Alternate implementations can be added here... */
1705
1706#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00001707
1708
1709/* Wrappers around sigaction() or signal(). */
1710
1711PyOS_sighandler_t
1712PyOS_getsig(int sig)
1713{
1714#ifdef HAVE_SIGACTION
1715 struct sigaction context;
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001716 if (sigaction(sig, NULL, &context) == -1)
1717 return SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00001718 return context.sa_handler;
1719#else
1720 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00001721/* Special signal handling for the secure CRT in Visual Studio 2005 */
1722#if defined(_MSC_VER) && _MSC_VER >= 1400
1723 switch (sig) {
1724 /* Only these signals are valid */
1725 case SIGINT:
1726 case SIGILL:
1727 case SIGFPE:
1728 case SIGSEGV:
1729 case SIGTERM:
1730 case SIGBREAK:
1731 case SIGABRT:
1732 break;
1733 /* Don't call signal() with other values or it will assert */
1734 default:
1735 return SIG_ERR;
1736 }
1737#endif /* _MSC_VER && _MSC_VER >= 1400 */
Guido van Rossum6f256182000-09-16 16:32:19 +00001738 handler = signal(sig, SIG_IGN);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001739 if (handler != SIG_ERR)
1740 signal(sig, handler);
Guido van Rossum6f256182000-09-16 16:32:19 +00001741 return handler;
1742#endif
1743}
1744
1745PyOS_sighandler_t
1746PyOS_setsig(int sig, PyOS_sighandler_t handler)
1747{
1748#ifdef HAVE_SIGACTION
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001749 struct sigaction context, ocontext;
Guido van Rossum6f256182000-09-16 16:32:19 +00001750 context.sa_handler = handler;
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001751 sigemptyset(&context.sa_mask);
1752 context.sa_flags = 0;
1753 if (sigaction(sig, &context, &ocontext) == -1)
1754 return SIG_ERR;
1755 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00001756#else
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001757 PyOS_sighandler_t oldhandler;
1758 oldhandler = signal(sig, handler);
1759#ifdef HAVE_SIGINTERRUPT
1760 siginterrupt(sig, 1);
1761#endif
1762 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00001763#endif
1764}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001765
1766/* Deprecated C API functions still provided for binary compatiblity */
1767
1768#undef PyParser_SimpleParseFile
Thomas Heller1b046642006-04-18 18:51:06 +00001769PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001770PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
1771{
1772 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
1773}
1774
Thomas Heller1b046642006-04-18 18:51:06 +00001775#undef PyParser_SimpleParseString
1776PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001777PyParser_SimpleParseString(const char *str, int start)
1778{
1779 return PyParser_SimpleParseStringFlags(str, start, 0);
1780}
Anthony Baxterac6bd462006-04-13 02:06:09 +00001781
Thomas Heller1b046642006-04-18 18:51:06 +00001782#undef PyRun_AnyFile
1783PyAPI_FUNC(int)
1784PyRun_AnyFile(FILE *fp, const char *name)
1785{
1786 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
1787}
1788
1789#undef PyRun_AnyFileEx
1790PyAPI_FUNC(int)
1791PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
1792{
1793 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
1794}
1795
1796#undef PyRun_AnyFileFlags
1797PyAPI_FUNC(int)
1798PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
1799{
1800 return PyRun_AnyFileExFlags(fp, name, 0, flags);
1801}
1802
1803#undef PyRun_File
1804PyAPI_FUNC(PyObject *)
1805PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
1806{
1807 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
1808}
1809
1810#undef PyRun_FileEx
1811PyAPI_FUNC(PyObject *)
1812PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
1813{
1814 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
1815}
1816
1817#undef PyRun_FileFlags
1818PyAPI_FUNC(PyObject *)
1819PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
1820 PyCompilerFlags *flags)
1821{
1822 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
1823}
1824
1825#undef PyRun_SimpleFile
1826PyAPI_FUNC(int)
1827PyRun_SimpleFile(FILE *f, const char *p)
1828{
1829 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
1830}
1831
1832#undef PyRun_SimpleFileEx
1833PyAPI_FUNC(int)
1834PyRun_SimpleFileEx(FILE *f, const char *p, int c)
1835{
1836 return PyRun_SimpleFileExFlags(f, p, c, NULL);
1837}
1838
1839
1840#undef PyRun_String
1841PyAPI_FUNC(PyObject *)
1842PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
1843{
1844 return PyRun_StringFlags(str, s, g, l, NULL);
1845}
1846
1847#undef PyRun_SimpleString
1848PyAPI_FUNC(int)
1849PyRun_SimpleString(const char *s)
1850{
1851 return PyRun_SimpleStringFlags(s, NULL);
1852}
1853
1854#undef Py_CompileString
1855PyAPI_FUNC(PyObject *)
1856Py_CompileString(const char *str, const char *p, int s)
1857{
1858 return Py_CompileStringFlags(str, p, s, NULL);
1859}
1860
1861#undef PyRun_InteractiveOne
1862PyAPI_FUNC(int)
1863PyRun_InteractiveOne(FILE *f, const char *p)
1864{
1865 return PyRun_InteractiveOneFlags(f, p, NULL);
1866}
1867
1868#undef PyRun_InteractiveLoop
1869PyAPI_FUNC(int)
1870PyRun_InteractiveLoop(FILE *f, const char *p)
1871{
1872 return PyRun_InteractiveLoopFlags(f, p, NULL);
1873}
1874
Anthony Baxterac6bd462006-04-13 02:06:09 +00001875#ifdef __cplusplus
1876}
1877#endif
1878