blob: 32b302455ac1a75ad515b75f2a040dd7396f3276 [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);
Guido van Rossumc94044c2000-03-10 23:03:54 +000052
Guido van Rossum82598051997-03-05 00:20:32 +000053int Py_DebugFlag; /* Needed by parser.c */
54int Py_VerboseFlag; /* Needed by import.c */
Guido van Rossum7433b121997-02-14 19:45:36 +000055int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Guido van Rossumdcc0c131997-08-29 22:32:42 +000056int Py_NoSiteFlag; /* Suppress 'import site' */
Barry Warsaw3ce09642000-05-02 19:18:59 +000057int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +000058int Py_FrozenFlag; /* Needed by getpath.c */
Guido van Rossumb16d1972000-05-01 17:55:15 +000059int Py_UnicodeFlag = 0; /* Needed by compile.c */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +000060int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Tim Peters3caca232001-12-06 06:23:26 +000061/* _XXX Py_QnewFlag should go away in 2.3. It's true iff -Qnew is passed,
62 on the command line, and is used in 2.2 by ceval.c to make all "/" divisions
63 true divisions (which they will be in 2.3). */
64int _Py_QnewFlag = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +000065
Mark Hammonda43fd0c2003-02-19 00:33:33 +000066/* Reference to 'warnings' module, to avoid importing it
67 on the fly when the import lock may be held. See 683658
68*/
69PyObject *PyModule_WarningsModule = NULL;
70
Guido van Rossum25ce5661997-08-02 03:10:38 +000071static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +000072
Thomas Wouters7e474022000-07-16 12:04:32 +000073/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +000074
75int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000076Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +000077{
78 return initialized;
79}
80
Guido van Rossum25ce5661997-08-02 03:10:38 +000081/* Global initializations. Can be undone by Py_Finalize(). Don't
82 call this twice without an intervening Py_Finalize() call. When
83 initializations fail, a fatal error is issued and the function does
84 not return. On return, the first thread and interpreter state have
85 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +000086
Guido van Rossum25ce5661997-08-02 03:10:38 +000087 Locking: you must hold the interpreter lock while calling this.
88 (If the lock has not yet been initialized, that's equivalent to
89 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000090
Guido van Rossum25ce5661997-08-02 03:10:38 +000091*/
Guido van Rossuma027efa1997-05-05 20:56:21 +000092
Guido van Rossum9abaf4d2001-10-12 22:17:56 +000093static int
94add_flag(int flag, const char *envs)
95{
96 int env = atoi(envs);
97 if (flag < env)
98 flag = env;
99 if (flag < 1)
100 flag = 1;
101 return flag;
102}
103
Guido van Rossuma027efa1997-05-05 20:56:21 +0000104void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000105Py_Initialize(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000106{
Guido van Rossuma027efa1997-05-05 20:56:21 +0000107 PyInterpreterState *interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000108 PyThreadState *tstate;
109 PyObject *bimod, *sysmod;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000110 char *p;
Guido van Rossum70d893a2001-08-16 08:21:42 +0000111 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000112
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000113 if (initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +0000114 return;
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000115 initialized = 1;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000116
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000117 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000118 Py_DebugFlag = add_flag(Py_DebugFlag, p);
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000119 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000120 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000121 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000122 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000123
Guido van Rossuma027efa1997-05-05 20:56:21 +0000124 interp = PyInterpreterState_New();
125 if (interp == NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000126 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000127
Guido van Rossuma027efa1997-05-05 20:56:21 +0000128 tstate = PyThreadState_New(interp);
129 if (tstate == NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000130 Py_FatalError("Py_Initialize: can't make first thread");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000131 (void) PyThreadState_Swap(tstate);
132
Guido van Rossum70d893a2001-08-16 08:21:42 +0000133 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000134
Neal Norwitzb2501f42002-12-31 03:42:13 +0000135 if (!_PyFrame_Init())
Neal Norwitzc91ed402002-12-30 22:29:22 +0000136 Py_FatalError("Py_Initialize: can't init frames");
137
Neal Norwitzb2501f42002-12-31 03:42:13 +0000138 if (!_PyInt_Init())
Neal Norwitzc91ed402002-12-30 22:29:22 +0000139 Py_FatalError("Py_Initialize: can't init ints");
140
Guido van Rossum25ce5661997-08-02 03:10:38 +0000141 interp->modules = PyDict_New();
142 if (interp->modules == NULL)
143 Py_FatalError("Py_Initialize: can't make modules dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000144
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000145#ifdef Py_USING_UNICODE
Guido van Rossumc94044c2000-03-10 23:03:54 +0000146 /* Init Unicode implementation; relies on the codec registry */
147 _PyUnicode_Init();
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000148#endif
Guido van Rossumc94044c2000-03-10 23:03:54 +0000149
Barry Warsawf242aa02000-05-25 23:09:49 +0000150 bimod = _PyBuiltin_Init();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000151 if (bimod == NULL)
152 Py_FatalError("Py_Initialize: can't initialize __builtin__");
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000153 interp->builtins = PyModule_GetDict(bimod);
154 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000155
156 sysmod = _PySys_Init();
157 if (sysmod == NULL)
158 Py_FatalError("Py_Initialize: can't initialize sys");
159 interp->sysdict = PyModule_GetDict(sysmod);
160 Py_INCREF(interp->sysdict);
161 _PyImport_FixupExtension("sys", "sys");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000162 PySys_SetPath(Py_GetPath());
Guido van Rossum25ce5661997-08-02 03:10:38 +0000163 PyDict_SetItemString(interp->sysdict, "modules",
164 interp->modules);
165
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000166 _PyImport_Init();
167
Barry Warsawf242aa02000-05-25 23:09:49 +0000168 /* initialize builtin exceptions */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000169 _PyExc_Init();
Barry Warsaw5821bc52001-08-13 23:04:56 +0000170 _PyImport_FixupExtension("exceptions", "exceptions");
Barry Warsawf242aa02000-05-25 23:09:49 +0000171
Barry Warsaw035574d1997-08-29 22:07:17 +0000172 /* phase 2 of builtins */
Barry Warsaw963b8711997-09-18 16:42:02 +0000173 _PyImport_FixupExtension("__builtin__", "__builtin__");
Barry Warsaw035574d1997-08-29 22:07:17 +0000174
Just van Rossum52e14d62002-12-30 22:08:05 +0000175 _PyImportHooks_Init();
176
Guido van Rossum25ce5661997-08-02 03:10:38 +0000177 initsigs(); /* Signal handling stuff, including initintr() */
178
179 initmain(); /* Module __main__ */
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000180 if (!Py_NoSiteFlag)
181 initsite(); /* Module site */
Just van Rossum5bfba3a2003-02-25 20:25:12 +0000182
183 PyModule_WarningsModule = PyImport_ImportModule("warnings");
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000184
185#if defined(Py_USING_UNICODE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
186 /* On Unix, set the file system encoding according to the
187 user's preference, if the CODESET names a well-known
188 Python codec, and Py_FileSystemDefaultEncoding isn't
189 initialized by other means. */
190 if (!Py_FileSystemDefaultEncoding) {
191 char *saved_locale = setlocale(LC_CTYPE, NULL);
192 char *codeset;
Fred Drake6a9a3292003-03-05 17:31:21 +0000193 PyObject *enc = NULL;
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000194 setlocale(LC_CTYPE, "");
195 codeset = nl_langinfo(CODESET);
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000196 if (*codeset) {
197 enc = PyCodec_Encoder(codeset);
198 if (enc) {
199 Py_FileSystemDefaultEncoding = strdup(codeset);
200 Py_DECREF(enc);
201 } else
202 PyErr_Clear();
203 }
204 setlocale(LC_CTYPE, saved_locale);
205 }
206#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000207}
208
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000209#ifdef COUNT_ALLOCS
Tim Petersdbd9ba62000-07-09 03:09:57 +0000210extern void dump_counts(void);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000211#endif
212
Guido van Rossum25ce5661997-08-02 03:10:38 +0000213/* Undo the effect of Py_Initialize().
214
215 Beware: if multiple interpreter and/or thread states exist, these
216 are not wiped out; only the current thread and interpreter state
217 are deleted. But since everything else is deleted, those other
218 interpreter and thread states should no longer be used.
219
220 (XXX We should do better, e.g. wipe out all interpreters and
221 threads.)
222
223 Locking: as above.
224
225*/
226
227void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000228Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000229{
230 PyInterpreterState *interp;
231 PyThreadState *tstate;
232
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000233 if (!initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +0000234 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000235
Tim Peters384fd102001-01-21 03:40:37 +0000236 /* The interpreter is still entirely intact at this point, and the
237 * exit funcs may be relying on that. In particular, if some thread
238 * or exit func is still waiting to do an import, the import machinery
239 * expects Py_IsInitialized() to return true. So don't say the
240 * interpreter is uninitialized until after the exit funcs have run.
241 * Note that Threading.py uses an exit func to do a join on all the
242 * threads created thru it, so this also protects pending imports in
243 * the threads created via Threading.
244 */
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000245 call_sys_exitfunc();
Tim Peters384fd102001-01-21 03:40:37 +0000246 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000247
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000248 /* Get current thread state and interpreter pointer */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000249 tstate = PyThreadState_Get();
250 interp = tstate->interp;
251
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000252 /* Disable signal handling */
253 PyOS_FiniInterrupts();
254
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000255 /* drop module references we saved */
256 Py_XDECREF(PyModule_WarningsModule);
257 PyModule_WarningsModule = NULL;
258
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000259 /* Destroy all modules */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000260 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000261
Guido van Rossum1707aad1997-12-08 23:43:45 +0000262 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
263 _PyImport_Fini();
264
265 /* Debugging stuff */
266#ifdef COUNT_ALLOCS
267 dump_counts();
268#endif
269
270#ifdef Py_REF_DEBUG
271 fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
272#endif
273
274#ifdef Py_TRACE_REFS
Guido van Rossum92e2d5c2001-08-09 16:37:16 +0000275 if (Py_GETENV("PYTHONDUMPREFS")) {
Guido van Rossum1707aad1997-12-08 23:43:45 +0000276 _Py_PrintReferences(stderr);
277 }
278#endif /* Py_TRACE_REFS */
279
Barry Warsaw035574d1997-08-29 22:07:17 +0000280 /* Now we decref the exception classes. After this point nothing
281 can raise an exception. That's okay, because each Fini() method
282 below has been checked to make sure no exceptions are ever
283 raised.
284 */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000285 _PyExc_Fini();
Barry Warsawf242aa02000-05-25 23:09:49 +0000286
287 /* Delete current thread */
288 PyInterpreterState_Clear(interp);
289 PyThreadState_Swap(NULL);
290 PyInterpreterState_Delete(interp);
291
Guido van Rossumcc283f51997-08-05 02:22:03 +0000292 PyMethod_Fini();
293 PyFrame_Fini();
294 PyCFunction_Fini();
295 PyTuple_Fini();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000296 PyString_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000297 PyInt_Fini();
298 PyFloat_Fini();
299
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000300#ifdef Py_USING_UNICODE
301 /* Cleanup Unicode implementation */
302 _PyUnicode_Fini();
303#endif
304
Guido van Rossumcc283f51997-08-05 02:22:03 +0000305 /* XXX Still allocated:
306 - various static ad-hoc pointers to interned strings
307 - int and float free list blocks
308 - whatever various modules and libraries allocate
309 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000310
311 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000312
Tim Peters0e871182002-04-13 08:29:14 +0000313#ifdef PYMALLOC_DEBUG
314 if (Py_GETENV("PYTHONMALLOCSTATS"))
315 _PyObject_DebugMallocStats();
316#endif
317
Guido van Rossumcc283f51997-08-05 02:22:03 +0000318 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000319}
320
321/* Create and initialize a new interpreter and thread, and return the
322 new thread. This requires that Py_Initialize() has been called
323 first.
324
325 Unsuccessful initialization yields a NULL pointer. Note that *no*
326 exception information is available even in this case -- the
327 exception information is held in the thread, and there is no
328 thread.
329
330 Locking: as above.
331
332*/
333
334PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000335Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000336{
337 PyInterpreterState *interp;
338 PyThreadState *tstate, *save_tstate;
339 PyObject *bimod, *sysmod;
340
341 if (!initialized)
342 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
343
344 interp = PyInterpreterState_New();
345 if (interp == NULL)
346 return NULL;
347
348 tstate = PyThreadState_New(interp);
349 if (tstate == NULL) {
350 PyInterpreterState_Delete(interp);
351 return NULL;
352 }
353
354 save_tstate = PyThreadState_Swap(tstate);
355
356 /* XXX The following is lax in error checking */
357
358 interp->modules = PyDict_New();
359
360 bimod = _PyImport_FindExtension("__builtin__", "__builtin__");
361 if (bimod != NULL) {
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000362 interp->builtins = PyModule_GetDict(bimod);
363 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000364 }
365 sysmod = _PyImport_FindExtension("sys", "sys");
366 if (bimod != NULL && sysmod != NULL) {
367 interp->sysdict = PyModule_GetDict(sysmod);
368 Py_INCREF(interp->sysdict);
369 PySys_SetPath(Py_GetPath());
370 PyDict_SetItemString(interp->sysdict, "modules",
371 interp->modules);
Martin v. Löwisd7ceb222003-01-22 09:00:38 +0000372 _PyImportHooks_Init();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000373 initmain();
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000374 if (!Py_NoSiteFlag)
375 initsite();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000376 }
377
378 if (!PyErr_Occurred())
379 return tstate;
380
381 /* Oops, it didn't work. Undo it all. */
382
383 PyErr_Print();
384 PyThreadState_Clear(tstate);
385 PyThreadState_Swap(save_tstate);
386 PyThreadState_Delete(tstate);
387 PyInterpreterState_Delete(interp);
388
389 return NULL;
390}
391
392/* Delete an interpreter and its last thread. This requires that the
393 given thread state is current, that the thread has no remaining
394 frames, and that it is its interpreter's only remaining thread.
395 It is a fatal error to violate these constraints.
396
397 (Py_Finalize() doesn't have these constraints -- it zaps
398 everything, regardless.)
399
400 Locking: as above.
401
402*/
403
404void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000405Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000406{
407 PyInterpreterState *interp = tstate->interp;
408
409 if (tstate != PyThreadState_Get())
410 Py_FatalError("Py_EndInterpreter: thread is not current");
411 if (tstate->frame != NULL)
412 Py_FatalError("Py_EndInterpreter: thread still has a frame");
413 if (tstate != interp->tstate_head || tstate->next != NULL)
414 Py_FatalError("Py_EndInterpreter: not the last thread");
415
416 PyImport_Cleanup();
417 PyInterpreterState_Clear(interp);
418 PyThreadState_Swap(NULL);
419 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000420}
421
422static char *progname = "python";
423
424void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000425Py_SetProgramName(char *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000426{
427 if (pn && *pn)
428 progname = pn;
429}
430
431char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000432Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000433{
434 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000435}
436
Guido van Rossuma61691e1998-02-06 22:27:24 +0000437static char *default_home = NULL;
438
439void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000440Py_SetPythonHome(char *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000441{
442 default_home = home;
443}
444
445char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000446Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000447{
448 char *home = default_home;
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000449 if (home == NULL && !Py_IgnoreEnvironmentFlag)
450 home = Py_GETENV("PYTHONHOME");
Guido van Rossuma61691e1998-02-06 22:27:24 +0000451 return home;
452}
453
Guido van Rossum6135a871995-01-09 17:53:26 +0000454/* Create __main__ module */
455
456static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000457initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000458{
Guido van Rossum82598051997-03-05 00:20:32 +0000459 PyObject *m, *d;
460 m = PyImport_AddModule("__main__");
Guido van Rossum6135a871995-01-09 17:53:26 +0000461 if (m == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +0000462 Py_FatalError("can't create __main__ module");
463 d = PyModule_GetDict(m);
464 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
Guido van Rossum858cb731997-11-19 16:15:37 +0000465 PyObject *bimod = PyImport_ImportModule("__builtin__");
466 if (bimod == NULL ||
467 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
Guido van Rossum82598051997-03-05 00:20:32 +0000468 Py_FatalError("can't add __builtins__ to __main__");
Barry Warsaw3d05b1a1999-01-29 21:30:22 +0000469 Py_DECREF(bimod);
Guido van Rossum6135a871995-01-09 17:53:26 +0000470 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000471}
472
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000473/* Import the site module (not into __main__ though) */
474
475static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000476initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000477{
478 PyObject *m, *f;
479 m = PyImport_ImportModule("site");
480 if (m == NULL) {
481 f = PySys_GetObject("stderr");
482 if (Py_VerboseFlag) {
483 PyFile_WriteString(
484 "'import site' failed; traceback:\n", f);
485 PyErr_Print();
486 }
487 else {
488 PyFile_WriteString(
489 "'import site' failed; use -v for traceback\n", f);
490 PyErr_Clear();
491 }
492 }
493 else {
494 Py_DECREF(m);
495 }
496}
497
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000498/* Parse input from a file and execute it */
499
500int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000501PyRun_AnyFile(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000502{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000503 return PyRun_AnyFileExFlags(fp, filename, 0, NULL);
504}
505
506int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000507PyRun_AnyFileFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000508{
509 return PyRun_AnyFileExFlags(fp, filename, 0, flags);
Guido van Rossum0df002c2000-08-27 19:21:52 +0000510}
511
512int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000513PyRun_AnyFileEx(FILE *fp, const char *filename, int closeit)
Guido van Rossum0df002c2000-08-27 19:21:52 +0000514{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000515 return PyRun_AnyFileExFlags(fp, filename, closeit, NULL);
516}
517
518int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000519PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000520 PyCompilerFlags *flags)
521{
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000522 if (filename == NULL)
523 filename = "???";
Guido van Rossum0df002c2000-08-27 19:21:52 +0000524 if (Py_FdIsInteractive(fp, filename)) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000525 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
Guido van Rossum0df002c2000-08-27 19:21:52 +0000526 if (closeit)
527 fclose(fp);
528 return err;
529 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000530 else
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000531 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000532}
533
534int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000535PyRun_InteractiveLoop(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000536{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000537 return PyRun_InteractiveLoopFlags(fp, filename, NULL);
538}
539
540int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000541PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000542{
Guido van Rossum82598051997-03-05 00:20:32 +0000543 PyObject *v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000544 int ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000545 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000546
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000547 if (flags == NULL) {
548 flags = &local_flags;
Tim Peters5ba58662001-07-16 02:29:45 +0000549 local_flags.cf_flags = 0;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000550 }
Guido van Rossum82598051997-03-05 00:20:32 +0000551 v = PySys_GetObject("ps1");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000552 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000553 PySys_SetObject("ps1", v = PyString_FromString(">>> "));
554 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000555 }
Guido van Rossum82598051997-03-05 00:20:32 +0000556 v = PySys_GetObject("ps2");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000557 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000558 PySys_SetObject("ps2", v = PyString_FromString("... "));
559 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000560 }
561 for (;;) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000562 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
Guido van Rossumaae0d321996-05-22 16:35:33 +0000563#ifdef Py_REF_DEBUG
Guido van Rossum6f9e4331995-03-29 16:57:48 +0000564 fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000565#endif
566 if (ret == E_EOF)
567 return 0;
568 /*
569 if (ret == E_NOMEM)
570 return -1;
571 */
572 }
573}
574
575int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000576PyRun_InteractiveOne(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000577{
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000578 return PyRun_InteractiveOneFlags(fp, filename, NULL);
579}
580
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000581/* compute parser flags based on compiler flags */
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000582#define PARSER_FLAGS(flags) \
Guido van Rossum4b499dd32003-02-13 22:07:59 +0000583 (((flags) && (flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
584 PyPARSE_DONT_IMPLY_DEDENT : 0)
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000585
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000586int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000587PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000588{
Guido van Rossum82598051997-03-05 00:20:32 +0000589 PyObject *m, *d, *v, *w;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000590 node *n;
Guido van Rossuma110aa61994-08-29 12:50:44 +0000591 perrdetail err;
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000592 char *ps1 = "", *ps2 = "";
Tim Petersfe2127d2001-07-16 05:37:24 +0000593
Guido van Rossum82598051997-03-05 00:20:32 +0000594 v = PySys_GetObject("ps1");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000595 if (v != NULL) {
596 v = PyObject_Str(v);
597 if (v == NULL)
598 PyErr_Clear();
599 else if (PyString_Check(v))
600 ps1 = PyString_AsString(v);
601 }
Guido van Rossum82598051997-03-05 00:20:32 +0000602 w = PySys_GetObject("ps2");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000603 if (w != NULL) {
604 w = PyObject_Str(w);
605 if (w == NULL)
606 PyErr_Clear();
607 else if (PyString_Check(w))
608 ps2 = PyString_AsString(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000609 }
Tim Petersfe2127d2001-07-16 05:37:24 +0000610 n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar,
611 Py_single_input, ps1, ps2, &err,
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000612 PARSER_FLAGS(flags));
Guido van Rossum82598051997-03-05 00:20:32 +0000613 Py_XDECREF(v);
614 Py_XDECREF(w);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000615 if (n == NULL) {
616 if (err.error == E_EOF) {
617 if (err.text)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000618 PyMem_DEL(err.text);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000619 return E_EOF;
620 }
621 err_input(&err);
Guido van Rossum82598051997-03-05 00:20:32 +0000622 PyErr_Print();
Guido van Rossuma110aa61994-08-29 12:50:44 +0000623 return err.error;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000624 }
Guido van Rossum82598051997-03-05 00:20:32 +0000625 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000626 if (m == NULL)
627 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000628 d = PyModule_GetDict(m);
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000629 v = run_node(n, filename, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000630 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000631 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000632 return -1;
633 }
Guido van Rossum82598051997-03-05 00:20:32 +0000634 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000635 if (Py_FlushLine())
636 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000637 return 0;
638}
639
640int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000641PyRun_SimpleFile(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000642{
Guido van Rossum0df002c2000-08-27 19:21:52 +0000643 return PyRun_SimpleFileEx(fp, filename, 0);
644}
645
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000646/* Check whether a file maybe a pyc file: Look at the extension,
647 the file type, and, if we may close it, at the first few bytes. */
648
649static int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000650maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000651{
652 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
653 return 1;
654
655#ifdef macintosh
656 /* On a mac, we also assume a pyc file for types 'PYC ' and 'APPL' */
Jack Jansen72f3b7a2002-12-13 15:23:10 +0000657 if (PyMac_getfiletype((char *)filename) == 'PYC '
658 || PyMac_getfiletype((char *)filename) == 'APPL')
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000659 return 1;
660#endif /* macintosh */
661
662 /* Only look into the file if we are allowed to close it, since
663 it then should also be seekable. */
664 if (closeit) {
665 /* Read only two bytes of the magic. If the file was opened in
666 text mode, the bytes 3 and 4 of the magic (\r\n) might not
667 be read as they are on disk. */
668 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
669 unsigned char buf[2];
Tim Peters3e876562001-02-11 04:35:39 +0000670 /* Mess: In case of -x, the stream is NOT at its start now,
671 and ungetc() was used to push back the first newline,
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000672 which makes the current stream position formally undefined,
673 and a x-platform nightmare.
674 Unfortunately, we have no direct way to know whether -x
675 was specified. So we use a terrible hack: if the current
676 stream position is not 0, we assume -x was specified, and
677 give up. Bug 132850 on SourceForge spells out the
678 hopelessness of trying anything else (fseek and ftell
679 don't work predictably x-platform for text-mode files).
Tim Peters3e876562001-02-11 04:35:39 +0000680 */
Tim Peters3e876562001-02-11 04:35:39 +0000681 int ispyc = 0;
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000682 if (ftell(fp) == 0) {
683 if (fread(buf, 1, 2, fp) == 2 &&
684 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
685 ispyc = 1;
686 rewind(fp);
687 }
Tim Peters3e876562001-02-11 04:35:39 +0000688 return ispyc;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000689 }
690 return 0;
691}
692
Guido van Rossum0df002c2000-08-27 19:21:52 +0000693int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000694PyRun_SimpleFileEx(FILE *fp, const char *filename, int closeit)
Guido van Rossum0df002c2000-08-27 19:21:52 +0000695{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000696 return PyRun_SimpleFileExFlags(fp, filename, closeit, NULL);
697}
698
699int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000700PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000701 PyCompilerFlags *flags)
702{
Guido van Rossum82598051997-03-05 00:20:32 +0000703 PyObject *m, *d, *v;
Martin v. Löwis95292d62002-12-11 14:04:59 +0000704 const char *ext;
Guido van Rossumfdef2711994-09-14 13:31:04 +0000705
Guido van Rossum82598051997-03-05 00:20:32 +0000706 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000707 if (m == NULL)
708 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000709 d = PyModule_GetDict(m);
Fred Drake8ed02042002-10-17 21:24:58 +0000710 if (PyDict_GetItemString(d, "__file__") == NULL) {
711 PyObject *f = PyString_FromString(filename);
712 if (f == NULL)
713 return -1;
714 if (PyDict_SetItemString(d, "__file__", f) < 0) {
715 Py_DECREF(f);
716 return -1;
717 }
718 Py_DECREF(f);
719 }
Guido van Rossumfdef2711994-09-14 13:31:04 +0000720 ext = filename + strlen(filename) - 4;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000721 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Guido van Rossumfdef2711994-09-14 13:31:04 +0000722 /* Try to run a pyc file. First, re-open in binary */
Guido van Rossum0df002c2000-08-27 19:21:52 +0000723 if (closeit)
724 fclose(fp);
Fred Drake8ed02042002-10-17 21:24:58 +0000725 if ((fp = fopen(filename, "rb")) == NULL) {
Guido van Rossumfdef2711994-09-14 13:31:04 +0000726 fprintf(stderr, "python: Can't reopen .pyc file\n");
727 return -1;
728 }
Guido van Rossum2a7f58d1997-04-02 05:28:38 +0000729 /* Turn on optimization if a .pyo file is given */
730 if (strcmp(ext, ".pyo") == 0)
731 Py_OptimizeFlag = 1;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000732 v = run_pyc_file(fp, filename, d, d, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000733 } else {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000734 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
735 closeit, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000736 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000737 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000738 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000739 return -1;
740 }
Guido van Rossum82598051997-03-05 00:20:32 +0000741 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000742 if (Py_FlushLine())
743 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000744 return 0;
745}
746
747int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000748PyRun_SimpleString(const char *command)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000749{
Guido van Rossum393661d2001-08-31 17:40:15 +0000750 return PyRun_SimpleStringFlags(command, NULL);
751}
752
753int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000754PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +0000755{
Guido van Rossum82598051997-03-05 00:20:32 +0000756 PyObject *m, *d, *v;
757 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000758 if (m == NULL)
759 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000760 d = PyModule_GetDict(m);
Guido van Rossum393661d2001-08-31 17:40:15 +0000761 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000762 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000763 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000764 return -1;
765 }
Guido van Rossum82598051997-03-05 00:20:32 +0000766 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000767 if (Py_FlushLine())
768 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000769 return 0;
770}
771
Barry Warsaw035574d1997-08-29 22:07:17 +0000772static int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000773parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
774 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +0000775{
776 long hold;
777 PyObject *v;
778
779 /* old style errors */
780 if (PyTuple_Check(err))
Neal Norwitz78293352002-04-01 01:41:20 +0000781 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
782 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +0000783
784 /* new style errors. `err' is an instance */
785
786 if (! (v = PyObject_GetAttrString(err, "msg")))
787 goto finally;
788 *message = v;
789
790 if (!(v = PyObject_GetAttrString(err, "filename")))
791 goto finally;
792 if (v == Py_None)
793 *filename = NULL;
794 else if (! (*filename = PyString_AsString(v)))
795 goto finally;
796
797 Py_DECREF(v);
798 if (!(v = PyObject_GetAttrString(err, "lineno")))
799 goto finally;
800 hold = PyInt_AsLong(v);
801 Py_DECREF(v);
802 v = NULL;
803 if (hold < 0 && PyErr_Occurred())
804 goto finally;
805 *lineno = (int)hold;
806
807 if (!(v = PyObject_GetAttrString(err, "offset")))
808 goto finally;
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000809 if (v == Py_None) {
810 *offset = -1;
811 Py_DECREF(v);
812 v = NULL;
813 } else {
814 hold = PyInt_AsLong(v);
815 Py_DECREF(v);
816 v = NULL;
817 if (hold < 0 && PyErr_Occurred())
818 goto finally;
819 *offset = (int)hold;
820 }
Barry Warsaw035574d1997-08-29 22:07:17 +0000821
822 if (!(v = PyObject_GetAttrString(err, "text")))
823 goto finally;
824 if (v == Py_None)
825 *text = NULL;
826 else if (! (*text = PyString_AsString(v)))
827 goto finally;
828 Py_DECREF(v);
829 return 1;
830
831finally:
832 Py_XDECREF(v);
833 return 0;
834}
835
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000836void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000837PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000838{
Guido van Rossuma61691e1998-02-06 22:27:24 +0000839 PyErr_PrintEx(1);
840}
841
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000842static void
Martin v. Löwis95292d62002-12-11 14:04:59 +0000843print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000844{
845 char *nl;
846 if (offset >= 0) {
847 if (offset > 0 && offset == (int)strlen(text))
848 offset--;
849 for (;;) {
850 nl = strchr(text, '\n');
851 if (nl == NULL || nl-text >= offset)
852 break;
853 offset -= (nl+1-text);
854 text = nl+1;
855 }
856 while (*text == ' ' || *text == '\t') {
857 text++;
858 offset--;
859 }
860 }
861 PyFile_WriteString(" ", f);
862 PyFile_WriteString(text, f);
863 if (*text == '\0' || text[strlen(text)-1] != '\n')
864 PyFile_WriteString("\n", f);
865 if (offset == -1)
866 return;
867 PyFile_WriteString(" ", f);
868 offset--;
869 while (offset > 0) {
870 PyFile_WriteString(" ", f);
871 offset--;
872 }
873 PyFile_WriteString("^\n", f);
874}
875
Guido van Rossum66e8e862001-03-23 17:54:43 +0000876static void
877handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000878{
Guido van Rossum66e8e862001-03-23 17:54:43 +0000879 PyObject *exception, *value, *tb;
880 PyErr_Fetch(&exception, &value, &tb);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000881 if (Py_FlushLine())
882 PyErr_Clear();
883 fflush(stdout);
884 if (value == NULL || value == Py_None)
885 Py_Exit(0);
886 if (PyInstance_Check(value)) {
887 /* The error code should be in the `code' attribute. */
888 PyObject *code = PyObject_GetAttrString(value, "code");
889 if (code) {
890 Py_DECREF(value);
891 value = code;
892 if (value == Py_None)
893 Py_Exit(0);
894 }
895 /* If we failed to dig out the 'code' attribute,
896 just let the else clause below print the error. */
897 }
898 if (PyInt_Check(value))
899 Py_Exit((int)PyInt_AsLong(value));
900 else {
901 PyObject_Print(value, stderr, Py_PRINT_RAW);
902 PySys_WriteStderr("\n");
903 Py_Exit(1);
904 }
905}
906
907void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000908PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000909{
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000910 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +0000911
912 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
913 handle_system_exit();
914 }
Guido van Rossum82598051997-03-05 00:20:32 +0000915 PyErr_Fetch(&exception, &v, &tb);
Barry Warsaw035574d1997-08-29 22:07:17 +0000916 PyErr_NormalizeException(&exception, &v, &tb);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000917 if (exception == NULL)
Guido van Rossum296b4751997-05-23 00:19:20 +0000918 return;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000919 if (set_sys_last_vars) {
920 PySys_SetObject("last_type", exception);
921 PySys_SetObject("last_value", v);
922 PySys_SetObject("last_traceback", tb);
923 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000924 hook = PySys_GetObject("excepthook");
925 if (hook) {
926 PyObject *args = Py_BuildValue("(OOO)",
927 exception, v ? v : Py_None, tb ? tb : Py_None);
928 PyObject *result = PyEval_CallObject(hook, args);
929 if (result == NULL) {
930 PyObject *exception2, *v2, *tb2;
Guido van Rossum66e8e862001-03-23 17:54:43 +0000931 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
932 handle_system_exit();
933 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000934 PyErr_Fetch(&exception2, &v2, &tb2);
935 PyErr_NormalizeException(&exception2, &v2, &tb2);
936 if (Py_FlushLine())
937 PyErr_Clear();
938 fflush(stdout);
939 PySys_WriteStderr("Error in sys.excepthook:\n");
940 PyErr_Display(exception2, v2, tb2);
941 PySys_WriteStderr("\nOriginal exception was:\n");
942 PyErr_Display(exception, v, tb);
Jeremy Hylton07028582001-12-07 15:35:35 +0000943 Py_XDECREF(exception2);
944 Py_XDECREF(v2);
945 Py_XDECREF(tb2);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000946 }
947 Py_XDECREF(result);
948 Py_XDECREF(args);
949 } else {
950 PySys_WriteStderr("sys.excepthook is missing\n");
951 PyErr_Display(exception, v, tb);
952 }
953 Py_XDECREF(exception);
954 Py_XDECREF(v);
955 Py_XDECREF(tb);
956}
957
958void PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
959{
960 int err = 0;
961 PyObject *v = value;
962 PyObject *f = PySys_GetObject("stderr");
Guido van Rossum3165fe61992-09-25 21:59:05 +0000963 if (f == NULL)
964 fprintf(stderr, "lost sys.stderr\n");
965 else {
Guido van Rossum0829c751998-02-28 04:31:39 +0000966 if (Py_FlushLine())
967 PyErr_Clear();
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000968 fflush(stdout);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000969 if (tb && tb != Py_None)
970 err = PyTraceBack_Print(tb, f);
Barry Warsaw36b8f941997-08-26 18:09:48 +0000971 if (err == 0 &&
Martin v. Löwiscfeb3b62002-03-03 21:30:27 +0000972 PyObject_HasAttrString(v, "print_file_and_line"))
Barry Warsaw36b8f941997-08-26 18:09:48 +0000973 {
Guido van Rossum82598051997-03-05 00:20:32 +0000974 PyObject *message;
Martin v. Löwis95292d62002-12-11 14:04:59 +0000975 const char *filename, *text;
Guido van Rossuma110aa61994-08-29 12:50:44 +0000976 int lineno, offset;
Barry Warsaw035574d1997-08-29 22:07:17 +0000977 if (!parse_syntax_error(v, &message, &filename,
978 &lineno, &offset, &text))
Guido van Rossum82598051997-03-05 00:20:32 +0000979 PyErr_Clear();
Guido van Rossuma110aa61994-08-29 12:50:44 +0000980 else {
981 char buf[10];
Guido van Rossum82598051997-03-05 00:20:32 +0000982 PyFile_WriteString(" File \"", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000983 if (filename == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +0000984 PyFile_WriteString("<string>", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000985 else
Guido van Rossum82598051997-03-05 00:20:32 +0000986 PyFile_WriteString(filename, f);
987 PyFile_WriteString("\", line ", f);
Jeremy Hylton518ab1c2001-11-28 20:42:20 +0000988 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
Guido van Rossum82598051997-03-05 00:20:32 +0000989 PyFile_WriteString(buf, f);
990 PyFile_WriteString("\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000991 if (text != NULL)
992 print_error_text(f, offset, text);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000993 v = message;
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000994 /* Can't be bothered to check all those
995 PyFile_WriteString() calls */
996 if (PyErr_Occurred())
997 err = -1;
Guido van Rossuma110aa61994-08-29 12:50:44 +0000998 }
999 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001000 if (err) {
1001 /* Don't do anything else */
1002 }
1003 else if (PyClass_Check(exception)) {
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001004 PyClassObject* exc = (PyClassObject*)exception;
1005 PyObject* className = exc->cl_name;
1006 PyObject* moduleName =
1007 PyDict_GetItemString(exc->cl_dict, "__module__");
1008
1009 if (moduleName == NULL)
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001010 err = PyFile_WriteString("<unknown>", f);
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001011 else {
1012 char* modstr = PyString_AsString(moduleName);
1013 if (modstr && strcmp(modstr, "exceptions"))
1014 {
1015 err = PyFile_WriteString(modstr, f);
1016 err += PyFile_WriteString(".", f);
1017 }
1018 }
1019 if (err == 0) {
1020 if (className == NULL)
1021 err = PyFile_WriteString("<unknown>", f);
1022 else
1023 err = PyFile_WriteObject(className, f,
1024 Py_PRINT_RAW);
1025 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001026 }
1027 else
1028 err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
1029 if (err == 0) {
1030 if (v != NULL && v != Py_None) {
Barry Warsaw035574d1997-08-29 22:07:17 +00001031 PyObject *s = PyObject_Str(v);
1032 /* only print colon if the str() of the
1033 object is not the empty string
1034 */
Guido van Rossumd6bf45b1997-09-05 19:11:53 +00001035 if (s == NULL)
1036 err = -1;
1037 else if (!PyString_Check(s) ||
1038 PyString_GET_SIZE(s) != 0)
Barry Warsaw035574d1997-08-29 22:07:17 +00001039 err = PyFile_WriteString(": ", f);
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001040 if (err == 0)
Guido van Rossumd6bf45b1997-09-05 19:11:53 +00001041 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1042 Py_XDECREF(s);
Guido van Rossum262e1241995-02-07 15:30:45 +00001043 }
Guido van Rossum262e1241995-02-07 15:30:45 +00001044 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001045 if (err == 0)
1046 err = PyFile_WriteString("\n", f);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001047 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001048 /* If an error happened here, don't show it.
1049 XXX This is wrong, but too many callers rely on this behavior. */
1050 if (err != 0)
1051 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001052}
1053
Guido van Rossum82598051997-03-05 00:20:32 +00001054PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001055PyRun_String(const char *str, int start, PyObject *globals, PyObject *locals)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001056{
Guido van Rossum82598051997-03-05 00:20:32 +00001057 return run_err_node(PyParser_SimpleParseString(str, start),
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001058 "<string>", globals, locals, NULL);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001059}
1060
Guido van Rossum82598051997-03-05 00:20:32 +00001061PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001062PyRun_File(FILE *fp, const char *filename, int start, PyObject *globals,
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001063 PyObject *locals)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001064{
Tim Peterse8682112000-08-27 20:18:17 +00001065 return PyRun_FileEx(fp, filename, start, globals, locals, 0);
Guido van Rossum0df002c2000-08-27 19:21:52 +00001066}
1067
1068PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001069PyRun_FileEx(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001070 PyObject *locals, int closeit)
Guido van Rossum0df002c2000-08-27 19:21:52 +00001071{
1072 node *n = PyParser_SimpleParseFile(fp, filename, start);
1073 if (closeit)
1074 fclose(fp);
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001075 return run_err_node(n, filename, globals, locals, NULL);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001076}
1077
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001078PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001079PyRun_StringFlags(const char *str, int start, PyObject *globals, PyObject *locals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001080 PyCompilerFlags *flags)
1081{
Guido van Rossuma1b3a472001-07-16 16:51:33 +00001082 return run_err_node(PyParser_SimpleParseStringFlags(
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001083 str, start, PARSER_FLAGS(flags)),
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001084 "<string>", globals, locals, flags);
1085}
1086
1087PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001088PyRun_FileFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001089 PyObject *locals, PyCompilerFlags *flags)
1090{
1091 return PyRun_FileExFlags(fp, filename, start, globals, locals, 0,
1092 flags);
1093}
1094
1095PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001096PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001097 PyObject *locals, int closeit, PyCompilerFlags *flags)
1098{
Tim Petersfe2127d2001-07-16 05:37:24 +00001099 node *n = PyParser_SimpleParseFileFlags(fp, filename, start,
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001100 PARSER_FLAGS(flags));
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001101 if (closeit)
1102 fclose(fp);
1103 return run_err_node(n, filename, globals, locals, flags);
1104}
1105
Guido van Rossum82598051997-03-05 00:20:32 +00001106static PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001107run_err_node(node *n, const char *filename, PyObject *globals, PyObject *locals,
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001108 PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001109{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001110 if (n == NULL)
1111 return NULL;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001112 return run_node(n, filename, globals, locals, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001113}
1114
Guido van Rossum82598051997-03-05 00:20:32 +00001115static PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001116run_node(node *n, const char *filename, PyObject *globals, PyObject *locals,
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001117 PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001118{
Guido van Rossum82598051997-03-05 00:20:32 +00001119 PyCodeObject *co;
1120 PyObject *v;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001121 co = PyNode_CompileFlags(n, filename, flags);
Guido van Rossum82598051997-03-05 00:20:32 +00001122 PyNode_Free(n);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001123 if (co == NULL)
1124 return NULL;
Guido van Rossum82598051997-03-05 00:20:32 +00001125 v = PyEval_EvalCode(co, globals, locals);
1126 Py_DECREF(co);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001127 return v;
1128}
1129
Guido van Rossum82598051997-03-05 00:20:32 +00001130static PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001131run_pyc_file(FILE *fp, const char *filename, PyObject *globals, PyObject *locals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001132 PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001133{
Guido van Rossum82598051997-03-05 00:20:32 +00001134 PyCodeObject *co;
1135 PyObject *v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001136 long magic;
Fred Drakee8de31c2000-08-31 05:38:39 +00001137 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001138
Guido van Rossum82598051997-03-05 00:20:32 +00001139 magic = PyMarshal_ReadLongFromFile(fp);
1140 if (magic != PyImport_GetMagicNumber()) {
1141 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001142 "Bad magic number in .pyc file");
1143 return NULL;
1144 }
Guido van Rossum82598051997-03-05 00:20:32 +00001145 (void) PyMarshal_ReadLongFromFile(fp);
Tim Petersd9b9ac82001-01-28 00:27:39 +00001146 v = PyMarshal_ReadLastObjectFromFile(fp);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001147 fclose(fp);
Guido van Rossum82598051997-03-05 00:20:32 +00001148 if (v == NULL || !PyCode_Check(v)) {
1149 Py_XDECREF(v);
1150 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001151 "Bad code object in .pyc file");
1152 return NULL;
1153 }
Guido van Rossum82598051997-03-05 00:20:32 +00001154 co = (PyCodeObject *)v;
1155 v = PyEval_EvalCode(co, globals, locals);
Jeremy Hyltonb857ba22001-08-10 21:41:33 +00001156 if (v && flags)
1157 flags->cf_flags |= (co->co_flags & PyCF_MASK);
Guido van Rossum82598051997-03-05 00:20:32 +00001158 Py_DECREF(co);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001159 return v;
1160}
1161
Guido van Rossum82598051997-03-05 00:20:32 +00001162PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001163Py_CompileString(const char *str, const char *filename, int start)
Guido van Rossum5b722181993-03-30 17:46:03 +00001164{
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001165 return Py_CompileStringFlags(str, filename, start, NULL);
1166}
1167
1168PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001169Py_CompileStringFlags(const char *str, const char *filename, int start,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001170 PyCompilerFlags *flags)
1171{
Guido van Rossum5b722181993-03-30 17:46:03 +00001172 node *n;
Guido van Rossum82598051997-03-05 00:20:32 +00001173 PyCodeObject *co;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001174
1175 n = PyParser_SimpleParseStringFlagsFilename(str, filename, start,
1176 PARSER_FLAGS(flags));
Guido van Rossuma110aa61994-08-29 12:50:44 +00001177 if (n == NULL)
Guido van Rossum5b722181993-03-30 17:46:03 +00001178 return NULL;
Jeremy Hylton673a4fd2001-03-26 19:53:38 +00001179 co = PyNode_CompileFlags(n, filename, flags);
Guido van Rossum82598051997-03-05 00:20:32 +00001180 PyNode_Free(n);
1181 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001182}
1183
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001184struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001185Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001186{
1187 node *n;
1188 struct symtable *st;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001189 n = PyParser_SimpleParseStringFlagsFilename(str, filename,
1190 start, 0);
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001191 if (n == NULL)
1192 return NULL;
1193 st = PyNode_CompileSymtable(n, filename);
1194 PyNode_Free(n);
1195 return st;
1196}
1197
Guido van Rossuma110aa61994-08-29 12:50:44 +00001198/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001199
Guido van Rossuma110aa61994-08-29 12:50:44 +00001200node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001201PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001202{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001203 node *n;
1204 perrdetail err;
Tim Petersfe2127d2001-07-16 05:37:24 +00001205 n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar, start,
1206 (char *)0, (char *)0, &err, flags);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001207 if (n == NULL)
1208 err_input(&err);
1209 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001210}
1211
Tim Petersfe2127d2001-07-16 05:37:24 +00001212node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001213PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
Tim Petersfe2127d2001-07-16 05:37:24 +00001214{
1215 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
1216}
1217
Guido van Rossuma110aa61994-08-29 12:50:44 +00001218/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001219
Guido van Rossuma110aa61994-08-29 12:50:44 +00001220node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001221PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001222{
1223 node *n;
1224 perrdetail err;
1225 n = PyParser_ParseStringFlags(str, &_PyParser_Grammar, start, &err,
1226 flags);
1227 if (n == NULL)
1228 err_input(&err);
1229 return n;
1230}
1231
1232node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001233PyParser_SimpleParseString(const char *str, int start)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001234{
Tim Petersfe2127d2001-07-16 05:37:24 +00001235 return PyParser_SimpleParseStringFlags(str, start, 0);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001236}
1237
Thomas Heller6b17abf2002-07-09 09:23:27 +00001238node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001239PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Thomas Heller6b17abf2002-07-09 09:23:27 +00001240 int start, int flags)
1241{
1242 node *n;
1243 perrdetail err;
1244
1245 n = PyParser_ParseStringFlagsFilename(str, filename,
1246 &_PyParser_Grammar,
1247 start, &err, flags);
1248 if (n == NULL)
1249 err_input(&err);
1250 return n;
1251}
1252
1253node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001254PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001255{
1256 return PyParser_SimpleParseStringFlagsFilename(str, filename,
1257 start, 0);
1258}
1259
Guido van Rossuma110aa61994-08-29 12:50:44 +00001260/* Set the error appropriate to the given input error code (see errcode.h) */
1261
1262static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001263err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001264{
Fred Drake85f36392000-07-11 17:53:00 +00001265 PyObject *v, *w, *errtype;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001266 PyObject* u = NULL;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001267 char *msg = NULL;
Fred Drake85f36392000-07-11 17:53:00 +00001268 errtype = PyExc_SyntaxError;
Guido van Rossum82598051997-03-05 00:20:32 +00001269 v = Py_BuildValue("(ziiz)", err->filename,
Guido van Rossuma110aa61994-08-29 12:50:44 +00001270 err->lineno, err->offset, err->text);
1271 if (err->text != NULL) {
Guido van Rossumb18618d2000-05-03 23:44:39 +00001272 PyMem_DEL(err->text);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001273 err->text = NULL;
1274 }
1275 switch (err->error) {
1276 case E_SYNTAX:
Fred Drake85f36392000-07-11 17:53:00 +00001277 errtype = PyExc_IndentationError;
1278 if (err->expected == INDENT)
1279 msg = "expected an indented block";
1280 else if (err->token == INDENT)
1281 msg = "unexpected indent";
1282 else if (err->token == DEDENT)
1283 msg = "unexpected unindent";
1284 else {
1285 errtype = PyExc_SyntaxError;
1286 msg = "invalid syntax";
1287 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001288 break;
1289 case E_TOKEN:
1290 msg = "invalid token";
Guido van Rossuma110aa61994-08-29 12:50:44 +00001291 break;
Skip Montanaro118ec702002-08-15 01:20:16 +00001292 case E_EOFS:
1293 msg = "EOF while scanning triple-quoted string";
1294 break;
1295 case E_EOLS:
1296 msg = "EOL while scanning single-quoted string";
1297 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001298 case E_INTR:
Guido van Rossum82598051997-03-05 00:20:32 +00001299 PyErr_SetNone(PyExc_KeyboardInterrupt);
Barry Warsawc80baa31999-01-27 16:39:40 +00001300 Py_XDECREF(v);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001301 return;
1302 case E_NOMEM:
Guido van Rossum82598051997-03-05 00:20:32 +00001303 PyErr_NoMemory();
Barry Warsawc80baa31999-01-27 16:39:40 +00001304 Py_XDECREF(v);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001305 return;
1306 case E_EOF:
1307 msg = "unexpected EOF while parsing";
1308 break;
Fred Drake85f36392000-07-11 17:53:00 +00001309 case E_TABSPACE:
1310 errtype = PyExc_TabError;
Guido van Rossum560e8ad1998-04-10 19:43:42 +00001311 msg = "inconsistent use of tabs and spaces in indentation";
1312 break;
Jeremy Hylton94988062000-06-20 19:10:44 +00001313 case E_OVERFLOW:
1314 msg = "expression too long";
1315 break;
Fred Drake85f36392000-07-11 17:53:00 +00001316 case E_DEDENT:
1317 errtype = PyExc_IndentationError;
1318 msg = "unindent does not match any outer indentation level";
1319 break;
1320 case E_TOODEEP:
1321 errtype = PyExc_IndentationError;
1322 msg = "too many levels of indentation";
1323 break;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001324 case E_DECODE: { /* XXX */
1325 PyThreadState* tstate = PyThreadState_Get();
1326 PyObject* value = tstate->curexc_value;
1327 if (value != NULL) {
1328 u = PyObject_Repr(value);
1329 if (u != NULL) {
1330 msg = PyString_AsString(u);
1331 break;
1332 }
1333 }
1334 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001335 default:
1336 fprintf(stderr, "error=%d\n", err->error);
1337 msg = "unknown parsing error";
1338 break;
1339 }
Guido van Rossum82598051997-03-05 00:20:32 +00001340 w = Py_BuildValue("(sO)", msg, v);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001341 Py_XDECREF(u);
Guido van Rossum41318302001-03-23 04:01:07 +00001342 Py_XDECREF(v);
Fred Drake85f36392000-07-11 17:53:00 +00001343 PyErr_SetObject(errtype, w);
Guido van Rossum82598051997-03-05 00:20:32 +00001344 Py_XDECREF(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001345}
1346
1347/* Print fatal error message and abort */
1348
1349void
Tim Peters7c321a82002-07-09 02:57:01 +00001350Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001351{
Guido van Rossum83dd6c31994-09-29 09:38:33 +00001352 fprintf(stderr, "Fatal Python error: %s\n", msg);
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001353#ifdef MS_WINDOWS
Guido van Rossum23c94461997-05-22 20:21:30 +00001354 OutputDebugString("Fatal Python error: ");
Guido van Rossuma44823b1995-03-14 15:01:17 +00001355 OutputDebugString(msg);
1356 OutputDebugString("\n");
Guido van Rossum0ba35361998-08-13 13:33:16 +00001357#ifdef _DEBUG
1358 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00001359#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001360#endif /* MS_WINDOWS */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001361 abort();
1362}
1363
1364/* Clean up and exit */
1365
Guido van Rossuma110aa61994-08-29 12:50:44 +00001366#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00001367#include "pythread.h"
Guido van Rossum82598051997-03-05 00:20:32 +00001368int _PyThread_Started = 0; /* Set by threadmodule.c and maybe others */
Guido van Rossumf9f2e821992-08-17 08:59:08 +00001369#endif
1370
Guido van Rossum2dcfc961998-10-01 16:01:57 +00001371#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001372static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00001373static int nexitfuncs = 0;
1374
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001375int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00001376{
1377 if (nexitfuncs >= NEXITFUNCS)
1378 return -1;
1379 exitfuncs[nexitfuncs++] = func;
1380 return 0;
1381}
1382
Guido van Rossumcc283f51997-08-05 02:22:03 +00001383static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001384call_sys_exitfunc(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001385{
Guido van Rossum82598051997-03-05 00:20:32 +00001386 PyObject *exitfunc = PySys_GetObject("exitfunc");
Guido van Rossum59bff391992-09-03 20:28:00 +00001387
1388 if (exitfunc) {
Fred Drake6a12d8d2001-03-23 17:34:02 +00001389 PyObject *res;
Guido van Rossum82598051997-03-05 00:20:32 +00001390 Py_INCREF(exitfunc);
1391 PySys_SetObject("exitfunc", (PyObject *)NULL);
1392 res = PyEval_CallObject(exitfunc, (PyObject *)NULL);
Guido van Rossum59bff391992-09-03 20:28:00 +00001393 if (res == NULL) {
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001394 if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
1395 PySys_WriteStderr("Error in sys.exitfunc:\n");
1396 }
Guido van Rossum82598051997-03-05 00:20:32 +00001397 PyErr_Print();
Guido van Rossum59bff391992-09-03 20:28:00 +00001398 }
Guido van Rossum82598051997-03-05 00:20:32 +00001399 Py_DECREF(exitfunc);
Guido van Rossum59bff391992-09-03 20:28:00 +00001400 }
1401
Guido van Rossum0829c751998-02-28 04:31:39 +00001402 if (Py_FlushLine())
1403 PyErr_Clear();
Guido van Rossumcc283f51997-08-05 02:22:03 +00001404}
Guido van Rossum1662dd51994-09-07 14:38:28 +00001405
Guido van Rossumcc283f51997-08-05 02:22:03 +00001406static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001407call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00001408{
Guido van Rossum1662dd51994-09-07 14:38:28 +00001409 while (nexitfuncs > 0)
1410 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00001411
1412 fflush(stdout);
1413 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001414}
1415
1416void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001417Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001418{
Guido van Rossumcc283f51997-08-05 02:22:03 +00001419 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001420
Jack Jansen66a89771995-10-27 13:22:14 +00001421#ifdef macintosh
1422 PyMac_Exit(sts);
1423#else
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001424 exit(sts);
Jack Jansen66a89771995-10-27 13:22:14 +00001425#endif
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001426}
1427
Guido van Rossumf1dc5661993-07-05 10:31:29 +00001428static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001429initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001430{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001431#ifdef HAVE_SIGNAL_H
1432#ifdef SIGPIPE
1433 signal(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001434#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00001435#ifdef SIGXFZ
1436 signal(SIGXFZ, SIG_IGN);
1437#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00001438#ifdef SIGXFSZ
1439 signal(SIGXFSZ, SIG_IGN);
1440#endif
Guido van Rossuma110aa61994-08-29 12:50:44 +00001441#endif /* HAVE_SIGNAL_H */
Guido van Rossum82598051997-03-05 00:20:32 +00001442 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001443}
1444
Guido van Rossuma110aa61994-08-29 12:50:44 +00001445#ifdef MPW
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001446
1447/* Check for file descriptor connected to interactive device.
1448 Pretend that stdin is always interactive, other files never. */
1449
1450int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001451isatty(int fd)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001452{
1453 return fd == fileno(stdin);
1454}
1455
1456#endif
Guido van Rossum7433b121997-02-14 19:45:36 +00001457
1458/*
1459 * The file descriptor fd is considered ``interactive'' if either
1460 * a) isatty(fd) is TRUE, or
1461 * b) the -i flag was given, and the filename associated with
1462 * the descriptor is NULL or "<stdin>" or "???".
1463 */
1464int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001465Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00001466{
1467 if (isatty((int)fileno(fp)))
1468 return 1;
1469 if (!Py_InteractiveFlag)
1470 return 0;
1471 return (filename == NULL) ||
1472 (strcmp(filename, "<stdin>") == 0) ||
1473 (strcmp(filename, "???") == 0);
1474}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001475
1476
1477#if defined(USE_STACKCHECK)
1478#if defined(WIN32) && defined(_MSC_VER)
1479
1480/* Stack checking for Microsoft C */
1481
1482#include <malloc.h>
1483#include <excpt.h>
1484
Fred Drakee8de31c2000-08-31 05:38:39 +00001485/*
1486 * Return non-zero when we run out of memory on the stack; zero otherwise.
1487 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001488int
Fred Drake399739f2000-08-31 05:52:44 +00001489PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001490{
1491 __try {
Tim Peters92e4dd82002-10-05 01:47:34 +00001492 /* alloca throws a stack overflow exception if there's
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001493 not enough space left on the stack */
Tim Peters92e4dd82002-10-05 01:47:34 +00001494 alloca(PYOS_STACK_MARGIN * sizeof(void*));
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001495 return 0;
1496 } __except (EXCEPTION_EXECUTE_HANDLER) {
1497 /* just ignore all errors */
1498 }
1499 return 1;
1500}
1501
1502#endif /* WIN32 && _MSC_VER */
1503
1504/* Alternate implementations can be added here... */
1505
1506#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00001507
1508
1509/* Wrappers around sigaction() or signal(). */
1510
1511PyOS_sighandler_t
1512PyOS_getsig(int sig)
1513{
1514#ifdef HAVE_SIGACTION
1515 struct sigaction context;
Barry Warsawafeb2a42001-11-13 23:08:26 +00001516 /* Initialize context.sa_handler to SIG_ERR which makes about as
1517 * much sense as anything else. It should get overwritten if
1518 * sigaction actually succeeds and otherwise we avoid an
1519 * uninitialized memory read.
1520 */
1521 context.sa_handler = SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00001522 sigaction(sig, NULL, &context);
1523 return context.sa_handler;
1524#else
1525 PyOS_sighandler_t handler;
1526 handler = signal(sig, SIG_IGN);
1527 signal(sig, handler);
1528 return handler;
1529#endif
1530}
1531
1532PyOS_sighandler_t
1533PyOS_setsig(int sig, PyOS_sighandler_t handler)
1534{
1535#ifdef HAVE_SIGACTION
1536 struct sigaction context;
1537 PyOS_sighandler_t oldhandler;
Barry Warsawafeb2a42001-11-13 23:08:26 +00001538 /* Initialize context.sa_handler to SIG_ERR which makes about as
1539 * much sense as anything else. It should get overwritten if
1540 * sigaction actually succeeds and otherwise we avoid an
1541 * uninitialized memory read.
1542 */
1543 context.sa_handler = SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00001544 sigaction(sig, NULL, &context);
1545 oldhandler = context.sa_handler;
1546 context.sa_handler = handler;
1547 sigaction(sig, &context, NULL);
1548 return oldhandler;
1549#else
1550 return signal(sig, handler);
1551#endif
1552}