blob: 1faab509ba9d6a1afcd26eed65f726ff541f02c0 [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öwis6238d2b2002-06-30 15:26:10 +000020#ifdef MS_WINDOWS
Guido van Rossuma44823b1995-03-14 15:01:17 +000021#undef BYTE
22#include "windows.h"
23#endif
24
Jack Jansencbf630f2000-07-11 21:59:16 +000025#ifdef macintosh
26#include "macglue.h"
27#endif
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000028extern char *Py_GetPath(void);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000029
Guido van Rossum82598051997-03-05 00:20:32 +000030extern grammar _PyParser_Grammar; /* From graminit.c */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000031
Guido van Rossumb73cc041993-11-01 16:28:59 +000032/* Forward */
Tim Petersdbd9ba62000-07-09 03:09:57 +000033static void initmain(void);
34static void initsite(void);
Martin v. Löwis95292d62002-12-11 14:04:59 +000035static PyObject *run_err_node(node *, const char *, PyObject *, PyObject *,
Jeremy Hylton9f324e92001-03-01 22:59:14 +000036 PyCompilerFlags *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000037static PyObject *run_node(node *, const char *, PyObject *, PyObject *,
Jeremy Hylton9f324e92001-03-01 22:59:14 +000038 PyCompilerFlags *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000039static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
Jeremy Hyltonbc320242001-03-22 02:47:58 +000040 PyCompilerFlags *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000041static void err_input(perrdetail *);
42static void initsigs(void);
43static void call_sys_exitfunc(void);
44static void call_ll_exitfuncs(void);
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000045extern void _PyUnicode_Init(void);
46extern void _PyUnicode_Fini(void);
47extern void _PyCodecRegistry_Init(void);
48extern void _PyCodecRegistry_Fini(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +000049
Guido van Rossum82598051997-03-05 00:20:32 +000050int Py_DebugFlag; /* Needed by parser.c */
51int Py_VerboseFlag; /* Needed by import.c */
Guido van Rossum7433b121997-02-14 19:45:36 +000052int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Guido van Rossumdcc0c131997-08-29 22:32:42 +000053int Py_NoSiteFlag; /* Suppress 'import site' */
Barry Warsaw3ce09642000-05-02 19:18:59 +000054int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +000055int Py_FrozenFlag; /* Needed by getpath.c */
Guido van Rossumb16d1972000-05-01 17:55:15 +000056int Py_UnicodeFlag = 0; /* Needed by compile.c */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +000057int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Tim Peters3caca232001-12-06 06:23:26 +000058/* _XXX Py_QnewFlag should go away in 2.3. It's true iff -Qnew is passed,
59 on the command line, and is used in 2.2 by ceval.c to make all "/" divisions
60 true divisions (which they will be in 2.3). */
61int _Py_QnewFlag = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +000062
Guido van Rossum25ce5661997-08-02 03:10:38 +000063static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +000064
Thomas Wouters7e474022000-07-16 12:04:32 +000065/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +000066
67int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000068Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +000069{
70 return initialized;
71}
72
Guido van Rossum25ce5661997-08-02 03:10:38 +000073/* Global initializations. Can be undone by Py_Finalize(). Don't
74 call this twice without an intervening Py_Finalize() call. When
75 initializations fail, a fatal error is issued and the function does
76 not return. On return, the first thread and interpreter state have
77 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +000078
Guido van Rossum25ce5661997-08-02 03:10:38 +000079 Locking: you must hold the interpreter lock while calling this.
80 (If the lock has not yet been initialized, that's equivalent to
81 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000082
Guido van Rossum25ce5661997-08-02 03:10:38 +000083*/
Guido van Rossuma027efa1997-05-05 20:56:21 +000084
Guido van Rossum9abaf4d2001-10-12 22:17:56 +000085static int
86add_flag(int flag, const char *envs)
87{
88 int env = atoi(envs);
89 if (flag < env)
90 flag = env;
91 if (flag < 1)
92 flag = 1;
93 return flag;
94}
95
Guido van Rossuma027efa1997-05-05 20:56:21 +000096void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000097Py_Initialize(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +000098{
Guido van Rossuma027efa1997-05-05 20:56:21 +000099 PyInterpreterState *interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000100 PyThreadState *tstate;
101 PyObject *bimod, *sysmod;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000102 char *p;
Guido van Rossum70d893a2001-08-16 08:21:42 +0000103 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000104
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000105 if (initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +0000106 return;
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000107 initialized = 1;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000108
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000109 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000110 Py_DebugFlag = add_flag(Py_DebugFlag, p);
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000111 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000112 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000113 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000114 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000115
Guido van Rossuma027efa1997-05-05 20:56:21 +0000116 interp = PyInterpreterState_New();
117 if (interp == NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000118 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000119
Guido van Rossuma027efa1997-05-05 20:56:21 +0000120 tstate = PyThreadState_New(interp);
121 if (tstate == NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000122 Py_FatalError("Py_Initialize: can't make first thread");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000123 (void) PyThreadState_Swap(tstate);
124
Guido van Rossum70d893a2001-08-16 08:21:42 +0000125 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000126
Neal Norwitzb2501f42002-12-31 03:42:13 +0000127 if (!_PyFrame_Init())
Neal Norwitzc91ed402002-12-30 22:29:22 +0000128 Py_FatalError("Py_Initialize: can't init frames");
129
Neal Norwitzb2501f42002-12-31 03:42:13 +0000130 if (!_PyInt_Init())
Neal Norwitzc91ed402002-12-30 22:29:22 +0000131 Py_FatalError("Py_Initialize: can't init ints");
132
Guido van Rossum25ce5661997-08-02 03:10:38 +0000133 interp->modules = PyDict_New();
134 if (interp->modules == NULL)
135 Py_FatalError("Py_Initialize: can't make modules dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000136
Guido van Rossumc94044c2000-03-10 23:03:54 +0000137 /* Init codec registry */
138 _PyCodecRegistry_Init();
139
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000140#ifdef Py_USING_UNICODE
Guido van Rossumc94044c2000-03-10 23:03:54 +0000141 /* Init Unicode implementation; relies on the codec registry */
142 _PyUnicode_Init();
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000143#endif
Guido van Rossumc94044c2000-03-10 23:03:54 +0000144
Barry Warsawf242aa02000-05-25 23:09:49 +0000145 bimod = _PyBuiltin_Init();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000146 if (bimod == NULL)
147 Py_FatalError("Py_Initialize: can't initialize __builtin__");
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000148 interp->builtins = PyModule_GetDict(bimod);
149 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000150
151 sysmod = _PySys_Init();
152 if (sysmod == NULL)
153 Py_FatalError("Py_Initialize: can't initialize sys");
154 interp->sysdict = PyModule_GetDict(sysmod);
155 Py_INCREF(interp->sysdict);
156 _PyImport_FixupExtension("sys", "sys");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000157 PySys_SetPath(Py_GetPath());
Guido van Rossum25ce5661997-08-02 03:10:38 +0000158 PyDict_SetItemString(interp->sysdict, "modules",
159 interp->modules);
160
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000161 _PyImport_Init();
162
Barry Warsawf242aa02000-05-25 23:09:49 +0000163 /* initialize builtin exceptions */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000164 _PyExc_Init();
Barry Warsaw5821bc52001-08-13 23:04:56 +0000165 _PyImport_FixupExtension("exceptions", "exceptions");
Barry Warsawf242aa02000-05-25 23:09:49 +0000166
Barry Warsaw035574d1997-08-29 22:07:17 +0000167 /* phase 2 of builtins */
Barry Warsaw963b8711997-09-18 16:42:02 +0000168 _PyImport_FixupExtension("__builtin__", "__builtin__");
Barry Warsaw035574d1997-08-29 22:07:17 +0000169
Just van Rossum52e14d62002-12-30 22:08:05 +0000170 _PyImportHooks_Init();
171
Guido van Rossum25ce5661997-08-02 03:10:38 +0000172 initsigs(); /* Signal handling stuff, including initintr() */
173
174 initmain(); /* Module __main__ */
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000175 if (!Py_NoSiteFlag)
176 initsite(); /* Module site */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000177}
178
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000179#ifdef COUNT_ALLOCS
Tim Petersdbd9ba62000-07-09 03:09:57 +0000180extern void dump_counts(void);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000181#endif
182
Guido van Rossum25ce5661997-08-02 03:10:38 +0000183/* Undo the effect of Py_Initialize().
184
185 Beware: if multiple interpreter and/or thread states exist, these
186 are not wiped out; only the current thread and interpreter state
187 are deleted. But since everything else is deleted, those other
188 interpreter and thread states should no longer be used.
189
190 (XXX We should do better, e.g. wipe out all interpreters and
191 threads.)
192
193 Locking: as above.
194
195*/
196
197void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000198Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000199{
200 PyInterpreterState *interp;
201 PyThreadState *tstate;
202
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000203 if (!initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +0000204 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000205
Tim Peters384fd102001-01-21 03:40:37 +0000206 /* The interpreter is still entirely intact at this point, and the
207 * exit funcs may be relying on that. In particular, if some thread
208 * or exit func is still waiting to do an import, the import machinery
209 * expects Py_IsInitialized() to return true. So don't say the
210 * interpreter is uninitialized until after the exit funcs have run.
211 * Note that Threading.py uses an exit func to do a join on all the
212 * threads created thru it, so this also protects pending imports in
213 * the threads created via Threading.
214 */
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000215 call_sys_exitfunc();
Tim Peters384fd102001-01-21 03:40:37 +0000216 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000217
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000218 /* Get current thread state and interpreter pointer */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000219 tstate = PyThreadState_Get();
220 interp = tstate->interp;
221
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000222 /* Disable signal handling */
223 PyOS_FiniInterrupts();
224
Guido van Rossumc94044c2000-03-10 23:03:54 +0000225 /* Cleanup Codec registry */
226 _PyCodecRegistry_Fini();
227
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000228 /* Destroy all modules */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000229 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000230
Guido van Rossum1707aad1997-12-08 23:43:45 +0000231 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
232 _PyImport_Fini();
233
234 /* Debugging stuff */
235#ifdef COUNT_ALLOCS
236 dump_counts();
237#endif
238
239#ifdef Py_REF_DEBUG
240 fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
241#endif
242
243#ifdef Py_TRACE_REFS
Guido van Rossum92e2d5c2001-08-09 16:37:16 +0000244 if (Py_GETENV("PYTHONDUMPREFS")) {
Guido van Rossum1707aad1997-12-08 23:43:45 +0000245 _Py_PrintReferences(stderr);
246 }
247#endif /* Py_TRACE_REFS */
248
Barry Warsaw035574d1997-08-29 22:07:17 +0000249 /* Now we decref the exception classes. After this point nothing
250 can raise an exception. That's okay, because each Fini() method
251 below has been checked to make sure no exceptions are ever
252 raised.
253 */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000254 _PyExc_Fini();
Barry Warsawf242aa02000-05-25 23:09:49 +0000255
256 /* Delete current thread */
257 PyInterpreterState_Clear(interp);
258 PyThreadState_Swap(NULL);
259 PyInterpreterState_Delete(interp);
260
Guido van Rossumcc283f51997-08-05 02:22:03 +0000261 PyMethod_Fini();
262 PyFrame_Fini();
263 PyCFunction_Fini();
264 PyTuple_Fini();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000265 PyString_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000266 PyInt_Fini();
267 PyFloat_Fini();
268
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000269#ifdef Py_USING_UNICODE
270 /* Cleanup Unicode implementation */
271 _PyUnicode_Fini();
272#endif
273
Guido van Rossumcc283f51997-08-05 02:22:03 +0000274 /* XXX Still allocated:
275 - various static ad-hoc pointers to interned strings
276 - int and float free list blocks
277 - whatever various modules and libraries allocate
278 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000279
280 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000281
Tim Peters0e871182002-04-13 08:29:14 +0000282#ifdef PYMALLOC_DEBUG
283 if (Py_GETENV("PYTHONMALLOCSTATS"))
284 _PyObject_DebugMallocStats();
285#endif
286
Guido van Rossumcc283f51997-08-05 02:22:03 +0000287 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000288}
289
290/* Create and initialize a new interpreter and thread, and return the
291 new thread. This requires that Py_Initialize() has been called
292 first.
293
294 Unsuccessful initialization yields a NULL pointer. Note that *no*
295 exception information is available even in this case -- the
296 exception information is held in the thread, and there is no
297 thread.
298
299 Locking: as above.
300
301*/
302
303PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000304Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000305{
306 PyInterpreterState *interp;
307 PyThreadState *tstate, *save_tstate;
308 PyObject *bimod, *sysmod;
309
310 if (!initialized)
311 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
312
313 interp = PyInterpreterState_New();
314 if (interp == NULL)
315 return NULL;
316
317 tstate = PyThreadState_New(interp);
318 if (tstate == NULL) {
319 PyInterpreterState_Delete(interp);
320 return NULL;
321 }
322
323 save_tstate = PyThreadState_Swap(tstate);
324
325 /* XXX The following is lax in error checking */
326
327 interp->modules = PyDict_New();
328
329 bimod = _PyImport_FindExtension("__builtin__", "__builtin__");
330 if (bimod != NULL) {
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000331 interp->builtins = PyModule_GetDict(bimod);
332 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000333 }
334 sysmod = _PyImport_FindExtension("sys", "sys");
335 if (bimod != NULL && sysmod != NULL) {
336 interp->sysdict = PyModule_GetDict(sysmod);
337 Py_INCREF(interp->sysdict);
338 PySys_SetPath(Py_GetPath());
339 PyDict_SetItemString(interp->sysdict, "modules",
340 interp->modules);
Martin v. Löwisd7ceb222003-01-22 09:00:38 +0000341 _PyImportHooks_Init();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000342 initmain();
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000343 if (!Py_NoSiteFlag)
344 initsite();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000345 }
346
347 if (!PyErr_Occurred())
348 return tstate;
349
350 /* Oops, it didn't work. Undo it all. */
351
352 PyErr_Print();
353 PyThreadState_Clear(tstate);
354 PyThreadState_Swap(save_tstate);
355 PyThreadState_Delete(tstate);
356 PyInterpreterState_Delete(interp);
357
358 return NULL;
359}
360
361/* Delete an interpreter and its last thread. This requires that the
362 given thread state is current, that the thread has no remaining
363 frames, and that it is its interpreter's only remaining thread.
364 It is a fatal error to violate these constraints.
365
366 (Py_Finalize() doesn't have these constraints -- it zaps
367 everything, regardless.)
368
369 Locking: as above.
370
371*/
372
373void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000374Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000375{
376 PyInterpreterState *interp = tstate->interp;
377
378 if (tstate != PyThreadState_Get())
379 Py_FatalError("Py_EndInterpreter: thread is not current");
380 if (tstate->frame != NULL)
381 Py_FatalError("Py_EndInterpreter: thread still has a frame");
382 if (tstate != interp->tstate_head || tstate->next != NULL)
383 Py_FatalError("Py_EndInterpreter: not the last thread");
384
385 PyImport_Cleanup();
386 PyInterpreterState_Clear(interp);
387 PyThreadState_Swap(NULL);
388 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000389}
390
391static char *progname = "python";
392
393void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000394Py_SetProgramName(char *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000395{
396 if (pn && *pn)
397 progname = pn;
398}
399
400char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000401Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000402{
403 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000404}
405
Guido van Rossuma61691e1998-02-06 22:27:24 +0000406static char *default_home = NULL;
407
408void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000409Py_SetPythonHome(char *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000410{
411 default_home = home;
412}
413
414char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000415Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000416{
417 char *home = default_home;
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000418 if (home == NULL && !Py_IgnoreEnvironmentFlag)
419 home = Py_GETENV("PYTHONHOME");
Guido van Rossuma61691e1998-02-06 22:27:24 +0000420 return home;
421}
422
Guido van Rossum6135a871995-01-09 17:53:26 +0000423/* Create __main__ module */
424
425static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000426initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000427{
Guido van Rossum82598051997-03-05 00:20:32 +0000428 PyObject *m, *d;
429 m = PyImport_AddModule("__main__");
Guido van Rossum6135a871995-01-09 17:53:26 +0000430 if (m == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +0000431 Py_FatalError("can't create __main__ module");
432 d = PyModule_GetDict(m);
433 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
Guido van Rossum858cb731997-11-19 16:15:37 +0000434 PyObject *bimod = PyImport_ImportModule("__builtin__");
435 if (bimod == NULL ||
436 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
Guido van Rossum82598051997-03-05 00:20:32 +0000437 Py_FatalError("can't add __builtins__ to __main__");
Barry Warsaw3d05b1a1999-01-29 21:30:22 +0000438 Py_DECREF(bimod);
Guido van Rossum6135a871995-01-09 17:53:26 +0000439 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000440}
441
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000442/* Import the site module (not into __main__ though) */
443
444static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000445initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000446{
447 PyObject *m, *f;
448 m = PyImport_ImportModule("site");
449 if (m == NULL) {
450 f = PySys_GetObject("stderr");
451 if (Py_VerboseFlag) {
452 PyFile_WriteString(
453 "'import site' failed; traceback:\n", f);
454 PyErr_Print();
455 }
456 else {
457 PyFile_WriteString(
458 "'import site' failed; use -v for traceback\n", f);
459 PyErr_Clear();
460 }
461 }
462 else {
463 Py_DECREF(m);
464 }
465}
466
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000467/* Parse input from a file and execute it */
468
469int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000470PyRun_AnyFile(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000471{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000472 return PyRun_AnyFileExFlags(fp, filename, 0, NULL);
473}
474
475int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000476PyRun_AnyFileFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000477{
478 return PyRun_AnyFileExFlags(fp, filename, 0, flags);
Guido van Rossum0df002c2000-08-27 19:21:52 +0000479}
480
481int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000482PyRun_AnyFileEx(FILE *fp, const char *filename, int closeit)
Guido van Rossum0df002c2000-08-27 19:21:52 +0000483{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000484 return PyRun_AnyFileExFlags(fp, filename, closeit, NULL);
485}
486
487int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000488PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000489 PyCompilerFlags *flags)
490{
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000491 if (filename == NULL)
492 filename = "???";
Guido van Rossum0df002c2000-08-27 19:21:52 +0000493 if (Py_FdIsInteractive(fp, filename)) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000494 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
Guido van Rossum0df002c2000-08-27 19:21:52 +0000495 if (closeit)
496 fclose(fp);
497 return err;
498 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000499 else
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000500 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000501}
502
503int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000504PyRun_InteractiveLoop(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000505{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000506 return PyRun_InteractiveLoopFlags(fp, filename, NULL);
507}
508
509int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000510PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000511{
Guido van Rossum82598051997-03-05 00:20:32 +0000512 PyObject *v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000513 int ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000514 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000515
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000516 if (flags == NULL) {
517 flags = &local_flags;
Tim Peters5ba58662001-07-16 02:29:45 +0000518 local_flags.cf_flags = 0;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000519 }
Guido van Rossum82598051997-03-05 00:20:32 +0000520 v = PySys_GetObject("ps1");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000521 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000522 PySys_SetObject("ps1", v = PyString_FromString(">>> "));
523 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000524 }
Guido van Rossum82598051997-03-05 00:20:32 +0000525 v = PySys_GetObject("ps2");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000526 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000527 PySys_SetObject("ps2", v = PyString_FromString("... "));
528 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000529 }
530 for (;;) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000531 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
Guido van Rossumaae0d321996-05-22 16:35:33 +0000532#ifdef Py_REF_DEBUG
Guido van Rossum6f9e4331995-03-29 16:57:48 +0000533 fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000534#endif
535 if (ret == E_EOF)
536 return 0;
537 /*
538 if (ret == E_NOMEM)
539 return -1;
540 */
541 }
542}
543
544int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000545PyRun_InteractiveOne(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000546{
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000547 return PyRun_InteractiveOneFlags(fp, filename, NULL);
548}
549
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000550/* compute parser flags based on compiler flags */
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000551#define PARSER_FLAGS(flags) \
Guido van Rossum4b499dd32003-02-13 22:07:59 +0000552 (((flags) && (flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
553 PyPARSE_DONT_IMPLY_DEDENT : 0)
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000554
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000555int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000556PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000557{
Guido van Rossum82598051997-03-05 00:20:32 +0000558 PyObject *m, *d, *v, *w;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000559 node *n;
Guido van Rossuma110aa61994-08-29 12:50:44 +0000560 perrdetail err;
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000561 char *ps1 = "", *ps2 = "";
Tim Petersfe2127d2001-07-16 05:37:24 +0000562
Guido van Rossum82598051997-03-05 00:20:32 +0000563 v = PySys_GetObject("ps1");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000564 if (v != NULL) {
565 v = PyObject_Str(v);
566 if (v == NULL)
567 PyErr_Clear();
568 else if (PyString_Check(v))
569 ps1 = PyString_AsString(v);
570 }
Guido van Rossum82598051997-03-05 00:20:32 +0000571 w = PySys_GetObject("ps2");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000572 if (w != NULL) {
573 w = PyObject_Str(w);
574 if (w == NULL)
575 PyErr_Clear();
576 else if (PyString_Check(w))
577 ps2 = PyString_AsString(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000578 }
Tim Petersfe2127d2001-07-16 05:37:24 +0000579 n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar,
580 Py_single_input, ps1, ps2, &err,
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000581 PARSER_FLAGS(flags));
Guido van Rossum82598051997-03-05 00:20:32 +0000582 Py_XDECREF(v);
583 Py_XDECREF(w);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000584 if (n == NULL) {
585 if (err.error == E_EOF) {
586 if (err.text)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000587 PyMem_DEL(err.text);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000588 return E_EOF;
589 }
590 err_input(&err);
Guido van Rossum82598051997-03-05 00:20:32 +0000591 PyErr_Print();
Guido van Rossuma110aa61994-08-29 12:50:44 +0000592 return err.error;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000593 }
Guido van Rossum82598051997-03-05 00:20:32 +0000594 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000595 if (m == NULL)
596 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000597 d = PyModule_GetDict(m);
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000598 v = run_node(n, filename, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000599 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000600 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000601 return -1;
602 }
Guido van Rossum82598051997-03-05 00:20:32 +0000603 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000604 if (Py_FlushLine())
605 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000606 return 0;
607}
608
609int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000610PyRun_SimpleFile(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000611{
Guido van Rossum0df002c2000-08-27 19:21:52 +0000612 return PyRun_SimpleFileEx(fp, filename, 0);
613}
614
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000615/* Check whether a file maybe a pyc file: Look at the extension,
616 the file type, and, if we may close it, at the first few bytes. */
617
618static int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000619maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000620{
621 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
622 return 1;
623
624#ifdef macintosh
625 /* On a mac, we also assume a pyc file for types 'PYC ' and 'APPL' */
Jack Jansen72f3b7a2002-12-13 15:23:10 +0000626 if (PyMac_getfiletype((char *)filename) == 'PYC '
627 || PyMac_getfiletype((char *)filename) == 'APPL')
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000628 return 1;
629#endif /* macintosh */
630
631 /* Only look into the file if we are allowed to close it, since
632 it then should also be seekable. */
633 if (closeit) {
634 /* Read only two bytes of the magic. If the file was opened in
635 text mode, the bytes 3 and 4 of the magic (\r\n) might not
636 be read as they are on disk. */
637 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
638 unsigned char buf[2];
Tim Peters3e876562001-02-11 04:35:39 +0000639 /* Mess: In case of -x, the stream is NOT at its start now,
640 and ungetc() was used to push back the first newline,
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000641 which makes the current stream position formally undefined,
642 and a x-platform nightmare.
643 Unfortunately, we have no direct way to know whether -x
644 was specified. So we use a terrible hack: if the current
645 stream position is not 0, we assume -x was specified, and
646 give up. Bug 132850 on SourceForge spells out the
647 hopelessness of trying anything else (fseek and ftell
648 don't work predictably x-platform for text-mode files).
Tim Peters3e876562001-02-11 04:35:39 +0000649 */
Tim Peters3e876562001-02-11 04:35:39 +0000650 int ispyc = 0;
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000651 if (ftell(fp) == 0) {
652 if (fread(buf, 1, 2, fp) == 2 &&
653 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
654 ispyc = 1;
655 rewind(fp);
656 }
Tim Peters3e876562001-02-11 04:35:39 +0000657 return ispyc;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000658 }
659 return 0;
660}
661
Guido van Rossum0df002c2000-08-27 19:21:52 +0000662int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000663PyRun_SimpleFileEx(FILE *fp, const char *filename, int closeit)
Guido van Rossum0df002c2000-08-27 19:21:52 +0000664{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000665 return PyRun_SimpleFileExFlags(fp, filename, closeit, NULL);
666}
667
668int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000669PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000670 PyCompilerFlags *flags)
671{
Guido van Rossum82598051997-03-05 00:20:32 +0000672 PyObject *m, *d, *v;
Martin v. Löwis95292d62002-12-11 14:04:59 +0000673 const char *ext;
Guido van Rossumfdef2711994-09-14 13:31:04 +0000674
Guido van Rossum82598051997-03-05 00:20:32 +0000675 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000676 if (m == NULL)
677 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000678 d = PyModule_GetDict(m);
Fred Drake8ed02042002-10-17 21:24:58 +0000679 if (PyDict_GetItemString(d, "__file__") == NULL) {
680 PyObject *f = PyString_FromString(filename);
681 if (f == NULL)
682 return -1;
683 if (PyDict_SetItemString(d, "__file__", f) < 0) {
684 Py_DECREF(f);
685 return -1;
686 }
687 Py_DECREF(f);
688 }
Guido van Rossumfdef2711994-09-14 13:31:04 +0000689 ext = filename + strlen(filename) - 4;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000690 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Guido van Rossumfdef2711994-09-14 13:31:04 +0000691 /* Try to run a pyc file. First, re-open in binary */
Guido van Rossum0df002c2000-08-27 19:21:52 +0000692 if (closeit)
693 fclose(fp);
Fred Drake8ed02042002-10-17 21:24:58 +0000694 if ((fp = fopen(filename, "rb")) == NULL) {
Guido van Rossumfdef2711994-09-14 13:31:04 +0000695 fprintf(stderr, "python: Can't reopen .pyc file\n");
696 return -1;
697 }
Guido van Rossum2a7f58d1997-04-02 05:28:38 +0000698 /* Turn on optimization if a .pyo file is given */
699 if (strcmp(ext, ".pyo") == 0)
700 Py_OptimizeFlag = 1;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000701 v = run_pyc_file(fp, filename, d, d, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000702 } else {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000703 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
704 closeit, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000705 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000706 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000707 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000708 return -1;
709 }
Guido van Rossum82598051997-03-05 00:20:32 +0000710 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000711 if (Py_FlushLine())
712 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000713 return 0;
714}
715
716int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000717PyRun_SimpleString(const char *command)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000718{
Guido van Rossum393661d2001-08-31 17:40:15 +0000719 return PyRun_SimpleStringFlags(command, NULL);
720}
721
722int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000723PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +0000724{
Guido van Rossum82598051997-03-05 00:20:32 +0000725 PyObject *m, *d, *v;
726 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000727 if (m == NULL)
728 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000729 d = PyModule_GetDict(m);
Guido van Rossum393661d2001-08-31 17:40:15 +0000730 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000731 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000732 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000733 return -1;
734 }
Guido van Rossum82598051997-03-05 00:20:32 +0000735 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000736 if (Py_FlushLine())
737 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000738 return 0;
739}
740
Barry Warsaw035574d1997-08-29 22:07:17 +0000741static int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000742parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
743 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +0000744{
745 long hold;
746 PyObject *v;
747
748 /* old style errors */
749 if (PyTuple_Check(err))
Neal Norwitz78293352002-04-01 01:41:20 +0000750 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
751 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +0000752
753 /* new style errors. `err' is an instance */
754
755 if (! (v = PyObject_GetAttrString(err, "msg")))
756 goto finally;
757 *message = v;
758
759 if (!(v = PyObject_GetAttrString(err, "filename")))
760 goto finally;
761 if (v == Py_None)
762 *filename = NULL;
763 else if (! (*filename = PyString_AsString(v)))
764 goto finally;
765
766 Py_DECREF(v);
767 if (!(v = PyObject_GetAttrString(err, "lineno")))
768 goto finally;
769 hold = PyInt_AsLong(v);
770 Py_DECREF(v);
771 v = NULL;
772 if (hold < 0 && PyErr_Occurred())
773 goto finally;
774 *lineno = (int)hold;
775
776 if (!(v = PyObject_GetAttrString(err, "offset")))
777 goto finally;
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000778 if (v == Py_None) {
779 *offset = -1;
780 Py_DECREF(v);
781 v = NULL;
782 } else {
783 hold = PyInt_AsLong(v);
784 Py_DECREF(v);
785 v = NULL;
786 if (hold < 0 && PyErr_Occurred())
787 goto finally;
788 *offset = (int)hold;
789 }
Barry Warsaw035574d1997-08-29 22:07:17 +0000790
791 if (!(v = PyObject_GetAttrString(err, "text")))
792 goto finally;
793 if (v == Py_None)
794 *text = NULL;
795 else if (! (*text = PyString_AsString(v)))
796 goto finally;
797 Py_DECREF(v);
798 return 1;
799
800finally:
801 Py_XDECREF(v);
802 return 0;
803}
804
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000805void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000806PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000807{
Guido van Rossuma61691e1998-02-06 22:27:24 +0000808 PyErr_PrintEx(1);
809}
810
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000811static void
Martin v. Löwis95292d62002-12-11 14:04:59 +0000812print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000813{
814 char *nl;
815 if (offset >= 0) {
816 if (offset > 0 && offset == (int)strlen(text))
817 offset--;
818 for (;;) {
819 nl = strchr(text, '\n');
820 if (nl == NULL || nl-text >= offset)
821 break;
822 offset -= (nl+1-text);
823 text = nl+1;
824 }
825 while (*text == ' ' || *text == '\t') {
826 text++;
827 offset--;
828 }
829 }
830 PyFile_WriteString(" ", f);
831 PyFile_WriteString(text, f);
832 if (*text == '\0' || text[strlen(text)-1] != '\n')
833 PyFile_WriteString("\n", f);
834 if (offset == -1)
835 return;
836 PyFile_WriteString(" ", f);
837 offset--;
838 while (offset > 0) {
839 PyFile_WriteString(" ", f);
840 offset--;
841 }
842 PyFile_WriteString("^\n", f);
843}
844
Guido van Rossum66e8e862001-03-23 17:54:43 +0000845static void
846handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000847{
Guido van Rossum66e8e862001-03-23 17:54:43 +0000848 PyObject *exception, *value, *tb;
849 PyErr_Fetch(&exception, &value, &tb);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000850 if (Py_FlushLine())
851 PyErr_Clear();
852 fflush(stdout);
853 if (value == NULL || value == Py_None)
854 Py_Exit(0);
855 if (PyInstance_Check(value)) {
856 /* The error code should be in the `code' attribute. */
857 PyObject *code = PyObject_GetAttrString(value, "code");
858 if (code) {
859 Py_DECREF(value);
860 value = code;
861 if (value == Py_None)
862 Py_Exit(0);
863 }
864 /* If we failed to dig out the 'code' attribute,
865 just let the else clause below print the error. */
866 }
867 if (PyInt_Check(value))
868 Py_Exit((int)PyInt_AsLong(value));
869 else {
870 PyObject_Print(value, stderr, Py_PRINT_RAW);
871 PySys_WriteStderr("\n");
872 Py_Exit(1);
873 }
874}
875
876void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000877PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000878{
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000879 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +0000880
881 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
882 handle_system_exit();
883 }
Guido van Rossum82598051997-03-05 00:20:32 +0000884 PyErr_Fetch(&exception, &v, &tb);
Barry Warsaw035574d1997-08-29 22:07:17 +0000885 PyErr_NormalizeException(&exception, &v, &tb);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000886 if (exception == NULL)
Guido van Rossum296b4751997-05-23 00:19:20 +0000887 return;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000888 if (set_sys_last_vars) {
889 PySys_SetObject("last_type", exception);
890 PySys_SetObject("last_value", v);
891 PySys_SetObject("last_traceback", tb);
892 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000893 hook = PySys_GetObject("excepthook");
894 if (hook) {
895 PyObject *args = Py_BuildValue("(OOO)",
896 exception, v ? v : Py_None, tb ? tb : Py_None);
897 PyObject *result = PyEval_CallObject(hook, args);
898 if (result == NULL) {
899 PyObject *exception2, *v2, *tb2;
Guido van Rossum66e8e862001-03-23 17:54:43 +0000900 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
901 handle_system_exit();
902 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000903 PyErr_Fetch(&exception2, &v2, &tb2);
904 PyErr_NormalizeException(&exception2, &v2, &tb2);
905 if (Py_FlushLine())
906 PyErr_Clear();
907 fflush(stdout);
908 PySys_WriteStderr("Error in sys.excepthook:\n");
909 PyErr_Display(exception2, v2, tb2);
910 PySys_WriteStderr("\nOriginal exception was:\n");
911 PyErr_Display(exception, v, tb);
Jeremy Hylton07028582001-12-07 15:35:35 +0000912 Py_XDECREF(exception2);
913 Py_XDECREF(v2);
914 Py_XDECREF(tb2);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000915 }
916 Py_XDECREF(result);
917 Py_XDECREF(args);
918 } else {
919 PySys_WriteStderr("sys.excepthook is missing\n");
920 PyErr_Display(exception, v, tb);
921 }
922 Py_XDECREF(exception);
923 Py_XDECREF(v);
924 Py_XDECREF(tb);
925}
926
927void PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
928{
929 int err = 0;
930 PyObject *v = value;
931 PyObject *f = PySys_GetObject("stderr");
Guido van Rossum3165fe61992-09-25 21:59:05 +0000932 if (f == NULL)
933 fprintf(stderr, "lost sys.stderr\n");
934 else {
Guido van Rossum0829c751998-02-28 04:31:39 +0000935 if (Py_FlushLine())
936 PyErr_Clear();
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000937 fflush(stdout);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000938 if (tb && tb != Py_None)
939 err = PyTraceBack_Print(tb, f);
Barry Warsaw36b8f941997-08-26 18:09:48 +0000940 if (err == 0 &&
Martin v. Löwiscfeb3b62002-03-03 21:30:27 +0000941 PyObject_HasAttrString(v, "print_file_and_line"))
Barry Warsaw36b8f941997-08-26 18:09:48 +0000942 {
Guido van Rossum82598051997-03-05 00:20:32 +0000943 PyObject *message;
Martin v. Löwis95292d62002-12-11 14:04:59 +0000944 const char *filename, *text;
Guido van Rossuma110aa61994-08-29 12:50:44 +0000945 int lineno, offset;
Barry Warsaw035574d1997-08-29 22:07:17 +0000946 if (!parse_syntax_error(v, &message, &filename,
947 &lineno, &offset, &text))
Guido van Rossum82598051997-03-05 00:20:32 +0000948 PyErr_Clear();
Guido van Rossuma110aa61994-08-29 12:50:44 +0000949 else {
950 char buf[10];
Guido van Rossum82598051997-03-05 00:20:32 +0000951 PyFile_WriteString(" File \"", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000952 if (filename == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +0000953 PyFile_WriteString("<string>", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000954 else
Guido van Rossum82598051997-03-05 00:20:32 +0000955 PyFile_WriteString(filename, f);
956 PyFile_WriteString("\", line ", f);
Jeremy Hylton518ab1c2001-11-28 20:42:20 +0000957 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
Guido van Rossum82598051997-03-05 00:20:32 +0000958 PyFile_WriteString(buf, f);
959 PyFile_WriteString("\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000960 if (text != NULL)
961 print_error_text(f, offset, text);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000962 v = message;
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000963 /* Can't be bothered to check all those
964 PyFile_WriteString() calls */
965 if (PyErr_Occurred())
966 err = -1;
Guido van Rossuma110aa61994-08-29 12:50:44 +0000967 }
968 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000969 if (err) {
970 /* Don't do anything else */
971 }
972 else if (PyClass_Check(exception)) {
Barry Warsaw2f5f6a21997-09-16 21:42:03 +0000973 PyClassObject* exc = (PyClassObject*)exception;
974 PyObject* className = exc->cl_name;
975 PyObject* moduleName =
976 PyDict_GetItemString(exc->cl_dict, "__module__");
977
978 if (moduleName == NULL)
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000979 err = PyFile_WriteString("<unknown>", f);
Barry Warsaw2f5f6a21997-09-16 21:42:03 +0000980 else {
981 char* modstr = PyString_AsString(moduleName);
982 if (modstr && strcmp(modstr, "exceptions"))
983 {
984 err = PyFile_WriteString(modstr, f);
985 err += PyFile_WriteString(".", f);
986 }
987 }
988 if (err == 0) {
989 if (className == NULL)
990 err = PyFile_WriteString("<unknown>", f);
991 else
992 err = PyFile_WriteObject(className, f,
993 Py_PRINT_RAW);
994 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000995 }
996 else
997 err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
998 if (err == 0) {
999 if (v != NULL && v != Py_None) {
Barry Warsaw035574d1997-08-29 22:07:17 +00001000 PyObject *s = PyObject_Str(v);
1001 /* only print colon if the str() of the
1002 object is not the empty string
1003 */
Guido van Rossumd6bf45b1997-09-05 19:11:53 +00001004 if (s == NULL)
1005 err = -1;
1006 else if (!PyString_Check(s) ||
1007 PyString_GET_SIZE(s) != 0)
Barry Warsaw035574d1997-08-29 22:07:17 +00001008 err = PyFile_WriteString(": ", f);
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001009 if (err == 0)
Guido van Rossumd6bf45b1997-09-05 19:11:53 +00001010 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1011 Py_XDECREF(s);
Guido van Rossum262e1241995-02-07 15:30:45 +00001012 }
Guido van Rossum262e1241995-02-07 15:30:45 +00001013 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001014 if (err == 0)
1015 err = PyFile_WriteString("\n", f);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001016 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001017 /* If an error happened here, don't show it.
1018 XXX This is wrong, but too many callers rely on this behavior. */
1019 if (err != 0)
1020 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001021}
1022
Guido van Rossum82598051997-03-05 00:20:32 +00001023PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001024PyRun_String(const char *str, int start, PyObject *globals, PyObject *locals)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001025{
Guido van Rossum82598051997-03-05 00:20:32 +00001026 return run_err_node(PyParser_SimpleParseString(str, start),
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001027 "<string>", globals, locals, NULL);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001028}
1029
Guido van Rossum82598051997-03-05 00:20:32 +00001030PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001031PyRun_File(FILE *fp, const char *filename, int start, PyObject *globals,
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001032 PyObject *locals)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001033{
Tim Peterse8682112000-08-27 20:18:17 +00001034 return PyRun_FileEx(fp, filename, start, globals, locals, 0);
Guido van Rossum0df002c2000-08-27 19:21:52 +00001035}
1036
1037PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001038PyRun_FileEx(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001039 PyObject *locals, int closeit)
Guido van Rossum0df002c2000-08-27 19:21:52 +00001040{
1041 node *n = PyParser_SimpleParseFile(fp, filename, start);
1042 if (closeit)
1043 fclose(fp);
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001044 return run_err_node(n, filename, globals, locals, NULL);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001045}
1046
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001047PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001048PyRun_StringFlags(const char *str, int start, PyObject *globals, PyObject *locals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001049 PyCompilerFlags *flags)
1050{
Guido van Rossuma1b3a472001-07-16 16:51:33 +00001051 return run_err_node(PyParser_SimpleParseStringFlags(
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001052 str, start, PARSER_FLAGS(flags)),
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001053 "<string>", globals, locals, flags);
1054}
1055
1056PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001057PyRun_FileFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001058 PyObject *locals, PyCompilerFlags *flags)
1059{
1060 return PyRun_FileExFlags(fp, filename, start, globals, locals, 0,
1061 flags);
1062}
1063
1064PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001065PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001066 PyObject *locals, int closeit, PyCompilerFlags *flags)
1067{
Tim Petersfe2127d2001-07-16 05:37:24 +00001068 node *n = PyParser_SimpleParseFileFlags(fp, filename, start,
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001069 PARSER_FLAGS(flags));
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001070 if (closeit)
1071 fclose(fp);
1072 return run_err_node(n, filename, globals, locals, flags);
1073}
1074
Guido van Rossum82598051997-03-05 00:20:32 +00001075static PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001076run_err_node(node *n, const char *filename, PyObject *globals, PyObject *locals,
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001077 PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001078{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001079 if (n == NULL)
1080 return NULL;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001081 return run_node(n, filename, globals, locals, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001082}
1083
Guido van Rossum82598051997-03-05 00:20:32 +00001084static PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001085run_node(node *n, const char *filename, PyObject *globals, PyObject *locals,
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001086 PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001087{
Guido van Rossum82598051997-03-05 00:20:32 +00001088 PyCodeObject *co;
1089 PyObject *v;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001090 co = PyNode_CompileFlags(n, filename, flags);
Guido van Rossum82598051997-03-05 00:20:32 +00001091 PyNode_Free(n);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001092 if (co == NULL)
1093 return NULL;
Guido van Rossum82598051997-03-05 00:20:32 +00001094 v = PyEval_EvalCode(co, globals, locals);
1095 Py_DECREF(co);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001096 return v;
1097}
1098
Guido van Rossum82598051997-03-05 00:20:32 +00001099static PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001100run_pyc_file(FILE *fp, const char *filename, PyObject *globals, PyObject *locals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001101 PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001102{
Guido van Rossum82598051997-03-05 00:20:32 +00001103 PyCodeObject *co;
1104 PyObject *v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001105 long magic;
Fred Drakee8de31c2000-08-31 05:38:39 +00001106 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001107
Guido van Rossum82598051997-03-05 00:20:32 +00001108 magic = PyMarshal_ReadLongFromFile(fp);
1109 if (magic != PyImport_GetMagicNumber()) {
1110 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001111 "Bad magic number in .pyc file");
1112 return NULL;
1113 }
Guido van Rossum82598051997-03-05 00:20:32 +00001114 (void) PyMarshal_ReadLongFromFile(fp);
Tim Petersd9b9ac82001-01-28 00:27:39 +00001115 v = PyMarshal_ReadLastObjectFromFile(fp);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001116 fclose(fp);
Guido van Rossum82598051997-03-05 00:20:32 +00001117 if (v == NULL || !PyCode_Check(v)) {
1118 Py_XDECREF(v);
1119 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001120 "Bad code object in .pyc file");
1121 return NULL;
1122 }
Guido van Rossum82598051997-03-05 00:20:32 +00001123 co = (PyCodeObject *)v;
1124 v = PyEval_EvalCode(co, globals, locals);
Jeremy Hyltonb857ba22001-08-10 21:41:33 +00001125 if (v && flags)
1126 flags->cf_flags |= (co->co_flags & PyCF_MASK);
Guido van Rossum82598051997-03-05 00:20:32 +00001127 Py_DECREF(co);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001128 return v;
1129}
1130
Guido van Rossum82598051997-03-05 00:20:32 +00001131PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001132Py_CompileString(const char *str, const char *filename, int start)
Guido van Rossum5b722181993-03-30 17:46:03 +00001133{
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001134 return Py_CompileStringFlags(str, filename, start, NULL);
1135}
1136
1137PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001138Py_CompileStringFlags(const char *str, const char *filename, int start,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001139 PyCompilerFlags *flags)
1140{
Guido van Rossum5b722181993-03-30 17:46:03 +00001141 node *n;
Guido van Rossum82598051997-03-05 00:20:32 +00001142 PyCodeObject *co;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001143
1144 n = PyParser_SimpleParseStringFlagsFilename(str, filename, start,
1145 PARSER_FLAGS(flags));
Guido van Rossuma110aa61994-08-29 12:50:44 +00001146 if (n == NULL)
Guido van Rossum5b722181993-03-30 17:46:03 +00001147 return NULL;
Jeremy Hylton673a4fd2001-03-26 19:53:38 +00001148 co = PyNode_CompileFlags(n, filename, flags);
Guido van Rossum82598051997-03-05 00:20:32 +00001149 PyNode_Free(n);
1150 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001151}
1152
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001153struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001154Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001155{
1156 node *n;
1157 struct symtable *st;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001158 n = PyParser_SimpleParseStringFlagsFilename(str, filename,
1159 start, 0);
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001160 if (n == NULL)
1161 return NULL;
1162 st = PyNode_CompileSymtable(n, filename);
1163 PyNode_Free(n);
1164 return st;
1165}
1166
Guido van Rossuma110aa61994-08-29 12:50:44 +00001167/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001168
Guido van Rossuma110aa61994-08-29 12:50:44 +00001169node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001170PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001171{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001172 node *n;
1173 perrdetail err;
Tim Petersfe2127d2001-07-16 05:37:24 +00001174 n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar, start,
1175 (char *)0, (char *)0, &err, flags);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001176 if (n == NULL)
1177 err_input(&err);
1178 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001179}
1180
Tim Petersfe2127d2001-07-16 05:37:24 +00001181node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001182PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
Tim Petersfe2127d2001-07-16 05:37:24 +00001183{
1184 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
1185}
1186
Guido van Rossuma110aa61994-08-29 12:50:44 +00001187/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001188
Guido van Rossuma110aa61994-08-29 12:50:44 +00001189node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001190PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001191{
1192 node *n;
1193 perrdetail err;
1194 n = PyParser_ParseStringFlags(str, &_PyParser_Grammar, start, &err,
1195 flags);
1196 if (n == NULL)
1197 err_input(&err);
1198 return n;
1199}
1200
1201node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001202PyParser_SimpleParseString(const char *str, int start)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001203{
Tim Petersfe2127d2001-07-16 05:37:24 +00001204 return PyParser_SimpleParseStringFlags(str, start, 0);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001205}
1206
Thomas Heller6b17abf2002-07-09 09:23:27 +00001207node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001208PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Thomas Heller6b17abf2002-07-09 09:23:27 +00001209 int start, int flags)
1210{
1211 node *n;
1212 perrdetail err;
1213
1214 n = PyParser_ParseStringFlagsFilename(str, filename,
1215 &_PyParser_Grammar,
1216 start, &err, flags);
1217 if (n == NULL)
1218 err_input(&err);
1219 return n;
1220}
1221
1222node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001223PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001224{
1225 return PyParser_SimpleParseStringFlagsFilename(str, filename,
1226 start, 0);
1227}
1228
Guido van Rossuma110aa61994-08-29 12:50:44 +00001229/* Set the error appropriate to the given input error code (see errcode.h) */
1230
1231static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001232err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001233{
Fred Drake85f36392000-07-11 17:53:00 +00001234 PyObject *v, *w, *errtype;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001235 PyObject* u = NULL;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001236 char *msg = NULL;
Fred Drake85f36392000-07-11 17:53:00 +00001237 errtype = PyExc_SyntaxError;
Guido van Rossum82598051997-03-05 00:20:32 +00001238 v = Py_BuildValue("(ziiz)", err->filename,
Guido van Rossuma110aa61994-08-29 12:50:44 +00001239 err->lineno, err->offset, err->text);
1240 if (err->text != NULL) {
Guido van Rossumb18618d2000-05-03 23:44:39 +00001241 PyMem_DEL(err->text);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001242 err->text = NULL;
1243 }
1244 switch (err->error) {
1245 case E_SYNTAX:
Fred Drake85f36392000-07-11 17:53:00 +00001246 errtype = PyExc_IndentationError;
1247 if (err->expected == INDENT)
1248 msg = "expected an indented block";
1249 else if (err->token == INDENT)
1250 msg = "unexpected indent";
1251 else if (err->token == DEDENT)
1252 msg = "unexpected unindent";
1253 else {
1254 errtype = PyExc_SyntaxError;
1255 msg = "invalid syntax";
1256 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001257 break;
1258 case E_TOKEN:
1259 msg = "invalid token";
Guido van Rossuma110aa61994-08-29 12:50:44 +00001260 break;
Skip Montanaro118ec702002-08-15 01:20:16 +00001261 case E_EOFS:
1262 msg = "EOF while scanning triple-quoted string";
1263 break;
1264 case E_EOLS:
1265 msg = "EOL while scanning single-quoted string";
1266 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001267 case E_INTR:
Guido van Rossum82598051997-03-05 00:20:32 +00001268 PyErr_SetNone(PyExc_KeyboardInterrupt);
Barry Warsawc80baa31999-01-27 16:39:40 +00001269 Py_XDECREF(v);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001270 return;
1271 case E_NOMEM:
Guido van Rossum82598051997-03-05 00:20:32 +00001272 PyErr_NoMemory();
Barry Warsawc80baa31999-01-27 16:39:40 +00001273 Py_XDECREF(v);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001274 return;
1275 case E_EOF:
1276 msg = "unexpected EOF while parsing";
1277 break;
Fred Drake85f36392000-07-11 17:53:00 +00001278 case E_TABSPACE:
1279 errtype = PyExc_TabError;
Guido van Rossum560e8ad1998-04-10 19:43:42 +00001280 msg = "inconsistent use of tabs and spaces in indentation";
1281 break;
Jeremy Hylton94988062000-06-20 19:10:44 +00001282 case E_OVERFLOW:
1283 msg = "expression too long";
1284 break;
Fred Drake85f36392000-07-11 17:53:00 +00001285 case E_DEDENT:
1286 errtype = PyExc_IndentationError;
1287 msg = "unindent does not match any outer indentation level";
1288 break;
1289 case E_TOODEEP:
1290 errtype = PyExc_IndentationError;
1291 msg = "too many levels of indentation";
1292 break;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001293 case E_DECODE: { /* XXX */
1294 PyThreadState* tstate = PyThreadState_Get();
1295 PyObject* value = tstate->curexc_value;
1296 if (value != NULL) {
1297 u = PyObject_Repr(value);
1298 if (u != NULL) {
1299 msg = PyString_AsString(u);
1300 break;
1301 }
1302 }
1303 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001304 default:
1305 fprintf(stderr, "error=%d\n", err->error);
1306 msg = "unknown parsing error";
1307 break;
1308 }
Guido van Rossum82598051997-03-05 00:20:32 +00001309 w = Py_BuildValue("(sO)", msg, v);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001310 Py_XDECREF(u);
Guido van Rossum41318302001-03-23 04:01:07 +00001311 Py_XDECREF(v);
Fred Drake85f36392000-07-11 17:53:00 +00001312 PyErr_SetObject(errtype, w);
Guido van Rossum82598051997-03-05 00:20:32 +00001313 Py_XDECREF(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001314}
1315
1316/* Print fatal error message and abort */
1317
1318void
Tim Peters7c321a82002-07-09 02:57:01 +00001319Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001320{
Guido van Rossum83dd6c31994-09-29 09:38:33 +00001321 fprintf(stderr, "Fatal Python error: %s\n", msg);
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001322#ifdef MS_WINDOWS
Guido van Rossum23c94461997-05-22 20:21:30 +00001323 OutputDebugString("Fatal Python error: ");
Guido van Rossuma44823b1995-03-14 15:01:17 +00001324 OutputDebugString(msg);
1325 OutputDebugString("\n");
Guido van Rossum0ba35361998-08-13 13:33:16 +00001326#ifdef _DEBUG
1327 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00001328#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001329#endif /* MS_WINDOWS */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001330 abort();
1331}
1332
1333/* Clean up and exit */
1334
Guido van Rossuma110aa61994-08-29 12:50:44 +00001335#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00001336#include "pythread.h"
Guido van Rossum82598051997-03-05 00:20:32 +00001337int _PyThread_Started = 0; /* Set by threadmodule.c and maybe others */
Guido van Rossumf9f2e821992-08-17 08:59:08 +00001338#endif
1339
Guido van Rossum2dcfc961998-10-01 16:01:57 +00001340#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001341static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00001342static int nexitfuncs = 0;
1343
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001344int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00001345{
1346 if (nexitfuncs >= NEXITFUNCS)
1347 return -1;
1348 exitfuncs[nexitfuncs++] = func;
1349 return 0;
1350}
1351
Guido van Rossumcc283f51997-08-05 02:22:03 +00001352static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001353call_sys_exitfunc(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001354{
Guido van Rossum82598051997-03-05 00:20:32 +00001355 PyObject *exitfunc = PySys_GetObject("exitfunc");
Guido van Rossum59bff391992-09-03 20:28:00 +00001356
1357 if (exitfunc) {
Fred Drake6a12d8d2001-03-23 17:34:02 +00001358 PyObject *res;
Guido van Rossum82598051997-03-05 00:20:32 +00001359 Py_INCREF(exitfunc);
1360 PySys_SetObject("exitfunc", (PyObject *)NULL);
1361 res = PyEval_CallObject(exitfunc, (PyObject *)NULL);
Guido van Rossum59bff391992-09-03 20:28:00 +00001362 if (res == NULL) {
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001363 if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
1364 PySys_WriteStderr("Error in sys.exitfunc:\n");
1365 }
Guido van Rossum82598051997-03-05 00:20:32 +00001366 PyErr_Print();
Guido van Rossum59bff391992-09-03 20:28:00 +00001367 }
Guido van Rossum82598051997-03-05 00:20:32 +00001368 Py_DECREF(exitfunc);
Guido van Rossum59bff391992-09-03 20:28:00 +00001369 }
1370
Guido van Rossum0829c751998-02-28 04:31:39 +00001371 if (Py_FlushLine())
1372 PyErr_Clear();
Guido van Rossumcc283f51997-08-05 02:22:03 +00001373}
Guido van Rossum1662dd51994-09-07 14:38:28 +00001374
Guido van Rossumcc283f51997-08-05 02:22:03 +00001375static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001376call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00001377{
Guido van Rossum1662dd51994-09-07 14:38:28 +00001378 while (nexitfuncs > 0)
1379 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00001380
1381 fflush(stdout);
1382 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001383}
1384
1385void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001386Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001387{
Guido van Rossumcc283f51997-08-05 02:22:03 +00001388 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001389
Jack Jansen66a89771995-10-27 13:22:14 +00001390#ifdef macintosh
1391 PyMac_Exit(sts);
1392#else
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001393 exit(sts);
Jack Jansen66a89771995-10-27 13:22:14 +00001394#endif
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001395}
1396
Guido van Rossumf1dc5661993-07-05 10:31:29 +00001397static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001398initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001399{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001400#ifdef HAVE_SIGNAL_H
1401#ifdef SIGPIPE
1402 signal(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001403#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00001404#ifdef SIGXFZ
1405 signal(SIGXFZ, SIG_IGN);
1406#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00001407#ifdef SIGXFSZ
1408 signal(SIGXFSZ, SIG_IGN);
1409#endif
Guido van Rossuma110aa61994-08-29 12:50:44 +00001410#endif /* HAVE_SIGNAL_H */
Guido van Rossum82598051997-03-05 00:20:32 +00001411 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001412}
1413
Guido van Rossuma110aa61994-08-29 12:50:44 +00001414#ifdef MPW
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001415
1416/* Check for file descriptor connected to interactive device.
1417 Pretend that stdin is always interactive, other files never. */
1418
1419int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001420isatty(int fd)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001421{
1422 return fd == fileno(stdin);
1423}
1424
1425#endif
Guido van Rossum7433b121997-02-14 19:45:36 +00001426
1427/*
1428 * The file descriptor fd is considered ``interactive'' if either
1429 * a) isatty(fd) is TRUE, or
1430 * b) the -i flag was given, and the filename associated with
1431 * the descriptor is NULL or "<stdin>" or "???".
1432 */
1433int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001434Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00001435{
1436 if (isatty((int)fileno(fp)))
1437 return 1;
1438 if (!Py_InteractiveFlag)
1439 return 0;
1440 return (filename == NULL) ||
1441 (strcmp(filename, "<stdin>") == 0) ||
1442 (strcmp(filename, "???") == 0);
1443}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001444
1445
1446#if defined(USE_STACKCHECK)
1447#if defined(WIN32) && defined(_MSC_VER)
1448
1449/* Stack checking for Microsoft C */
1450
1451#include <malloc.h>
1452#include <excpt.h>
1453
Fred Drakee8de31c2000-08-31 05:38:39 +00001454/*
1455 * Return non-zero when we run out of memory on the stack; zero otherwise.
1456 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001457int
Fred Drake399739f2000-08-31 05:52:44 +00001458PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001459{
1460 __try {
Tim Peters92e4dd82002-10-05 01:47:34 +00001461 /* alloca throws a stack overflow exception if there's
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001462 not enough space left on the stack */
Tim Peters92e4dd82002-10-05 01:47:34 +00001463 alloca(PYOS_STACK_MARGIN * sizeof(void*));
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001464 return 0;
1465 } __except (EXCEPTION_EXECUTE_HANDLER) {
1466 /* just ignore all errors */
1467 }
1468 return 1;
1469}
1470
1471#endif /* WIN32 && _MSC_VER */
1472
1473/* Alternate implementations can be added here... */
1474
1475#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00001476
1477
1478/* Wrappers around sigaction() or signal(). */
1479
1480PyOS_sighandler_t
1481PyOS_getsig(int sig)
1482{
1483#ifdef HAVE_SIGACTION
1484 struct sigaction context;
Barry Warsawafeb2a42001-11-13 23:08:26 +00001485 /* Initialize context.sa_handler to SIG_ERR which makes about as
1486 * much sense as anything else. It should get overwritten if
1487 * sigaction actually succeeds and otherwise we avoid an
1488 * uninitialized memory read.
1489 */
1490 context.sa_handler = SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00001491 sigaction(sig, NULL, &context);
1492 return context.sa_handler;
1493#else
1494 PyOS_sighandler_t handler;
1495 handler = signal(sig, SIG_IGN);
1496 signal(sig, handler);
1497 return handler;
1498#endif
1499}
1500
1501PyOS_sighandler_t
1502PyOS_setsig(int sig, PyOS_sighandler_t handler)
1503{
1504#ifdef HAVE_SIGACTION
1505 struct sigaction context;
1506 PyOS_sighandler_t oldhandler;
Barry Warsawafeb2a42001-11-13 23:08:26 +00001507 /* Initialize context.sa_handler to SIG_ERR which makes about as
1508 * much sense as anything else. It should get overwritten if
1509 * sigaction actually succeeds and otherwise we avoid an
1510 * uninitialized memory read.
1511 */
1512 context.sa_handler = SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00001513 sigaction(sig, NULL, &context);
1514 oldhandler = context.sa_handler;
1515 context.sa_handler = handler;
1516 sigaction(sig, &context, NULL);
1517 return oldhandler;
1518#else
1519 return signal(sig, handler);
1520#endif
1521}