blob: 2de1bded5610a31cdbde87e6fcb3a3e8cf2b9280 [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;
193 setlocale(LC_CTYPE, "");
194 codeset = nl_langinfo(CODESET);
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000195 if (*codeset) {
Neal Norwitz5c16c7b2003-04-10 21:53:14 +0000196 PyObject *enc = PyCodec_Encoder(codeset);
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000197 if (enc) {
198 Py_FileSystemDefaultEncoding = strdup(codeset);
199 Py_DECREF(enc);
200 } else
201 PyErr_Clear();
202 }
203 setlocale(LC_CTYPE, saved_locale);
204 }
205#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000206}
207
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000208#ifdef COUNT_ALLOCS
Tim Petersdbd9ba62000-07-09 03:09:57 +0000209extern void dump_counts(void);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000210#endif
211
Guido van Rossum25ce5661997-08-02 03:10:38 +0000212/* Undo the effect of Py_Initialize().
213
214 Beware: if multiple interpreter and/or thread states exist, these
215 are not wiped out; only the current thread and interpreter state
216 are deleted. But since everything else is deleted, those other
217 interpreter and thread states should no longer be used.
218
219 (XXX We should do better, e.g. wipe out all interpreters and
220 threads.)
221
222 Locking: as above.
223
224*/
225
226void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000227Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000228{
229 PyInterpreterState *interp;
230 PyThreadState *tstate;
231
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000232 if (!initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +0000233 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000234
Tim Peters384fd102001-01-21 03:40:37 +0000235 /* The interpreter is still entirely intact at this point, and the
236 * exit funcs may be relying on that. In particular, if some thread
237 * or exit func is still waiting to do an import, the import machinery
238 * expects Py_IsInitialized() to return true. So don't say the
239 * interpreter is uninitialized until after the exit funcs have run.
240 * Note that Threading.py uses an exit func to do a join on all the
241 * threads created thru it, so this also protects pending imports in
242 * the threads created via Threading.
243 */
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000244 call_sys_exitfunc();
Tim Peters384fd102001-01-21 03:40:37 +0000245 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000246
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000247 /* Get current thread state and interpreter pointer */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000248 tstate = PyThreadState_Get();
249 interp = tstate->interp;
250
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000251 /* Disable signal handling */
252 PyOS_FiniInterrupts();
253
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000254 /* drop module references we saved */
255 Py_XDECREF(PyModule_WarningsModule);
256 PyModule_WarningsModule = NULL;
257
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000258 /* Destroy all modules */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000259 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000260
Guido van Rossum1707aad1997-12-08 23:43:45 +0000261 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
262 _PyImport_Fini();
263
264 /* Debugging stuff */
265#ifdef COUNT_ALLOCS
266 dump_counts();
267#endif
268
269#ifdef Py_REF_DEBUG
270 fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
271#endif
272
273#ifdef Py_TRACE_REFS
Guido van Rossum92e2d5c2001-08-09 16:37:16 +0000274 if (Py_GETENV("PYTHONDUMPREFS")) {
Guido van Rossum1707aad1997-12-08 23:43:45 +0000275 _Py_PrintReferences(stderr);
276 }
277#endif /* Py_TRACE_REFS */
278
Barry Warsaw035574d1997-08-29 22:07:17 +0000279 /* Now we decref the exception classes. After this point nothing
280 can raise an exception. That's okay, because each Fini() method
281 below has been checked to make sure no exceptions are ever
282 raised.
283 */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000284 _PyExc_Fini();
Barry Warsawf242aa02000-05-25 23:09:49 +0000285
286 /* Delete current thread */
287 PyInterpreterState_Clear(interp);
288 PyThreadState_Swap(NULL);
289 PyInterpreterState_Delete(interp);
290
Guido van Rossumcc283f51997-08-05 02:22:03 +0000291 PyMethod_Fini();
292 PyFrame_Fini();
293 PyCFunction_Fini();
294 PyTuple_Fini();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000295 PyString_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000296 PyInt_Fini();
297 PyFloat_Fini();
298
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000299#ifdef Py_USING_UNICODE
300 /* Cleanup Unicode implementation */
301 _PyUnicode_Fini();
302#endif
303
Guido van Rossumcc283f51997-08-05 02:22:03 +0000304 /* XXX Still allocated:
305 - various static ad-hoc pointers to interned strings
306 - int and float free list blocks
307 - whatever various modules and libraries allocate
308 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000309
310 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000311
Tim Peters0e871182002-04-13 08:29:14 +0000312#ifdef PYMALLOC_DEBUG
313 if (Py_GETENV("PYTHONMALLOCSTATS"))
314 _PyObject_DebugMallocStats();
315#endif
316
Guido van Rossumcc283f51997-08-05 02:22:03 +0000317 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000318}
319
320/* Create and initialize a new interpreter and thread, and return the
321 new thread. This requires that Py_Initialize() has been called
322 first.
323
324 Unsuccessful initialization yields a NULL pointer. Note that *no*
325 exception information is available even in this case -- the
326 exception information is held in the thread, and there is no
327 thread.
328
329 Locking: as above.
330
331*/
332
333PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000334Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000335{
336 PyInterpreterState *interp;
337 PyThreadState *tstate, *save_tstate;
338 PyObject *bimod, *sysmod;
339
340 if (!initialized)
341 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
342
343 interp = PyInterpreterState_New();
344 if (interp == NULL)
345 return NULL;
346
347 tstate = PyThreadState_New(interp);
348 if (tstate == NULL) {
349 PyInterpreterState_Delete(interp);
350 return NULL;
351 }
352
353 save_tstate = PyThreadState_Swap(tstate);
354
355 /* XXX The following is lax in error checking */
356
357 interp->modules = PyDict_New();
358
359 bimod = _PyImport_FindExtension("__builtin__", "__builtin__");
360 if (bimod != NULL) {
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000361 interp->builtins = PyModule_GetDict(bimod);
362 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000363 }
364 sysmod = _PyImport_FindExtension("sys", "sys");
365 if (bimod != NULL && sysmod != NULL) {
366 interp->sysdict = PyModule_GetDict(sysmod);
367 Py_INCREF(interp->sysdict);
368 PySys_SetPath(Py_GetPath());
369 PyDict_SetItemString(interp->sysdict, "modules",
370 interp->modules);
Martin v. Löwisd7ceb222003-01-22 09:00:38 +0000371 _PyImportHooks_Init();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000372 initmain();
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000373 if (!Py_NoSiteFlag)
374 initsite();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000375 }
376
377 if (!PyErr_Occurred())
378 return tstate;
379
380 /* Oops, it didn't work. Undo it all. */
381
382 PyErr_Print();
383 PyThreadState_Clear(tstate);
384 PyThreadState_Swap(save_tstate);
385 PyThreadState_Delete(tstate);
386 PyInterpreterState_Delete(interp);
387
388 return NULL;
389}
390
391/* Delete an interpreter and its last thread. This requires that the
392 given thread state is current, that the thread has no remaining
393 frames, and that it is its interpreter's only remaining thread.
394 It is a fatal error to violate these constraints.
395
396 (Py_Finalize() doesn't have these constraints -- it zaps
397 everything, regardless.)
398
399 Locking: as above.
400
401*/
402
403void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000404Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000405{
406 PyInterpreterState *interp = tstate->interp;
407
408 if (tstate != PyThreadState_Get())
409 Py_FatalError("Py_EndInterpreter: thread is not current");
410 if (tstate->frame != NULL)
411 Py_FatalError("Py_EndInterpreter: thread still has a frame");
412 if (tstate != interp->tstate_head || tstate->next != NULL)
413 Py_FatalError("Py_EndInterpreter: not the last thread");
414
415 PyImport_Cleanup();
416 PyInterpreterState_Clear(interp);
417 PyThreadState_Swap(NULL);
418 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000419}
420
421static char *progname = "python";
422
423void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000424Py_SetProgramName(char *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000425{
426 if (pn && *pn)
427 progname = pn;
428}
429
430char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000431Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000432{
433 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000434}
435
Guido van Rossuma61691e1998-02-06 22:27:24 +0000436static char *default_home = NULL;
437
438void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000439Py_SetPythonHome(char *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000440{
441 default_home = home;
442}
443
444char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000445Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000446{
447 char *home = default_home;
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000448 if (home == NULL && !Py_IgnoreEnvironmentFlag)
449 home = Py_GETENV("PYTHONHOME");
Guido van Rossuma61691e1998-02-06 22:27:24 +0000450 return home;
451}
452
Guido van Rossum6135a871995-01-09 17:53:26 +0000453/* Create __main__ module */
454
455static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000456initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000457{
Guido van Rossum82598051997-03-05 00:20:32 +0000458 PyObject *m, *d;
459 m = PyImport_AddModule("__main__");
Guido van Rossum6135a871995-01-09 17:53:26 +0000460 if (m == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +0000461 Py_FatalError("can't create __main__ module");
462 d = PyModule_GetDict(m);
463 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
Guido van Rossum858cb731997-11-19 16:15:37 +0000464 PyObject *bimod = PyImport_ImportModule("__builtin__");
465 if (bimod == NULL ||
466 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
Guido van Rossum82598051997-03-05 00:20:32 +0000467 Py_FatalError("can't add __builtins__ to __main__");
Barry Warsaw3d05b1a1999-01-29 21:30:22 +0000468 Py_DECREF(bimod);
Guido van Rossum6135a871995-01-09 17:53:26 +0000469 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000470}
471
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000472/* Import the site module (not into __main__ though) */
473
474static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000475initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000476{
477 PyObject *m, *f;
478 m = PyImport_ImportModule("site");
479 if (m == NULL) {
480 f = PySys_GetObject("stderr");
481 if (Py_VerboseFlag) {
482 PyFile_WriteString(
483 "'import site' failed; traceback:\n", f);
484 PyErr_Print();
485 }
486 else {
487 PyFile_WriteString(
488 "'import site' failed; use -v for traceback\n", f);
489 PyErr_Clear();
490 }
491 }
492 else {
493 Py_DECREF(m);
494 }
495}
496
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000497/* Parse input from a file and execute it */
498
499int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000500PyRun_AnyFile(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000501{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000502 return PyRun_AnyFileExFlags(fp, filename, 0, NULL);
503}
504
505int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000506PyRun_AnyFileFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000507{
508 return PyRun_AnyFileExFlags(fp, filename, 0, flags);
Guido van Rossum0df002c2000-08-27 19:21:52 +0000509}
510
511int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000512PyRun_AnyFileEx(FILE *fp, const char *filename, int closeit)
Guido van Rossum0df002c2000-08-27 19:21:52 +0000513{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000514 return PyRun_AnyFileExFlags(fp, filename, closeit, NULL);
515}
516
517int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000518PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000519 PyCompilerFlags *flags)
520{
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000521 if (filename == NULL)
522 filename = "???";
Guido van Rossum0df002c2000-08-27 19:21:52 +0000523 if (Py_FdIsInteractive(fp, filename)) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000524 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
Guido van Rossum0df002c2000-08-27 19:21:52 +0000525 if (closeit)
526 fclose(fp);
527 return err;
528 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000529 else
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000530 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000531}
532
533int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000534PyRun_InteractiveLoop(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000535{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000536 return PyRun_InteractiveLoopFlags(fp, filename, NULL);
537}
538
539int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000540PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000541{
Guido van Rossum82598051997-03-05 00:20:32 +0000542 PyObject *v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000543 int ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000544 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000545
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000546 if (flags == NULL) {
547 flags = &local_flags;
Tim Peters5ba58662001-07-16 02:29:45 +0000548 local_flags.cf_flags = 0;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000549 }
Guido van Rossum82598051997-03-05 00:20:32 +0000550 v = PySys_GetObject("ps1");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000551 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000552 PySys_SetObject("ps1", v = PyString_FromString(">>> "));
553 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000554 }
Guido van Rossum82598051997-03-05 00:20:32 +0000555 v = PySys_GetObject("ps2");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000556 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000557 PySys_SetObject("ps2", v = PyString_FromString("... "));
558 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000559 }
560 for (;;) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000561 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
Guido van Rossumaae0d321996-05-22 16:35:33 +0000562#ifdef Py_REF_DEBUG
Guido van Rossum6f9e4331995-03-29 16:57:48 +0000563 fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000564#endif
565 if (ret == E_EOF)
566 return 0;
567 /*
568 if (ret == E_NOMEM)
569 return -1;
570 */
571 }
572}
573
574int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000575PyRun_InteractiveOne(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000576{
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000577 return PyRun_InteractiveOneFlags(fp, filename, NULL);
578}
579
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000580/* compute parser flags based on compiler flags */
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000581#define PARSER_FLAGS(flags) \
Guido van Rossum4b499dd32003-02-13 22:07:59 +0000582 (((flags) && (flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
583 PyPARSE_DONT_IMPLY_DEDENT : 0)
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000584
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000585int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000586PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000587{
Guido van Rossum82598051997-03-05 00:20:32 +0000588 PyObject *m, *d, *v, *w;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000589 node *n;
Guido van Rossuma110aa61994-08-29 12:50:44 +0000590 perrdetail err;
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000591 char *ps1 = "", *ps2 = "";
Tim Petersfe2127d2001-07-16 05:37:24 +0000592
Guido van Rossum82598051997-03-05 00:20:32 +0000593 v = PySys_GetObject("ps1");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000594 if (v != NULL) {
595 v = PyObject_Str(v);
596 if (v == NULL)
597 PyErr_Clear();
598 else if (PyString_Check(v))
599 ps1 = PyString_AsString(v);
600 }
Guido van Rossum82598051997-03-05 00:20:32 +0000601 w = PySys_GetObject("ps2");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000602 if (w != NULL) {
603 w = PyObject_Str(w);
604 if (w == NULL)
605 PyErr_Clear();
606 else if (PyString_Check(w))
607 ps2 = PyString_AsString(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000608 }
Tim Petersfe2127d2001-07-16 05:37:24 +0000609 n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar,
610 Py_single_input, ps1, ps2, &err,
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000611 PARSER_FLAGS(flags));
Guido van Rossum82598051997-03-05 00:20:32 +0000612 Py_XDECREF(v);
613 Py_XDECREF(w);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000614 if (n == NULL) {
615 if (err.error == E_EOF) {
616 if (err.text)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000617 PyMem_DEL(err.text);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000618 return E_EOF;
619 }
620 err_input(&err);
Guido van Rossum82598051997-03-05 00:20:32 +0000621 PyErr_Print();
Guido van Rossuma110aa61994-08-29 12:50:44 +0000622 return err.error;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000623 }
Guido van Rossum82598051997-03-05 00:20:32 +0000624 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000625 if (m == NULL)
626 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000627 d = PyModule_GetDict(m);
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000628 v = run_node(n, filename, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000629 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000630 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000631 return -1;
632 }
Guido van Rossum82598051997-03-05 00:20:32 +0000633 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000634 if (Py_FlushLine())
635 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000636 return 0;
637}
638
639int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000640PyRun_SimpleFile(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000641{
Guido van Rossum0df002c2000-08-27 19:21:52 +0000642 return PyRun_SimpleFileEx(fp, filename, 0);
643}
644
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000645/* Check whether a file maybe a pyc file: Look at the extension,
646 the file type, and, if we may close it, at the first few bytes. */
647
648static int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000649maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000650{
651 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
652 return 1;
653
654#ifdef macintosh
655 /* On a mac, we also assume a pyc file for types 'PYC ' and 'APPL' */
Jack Jansen72f3b7a2002-12-13 15:23:10 +0000656 if (PyMac_getfiletype((char *)filename) == 'PYC '
657 || PyMac_getfiletype((char *)filename) == 'APPL')
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000658 return 1;
659#endif /* macintosh */
660
661 /* Only look into the file if we are allowed to close it, since
662 it then should also be seekable. */
663 if (closeit) {
664 /* Read only two bytes of the magic. If the file was opened in
665 text mode, the bytes 3 and 4 of the magic (\r\n) might not
666 be read as they are on disk. */
667 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
668 unsigned char buf[2];
Tim Peters3e876562001-02-11 04:35:39 +0000669 /* Mess: In case of -x, the stream is NOT at its start now,
670 and ungetc() was used to push back the first newline,
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000671 which makes the current stream position formally undefined,
672 and a x-platform nightmare.
673 Unfortunately, we have no direct way to know whether -x
674 was specified. So we use a terrible hack: if the current
675 stream position is not 0, we assume -x was specified, and
676 give up. Bug 132850 on SourceForge spells out the
677 hopelessness of trying anything else (fseek and ftell
678 don't work predictably x-platform for text-mode files).
Tim Peters3e876562001-02-11 04:35:39 +0000679 */
Tim Peters3e876562001-02-11 04:35:39 +0000680 int ispyc = 0;
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000681 if (ftell(fp) == 0) {
682 if (fread(buf, 1, 2, fp) == 2 &&
683 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
684 ispyc = 1;
685 rewind(fp);
686 }
Tim Peters3e876562001-02-11 04:35:39 +0000687 return ispyc;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000688 }
689 return 0;
690}
691
Guido van Rossum0df002c2000-08-27 19:21:52 +0000692int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000693PyRun_SimpleFileEx(FILE *fp, const char *filename, int closeit)
Guido van Rossum0df002c2000-08-27 19:21:52 +0000694{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000695 return PyRun_SimpleFileExFlags(fp, filename, closeit, NULL);
696}
697
698int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000699PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000700 PyCompilerFlags *flags)
701{
Guido van Rossum82598051997-03-05 00:20:32 +0000702 PyObject *m, *d, *v;
Martin v. Löwis95292d62002-12-11 14:04:59 +0000703 const char *ext;
Guido van Rossumfdef2711994-09-14 13:31:04 +0000704
Guido van Rossum82598051997-03-05 00:20:32 +0000705 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000706 if (m == NULL)
707 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000708 d = PyModule_GetDict(m);
Fred Drake8ed02042002-10-17 21:24:58 +0000709 if (PyDict_GetItemString(d, "__file__") == NULL) {
710 PyObject *f = PyString_FromString(filename);
711 if (f == NULL)
712 return -1;
713 if (PyDict_SetItemString(d, "__file__", f) < 0) {
714 Py_DECREF(f);
715 return -1;
716 }
717 Py_DECREF(f);
718 }
Guido van Rossumfdef2711994-09-14 13:31:04 +0000719 ext = filename + strlen(filename) - 4;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000720 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Guido van Rossumfdef2711994-09-14 13:31:04 +0000721 /* Try to run a pyc file. First, re-open in binary */
Guido van Rossum0df002c2000-08-27 19:21:52 +0000722 if (closeit)
723 fclose(fp);
Fred Drake8ed02042002-10-17 21:24:58 +0000724 if ((fp = fopen(filename, "rb")) == NULL) {
Guido van Rossumfdef2711994-09-14 13:31:04 +0000725 fprintf(stderr, "python: Can't reopen .pyc file\n");
726 return -1;
727 }
Guido van Rossum2a7f58d1997-04-02 05:28:38 +0000728 /* Turn on optimization if a .pyo file is given */
729 if (strcmp(ext, ".pyo") == 0)
730 Py_OptimizeFlag = 1;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000731 v = run_pyc_file(fp, filename, d, d, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000732 } else {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000733 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
734 closeit, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000735 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000736 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000737 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000738 return -1;
739 }
Guido van Rossum82598051997-03-05 00:20:32 +0000740 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000741 if (Py_FlushLine())
742 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000743 return 0;
744}
745
746int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000747PyRun_SimpleString(const char *command)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000748{
Guido van Rossum393661d2001-08-31 17:40:15 +0000749 return PyRun_SimpleStringFlags(command, NULL);
750}
751
752int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000753PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +0000754{
Guido van Rossum82598051997-03-05 00:20:32 +0000755 PyObject *m, *d, *v;
756 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000757 if (m == NULL)
758 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000759 d = PyModule_GetDict(m);
Guido van Rossum393661d2001-08-31 17:40:15 +0000760 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000761 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000762 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000763 return -1;
764 }
Guido van Rossum82598051997-03-05 00:20:32 +0000765 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000766 if (Py_FlushLine())
767 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000768 return 0;
769}
770
Barry Warsaw035574d1997-08-29 22:07:17 +0000771static int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000772parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
773 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +0000774{
775 long hold;
776 PyObject *v;
777
778 /* old style errors */
779 if (PyTuple_Check(err))
Neal Norwitz78293352002-04-01 01:41:20 +0000780 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
781 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +0000782
783 /* new style errors. `err' is an instance */
784
785 if (! (v = PyObject_GetAttrString(err, "msg")))
786 goto finally;
787 *message = v;
788
789 if (!(v = PyObject_GetAttrString(err, "filename")))
790 goto finally;
791 if (v == Py_None)
792 *filename = NULL;
793 else if (! (*filename = PyString_AsString(v)))
794 goto finally;
795
796 Py_DECREF(v);
797 if (!(v = PyObject_GetAttrString(err, "lineno")))
798 goto finally;
799 hold = PyInt_AsLong(v);
800 Py_DECREF(v);
801 v = NULL;
802 if (hold < 0 && PyErr_Occurred())
803 goto finally;
804 *lineno = (int)hold;
805
806 if (!(v = PyObject_GetAttrString(err, "offset")))
807 goto finally;
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000808 if (v == Py_None) {
809 *offset = -1;
810 Py_DECREF(v);
811 v = NULL;
812 } else {
813 hold = PyInt_AsLong(v);
814 Py_DECREF(v);
815 v = NULL;
816 if (hold < 0 && PyErr_Occurred())
817 goto finally;
818 *offset = (int)hold;
819 }
Barry Warsaw035574d1997-08-29 22:07:17 +0000820
821 if (!(v = PyObject_GetAttrString(err, "text")))
822 goto finally;
823 if (v == Py_None)
824 *text = NULL;
825 else if (! (*text = PyString_AsString(v)))
826 goto finally;
827 Py_DECREF(v);
828 return 1;
829
830finally:
831 Py_XDECREF(v);
832 return 0;
833}
834
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000835void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000836PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000837{
Guido van Rossuma61691e1998-02-06 22:27:24 +0000838 PyErr_PrintEx(1);
839}
840
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000841static void
Martin v. Löwis95292d62002-12-11 14:04:59 +0000842print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000843{
844 char *nl;
845 if (offset >= 0) {
846 if (offset > 0 && offset == (int)strlen(text))
847 offset--;
848 for (;;) {
849 nl = strchr(text, '\n');
850 if (nl == NULL || nl-text >= offset)
851 break;
852 offset -= (nl+1-text);
853 text = nl+1;
854 }
855 while (*text == ' ' || *text == '\t') {
856 text++;
857 offset--;
858 }
859 }
860 PyFile_WriteString(" ", f);
861 PyFile_WriteString(text, f);
862 if (*text == '\0' || text[strlen(text)-1] != '\n')
863 PyFile_WriteString("\n", f);
864 if (offset == -1)
865 return;
866 PyFile_WriteString(" ", f);
867 offset--;
868 while (offset > 0) {
869 PyFile_WriteString(" ", f);
870 offset--;
871 }
872 PyFile_WriteString("^\n", f);
873}
874
Guido van Rossum66e8e862001-03-23 17:54:43 +0000875static void
876handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000877{
Guido van Rossum66e8e862001-03-23 17:54:43 +0000878 PyObject *exception, *value, *tb;
879 PyErr_Fetch(&exception, &value, &tb);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000880 if (Py_FlushLine())
881 PyErr_Clear();
882 fflush(stdout);
883 if (value == NULL || value == Py_None)
884 Py_Exit(0);
885 if (PyInstance_Check(value)) {
886 /* The error code should be in the `code' attribute. */
887 PyObject *code = PyObject_GetAttrString(value, "code");
888 if (code) {
889 Py_DECREF(value);
890 value = code;
891 if (value == Py_None)
892 Py_Exit(0);
893 }
894 /* If we failed to dig out the 'code' attribute,
895 just let the else clause below print the error. */
896 }
897 if (PyInt_Check(value))
898 Py_Exit((int)PyInt_AsLong(value));
899 else {
900 PyObject_Print(value, stderr, Py_PRINT_RAW);
901 PySys_WriteStderr("\n");
902 Py_Exit(1);
903 }
904}
905
906void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000907PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000908{
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000909 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +0000910
911 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
912 handle_system_exit();
913 }
Guido van Rossum82598051997-03-05 00:20:32 +0000914 PyErr_Fetch(&exception, &v, &tb);
Barry Warsaw035574d1997-08-29 22:07:17 +0000915 PyErr_NormalizeException(&exception, &v, &tb);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000916 if (exception == NULL)
Guido van Rossum296b4751997-05-23 00:19:20 +0000917 return;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000918 if (set_sys_last_vars) {
919 PySys_SetObject("last_type", exception);
920 PySys_SetObject("last_value", v);
921 PySys_SetObject("last_traceback", tb);
922 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000923 hook = PySys_GetObject("excepthook");
924 if (hook) {
925 PyObject *args = Py_BuildValue("(OOO)",
926 exception, v ? v : Py_None, tb ? tb : Py_None);
927 PyObject *result = PyEval_CallObject(hook, args);
928 if (result == NULL) {
929 PyObject *exception2, *v2, *tb2;
Guido van Rossum66e8e862001-03-23 17:54:43 +0000930 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
931 handle_system_exit();
932 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000933 PyErr_Fetch(&exception2, &v2, &tb2);
934 PyErr_NormalizeException(&exception2, &v2, &tb2);
935 if (Py_FlushLine())
936 PyErr_Clear();
937 fflush(stdout);
938 PySys_WriteStderr("Error in sys.excepthook:\n");
939 PyErr_Display(exception2, v2, tb2);
940 PySys_WriteStderr("\nOriginal exception was:\n");
941 PyErr_Display(exception, v, tb);
Jeremy Hylton07028582001-12-07 15:35:35 +0000942 Py_XDECREF(exception2);
943 Py_XDECREF(v2);
944 Py_XDECREF(tb2);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000945 }
946 Py_XDECREF(result);
947 Py_XDECREF(args);
948 } else {
949 PySys_WriteStderr("sys.excepthook is missing\n");
950 PyErr_Display(exception, v, tb);
951 }
952 Py_XDECREF(exception);
953 Py_XDECREF(v);
954 Py_XDECREF(tb);
955}
956
957void PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
958{
959 int err = 0;
960 PyObject *v = value;
961 PyObject *f = PySys_GetObject("stderr");
Guido van Rossum3165fe61992-09-25 21:59:05 +0000962 if (f == NULL)
963 fprintf(stderr, "lost sys.stderr\n");
964 else {
Guido van Rossum0829c751998-02-28 04:31:39 +0000965 if (Py_FlushLine())
966 PyErr_Clear();
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000967 fflush(stdout);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000968 if (tb && tb != Py_None)
969 err = PyTraceBack_Print(tb, f);
Barry Warsaw36b8f941997-08-26 18:09:48 +0000970 if (err == 0 &&
Martin v. Löwiscfeb3b62002-03-03 21:30:27 +0000971 PyObject_HasAttrString(v, "print_file_and_line"))
Barry Warsaw36b8f941997-08-26 18:09:48 +0000972 {
Guido van Rossum82598051997-03-05 00:20:32 +0000973 PyObject *message;
Martin v. Löwis95292d62002-12-11 14:04:59 +0000974 const char *filename, *text;
Guido van Rossuma110aa61994-08-29 12:50:44 +0000975 int lineno, offset;
Barry Warsaw035574d1997-08-29 22:07:17 +0000976 if (!parse_syntax_error(v, &message, &filename,
977 &lineno, &offset, &text))
Guido van Rossum82598051997-03-05 00:20:32 +0000978 PyErr_Clear();
Guido van Rossuma110aa61994-08-29 12:50:44 +0000979 else {
980 char buf[10];
Guido van Rossum82598051997-03-05 00:20:32 +0000981 PyFile_WriteString(" File \"", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000982 if (filename == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +0000983 PyFile_WriteString("<string>", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000984 else
Guido van Rossum82598051997-03-05 00:20:32 +0000985 PyFile_WriteString(filename, f);
986 PyFile_WriteString("\", line ", f);
Jeremy Hylton518ab1c2001-11-28 20:42:20 +0000987 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
Guido van Rossum82598051997-03-05 00:20:32 +0000988 PyFile_WriteString(buf, f);
989 PyFile_WriteString("\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000990 if (text != NULL)
991 print_error_text(f, offset, text);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000992 v = message;
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000993 /* Can't be bothered to check all those
994 PyFile_WriteString() calls */
995 if (PyErr_Occurred())
996 err = -1;
Guido van Rossuma110aa61994-08-29 12:50:44 +0000997 }
998 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000999 if (err) {
1000 /* Don't do anything else */
1001 }
1002 else if (PyClass_Check(exception)) {
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001003 PyClassObject* exc = (PyClassObject*)exception;
1004 PyObject* className = exc->cl_name;
1005 PyObject* moduleName =
1006 PyDict_GetItemString(exc->cl_dict, "__module__");
1007
1008 if (moduleName == NULL)
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001009 err = PyFile_WriteString("<unknown>", f);
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001010 else {
1011 char* modstr = PyString_AsString(moduleName);
1012 if (modstr && strcmp(modstr, "exceptions"))
1013 {
1014 err = PyFile_WriteString(modstr, f);
1015 err += PyFile_WriteString(".", f);
1016 }
1017 }
1018 if (err == 0) {
1019 if (className == NULL)
1020 err = PyFile_WriteString("<unknown>", f);
1021 else
1022 err = PyFile_WriteObject(className, f,
1023 Py_PRINT_RAW);
1024 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001025 }
1026 else
1027 err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
1028 if (err == 0) {
1029 if (v != NULL && v != Py_None) {
Barry Warsaw035574d1997-08-29 22:07:17 +00001030 PyObject *s = PyObject_Str(v);
1031 /* only print colon if the str() of the
1032 object is not the empty string
1033 */
Guido van Rossumd6bf45b1997-09-05 19:11:53 +00001034 if (s == NULL)
1035 err = -1;
1036 else if (!PyString_Check(s) ||
1037 PyString_GET_SIZE(s) != 0)
Barry Warsaw035574d1997-08-29 22:07:17 +00001038 err = PyFile_WriteString(": ", f);
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001039 if (err == 0)
Guido van Rossumd6bf45b1997-09-05 19:11:53 +00001040 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1041 Py_XDECREF(s);
Guido van Rossum262e1241995-02-07 15:30:45 +00001042 }
Guido van Rossum262e1241995-02-07 15:30:45 +00001043 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001044 if (err == 0)
1045 err = PyFile_WriteString("\n", f);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001046 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001047 /* If an error happened here, don't show it.
1048 XXX This is wrong, but too many callers rely on this behavior. */
1049 if (err != 0)
1050 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001051}
1052
Guido van Rossum82598051997-03-05 00:20:32 +00001053PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001054PyRun_String(const char *str, int start, PyObject *globals, PyObject *locals)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001055{
Guido van Rossum82598051997-03-05 00:20:32 +00001056 return run_err_node(PyParser_SimpleParseString(str, start),
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001057 "<string>", globals, locals, NULL);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001058}
1059
Guido van Rossum82598051997-03-05 00:20:32 +00001060PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001061PyRun_File(FILE *fp, const char *filename, int start, PyObject *globals,
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001062 PyObject *locals)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001063{
Tim Peterse8682112000-08-27 20:18:17 +00001064 return PyRun_FileEx(fp, filename, start, globals, locals, 0);
Guido van Rossum0df002c2000-08-27 19:21:52 +00001065}
1066
1067PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001068PyRun_FileEx(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001069 PyObject *locals, int closeit)
Guido van Rossum0df002c2000-08-27 19:21:52 +00001070{
1071 node *n = PyParser_SimpleParseFile(fp, filename, start);
1072 if (closeit)
1073 fclose(fp);
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001074 return run_err_node(n, filename, globals, locals, NULL);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001075}
1076
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001077PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001078PyRun_StringFlags(const char *str, int start, PyObject *globals, PyObject *locals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001079 PyCompilerFlags *flags)
1080{
Guido van Rossuma1b3a472001-07-16 16:51:33 +00001081 return run_err_node(PyParser_SimpleParseStringFlags(
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001082 str, start, PARSER_FLAGS(flags)),
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001083 "<string>", globals, locals, flags);
1084}
1085
1086PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001087PyRun_FileFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001088 PyObject *locals, PyCompilerFlags *flags)
1089{
1090 return PyRun_FileExFlags(fp, filename, start, globals, locals, 0,
1091 flags);
1092}
1093
1094PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001095PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001096 PyObject *locals, int closeit, PyCompilerFlags *flags)
1097{
Tim Petersfe2127d2001-07-16 05:37:24 +00001098 node *n = PyParser_SimpleParseFileFlags(fp, filename, start,
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001099 PARSER_FLAGS(flags));
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001100 if (closeit)
1101 fclose(fp);
1102 return run_err_node(n, filename, globals, locals, flags);
1103}
1104
Guido van Rossum82598051997-03-05 00:20:32 +00001105static PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001106run_err_node(node *n, const char *filename, PyObject *globals, PyObject *locals,
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001107 PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001108{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001109 if (n == NULL)
1110 return NULL;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001111 return run_node(n, filename, globals, locals, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001112}
1113
Guido van Rossum82598051997-03-05 00:20:32 +00001114static PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001115run_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 Rossum82598051997-03-05 00:20:32 +00001118 PyCodeObject *co;
1119 PyObject *v;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001120 co = PyNode_CompileFlags(n, filename, flags);
Guido van Rossum82598051997-03-05 00:20:32 +00001121 PyNode_Free(n);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001122 if (co == NULL)
1123 return NULL;
Guido van Rossum82598051997-03-05 00:20:32 +00001124 v = PyEval_EvalCode(co, globals, locals);
1125 Py_DECREF(co);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001126 return v;
1127}
1128
Guido van Rossum82598051997-03-05 00:20:32 +00001129static PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001130run_pyc_file(FILE *fp, const char *filename, PyObject *globals, PyObject *locals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001131 PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001132{
Guido van Rossum82598051997-03-05 00:20:32 +00001133 PyCodeObject *co;
1134 PyObject *v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001135 long magic;
Fred Drakee8de31c2000-08-31 05:38:39 +00001136 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001137
Guido van Rossum82598051997-03-05 00:20:32 +00001138 magic = PyMarshal_ReadLongFromFile(fp);
1139 if (magic != PyImport_GetMagicNumber()) {
1140 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001141 "Bad magic number in .pyc file");
1142 return NULL;
1143 }
Guido van Rossum82598051997-03-05 00:20:32 +00001144 (void) PyMarshal_ReadLongFromFile(fp);
Tim Petersd9b9ac82001-01-28 00:27:39 +00001145 v = PyMarshal_ReadLastObjectFromFile(fp);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001146 fclose(fp);
Guido van Rossum82598051997-03-05 00:20:32 +00001147 if (v == NULL || !PyCode_Check(v)) {
1148 Py_XDECREF(v);
1149 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001150 "Bad code object in .pyc file");
1151 return NULL;
1152 }
Guido van Rossum82598051997-03-05 00:20:32 +00001153 co = (PyCodeObject *)v;
1154 v = PyEval_EvalCode(co, globals, locals);
Jeremy Hyltonb857ba22001-08-10 21:41:33 +00001155 if (v && flags)
1156 flags->cf_flags |= (co->co_flags & PyCF_MASK);
Guido van Rossum82598051997-03-05 00:20:32 +00001157 Py_DECREF(co);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001158 return v;
1159}
1160
Guido van Rossum82598051997-03-05 00:20:32 +00001161PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001162Py_CompileString(const char *str, const char *filename, int start)
Guido van Rossum5b722181993-03-30 17:46:03 +00001163{
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001164 return Py_CompileStringFlags(str, filename, start, NULL);
1165}
1166
1167PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001168Py_CompileStringFlags(const char *str, const char *filename, int start,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001169 PyCompilerFlags *flags)
1170{
Guido van Rossum5b722181993-03-30 17:46:03 +00001171 node *n;
Guido van Rossum82598051997-03-05 00:20:32 +00001172 PyCodeObject *co;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001173
1174 n = PyParser_SimpleParseStringFlagsFilename(str, filename, start,
1175 PARSER_FLAGS(flags));
Guido van Rossuma110aa61994-08-29 12:50:44 +00001176 if (n == NULL)
Guido van Rossum5b722181993-03-30 17:46:03 +00001177 return NULL;
Jeremy Hylton673a4fd2001-03-26 19:53:38 +00001178 co = PyNode_CompileFlags(n, filename, flags);
Guido van Rossum82598051997-03-05 00:20:32 +00001179 PyNode_Free(n);
1180 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001181}
1182
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001183struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001184Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001185{
1186 node *n;
1187 struct symtable *st;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001188 n = PyParser_SimpleParseStringFlagsFilename(str, filename,
1189 start, 0);
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001190 if (n == NULL)
1191 return NULL;
1192 st = PyNode_CompileSymtable(n, filename);
1193 PyNode_Free(n);
1194 return st;
1195}
1196
Guido van Rossuma110aa61994-08-29 12:50:44 +00001197/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001198
Guido van Rossuma110aa61994-08-29 12:50:44 +00001199node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001200PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001201{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001202 node *n;
1203 perrdetail err;
Tim Petersfe2127d2001-07-16 05:37:24 +00001204 n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar, start,
1205 (char *)0, (char *)0, &err, flags);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001206 if (n == NULL)
1207 err_input(&err);
1208 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001209}
1210
Tim Petersfe2127d2001-07-16 05:37:24 +00001211node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001212PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
Tim Petersfe2127d2001-07-16 05:37:24 +00001213{
1214 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
1215}
1216
Guido van Rossuma110aa61994-08-29 12:50:44 +00001217/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001218
Guido van Rossuma110aa61994-08-29 12:50:44 +00001219node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001220PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001221{
1222 node *n;
1223 perrdetail err;
1224 n = PyParser_ParseStringFlags(str, &_PyParser_Grammar, start, &err,
1225 flags);
1226 if (n == NULL)
1227 err_input(&err);
1228 return n;
1229}
1230
1231node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001232PyParser_SimpleParseString(const char *str, int start)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001233{
Tim Petersfe2127d2001-07-16 05:37:24 +00001234 return PyParser_SimpleParseStringFlags(str, start, 0);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001235}
1236
Thomas Heller6b17abf2002-07-09 09:23:27 +00001237node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001238PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Thomas Heller6b17abf2002-07-09 09:23:27 +00001239 int start, int flags)
1240{
1241 node *n;
1242 perrdetail err;
1243
1244 n = PyParser_ParseStringFlagsFilename(str, filename,
1245 &_PyParser_Grammar,
1246 start, &err, flags);
1247 if (n == NULL)
1248 err_input(&err);
1249 return n;
1250}
1251
1252node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001253PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001254{
1255 return PyParser_SimpleParseStringFlagsFilename(str, filename,
1256 start, 0);
1257}
1258
Guido van Rossuma110aa61994-08-29 12:50:44 +00001259/* Set the error appropriate to the given input error code (see errcode.h) */
1260
1261static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001262err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001263{
Fred Drake85f36392000-07-11 17:53:00 +00001264 PyObject *v, *w, *errtype;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001265 PyObject* u = NULL;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001266 char *msg = NULL;
Fred Drake85f36392000-07-11 17:53:00 +00001267 errtype = PyExc_SyntaxError;
Guido van Rossum82598051997-03-05 00:20:32 +00001268 v = Py_BuildValue("(ziiz)", err->filename,
Guido van Rossuma110aa61994-08-29 12:50:44 +00001269 err->lineno, err->offset, err->text);
1270 if (err->text != NULL) {
Guido van Rossumb18618d2000-05-03 23:44:39 +00001271 PyMem_DEL(err->text);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001272 err->text = NULL;
1273 }
1274 switch (err->error) {
1275 case E_SYNTAX:
Fred Drake85f36392000-07-11 17:53:00 +00001276 errtype = PyExc_IndentationError;
1277 if (err->expected == INDENT)
1278 msg = "expected an indented block";
1279 else if (err->token == INDENT)
1280 msg = "unexpected indent";
1281 else if (err->token == DEDENT)
1282 msg = "unexpected unindent";
1283 else {
1284 errtype = PyExc_SyntaxError;
1285 msg = "invalid syntax";
1286 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001287 break;
1288 case E_TOKEN:
1289 msg = "invalid token";
Guido van Rossuma110aa61994-08-29 12:50:44 +00001290 break;
Skip Montanaro118ec702002-08-15 01:20:16 +00001291 case E_EOFS:
1292 msg = "EOF while scanning triple-quoted string";
1293 break;
1294 case E_EOLS:
1295 msg = "EOL while scanning single-quoted string";
1296 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001297 case E_INTR:
Guido van Rossum82598051997-03-05 00:20:32 +00001298 PyErr_SetNone(PyExc_KeyboardInterrupt);
Barry Warsawc80baa31999-01-27 16:39:40 +00001299 Py_XDECREF(v);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001300 return;
1301 case E_NOMEM:
Guido van Rossum82598051997-03-05 00:20:32 +00001302 PyErr_NoMemory();
Barry Warsawc80baa31999-01-27 16:39:40 +00001303 Py_XDECREF(v);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001304 return;
1305 case E_EOF:
1306 msg = "unexpected EOF while parsing";
1307 break;
Fred Drake85f36392000-07-11 17:53:00 +00001308 case E_TABSPACE:
1309 errtype = PyExc_TabError;
Guido van Rossum560e8ad1998-04-10 19:43:42 +00001310 msg = "inconsistent use of tabs and spaces in indentation";
1311 break;
Jeremy Hylton94988062000-06-20 19:10:44 +00001312 case E_OVERFLOW:
1313 msg = "expression too long";
1314 break;
Fred Drake85f36392000-07-11 17:53:00 +00001315 case E_DEDENT:
1316 errtype = PyExc_IndentationError;
1317 msg = "unindent does not match any outer indentation level";
1318 break;
1319 case E_TOODEEP:
1320 errtype = PyExc_IndentationError;
1321 msg = "too many levels of indentation";
1322 break;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001323 case E_DECODE: { /* XXX */
1324 PyThreadState* tstate = PyThreadState_Get();
1325 PyObject* value = tstate->curexc_value;
1326 if (value != NULL) {
1327 u = PyObject_Repr(value);
1328 if (u != NULL) {
1329 msg = PyString_AsString(u);
1330 break;
1331 }
1332 }
1333 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001334 default:
1335 fprintf(stderr, "error=%d\n", err->error);
1336 msg = "unknown parsing error";
1337 break;
1338 }
Guido van Rossum82598051997-03-05 00:20:32 +00001339 w = Py_BuildValue("(sO)", msg, v);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001340 Py_XDECREF(u);
Guido van Rossum41318302001-03-23 04:01:07 +00001341 Py_XDECREF(v);
Fred Drake85f36392000-07-11 17:53:00 +00001342 PyErr_SetObject(errtype, w);
Guido van Rossum82598051997-03-05 00:20:32 +00001343 Py_XDECREF(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001344}
1345
1346/* Print fatal error message and abort */
1347
1348void
Tim Peters7c321a82002-07-09 02:57:01 +00001349Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001350{
Guido van Rossum83dd6c31994-09-29 09:38:33 +00001351 fprintf(stderr, "Fatal Python error: %s\n", msg);
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001352#ifdef MS_WINDOWS
Guido van Rossum23c94461997-05-22 20:21:30 +00001353 OutputDebugString("Fatal Python error: ");
Guido van Rossuma44823b1995-03-14 15:01:17 +00001354 OutputDebugString(msg);
1355 OutputDebugString("\n");
Guido van Rossum0ba35361998-08-13 13:33:16 +00001356#ifdef _DEBUG
1357 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00001358#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001359#endif /* MS_WINDOWS */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001360 abort();
1361}
1362
1363/* Clean up and exit */
1364
Guido van Rossuma110aa61994-08-29 12:50:44 +00001365#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00001366#include "pythread.h"
Guido van Rossum82598051997-03-05 00:20:32 +00001367int _PyThread_Started = 0; /* Set by threadmodule.c and maybe others */
Guido van Rossumf9f2e821992-08-17 08:59:08 +00001368#endif
1369
Guido van Rossum2dcfc961998-10-01 16:01:57 +00001370#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001371static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00001372static int nexitfuncs = 0;
1373
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001374int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00001375{
1376 if (nexitfuncs >= NEXITFUNCS)
1377 return -1;
1378 exitfuncs[nexitfuncs++] = func;
1379 return 0;
1380}
1381
Guido van Rossumcc283f51997-08-05 02:22:03 +00001382static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001383call_sys_exitfunc(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001384{
Guido van Rossum82598051997-03-05 00:20:32 +00001385 PyObject *exitfunc = PySys_GetObject("exitfunc");
Guido van Rossum59bff391992-09-03 20:28:00 +00001386
1387 if (exitfunc) {
Fred Drake6a12d8d2001-03-23 17:34:02 +00001388 PyObject *res;
Guido van Rossum82598051997-03-05 00:20:32 +00001389 Py_INCREF(exitfunc);
1390 PySys_SetObject("exitfunc", (PyObject *)NULL);
1391 res = PyEval_CallObject(exitfunc, (PyObject *)NULL);
Guido van Rossum59bff391992-09-03 20:28:00 +00001392 if (res == NULL) {
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001393 if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
1394 PySys_WriteStderr("Error in sys.exitfunc:\n");
1395 }
Guido van Rossum82598051997-03-05 00:20:32 +00001396 PyErr_Print();
Guido van Rossum59bff391992-09-03 20:28:00 +00001397 }
Guido van Rossum82598051997-03-05 00:20:32 +00001398 Py_DECREF(exitfunc);
Guido van Rossum59bff391992-09-03 20:28:00 +00001399 }
1400
Guido van Rossum0829c751998-02-28 04:31:39 +00001401 if (Py_FlushLine())
1402 PyErr_Clear();
Guido van Rossumcc283f51997-08-05 02:22:03 +00001403}
Guido van Rossum1662dd51994-09-07 14:38:28 +00001404
Guido van Rossumcc283f51997-08-05 02:22:03 +00001405static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001406call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00001407{
Guido van Rossum1662dd51994-09-07 14:38:28 +00001408 while (nexitfuncs > 0)
1409 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00001410
1411 fflush(stdout);
1412 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001413}
1414
1415void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001416Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001417{
Guido van Rossumcc283f51997-08-05 02:22:03 +00001418 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001419
Jack Jansen66a89771995-10-27 13:22:14 +00001420#ifdef macintosh
1421 PyMac_Exit(sts);
1422#else
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001423 exit(sts);
Jack Jansen66a89771995-10-27 13:22:14 +00001424#endif
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001425}
1426
Guido van Rossumf1dc5661993-07-05 10:31:29 +00001427static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001428initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001429{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001430#ifdef HAVE_SIGNAL_H
1431#ifdef SIGPIPE
1432 signal(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001433#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00001434#ifdef SIGXFZ
1435 signal(SIGXFZ, SIG_IGN);
1436#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00001437#ifdef SIGXFSZ
1438 signal(SIGXFSZ, SIG_IGN);
1439#endif
Guido van Rossuma110aa61994-08-29 12:50:44 +00001440#endif /* HAVE_SIGNAL_H */
Guido van Rossum82598051997-03-05 00:20:32 +00001441 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001442}
1443
Guido van Rossuma110aa61994-08-29 12:50:44 +00001444#ifdef MPW
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001445
1446/* Check for file descriptor connected to interactive device.
1447 Pretend that stdin is always interactive, other files never. */
1448
1449int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001450isatty(int fd)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001451{
1452 return fd == fileno(stdin);
1453}
1454
1455#endif
Guido van Rossum7433b121997-02-14 19:45:36 +00001456
1457/*
1458 * The file descriptor fd is considered ``interactive'' if either
1459 * a) isatty(fd) is TRUE, or
1460 * b) the -i flag was given, and the filename associated with
1461 * the descriptor is NULL or "<stdin>" or "???".
1462 */
1463int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001464Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00001465{
1466 if (isatty((int)fileno(fp)))
1467 return 1;
1468 if (!Py_InteractiveFlag)
1469 return 0;
1470 return (filename == NULL) ||
1471 (strcmp(filename, "<stdin>") == 0) ||
1472 (strcmp(filename, "???") == 0);
1473}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001474
1475
1476#if defined(USE_STACKCHECK)
1477#if defined(WIN32) && defined(_MSC_VER)
1478
1479/* Stack checking for Microsoft C */
1480
1481#include <malloc.h>
1482#include <excpt.h>
1483
Fred Drakee8de31c2000-08-31 05:38:39 +00001484/*
1485 * Return non-zero when we run out of memory on the stack; zero otherwise.
1486 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001487int
Fred Drake399739f2000-08-31 05:52:44 +00001488PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001489{
1490 __try {
Tim Peters92e4dd82002-10-05 01:47:34 +00001491 /* alloca throws a stack overflow exception if there's
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001492 not enough space left on the stack */
Tim Peters92e4dd82002-10-05 01:47:34 +00001493 alloca(PYOS_STACK_MARGIN * sizeof(void*));
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001494 return 0;
1495 } __except (EXCEPTION_EXECUTE_HANDLER) {
1496 /* just ignore all errors */
1497 }
1498 return 1;
1499}
1500
1501#endif /* WIN32 && _MSC_VER */
1502
1503/* Alternate implementations can be added here... */
1504
1505#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00001506
1507
1508/* Wrappers around sigaction() or signal(). */
1509
1510PyOS_sighandler_t
1511PyOS_getsig(int sig)
1512{
1513#ifdef HAVE_SIGACTION
1514 struct sigaction context;
Barry Warsawafeb2a42001-11-13 23:08:26 +00001515 /* Initialize context.sa_handler to SIG_ERR which makes about as
1516 * much sense as anything else. It should get overwritten if
1517 * sigaction actually succeeds and otherwise we avoid an
1518 * uninitialized memory read.
1519 */
1520 context.sa_handler = SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00001521 sigaction(sig, NULL, &context);
1522 return context.sa_handler;
1523#else
1524 PyOS_sighandler_t handler;
1525 handler = signal(sig, SIG_IGN);
1526 signal(sig, handler);
1527 return handler;
1528#endif
1529}
1530
1531PyOS_sighandler_t
1532PyOS_setsig(int sig, PyOS_sighandler_t handler)
1533{
1534#ifdef HAVE_SIGACTION
1535 struct sigaction context;
1536 PyOS_sighandler_t oldhandler;
Barry Warsawafeb2a42001-11-13 23:08:26 +00001537 /* Initialize context.sa_handler to SIG_ERR which makes about as
1538 * much sense as anything else. It should get overwritten if
1539 * sigaction actually succeeds and otherwise we avoid an
1540 * uninitialized memory read.
1541 */
1542 context.sa_handler = SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00001543 sigaction(sig, NULL, &context);
1544 oldhandler = context.sa_handler;
1545 context.sa_handler = handler;
1546 sigaction(sig, &context, NULL);
1547 return oldhandler;
1548#else
1549 return signal(sig, handler);
1550#endif
1551}