blob: b82d77e0b9560a6ca77431f91630d11c10c35b86 [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
6#include "grammar.h"
7#include "node.h"
Fred Drake85f36392000-07-11 17:53:00 +00008#include "token.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +00009#include "parsetok.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000010#include "errcode.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000011#include "compile.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000012#include "symtable.h"
Guido van Rossumff4949e1992-08-05 19:58:53 +000013#include "eval.h"
Guido van Rossumfdef2711994-09-14 13:31:04 +000014#include "marshal.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000015
Guido van Rossuma110aa61994-08-29 12:50:44 +000016#ifdef HAVE_SIGNAL_H
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000017#include <signal.h>
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000018#endif
19
Martin v. Löwis73d538b2003-03-05 15:13:47 +000020#ifdef HAVE_LANGINFO_H
21#include <locale.h>
22#include <langinfo.h>
23#endif
24
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000025#ifdef MS_WINDOWS
Guido van Rossuma44823b1995-03-14 15:01:17 +000026#undef BYTE
27#include "windows.h"
28#endif
29
Jack Jansencbf630f2000-07-11 21:59:16 +000030#ifdef macintosh
31#include "macglue.h"
32#endif
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000033extern char *Py_GetPath(void);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000034
Guido van Rossum82598051997-03-05 00:20:32 +000035extern grammar _PyParser_Grammar; /* From graminit.c */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000036
Guido van Rossumb73cc041993-11-01 16:28:59 +000037/* Forward */
Tim Petersdbd9ba62000-07-09 03:09:57 +000038static void initmain(void);
39static void initsite(void);
Martin v. Löwis95292d62002-12-11 14:04:59 +000040static PyObject *run_err_node(node *, const char *, PyObject *, PyObject *,
Jeremy Hylton9f324e92001-03-01 22:59:14 +000041 PyCompilerFlags *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000042static PyObject *run_node(node *, const char *, PyObject *, PyObject *,
Jeremy Hylton9f324e92001-03-01 22:59:14 +000043 PyCompilerFlags *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000044static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
Jeremy Hyltonbc320242001-03-22 02:47:58 +000045 PyCompilerFlags *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000046static void err_input(perrdetail *);
47static void initsigs(void);
48static void call_sys_exitfunc(void);
49static void call_ll_exitfuncs(void);
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000050extern void _PyUnicode_Init(void);
51extern void _PyUnicode_Fini(void);
52extern void _PyCodecRegistry_Init(void);
53extern void _PyCodecRegistry_Fini(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +000054
Guido van Rossum82598051997-03-05 00:20:32 +000055int Py_DebugFlag; /* Needed by parser.c */
56int Py_VerboseFlag; /* Needed by import.c */
Guido van Rossum7433b121997-02-14 19:45:36 +000057int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Guido van Rossumdcc0c131997-08-29 22:32:42 +000058int Py_NoSiteFlag; /* Suppress 'import site' */
Barry Warsaw3ce09642000-05-02 19:18:59 +000059int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +000060int Py_FrozenFlag; /* Needed by getpath.c */
Guido van Rossumb16d1972000-05-01 17:55:15 +000061int Py_UnicodeFlag = 0; /* Needed by compile.c */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +000062int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Tim Peters3caca232001-12-06 06:23:26 +000063/* _XXX Py_QnewFlag should go away in 2.3. It's true iff -Qnew is passed,
64 on the command line, and is used in 2.2 by ceval.c to make all "/" divisions
65 true divisions (which they will be in 2.3). */
66int _Py_QnewFlag = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +000067
Mark Hammonda43fd0c2003-02-19 00:33:33 +000068/* Reference to 'warnings' module, to avoid importing it
69 on the fly when the import lock may be held. See 683658
70*/
71PyObject *PyModule_WarningsModule = NULL;
72
Guido van Rossum25ce5661997-08-02 03:10:38 +000073static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +000074
Thomas Wouters7e474022000-07-16 12:04:32 +000075/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +000076
77int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000078Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +000079{
80 return initialized;
81}
82
Guido van Rossum25ce5661997-08-02 03:10:38 +000083/* Global initializations. Can be undone by Py_Finalize(). Don't
84 call this twice without an intervening Py_Finalize() call. When
85 initializations fail, a fatal error is issued and the function does
86 not return. On return, the first thread and interpreter state have
87 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +000088
Guido van Rossum25ce5661997-08-02 03:10:38 +000089 Locking: you must hold the interpreter lock while calling this.
90 (If the lock has not yet been initialized, that's equivalent to
91 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000092
Guido van Rossum25ce5661997-08-02 03:10:38 +000093*/
Guido van Rossuma027efa1997-05-05 20:56:21 +000094
Guido van Rossum9abaf4d2001-10-12 22:17:56 +000095static int
96add_flag(int flag, const char *envs)
97{
98 int env = atoi(envs);
99 if (flag < env)
100 flag = env;
101 if (flag < 1)
102 flag = 1;
103 return flag;
104}
105
Guido van Rossuma027efa1997-05-05 20:56:21 +0000106void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000107Py_Initialize(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000108{
Guido van Rossuma027efa1997-05-05 20:56:21 +0000109 PyInterpreterState *interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000110 PyThreadState *tstate;
111 PyObject *bimod, *sysmod;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000112 char *p;
Guido van Rossum70d893a2001-08-16 08:21:42 +0000113 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000114
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000115 if (initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +0000116 return;
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000117 initialized = 1;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000118
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000119 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000120 Py_DebugFlag = add_flag(Py_DebugFlag, p);
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000121 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000122 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000123 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000124 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000125
Guido van Rossuma027efa1997-05-05 20:56:21 +0000126 interp = PyInterpreterState_New();
127 if (interp == NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000128 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000129
Guido van Rossuma027efa1997-05-05 20:56:21 +0000130 tstate = PyThreadState_New(interp);
131 if (tstate == NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000132 Py_FatalError("Py_Initialize: can't make first thread");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000133 (void) PyThreadState_Swap(tstate);
134
Guido van Rossum70d893a2001-08-16 08:21:42 +0000135 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000136
Neal Norwitzb2501f42002-12-31 03:42:13 +0000137 if (!_PyFrame_Init())
Neal Norwitzc91ed402002-12-30 22:29:22 +0000138 Py_FatalError("Py_Initialize: can't init frames");
139
Neal Norwitzb2501f42002-12-31 03:42:13 +0000140 if (!_PyInt_Init())
Neal Norwitzc91ed402002-12-30 22:29:22 +0000141 Py_FatalError("Py_Initialize: can't init ints");
142
Guido van Rossum25ce5661997-08-02 03:10:38 +0000143 interp->modules = PyDict_New();
144 if (interp->modules == NULL)
145 Py_FatalError("Py_Initialize: can't make modules dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000146
Guido van Rossumc94044c2000-03-10 23:03:54 +0000147 /* Init codec registry */
148 _PyCodecRegistry_Init();
149
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000150#ifdef Py_USING_UNICODE
Guido van Rossumc94044c2000-03-10 23:03:54 +0000151 /* Init Unicode implementation; relies on the codec registry */
152 _PyUnicode_Init();
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000153#endif
Guido van Rossumc94044c2000-03-10 23:03:54 +0000154
Barry Warsawf242aa02000-05-25 23:09:49 +0000155 bimod = _PyBuiltin_Init();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000156 if (bimod == NULL)
157 Py_FatalError("Py_Initialize: can't initialize __builtin__");
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000158 interp->builtins = PyModule_GetDict(bimod);
159 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000160
161 sysmod = _PySys_Init();
162 if (sysmod == NULL)
163 Py_FatalError("Py_Initialize: can't initialize sys");
164 interp->sysdict = PyModule_GetDict(sysmod);
165 Py_INCREF(interp->sysdict);
166 _PyImport_FixupExtension("sys", "sys");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000167 PySys_SetPath(Py_GetPath());
Guido van Rossum25ce5661997-08-02 03:10:38 +0000168 PyDict_SetItemString(interp->sysdict, "modules",
169 interp->modules);
170
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000171 _PyImport_Init();
172
Barry Warsawf242aa02000-05-25 23:09:49 +0000173 /* initialize builtin exceptions */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000174 _PyExc_Init();
Barry Warsaw5821bc52001-08-13 23:04:56 +0000175 _PyImport_FixupExtension("exceptions", "exceptions");
Barry Warsawf242aa02000-05-25 23:09:49 +0000176
Barry Warsaw035574d1997-08-29 22:07:17 +0000177 /* phase 2 of builtins */
Barry Warsaw963b8711997-09-18 16:42:02 +0000178 _PyImport_FixupExtension("__builtin__", "__builtin__");
Barry Warsaw035574d1997-08-29 22:07:17 +0000179
Just van Rossum52e14d62002-12-30 22:08:05 +0000180 _PyImportHooks_Init();
181
Guido van Rossum25ce5661997-08-02 03:10:38 +0000182 initsigs(); /* Signal handling stuff, including initintr() */
183
184 initmain(); /* Module __main__ */
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000185 if (!Py_NoSiteFlag)
186 initsite(); /* Module site */
Just van Rossum5bfba3a2003-02-25 20:25:12 +0000187
188 PyModule_WarningsModule = PyImport_ImportModule("warnings");
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000189
190#if defined(Py_USING_UNICODE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
191 /* On Unix, set the file system encoding according to the
192 user's preference, if the CODESET names a well-known
193 Python codec, and Py_FileSystemDefaultEncoding isn't
194 initialized by other means. */
195 if (!Py_FileSystemDefaultEncoding) {
196 char *saved_locale = setlocale(LC_CTYPE, NULL);
197 char *codeset;
Fred Drake6a9a3292003-03-05 17:31:21 +0000198 PyObject *enc = NULL;
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000199 setlocale(LC_CTYPE, "");
200 codeset = nl_langinfo(CODESET);
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000201 if (*codeset) {
202 enc = PyCodec_Encoder(codeset);
203 if (enc) {
204 Py_FileSystemDefaultEncoding = strdup(codeset);
205 Py_DECREF(enc);
206 } else
207 PyErr_Clear();
208 }
209 setlocale(LC_CTYPE, saved_locale);
210 }
211#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000212}
213
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000214#ifdef COUNT_ALLOCS
Tim Petersdbd9ba62000-07-09 03:09:57 +0000215extern void dump_counts(void);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000216#endif
217
Guido van Rossum25ce5661997-08-02 03:10:38 +0000218/* Undo the effect of Py_Initialize().
219
220 Beware: if multiple interpreter and/or thread states exist, these
221 are not wiped out; only the current thread and interpreter state
222 are deleted. But since everything else is deleted, those other
223 interpreter and thread states should no longer be used.
224
225 (XXX We should do better, e.g. wipe out all interpreters and
226 threads.)
227
228 Locking: as above.
229
230*/
231
232void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000233Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000234{
235 PyInterpreterState *interp;
236 PyThreadState *tstate;
237
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000238 if (!initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +0000239 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000240
Tim Peters384fd102001-01-21 03:40:37 +0000241 /* The interpreter is still entirely intact at this point, and the
242 * exit funcs may be relying on that. In particular, if some thread
243 * or exit func is still waiting to do an import, the import machinery
244 * expects Py_IsInitialized() to return true. So don't say the
245 * interpreter is uninitialized until after the exit funcs have run.
246 * Note that Threading.py uses an exit func to do a join on all the
247 * threads created thru it, so this also protects pending imports in
248 * the threads created via Threading.
249 */
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000250 call_sys_exitfunc();
Tim Peters384fd102001-01-21 03:40:37 +0000251 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000252
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000253 /* Get current thread state and interpreter pointer */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000254 tstate = PyThreadState_Get();
255 interp = tstate->interp;
256
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000257 /* Disable signal handling */
258 PyOS_FiniInterrupts();
259
Guido van Rossumc94044c2000-03-10 23:03:54 +0000260 /* Cleanup Codec registry */
261 _PyCodecRegistry_Fini();
262
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000263 /* drop module references we saved */
264 Py_XDECREF(PyModule_WarningsModule);
265 PyModule_WarningsModule = NULL;
266
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000267 /* Destroy all modules */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000268 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000269
Guido van Rossum1707aad1997-12-08 23:43:45 +0000270 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
271 _PyImport_Fini();
272
273 /* Debugging stuff */
274#ifdef COUNT_ALLOCS
275 dump_counts();
276#endif
277
278#ifdef Py_REF_DEBUG
279 fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
280#endif
281
282#ifdef Py_TRACE_REFS
Guido van Rossum92e2d5c2001-08-09 16:37:16 +0000283 if (Py_GETENV("PYTHONDUMPREFS")) {
Guido van Rossum1707aad1997-12-08 23:43:45 +0000284 _Py_PrintReferences(stderr);
285 }
286#endif /* Py_TRACE_REFS */
287
Barry Warsaw035574d1997-08-29 22:07:17 +0000288 /* Now we decref the exception classes. After this point nothing
289 can raise an exception. That's okay, because each Fini() method
290 below has been checked to make sure no exceptions are ever
291 raised.
292 */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000293 _PyExc_Fini();
Barry Warsawf242aa02000-05-25 23:09:49 +0000294
295 /* Delete current thread */
296 PyInterpreterState_Clear(interp);
297 PyThreadState_Swap(NULL);
298 PyInterpreterState_Delete(interp);
299
Guido van Rossumcc283f51997-08-05 02:22:03 +0000300 PyMethod_Fini();
301 PyFrame_Fini();
302 PyCFunction_Fini();
303 PyTuple_Fini();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000304 PyString_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000305 PyInt_Fini();
306 PyFloat_Fini();
307
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000308#ifdef Py_USING_UNICODE
309 /* Cleanup Unicode implementation */
310 _PyUnicode_Fini();
311#endif
312
Guido van Rossumcc283f51997-08-05 02:22:03 +0000313 /* XXX Still allocated:
314 - various static ad-hoc pointers to interned strings
315 - int and float free list blocks
316 - whatever various modules and libraries allocate
317 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000318
319 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000320
Tim Peters0e871182002-04-13 08:29:14 +0000321#ifdef PYMALLOC_DEBUG
322 if (Py_GETENV("PYTHONMALLOCSTATS"))
323 _PyObject_DebugMallocStats();
324#endif
325
Guido van Rossumcc283f51997-08-05 02:22:03 +0000326 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000327}
328
329/* Create and initialize a new interpreter and thread, and return the
330 new thread. This requires that Py_Initialize() has been called
331 first.
332
333 Unsuccessful initialization yields a NULL pointer. Note that *no*
334 exception information is available even in this case -- the
335 exception information is held in the thread, and there is no
336 thread.
337
338 Locking: as above.
339
340*/
341
342PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000343Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000344{
345 PyInterpreterState *interp;
346 PyThreadState *tstate, *save_tstate;
347 PyObject *bimod, *sysmod;
348
349 if (!initialized)
350 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
351
352 interp = PyInterpreterState_New();
353 if (interp == NULL)
354 return NULL;
355
356 tstate = PyThreadState_New(interp);
357 if (tstate == NULL) {
358 PyInterpreterState_Delete(interp);
359 return NULL;
360 }
361
362 save_tstate = PyThreadState_Swap(tstate);
363
364 /* XXX The following is lax in error checking */
365
366 interp->modules = PyDict_New();
367
368 bimod = _PyImport_FindExtension("__builtin__", "__builtin__");
369 if (bimod != NULL) {
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000370 interp->builtins = PyModule_GetDict(bimod);
371 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000372 }
373 sysmod = _PyImport_FindExtension("sys", "sys");
374 if (bimod != NULL && sysmod != NULL) {
375 interp->sysdict = PyModule_GetDict(sysmod);
376 Py_INCREF(interp->sysdict);
377 PySys_SetPath(Py_GetPath());
378 PyDict_SetItemString(interp->sysdict, "modules",
379 interp->modules);
Martin v. Löwisd7ceb222003-01-22 09:00:38 +0000380 _PyImportHooks_Init();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000381 initmain();
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000382 if (!Py_NoSiteFlag)
383 initsite();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000384 }
385
386 if (!PyErr_Occurred())
387 return tstate;
388
389 /* Oops, it didn't work. Undo it all. */
390
391 PyErr_Print();
392 PyThreadState_Clear(tstate);
393 PyThreadState_Swap(save_tstate);
394 PyThreadState_Delete(tstate);
395 PyInterpreterState_Delete(interp);
396
397 return NULL;
398}
399
400/* Delete an interpreter and its last thread. This requires that the
401 given thread state is current, that the thread has no remaining
402 frames, and that it is its interpreter's only remaining thread.
403 It is a fatal error to violate these constraints.
404
405 (Py_Finalize() doesn't have these constraints -- it zaps
406 everything, regardless.)
407
408 Locking: as above.
409
410*/
411
412void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000413Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000414{
415 PyInterpreterState *interp = tstate->interp;
416
417 if (tstate != PyThreadState_Get())
418 Py_FatalError("Py_EndInterpreter: thread is not current");
419 if (tstate->frame != NULL)
420 Py_FatalError("Py_EndInterpreter: thread still has a frame");
421 if (tstate != interp->tstate_head || tstate->next != NULL)
422 Py_FatalError("Py_EndInterpreter: not the last thread");
423
424 PyImport_Cleanup();
425 PyInterpreterState_Clear(interp);
426 PyThreadState_Swap(NULL);
427 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000428}
429
430static char *progname = "python";
431
432void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000433Py_SetProgramName(char *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000434{
435 if (pn && *pn)
436 progname = pn;
437}
438
439char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000440Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000441{
442 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000443}
444
Guido van Rossuma61691e1998-02-06 22:27:24 +0000445static char *default_home = NULL;
446
447void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000448Py_SetPythonHome(char *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000449{
450 default_home = home;
451}
452
453char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000454Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000455{
456 char *home = default_home;
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000457 if (home == NULL && !Py_IgnoreEnvironmentFlag)
458 home = Py_GETENV("PYTHONHOME");
Guido van Rossuma61691e1998-02-06 22:27:24 +0000459 return home;
460}
461
Guido van Rossum6135a871995-01-09 17:53:26 +0000462/* Create __main__ module */
463
464static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000465initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000466{
Guido van Rossum82598051997-03-05 00:20:32 +0000467 PyObject *m, *d;
468 m = PyImport_AddModule("__main__");
Guido van Rossum6135a871995-01-09 17:53:26 +0000469 if (m == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +0000470 Py_FatalError("can't create __main__ module");
471 d = PyModule_GetDict(m);
472 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
Guido van Rossum858cb731997-11-19 16:15:37 +0000473 PyObject *bimod = PyImport_ImportModule("__builtin__");
474 if (bimod == NULL ||
475 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
Guido van Rossum82598051997-03-05 00:20:32 +0000476 Py_FatalError("can't add __builtins__ to __main__");
Barry Warsaw3d05b1a1999-01-29 21:30:22 +0000477 Py_DECREF(bimod);
Guido van Rossum6135a871995-01-09 17:53:26 +0000478 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000479}
480
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000481/* Import the site module (not into __main__ though) */
482
483static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000484initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000485{
486 PyObject *m, *f;
487 m = PyImport_ImportModule("site");
488 if (m == NULL) {
489 f = PySys_GetObject("stderr");
490 if (Py_VerboseFlag) {
491 PyFile_WriteString(
492 "'import site' failed; traceback:\n", f);
493 PyErr_Print();
494 }
495 else {
496 PyFile_WriteString(
497 "'import site' failed; use -v for traceback\n", f);
498 PyErr_Clear();
499 }
500 }
501 else {
502 Py_DECREF(m);
503 }
504}
505
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000506/* Parse input from a file and execute it */
507
508int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000509PyRun_AnyFile(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000510{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000511 return PyRun_AnyFileExFlags(fp, filename, 0, NULL);
512}
513
514int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000515PyRun_AnyFileFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000516{
517 return PyRun_AnyFileExFlags(fp, filename, 0, flags);
Guido van Rossum0df002c2000-08-27 19:21:52 +0000518}
519
520int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000521PyRun_AnyFileEx(FILE *fp, const char *filename, int closeit)
Guido van Rossum0df002c2000-08-27 19:21:52 +0000522{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000523 return PyRun_AnyFileExFlags(fp, filename, closeit, NULL);
524}
525
526int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000527PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000528 PyCompilerFlags *flags)
529{
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000530 if (filename == NULL)
531 filename = "???";
Guido van Rossum0df002c2000-08-27 19:21:52 +0000532 if (Py_FdIsInteractive(fp, filename)) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000533 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
Guido van Rossum0df002c2000-08-27 19:21:52 +0000534 if (closeit)
535 fclose(fp);
536 return err;
537 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000538 else
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000539 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000540}
541
542int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000543PyRun_InteractiveLoop(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000544{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000545 return PyRun_InteractiveLoopFlags(fp, filename, NULL);
546}
547
548int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000549PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000550{
Guido van Rossum82598051997-03-05 00:20:32 +0000551 PyObject *v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000552 int ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000553 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000554
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000555 if (flags == NULL) {
556 flags = &local_flags;
Tim Peters5ba58662001-07-16 02:29:45 +0000557 local_flags.cf_flags = 0;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000558 }
Guido van Rossum82598051997-03-05 00:20:32 +0000559 v = PySys_GetObject("ps1");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000560 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000561 PySys_SetObject("ps1", v = PyString_FromString(">>> "));
562 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000563 }
Guido van Rossum82598051997-03-05 00:20:32 +0000564 v = PySys_GetObject("ps2");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000565 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000566 PySys_SetObject("ps2", v = PyString_FromString("... "));
567 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000568 }
569 for (;;) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000570 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
Guido van Rossumaae0d321996-05-22 16:35:33 +0000571#ifdef Py_REF_DEBUG
Guido van Rossum6f9e4331995-03-29 16:57:48 +0000572 fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000573#endif
574 if (ret == E_EOF)
575 return 0;
576 /*
577 if (ret == E_NOMEM)
578 return -1;
579 */
580 }
581}
582
583int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000584PyRun_InteractiveOne(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000585{
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000586 return PyRun_InteractiveOneFlags(fp, filename, NULL);
587}
588
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000589/* compute parser flags based on compiler flags */
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000590#define PARSER_FLAGS(flags) \
Guido van Rossum4b499dd32003-02-13 22:07:59 +0000591 (((flags) && (flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
592 PyPARSE_DONT_IMPLY_DEDENT : 0)
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000593
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000594int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000595PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000596{
Guido van Rossum82598051997-03-05 00:20:32 +0000597 PyObject *m, *d, *v, *w;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000598 node *n;
Guido van Rossuma110aa61994-08-29 12:50:44 +0000599 perrdetail err;
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000600 char *ps1 = "", *ps2 = "";
Tim Petersfe2127d2001-07-16 05:37:24 +0000601
Guido van Rossum82598051997-03-05 00:20:32 +0000602 v = PySys_GetObject("ps1");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000603 if (v != NULL) {
604 v = PyObject_Str(v);
605 if (v == NULL)
606 PyErr_Clear();
607 else if (PyString_Check(v))
608 ps1 = PyString_AsString(v);
609 }
Guido van Rossum82598051997-03-05 00:20:32 +0000610 w = PySys_GetObject("ps2");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000611 if (w != NULL) {
612 w = PyObject_Str(w);
613 if (w == NULL)
614 PyErr_Clear();
615 else if (PyString_Check(w))
616 ps2 = PyString_AsString(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000617 }
Tim Petersfe2127d2001-07-16 05:37:24 +0000618 n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar,
619 Py_single_input, ps1, ps2, &err,
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000620 PARSER_FLAGS(flags));
Guido van Rossum82598051997-03-05 00:20:32 +0000621 Py_XDECREF(v);
622 Py_XDECREF(w);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000623 if (n == NULL) {
624 if (err.error == E_EOF) {
625 if (err.text)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000626 PyMem_DEL(err.text);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000627 return E_EOF;
628 }
629 err_input(&err);
Guido van Rossum82598051997-03-05 00:20:32 +0000630 PyErr_Print();
Guido van Rossuma110aa61994-08-29 12:50:44 +0000631 return err.error;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000632 }
Guido van Rossum82598051997-03-05 00:20:32 +0000633 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000634 if (m == NULL)
635 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000636 d = PyModule_GetDict(m);
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000637 v = run_node(n, filename, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000638 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000639 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000640 return -1;
641 }
Guido van Rossum82598051997-03-05 00:20:32 +0000642 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000643 if (Py_FlushLine())
644 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000645 return 0;
646}
647
648int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000649PyRun_SimpleFile(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000650{
Guido van Rossum0df002c2000-08-27 19:21:52 +0000651 return PyRun_SimpleFileEx(fp, filename, 0);
652}
653
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000654/* Check whether a file maybe a pyc file: Look at the extension,
655 the file type, and, if we may close it, at the first few bytes. */
656
657static int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000658maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000659{
660 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
661 return 1;
662
663#ifdef macintosh
664 /* On a mac, we also assume a pyc file for types 'PYC ' and 'APPL' */
Jack Jansen72f3b7a2002-12-13 15:23:10 +0000665 if (PyMac_getfiletype((char *)filename) == 'PYC '
666 || PyMac_getfiletype((char *)filename) == 'APPL')
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000667 return 1;
668#endif /* macintosh */
669
670 /* Only look into the file if we are allowed to close it, since
671 it then should also be seekable. */
672 if (closeit) {
673 /* Read only two bytes of the magic. If the file was opened in
674 text mode, the bytes 3 and 4 of the magic (\r\n) might not
675 be read as they are on disk. */
676 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
677 unsigned char buf[2];
Tim Peters3e876562001-02-11 04:35:39 +0000678 /* Mess: In case of -x, the stream is NOT at its start now,
679 and ungetc() was used to push back the first newline,
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000680 which makes the current stream position formally undefined,
681 and a x-platform nightmare.
682 Unfortunately, we have no direct way to know whether -x
683 was specified. So we use a terrible hack: if the current
684 stream position is not 0, we assume -x was specified, and
685 give up. Bug 132850 on SourceForge spells out the
686 hopelessness of trying anything else (fseek and ftell
687 don't work predictably x-platform for text-mode files).
Tim Peters3e876562001-02-11 04:35:39 +0000688 */
Tim Peters3e876562001-02-11 04:35:39 +0000689 int ispyc = 0;
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000690 if (ftell(fp) == 0) {
691 if (fread(buf, 1, 2, fp) == 2 &&
692 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
693 ispyc = 1;
694 rewind(fp);
695 }
Tim Peters3e876562001-02-11 04:35:39 +0000696 return ispyc;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000697 }
698 return 0;
699}
700
Guido van Rossum0df002c2000-08-27 19:21:52 +0000701int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000702PyRun_SimpleFileEx(FILE *fp, const char *filename, int closeit)
Guido van Rossum0df002c2000-08-27 19:21:52 +0000703{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000704 return PyRun_SimpleFileExFlags(fp, filename, closeit, NULL);
705}
706
707int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000708PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000709 PyCompilerFlags *flags)
710{
Guido van Rossum82598051997-03-05 00:20:32 +0000711 PyObject *m, *d, *v;
Martin v. Löwis95292d62002-12-11 14:04:59 +0000712 const char *ext;
Guido van Rossumfdef2711994-09-14 13:31:04 +0000713
Guido van Rossum82598051997-03-05 00:20:32 +0000714 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000715 if (m == NULL)
716 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000717 d = PyModule_GetDict(m);
Fred Drake8ed02042002-10-17 21:24:58 +0000718 if (PyDict_GetItemString(d, "__file__") == NULL) {
719 PyObject *f = PyString_FromString(filename);
720 if (f == NULL)
721 return -1;
722 if (PyDict_SetItemString(d, "__file__", f) < 0) {
723 Py_DECREF(f);
724 return -1;
725 }
726 Py_DECREF(f);
727 }
Guido van Rossumfdef2711994-09-14 13:31:04 +0000728 ext = filename + strlen(filename) - 4;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000729 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Guido van Rossumfdef2711994-09-14 13:31:04 +0000730 /* Try to run a pyc file. First, re-open in binary */
Guido van Rossum0df002c2000-08-27 19:21:52 +0000731 if (closeit)
732 fclose(fp);
Fred Drake8ed02042002-10-17 21:24:58 +0000733 if ((fp = fopen(filename, "rb")) == NULL) {
Guido van Rossumfdef2711994-09-14 13:31:04 +0000734 fprintf(stderr, "python: Can't reopen .pyc file\n");
735 return -1;
736 }
Guido van Rossum2a7f58d1997-04-02 05:28:38 +0000737 /* Turn on optimization if a .pyo file is given */
738 if (strcmp(ext, ".pyo") == 0)
739 Py_OptimizeFlag = 1;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000740 v = run_pyc_file(fp, filename, d, d, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000741 } else {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000742 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
743 closeit, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000744 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000745 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000746 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000747 return -1;
748 }
Guido van Rossum82598051997-03-05 00:20:32 +0000749 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000750 if (Py_FlushLine())
751 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000752 return 0;
753}
754
755int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000756PyRun_SimpleString(const char *command)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000757{
Guido van Rossum393661d2001-08-31 17:40:15 +0000758 return PyRun_SimpleStringFlags(command, NULL);
759}
760
761int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000762PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +0000763{
Guido van Rossum82598051997-03-05 00:20:32 +0000764 PyObject *m, *d, *v;
765 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000766 if (m == NULL)
767 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000768 d = PyModule_GetDict(m);
Guido van Rossum393661d2001-08-31 17:40:15 +0000769 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000770 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000771 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000772 return -1;
773 }
Guido van Rossum82598051997-03-05 00:20:32 +0000774 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000775 if (Py_FlushLine())
776 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000777 return 0;
778}
779
Barry Warsaw035574d1997-08-29 22:07:17 +0000780static int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000781parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
782 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +0000783{
784 long hold;
785 PyObject *v;
786
787 /* old style errors */
788 if (PyTuple_Check(err))
Neal Norwitz78293352002-04-01 01:41:20 +0000789 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
790 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +0000791
792 /* new style errors. `err' is an instance */
793
794 if (! (v = PyObject_GetAttrString(err, "msg")))
795 goto finally;
796 *message = v;
797
798 if (!(v = PyObject_GetAttrString(err, "filename")))
799 goto finally;
800 if (v == Py_None)
801 *filename = NULL;
802 else if (! (*filename = PyString_AsString(v)))
803 goto finally;
804
805 Py_DECREF(v);
806 if (!(v = PyObject_GetAttrString(err, "lineno")))
807 goto finally;
808 hold = PyInt_AsLong(v);
809 Py_DECREF(v);
810 v = NULL;
811 if (hold < 0 && PyErr_Occurred())
812 goto finally;
813 *lineno = (int)hold;
814
815 if (!(v = PyObject_GetAttrString(err, "offset")))
816 goto finally;
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000817 if (v == Py_None) {
818 *offset = -1;
819 Py_DECREF(v);
820 v = NULL;
821 } else {
822 hold = PyInt_AsLong(v);
823 Py_DECREF(v);
824 v = NULL;
825 if (hold < 0 && PyErr_Occurred())
826 goto finally;
827 *offset = (int)hold;
828 }
Barry Warsaw035574d1997-08-29 22:07:17 +0000829
830 if (!(v = PyObject_GetAttrString(err, "text")))
831 goto finally;
832 if (v == Py_None)
833 *text = NULL;
834 else if (! (*text = PyString_AsString(v)))
835 goto finally;
836 Py_DECREF(v);
837 return 1;
838
839finally:
840 Py_XDECREF(v);
841 return 0;
842}
843
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000844void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000845PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000846{
Guido van Rossuma61691e1998-02-06 22:27:24 +0000847 PyErr_PrintEx(1);
848}
849
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000850static void
Martin v. Löwis95292d62002-12-11 14:04:59 +0000851print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000852{
853 char *nl;
854 if (offset >= 0) {
855 if (offset > 0 && offset == (int)strlen(text))
856 offset--;
857 for (;;) {
858 nl = strchr(text, '\n');
859 if (nl == NULL || nl-text >= offset)
860 break;
861 offset -= (nl+1-text);
862 text = nl+1;
863 }
864 while (*text == ' ' || *text == '\t') {
865 text++;
866 offset--;
867 }
868 }
869 PyFile_WriteString(" ", f);
870 PyFile_WriteString(text, f);
871 if (*text == '\0' || text[strlen(text)-1] != '\n')
872 PyFile_WriteString("\n", f);
873 if (offset == -1)
874 return;
875 PyFile_WriteString(" ", f);
876 offset--;
877 while (offset > 0) {
878 PyFile_WriteString(" ", f);
879 offset--;
880 }
881 PyFile_WriteString("^\n", f);
882}
883
Guido van Rossum66e8e862001-03-23 17:54:43 +0000884static void
885handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000886{
Guido van Rossum66e8e862001-03-23 17:54:43 +0000887 PyObject *exception, *value, *tb;
888 PyErr_Fetch(&exception, &value, &tb);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000889 if (Py_FlushLine())
890 PyErr_Clear();
891 fflush(stdout);
892 if (value == NULL || value == Py_None)
893 Py_Exit(0);
894 if (PyInstance_Check(value)) {
895 /* The error code should be in the `code' attribute. */
896 PyObject *code = PyObject_GetAttrString(value, "code");
897 if (code) {
898 Py_DECREF(value);
899 value = code;
900 if (value == Py_None)
901 Py_Exit(0);
902 }
903 /* If we failed to dig out the 'code' attribute,
904 just let the else clause below print the error. */
905 }
906 if (PyInt_Check(value))
907 Py_Exit((int)PyInt_AsLong(value));
908 else {
909 PyObject_Print(value, stderr, Py_PRINT_RAW);
910 PySys_WriteStderr("\n");
911 Py_Exit(1);
912 }
913}
914
915void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000916PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000917{
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000918 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +0000919
920 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
921 handle_system_exit();
922 }
Guido van Rossum82598051997-03-05 00:20:32 +0000923 PyErr_Fetch(&exception, &v, &tb);
Barry Warsaw035574d1997-08-29 22:07:17 +0000924 PyErr_NormalizeException(&exception, &v, &tb);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000925 if (exception == NULL)
Guido van Rossum296b4751997-05-23 00:19:20 +0000926 return;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000927 if (set_sys_last_vars) {
928 PySys_SetObject("last_type", exception);
929 PySys_SetObject("last_value", v);
930 PySys_SetObject("last_traceback", tb);
931 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000932 hook = PySys_GetObject("excepthook");
933 if (hook) {
934 PyObject *args = Py_BuildValue("(OOO)",
935 exception, v ? v : Py_None, tb ? tb : Py_None);
936 PyObject *result = PyEval_CallObject(hook, args);
937 if (result == NULL) {
938 PyObject *exception2, *v2, *tb2;
Guido van Rossum66e8e862001-03-23 17:54:43 +0000939 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
940 handle_system_exit();
941 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000942 PyErr_Fetch(&exception2, &v2, &tb2);
943 PyErr_NormalizeException(&exception2, &v2, &tb2);
944 if (Py_FlushLine())
945 PyErr_Clear();
946 fflush(stdout);
947 PySys_WriteStderr("Error in sys.excepthook:\n");
948 PyErr_Display(exception2, v2, tb2);
949 PySys_WriteStderr("\nOriginal exception was:\n");
950 PyErr_Display(exception, v, tb);
Jeremy Hylton07028582001-12-07 15:35:35 +0000951 Py_XDECREF(exception2);
952 Py_XDECREF(v2);
953 Py_XDECREF(tb2);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000954 }
955 Py_XDECREF(result);
956 Py_XDECREF(args);
957 } else {
958 PySys_WriteStderr("sys.excepthook is missing\n");
959 PyErr_Display(exception, v, tb);
960 }
961 Py_XDECREF(exception);
962 Py_XDECREF(v);
963 Py_XDECREF(tb);
964}
965
966void PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
967{
968 int err = 0;
969 PyObject *v = value;
970 PyObject *f = PySys_GetObject("stderr");
Guido van Rossum3165fe61992-09-25 21:59:05 +0000971 if (f == NULL)
972 fprintf(stderr, "lost sys.stderr\n");
973 else {
Guido van Rossum0829c751998-02-28 04:31:39 +0000974 if (Py_FlushLine())
975 PyErr_Clear();
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000976 fflush(stdout);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000977 if (tb && tb != Py_None)
978 err = PyTraceBack_Print(tb, f);
Barry Warsaw36b8f941997-08-26 18:09:48 +0000979 if (err == 0 &&
Martin v. Löwiscfeb3b62002-03-03 21:30:27 +0000980 PyObject_HasAttrString(v, "print_file_and_line"))
Barry Warsaw36b8f941997-08-26 18:09:48 +0000981 {
Guido van Rossum82598051997-03-05 00:20:32 +0000982 PyObject *message;
Martin v. Löwis95292d62002-12-11 14:04:59 +0000983 const char *filename, *text;
Guido van Rossuma110aa61994-08-29 12:50:44 +0000984 int lineno, offset;
Barry Warsaw035574d1997-08-29 22:07:17 +0000985 if (!parse_syntax_error(v, &message, &filename,
986 &lineno, &offset, &text))
Guido van Rossum82598051997-03-05 00:20:32 +0000987 PyErr_Clear();
Guido van Rossuma110aa61994-08-29 12:50:44 +0000988 else {
989 char buf[10];
Guido van Rossum82598051997-03-05 00:20:32 +0000990 PyFile_WriteString(" File \"", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000991 if (filename == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +0000992 PyFile_WriteString("<string>", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000993 else
Guido van Rossum82598051997-03-05 00:20:32 +0000994 PyFile_WriteString(filename, f);
995 PyFile_WriteString("\", line ", f);
Jeremy Hylton518ab1c2001-11-28 20:42:20 +0000996 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
Guido van Rossum82598051997-03-05 00:20:32 +0000997 PyFile_WriteString(buf, f);
998 PyFile_WriteString("\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000999 if (text != NULL)
1000 print_error_text(f, offset, text);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001001 v = message;
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001002 /* Can't be bothered to check all those
1003 PyFile_WriteString() calls */
1004 if (PyErr_Occurred())
1005 err = -1;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001006 }
1007 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001008 if (err) {
1009 /* Don't do anything else */
1010 }
1011 else if (PyClass_Check(exception)) {
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001012 PyClassObject* exc = (PyClassObject*)exception;
1013 PyObject* className = exc->cl_name;
1014 PyObject* moduleName =
1015 PyDict_GetItemString(exc->cl_dict, "__module__");
1016
1017 if (moduleName == NULL)
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001018 err = PyFile_WriteString("<unknown>", f);
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001019 else {
1020 char* modstr = PyString_AsString(moduleName);
1021 if (modstr && strcmp(modstr, "exceptions"))
1022 {
1023 err = PyFile_WriteString(modstr, f);
1024 err += PyFile_WriteString(".", f);
1025 }
1026 }
1027 if (err == 0) {
1028 if (className == NULL)
1029 err = PyFile_WriteString("<unknown>", f);
1030 else
1031 err = PyFile_WriteObject(className, f,
1032 Py_PRINT_RAW);
1033 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001034 }
1035 else
1036 err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
1037 if (err == 0) {
1038 if (v != NULL && v != Py_None) {
Barry Warsaw035574d1997-08-29 22:07:17 +00001039 PyObject *s = PyObject_Str(v);
1040 /* only print colon if the str() of the
1041 object is not the empty string
1042 */
Guido van Rossumd6bf45b1997-09-05 19:11:53 +00001043 if (s == NULL)
1044 err = -1;
1045 else if (!PyString_Check(s) ||
1046 PyString_GET_SIZE(s) != 0)
Barry Warsaw035574d1997-08-29 22:07:17 +00001047 err = PyFile_WriteString(": ", f);
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001048 if (err == 0)
Guido van Rossumd6bf45b1997-09-05 19:11:53 +00001049 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1050 Py_XDECREF(s);
Guido van Rossum262e1241995-02-07 15:30:45 +00001051 }
Guido van Rossum262e1241995-02-07 15:30:45 +00001052 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001053 if (err == 0)
1054 err = PyFile_WriteString("\n", f);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001055 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001056 /* If an error happened here, don't show it.
1057 XXX This is wrong, but too many callers rely on this behavior. */
1058 if (err != 0)
1059 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001060}
1061
Guido van Rossum82598051997-03-05 00:20:32 +00001062PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001063PyRun_String(const char *str, int start, PyObject *globals, PyObject *locals)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001064{
Guido van Rossum82598051997-03-05 00:20:32 +00001065 return run_err_node(PyParser_SimpleParseString(str, start),
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001066 "<string>", globals, locals, NULL);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001067}
1068
Guido van Rossum82598051997-03-05 00:20:32 +00001069PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001070PyRun_File(FILE *fp, const char *filename, int start, PyObject *globals,
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001071 PyObject *locals)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001072{
Tim Peterse8682112000-08-27 20:18:17 +00001073 return PyRun_FileEx(fp, filename, start, globals, locals, 0);
Guido van Rossum0df002c2000-08-27 19:21:52 +00001074}
1075
1076PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001077PyRun_FileEx(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001078 PyObject *locals, int closeit)
Guido van Rossum0df002c2000-08-27 19:21:52 +00001079{
1080 node *n = PyParser_SimpleParseFile(fp, filename, start);
1081 if (closeit)
1082 fclose(fp);
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001083 return run_err_node(n, filename, globals, locals, NULL);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001084}
1085
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001086PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001087PyRun_StringFlags(const char *str, int start, PyObject *globals, PyObject *locals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001088 PyCompilerFlags *flags)
1089{
Guido van Rossuma1b3a472001-07-16 16:51:33 +00001090 return run_err_node(PyParser_SimpleParseStringFlags(
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001091 str, start, PARSER_FLAGS(flags)),
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001092 "<string>", globals, locals, flags);
1093}
1094
1095PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001096PyRun_FileFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001097 PyObject *locals, PyCompilerFlags *flags)
1098{
1099 return PyRun_FileExFlags(fp, filename, start, globals, locals, 0,
1100 flags);
1101}
1102
1103PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001104PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001105 PyObject *locals, int closeit, PyCompilerFlags *flags)
1106{
Tim Petersfe2127d2001-07-16 05:37:24 +00001107 node *n = PyParser_SimpleParseFileFlags(fp, filename, start,
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001108 PARSER_FLAGS(flags));
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001109 if (closeit)
1110 fclose(fp);
1111 return run_err_node(n, filename, globals, locals, flags);
1112}
1113
Guido van Rossum82598051997-03-05 00:20:32 +00001114static PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001115run_err_node(node *n, const char *filename, PyObject *globals, PyObject *locals,
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001116 PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001117{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001118 if (n == NULL)
1119 return NULL;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001120 return run_node(n, filename, globals, locals, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001121}
1122
Guido van Rossum82598051997-03-05 00:20:32 +00001123static PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001124run_node(node *n, const char *filename, PyObject *globals, PyObject *locals,
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001125 PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001126{
Guido van Rossum82598051997-03-05 00:20:32 +00001127 PyCodeObject *co;
1128 PyObject *v;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001129 co = PyNode_CompileFlags(n, filename, flags);
Guido van Rossum82598051997-03-05 00:20:32 +00001130 PyNode_Free(n);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001131 if (co == NULL)
1132 return NULL;
Guido van Rossum82598051997-03-05 00:20:32 +00001133 v = PyEval_EvalCode(co, globals, locals);
1134 Py_DECREF(co);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001135 return v;
1136}
1137
Guido van Rossum82598051997-03-05 00:20:32 +00001138static PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001139run_pyc_file(FILE *fp, const char *filename, PyObject *globals, PyObject *locals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001140 PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001141{
Guido van Rossum82598051997-03-05 00:20:32 +00001142 PyCodeObject *co;
1143 PyObject *v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001144 long magic;
Fred Drakee8de31c2000-08-31 05:38:39 +00001145 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001146
Guido van Rossum82598051997-03-05 00:20:32 +00001147 magic = PyMarshal_ReadLongFromFile(fp);
1148 if (magic != PyImport_GetMagicNumber()) {
1149 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001150 "Bad magic number in .pyc file");
1151 return NULL;
1152 }
Guido van Rossum82598051997-03-05 00:20:32 +00001153 (void) PyMarshal_ReadLongFromFile(fp);
Tim Petersd9b9ac82001-01-28 00:27:39 +00001154 v = PyMarshal_ReadLastObjectFromFile(fp);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001155 fclose(fp);
Guido van Rossum82598051997-03-05 00:20:32 +00001156 if (v == NULL || !PyCode_Check(v)) {
1157 Py_XDECREF(v);
1158 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001159 "Bad code object in .pyc file");
1160 return NULL;
1161 }
Guido van Rossum82598051997-03-05 00:20:32 +00001162 co = (PyCodeObject *)v;
1163 v = PyEval_EvalCode(co, globals, locals);
Jeremy Hyltonb857ba22001-08-10 21:41:33 +00001164 if (v && flags)
1165 flags->cf_flags |= (co->co_flags & PyCF_MASK);
Guido van Rossum82598051997-03-05 00:20:32 +00001166 Py_DECREF(co);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001167 return v;
1168}
1169
Guido van Rossum82598051997-03-05 00:20:32 +00001170PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001171Py_CompileString(const char *str, const char *filename, int start)
Guido van Rossum5b722181993-03-30 17:46:03 +00001172{
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001173 return Py_CompileStringFlags(str, filename, start, NULL);
1174}
1175
1176PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001177Py_CompileStringFlags(const char *str, const char *filename, int start,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001178 PyCompilerFlags *flags)
1179{
Guido van Rossum5b722181993-03-30 17:46:03 +00001180 node *n;
Guido van Rossum82598051997-03-05 00:20:32 +00001181 PyCodeObject *co;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001182
1183 n = PyParser_SimpleParseStringFlagsFilename(str, filename, start,
1184 PARSER_FLAGS(flags));
Guido van Rossuma110aa61994-08-29 12:50:44 +00001185 if (n == NULL)
Guido van Rossum5b722181993-03-30 17:46:03 +00001186 return NULL;
Jeremy Hylton673a4fd2001-03-26 19:53:38 +00001187 co = PyNode_CompileFlags(n, filename, flags);
Guido van Rossum82598051997-03-05 00:20:32 +00001188 PyNode_Free(n);
1189 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001190}
1191
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001192struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001193Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001194{
1195 node *n;
1196 struct symtable *st;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001197 n = PyParser_SimpleParseStringFlagsFilename(str, filename,
1198 start, 0);
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001199 if (n == NULL)
1200 return NULL;
1201 st = PyNode_CompileSymtable(n, filename);
1202 PyNode_Free(n);
1203 return st;
1204}
1205
Guido van Rossuma110aa61994-08-29 12:50:44 +00001206/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001207
Guido van Rossuma110aa61994-08-29 12:50:44 +00001208node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001209PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001210{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001211 node *n;
1212 perrdetail err;
Tim Petersfe2127d2001-07-16 05:37:24 +00001213 n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar, start,
1214 (char *)0, (char *)0, &err, flags);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001215 if (n == NULL)
1216 err_input(&err);
1217 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001218}
1219
Tim Petersfe2127d2001-07-16 05:37:24 +00001220node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001221PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
Tim Petersfe2127d2001-07-16 05:37:24 +00001222{
1223 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
1224}
1225
Guido van Rossuma110aa61994-08-29 12:50:44 +00001226/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001227
Guido van Rossuma110aa61994-08-29 12:50:44 +00001228node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001229PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001230{
1231 node *n;
1232 perrdetail err;
1233 n = PyParser_ParseStringFlags(str, &_PyParser_Grammar, start, &err,
1234 flags);
1235 if (n == NULL)
1236 err_input(&err);
1237 return n;
1238}
1239
1240node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001241PyParser_SimpleParseString(const char *str, int start)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001242{
Tim Petersfe2127d2001-07-16 05:37:24 +00001243 return PyParser_SimpleParseStringFlags(str, start, 0);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001244}
1245
Thomas Heller6b17abf2002-07-09 09:23:27 +00001246node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001247PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Thomas Heller6b17abf2002-07-09 09:23:27 +00001248 int start, int flags)
1249{
1250 node *n;
1251 perrdetail err;
1252
1253 n = PyParser_ParseStringFlagsFilename(str, filename,
1254 &_PyParser_Grammar,
1255 start, &err, flags);
1256 if (n == NULL)
1257 err_input(&err);
1258 return n;
1259}
1260
1261node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001262PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001263{
1264 return PyParser_SimpleParseStringFlagsFilename(str, filename,
1265 start, 0);
1266}
1267
Guido van Rossuma110aa61994-08-29 12:50:44 +00001268/* Set the error appropriate to the given input error code (see errcode.h) */
1269
1270static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001271err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001272{
Fred Drake85f36392000-07-11 17:53:00 +00001273 PyObject *v, *w, *errtype;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001274 PyObject* u = NULL;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001275 char *msg = NULL;
Fred Drake85f36392000-07-11 17:53:00 +00001276 errtype = PyExc_SyntaxError;
Guido van Rossum82598051997-03-05 00:20:32 +00001277 v = Py_BuildValue("(ziiz)", err->filename,
Guido van Rossuma110aa61994-08-29 12:50:44 +00001278 err->lineno, err->offset, err->text);
1279 if (err->text != NULL) {
Guido van Rossumb18618d2000-05-03 23:44:39 +00001280 PyMem_DEL(err->text);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001281 err->text = NULL;
1282 }
1283 switch (err->error) {
1284 case E_SYNTAX:
Fred Drake85f36392000-07-11 17:53:00 +00001285 errtype = PyExc_IndentationError;
1286 if (err->expected == INDENT)
1287 msg = "expected an indented block";
1288 else if (err->token == INDENT)
1289 msg = "unexpected indent";
1290 else if (err->token == DEDENT)
1291 msg = "unexpected unindent";
1292 else {
1293 errtype = PyExc_SyntaxError;
1294 msg = "invalid syntax";
1295 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001296 break;
1297 case E_TOKEN:
1298 msg = "invalid token";
Guido van Rossuma110aa61994-08-29 12:50:44 +00001299 break;
Skip Montanaro118ec702002-08-15 01:20:16 +00001300 case E_EOFS:
1301 msg = "EOF while scanning triple-quoted string";
1302 break;
1303 case E_EOLS:
1304 msg = "EOL while scanning single-quoted string";
1305 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001306 case E_INTR:
Guido van Rossum82598051997-03-05 00:20:32 +00001307 PyErr_SetNone(PyExc_KeyboardInterrupt);
Barry Warsawc80baa31999-01-27 16:39:40 +00001308 Py_XDECREF(v);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001309 return;
1310 case E_NOMEM:
Guido van Rossum82598051997-03-05 00:20:32 +00001311 PyErr_NoMemory();
Barry Warsawc80baa31999-01-27 16:39:40 +00001312 Py_XDECREF(v);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001313 return;
1314 case E_EOF:
1315 msg = "unexpected EOF while parsing";
1316 break;
Fred Drake85f36392000-07-11 17:53:00 +00001317 case E_TABSPACE:
1318 errtype = PyExc_TabError;
Guido van Rossum560e8ad1998-04-10 19:43:42 +00001319 msg = "inconsistent use of tabs and spaces in indentation";
1320 break;
Jeremy Hylton94988062000-06-20 19:10:44 +00001321 case E_OVERFLOW:
1322 msg = "expression too long";
1323 break;
Fred Drake85f36392000-07-11 17:53:00 +00001324 case E_DEDENT:
1325 errtype = PyExc_IndentationError;
1326 msg = "unindent does not match any outer indentation level";
1327 break;
1328 case E_TOODEEP:
1329 errtype = PyExc_IndentationError;
1330 msg = "too many levels of indentation";
1331 break;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001332 case E_DECODE: { /* XXX */
1333 PyThreadState* tstate = PyThreadState_Get();
1334 PyObject* value = tstate->curexc_value;
1335 if (value != NULL) {
1336 u = PyObject_Repr(value);
1337 if (u != NULL) {
1338 msg = PyString_AsString(u);
1339 break;
1340 }
1341 }
1342 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001343 default:
1344 fprintf(stderr, "error=%d\n", err->error);
1345 msg = "unknown parsing error";
1346 break;
1347 }
Guido van Rossum82598051997-03-05 00:20:32 +00001348 w = Py_BuildValue("(sO)", msg, v);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001349 Py_XDECREF(u);
Guido van Rossum41318302001-03-23 04:01:07 +00001350 Py_XDECREF(v);
Fred Drake85f36392000-07-11 17:53:00 +00001351 PyErr_SetObject(errtype, w);
Guido van Rossum82598051997-03-05 00:20:32 +00001352 Py_XDECREF(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001353}
1354
1355/* Print fatal error message and abort */
1356
1357void
Tim Peters7c321a82002-07-09 02:57:01 +00001358Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001359{
Guido van Rossum83dd6c31994-09-29 09:38:33 +00001360 fprintf(stderr, "Fatal Python error: %s\n", msg);
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001361#ifdef MS_WINDOWS
Guido van Rossum23c94461997-05-22 20:21:30 +00001362 OutputDebugString("Fatal Python error: ");
Guido van Rossuma44823b1995-03-14 15:01:17 +00001363 OutputDebugString(msg);
1364 OutputDebugString("\n");
Guido van Rossum0ba35361998-08-13 13:33:16 +00001365#ifdef _DEBUG
1366 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00001367#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001368#endif /* MS_WINDOWS */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001369 abort();
1370}
1371
1372/* Clean up and exit */
1373
Guido van Rossuma110aa61994-08-29 12:50:44 +00001374#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00001375#include "pythread.h"
Guido van Rossum82598051997-03-05 00:20:32 +00001376int _PyThread_Started = 0; /* Set by threadmodule.c and maybe others */
Guido van Rossumf9f2e821992-08-17 08:59:08 +00001377#endif
1378
Guido van Rossum2dcfc961998-10-01 16:01:57 +00001379#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001380static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00001381static int nexitfuncs = 0;
1382
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001383int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00001384{
1385 if (nexitfuncs >= NEXITFUNCS)
1386 return -1;
1387 exitfuncs[nexitfuncs++] = func;
1388 return 0;
1389}
1390
Guido van Rossumcc283f51997-08-05 02:22:03 +00001391static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001392call_sys_exitfunc(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001393{
Guido van Rossum82598051997-03-05 00:20:32 +00001394 PyObject *exitfunc = PySys_GetObject("exitfunc");
Guido van Rossum59bff391992-09-03 20:28:00 +00001395
1396 if (exitfunc) {
Fred Drake6a12d8d2001-03-23 17:34:02 +00001397 PyObject *res;
Guido van Rossum82598051997-03-05 00:20:32 +00001398 Py_INCREF(exitfunc);
1399 PySys_SetObject("exitfunc", (PyObject *)NULL);
1400 res = PyEval_CallObject(exitfunc, (PyObject *)NULL);
Guido van Rossum59bff391992-09-03 20:28:00 +00001401 if (res == NULL) {
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001402 if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
1403 PySys_WriteStderr("Error in sys.exitfunc:\n");
1404 }
Guido van Rossum82598051997-03-05 00:20:32 +00001405 PyErr_Print();
Guido van Rossum59bff391992-09-03 20:28:00 +00001406 }
Guido van Rossum82598051997-03-05 00:20:32 +00001407 Py_DECREF(exitfunc);
Guido van Rossum59bff391992-09-03 20:28:00 +00001408 }
1409
Guido van Rossum0829c751998-02-28 04:31:39 +00001410 if (Py_FlushLine())
1411 PyErr_Clear();
Guido van Rossumcc283f51997-08-05 02:22:03 +00001412}
Guido van Rossum1662dd51994-09-07 14:38:28 +00001413
Guido van Rossumcc283f51997-08-05 02:22:03 +00001414static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001415call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00001416{
Guido van Rossum1662dd51994-09-07 14:38:28 +00001417 while (nexitfuncs > 0)
1418 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00001419
1420 fflush(stdout);
1421 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001422}
1423
1424void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001425Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001426{
Guido van Rossumcc283f51997-08-05 02:22:03 +00001427 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001428
Jack Jansen66a89771995-10-27 13:22:14 +00001429#ifdef macintosh
1430 PyMac_Exit(sts);
1431#else
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001432 exit(sts);
Jack Jansen66a89771995-10-27 13:22:14 +00001433#endif
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001434}
1435
Guido van Rossumf1dc5661993-07-05 10:31:29 +00001436static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001437initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001438{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001439#ifdef HAVE_SIGNAL_H
1440#ifdef SIGPIPE
1441 signal(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001442#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00001443#ifdef SIGXFZ
1444 signal(SIGXFZ, SIG_IGN);
1445#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00001446#ifdef SIGXFSZ
1447 signal(SIGXFSZ, SIG_IGN);
1448#endif
Guido van Rossuma110aa61994-08-29 12:50:44 +00001449#endif /* HAVE_SIGNAL_H */
Guido van Rossum82598051997-03-05 00:20:32 +00001450 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001451}
1452
Guido van Rossuma110aa61994-08-29 12:50:44 +00001453#ifdef MPW
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001454
1455/* Check for file descriptor connected to interactive device.
1456 Pretend that stdin is always interactive, other files never. */
1457
1458int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001459isatty(int fd)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001460{
1461 return fd == fileno(stdin);
1462}
1463
1464#endif
Guido van Rossum7433b121997-02-14 19:45:36 +00001465
1466/*
1467 * The file descriptor fd is considered ``interactive'' if either
1468 * a) isatty(fd) is TRUE, or
1469 * b) the -i flag was given, and the filename associated with
1470 * the descriptor is NULL or "<stdin>" or "???".
1471 */
1472int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001473Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00001474{
1475 if (isatty((int)fileno(fp)))
1476 return 1;
1477 if (!Py_InteractiveFlag)
1478 return 0;
1479 return (filename == NULL) ||
1480 (strcmp(filename, "<stdin>") == 0) ||
1481 (strcmp(filename, "???") == 0);
1482}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001483
1484
1485#if defined(USE_STACKCHECK)
1486#if defined(WIN32) && defined(_MSC_VER)
1487
1488/* Stack checking for Microsoft C */
1489
1490#include <malloc.h>
1491#include <excpt.h>
1492
Fred Drakee8de31c2000-08-31 05:38:39 +00001493/*
1494 * Return non-zero when we run out of memory on the stack; zero otherwise.
1495 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001496int
Fred Drake399739f2000-08-31 05:52:44 +00001497PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001498{
1499 __try {
Tim Peters92e4dd82002-10-05 01:47:34 +00001500 /* alloca throws a stack overflow exception if there's
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001501 not enough space left on the stack */
Tim Peters92e4dd82002-10-05 01:47:34 +00001502 alloca(PYOS_STACK_MARGIN * sizeof(void*));
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001503 return 0;
1504 } __except (EXCEPTION_EXECUTE_HANDLER) {
1505 /* just ignore all errors */
1506 }
1507 return 1;
1508}
1509
1510#endif /* WIN32 && _MSC_VER */
1511
1512/* Alternate implementations can be added here... */
1513
1514#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00001515
1516
1517/* Wrappers around sigaction() or signal(). */
1518
1519PyOS_sighandler_t
1520PyOS_getsig(int sig)
1521{
1522#ifdef HAVE_SIGACTION
1523 struct sigaction context;
Barry Warsawafeb2a42001-11-13 23:08:26 +00001524 /* Initialize context.sa_handler to SIG_ERR which makes about as
1525 * much sense as anything else. It should get overwritten if
1526 * sigaction actually succeeds and otherwise we avoid an
1527 * uninitialized memory read.
1528 */
1529 context.sa_handler = SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00001530 sigaction(sig, NULL, &context);
1531 return context.sa_handler;
1532#else
1533 PyOS_sighandler_t handler;
1534 handler = signal(sig, SIG_IGN);
1535 signal(sig, handler);
1536 return handler;
1537#endif
1538}
1539
1540PyOS_sighandler_t
1541PyOS_setsig(int sig, PyOS_sighandler_t handler)
1542{
1543#ifdef HAVE_SIGACTION
1544 struct sigaction context;
1545 PyOS_sighandler_t oldhandler;
Barry Warsawafeb2a42001-11-13 23:08:26 +00001546 /* Initialize context.sa_handler to SIG_ERR which makes about as
1547 * much sense as anything else. It should get overwritten if
1548 * sigaction actually succeeds and otherwise we avoid an
1549 * uninitialized memory read.
1550 */
1551 context.sa_handler = SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00001552 sigaction(sig, NULL, &context);
1553 oldhandler = context.sa_handler;
1554 context.sa_handler = handler;
1555 sigaction(sig, &context, NULL);
1556 return oldhandler;
1557#else
1558 return signal(sig, handler);
1559#endif
1560}