blob: fdbd19f187666eb0739fb39a520b9a2603139f31 [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
Barry Warsaw035574d1997-08-29 22:07:17 +0000273 /* Now we decref the exception classes. After this point nothing
274 can raise an exception. That's okay, because each Fini() method
275 below has been checked to make sure no exceptions are ever
276 raised.
277 */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000278 _PyExc_Fini();
Barry Warsawf242aa02000-05-25 23:09:49 +0000279
Guido van Rossumd922fa42003-04-15 14:10:09 +0000280 /* Clear interpreter state */
Barry Warsawf242aa02000-05-25 23:09:49 +0000281 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000282
283#ifdef Py_TRACE_REFS
284 /* Dump references -- this may implicitly need the thread state,
285 so this is the last possible place where we can do this. */
286 if (Py_GETENV("PYTHONDUMPREFS")) {
287 _Py_PrintReferences(stderr);
288 }
289#endif /* Py_TRACE_REFS */
290
291 /* Delete current thread */
Barry Warsawf242aa02000-05-25 23:09:49 +0000292 PyThreadState_Swap(NULL);
293 PyInterpreterState_Delete(interp);
294
Guido van Rossumd922fa42003-04-15 14:10:09 +0000295 /* Sundry finalizers */
Guido van Rossumcc283f51997-08-05 02:22:03 +0000296 PyMethod_Fini();
297 PyFrame_Fini();
298 PyCFunction_Fini();
299 PyTuple_Fini();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000300 PyString_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000301 PyInt_Fini();
302 PyFloat_Fini();
303
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000304#ifdef Py_USING_UNICODE
305 /* Cleanup Unicode implementation */
306 _PyUnicode_Fini();
307#endif
308
Guido van Rossumcc283f51997-08-05 02:22:03 +0000309 /* XXX Still allocated:
310 - various static ad-hoc pointers to interned strings
311 - int and float free list blocks
312 - whatever various modules and libraries allocate
313 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000314
315 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000316
Tim Peters0e871182002-04-13 08:29:14 +0000317#ifdef PYMALLOC_DEBUG
318 if (Py_GETENV("PYTHONMALLOCSTATS"))
319 _PyObject_DebugMallocStats();
320#endif
321
Guido van Rossumcc283f51997-08-05 02:22:03 +0000322 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000323}
324
325/* Create and initialize a new interpreter and thread, and return the
326 new thread. This requires that Py_Initialize() has been called
327 first.
328
329 Unsuccessful initialization yields a NULL pointer. Note that *no*
330 exception information is available even in this case -- the
331 exception information is held in the thread, and there is no
332 thread.
333
334 Locking: as above.
335
336*/
337
338PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000339Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000340{
341 PyInterpreterState *interp;
342 PyThreadState *tstate, *save_tstate;
343 PyObject *bimod, *sysmod;
344
345 if (!initialized)
346 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
347
348 interp = PyInterpreterState_New();
349 if (interp == NULL)
350 return NULL;
351
352 tstate = PyThreadState_New(interp);
353 if (tstate == NULL) {
354 PyInterpreterState_Delete(interp);
355 return NULL;
356 }
357
358 save_tstate = PyThreadState_Swap(tstate);
359
360 /* XXX The following is lax in error checking */
361
362 interp->modules = PyDict_New();
363
364 bimod = _PyImport_FindExtension("__builtin__", "__builtin__");
365 if (bimod != NULL) {
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000366 interp->builtins = PyModule_GetDict(bimod);
367 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000368 }
369 sysmod = _PyImport_FindExtension("sys", "sys");
370 if (bimod != NULL && sysmod != NULL) {
371 interp->sysdict = PyModule_GetDict(sysmod);
372 Py_INCREF(interp->sysdict);
373 PySys_SetPath(Py_GetPath());
374 PyDict_SetItemString(interp->sysdict, "modules",
375 interp->modules);
Martin v. Löwisd7ceb222003-01-22 09:00:38 +0000376 _PyImportHooks_Init();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000377 initmain();
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000378 if (!Py_NoSiteFlag)
379 initsite();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000380 }
381
382 if (!PyErr_Occurred())
383 return tstate;
384
385 /* Oops, it didn't work. Undo it all. */
386
387 PyErr_Print();
388 PyThreadState_Clear(tstate);
389 PyThreadState_Swap(save_tstate);
390 PyThreadState_Delete(tstate);
391 PyInterpreterState_Delete(interp);
392
393 return NULL;
394}
395
396/* Delete an interpreter and its last thread. This requires that the
397 given thread state is current, that the thread has no remaining
398 frames, and that it is its interpreter's only remaining thread.
399 It is a fatal error to violate these constraints.
400
401 (Py_Finalize() doesn't have these constraints -- it zaps
402 everything, regardless.)
403
404 Locking: as above.
405
406*/
407
408void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000409Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000410{
411 PyInterpreterState *interp = tstate->interp;
412
413 if (tstate != PyThreadState_Get())
414 Py_FatalError("Py_EndInterpreter: thread is not current");
415 if (tstate->frame != NULL)
416 Py_FatalError("Py_EndInterpreter: thread still has a frame");
417 if (tstate != interp->tstate_head || tstate->next != NULL)
418 Py_FatalError("Py_EndInterpreter: not the last thread");
419
420 PyImport_Cleanup();
421 PyInterpreterState_Clear(interp);
422 PyThreadState_Swap(NULL);
423 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000424}
425
426static char *progname = "python";
427
428void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000429Py_SetProgramName(char *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000430{
431 if (pn && *pn)
432 progname = pn;
433}
434
435char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000436Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000437{
438 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000439}
440
Guido van Rossuma61691e1998-02-06 22:27:24 +0000441static char *default_home = NULL;
442
443void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000444Py_SetPythonHome(char *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000445{
446 default_home = home;
447}
448
449char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000450Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000451{
452 char *home = default_home;
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000453 if (home == NULL && !Py_IgnoreEnvironmentFlag)
454 home = Py_GETENV("PYTHONHOME");
Guido van Rossuma61691e1998-02-06 22:27:24 +0000455 return home;
456}
457
Guido van Rossum6135a871995-01-09 17:53:26 +0000458/* Create __main__ module */
459
460static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000461initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000462{
Guido van Rossum82598051997-03-05 00:20:32 +0000463 PyObject *m, *d;
464 m = PyImport_AddModule("__main__");
Guido van Rossum6135a871995-01-09 17:53:26 +0000465 if (m == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +0000466 Py_FatalError("can't create __main__ module");
467 d = PyModule_GetDict(m);
468 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
Guido van Rossum858cb731997-11-19 16:15:37 +0000469 PyObject *bimod = PyImport_ImportModule("__builtin__");
470 if (bimod == NULL ||
471 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
Guido van Rossum82598051997-03-05 00:20:32 +0000472 Py_FatalError("can't add __builtins__ to __main__");
Barry Warsaw3d05b1a1999-01-29 21:30:22 +0000473 Py_DECREF(bimod);
Guido van Rossum6135a871995-01-09 17:53:26 +0000474 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000475}
476
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000477/* Import the site module (not into __main__ though) */
478
479static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000480initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000481{
482 PyObject *m, *f;
483 m = PyImport_ImportModule("site");
484 if (m == NULL) {
485 f = PySys_GetObject("stderr");
486 if (Py_VerboseFlag) {
487 PyFile_WriteString(
488 "'import site' failed; traceback:\n", f);
489 PyErr_Print();
490 }
491 else {
492 PyFile_WriteString(
493 "'import site' failed; use -v for traceback\n", f);
494 PyErr_Clear();
495 }
496 }
497 else {
498 Py_DECREF(m);
499 }
500}
501
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000502/* Parse input from a file and execute it */
503
504int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000505PyRun_AnyFile(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000506{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000507 return PyRun_AnyFileExFlags(fp, filename, 0, NULL);
508}
509
510int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000511PyRun_AnyFileFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000512{
513 return PyRun_AnyFileExFlags(fp, filename, 0, flags);
Guido van Rossum0df002c2000-08-27 19:21:52 +0000514}
515
516int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000517PyRun_AnyFileEx(FILE *fp, const char *filename, int closeit)
Guido van Rossum0df002c2000-08-27 19:21:52 +0000518{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000519 return PyRun_AnyFileExFlags(fp, filename, closeit, NULL);
520}
521
522int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000523PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000524 PyCompilerFlags *flags)
525{
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000526 if (filename == NULL)
527 filename = "???";
Guido van Rossum0df002c2000-08-27 19:21:52 +0000528 if (Py_FdIsInteractive(fp, filename)) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000529 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
Guido van Rossum0df002c2000-08-27 19:21:52 +0000530 if (closeit)
531 fclose(fp);
532 return err;
533 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000534 else
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000535 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000536}
537
538int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000539PyRun_InteractiveLoop(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000540{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000541 return PyRun_InteractiveLoopFlags(fp, filename, NULL);
542}
543
544int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000545PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000546{
Guido van Rossum82598051997-03-05 00:20:32 +0000547 PyObject *v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000548 int ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000549 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000550
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000551 if (flags == NULL) {
552 flags = &local_flags;
Tim Peters5ba58662001-07-16 02:29:45 +0000553 local_flags.cf_flags = 0;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000554 }
Guido van Rossum82598051997-03-05 00:20:32 +0000555 v = PySys_GetObject("ps1");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000556 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000557 PySys_SetObject("ps1", v = PyString_FromString(">>> "));
558 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000559 }
Guido van Rossum82598051997-03-05 00:20:32 +0000560 v = PySys_GetObject("ps2");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000561 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000562 PySys_SetObject("ps2", v = PyString_FromString("... "));
563 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000564 }
565 for (;;) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000566 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
Guido van Rossumaae0d321996-05-22 16:35:33 +0000567#ifdef Py_REF_DEBUG
Guido van Rossum6f9e4331995-03-29 16:57:48 +0000568 fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000569#endif
570 if (ret == E_EOF)
571 return 0;
572 /*
573 if (ret == E_NOMEM)
574 return -1;
575 */
576 }
577}
578
579int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000580PyRun_InteractiveOne(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000581{
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000582 return PyRun_InteractiveOneFlags(fp, filename, NULL);
583}
584
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000585/* compute parser flags based on compiler flags */
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000586#define PARSER_FLAGS(flags) \
Guido van Rossum4b499dd32003-02-13 22:07:59 +0000587 (((flags) && (flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
588 PyPARSE_DONT_IMPLY_DEDENT : 0)
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000589
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000590int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000591PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000592{
Guido van Rossum82598051997-03-05 00:20:32 +0000593 PyObject *m, *d, *v, *w;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000594 node *n;
Guido van Rossuma110aa61994-08-29 12:50:44 +0000595 perrdetail err;
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000596 char *ps1 = "", *ps2 = "";
Tim Petersfe2127d2001-07-16 05:37:24 +0000597
Guido van Rossum82598051997-03-05 00:20:32 +0000598 v = PySys_GetObject("ps1");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000599 if (v != NULL) {
600 v = PyObject_Str(v);
601 if (v == NULL)
602 PyErr_Clear();
603 else if (PyString_Check(v))
604 ps1 = PyString_AsString(v);
605 }
Guido van Rossum82598051997-03-05 00:20:32 +0000606 w = PySys_GetObject("ps2");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000607 if (w != NULL) {
608 w = PyObject_Str(w);
609 if (w == NULL)
610 PyErr_Clear();
611 else if (PyString_Check(w))
612 ps2 = PyString_AsString(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000613 }
Tim Petersfe2127d2001-07-16 05:37:24 +0000614 n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar,
615 Py_single_input, ps1, ps2, &err,
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000616 PARSER_FLAGS(flags));
Guido van Rossum82598051997-03-05 00:20:32 +0000617 Py_XDECREF(v);
618 Py_XDECREF(w);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000619 if (n == NULL) {
620 if (err.error == E_EOF) {
621 if (err.text)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000622 PyMem_DEL(err.text);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000623 return E_EOF;
624 }
625 err_input(&err);
Guido van Rossum82598051997-03-05 00:20:32 +0000626 PyErr_Print();
Guido van Rossuma110aa61994-08-29 12:50:44 +0000627 return err.error;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000628 }
Guido van Rossum82598051997-03-05 00:20:32 +0000629 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000630 if (m == NULL)
631 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000632 d = PyModule_GetDict(m);
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000633 v = run_node(n, filename, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000634 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000635 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000636 return -1;
637 }
Guido van Rossum82598051997-03-05 00:20:32 +0000638 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000639 if (Py_FlushLine())
640 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000641 return 0;
642}
643
644int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000645PyRun_SimpleFile(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000646{
Guido van Rossum0df002c2000-08-27 19:21:52 +0000647 return PyRun_SimpleFileEx(fp, filename, 0);
648}
649
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000650/* Check whether a file maybe a pyc file: Look at the extension,
651 the file type, and, if we may close it, at the first few bytes. */
652
653static int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000654maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000655{
656 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
657 return 1;
658
659#ifdef macintosh
660 /* On a mac, we also assume a pyc file for types 'PYC ' and 'APPL' */
Jack Jansen72f3b7a2002-12-13 15:23:10 +0000661 if (PyMac_getfiletype((char *)filename) == 'PYC '
662 || PyMac_getfiletype((char *)filename) == 'APPL')
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000663 return 1;
664#endif /* macintosh */
665
666 /* Only look into the file if we are allowed to close it, since
667 it then should also be seekable. */
668 if (closeit) {
669 /* Read only two bytes of the magic. If the file was opened in
670 text mode, the bytes 3 and 4 of the magic (\r\n) might not
671 be read as they are on disk. */
672 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
673 unsigned char buf[2];
Tim Peters3e876562001-02-11 04:35:39 +0000674 /* Mess: In case of -x, the stream is NOT at its start now,
675 and ungetc() was used to push back the first newline,
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000676 which makes the current stream position formally undefined,
677 and a x-platform nightmare.
678 Unfortunately, we have no direct way to know whether -x
679 was specified. So we use a terrible hack: if the current
680 stream position is not 0, we assume -x was specified, and
681 give up. Bug 132850 on SourceForge spells out the
682 hopelessness of trying anything else (fseek and ftell
683 don't work predictably x-platform for text-mode files).
Tim Peters3e876562001-02-11 04:35:39 +0000684 */
Tim Peters3e876562001-02-11 04:35:39 +0000685 int ispyc = 0;
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000686 if (ftell(fp) == 0) {
687 if (fread(buf, 1, 2, fp) == 2 &&
688 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
689 ispyc = 1;
690 rewind(fp);
691 }
Tim Peters3e876562001-02-11 04:35:39 +0000692 return ispyc;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000693 }
694 return 0;
695}
696
Guido van Rossum0df002c2000-08-27 19:21:52 +0000697int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000698PyRun_SimpleFileEx(FILE *fp, const char *filename, int closeit)
Guido van Rossum0df002c2000-08-27 19:21:52 +0000699{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000700 return PyRun_SimpleFileExFlags(fp, filename, closeit, NULL);
701}
702
703int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000704PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000705 PyCompilerFlags *flags)
706{
Guido van Rossum82598051997-03-05 00:20:32 +0000707 PyObject *m, *d, *v;
Martin v. Löwis95292d62002-12-11 14:04:59 +0000708 const char *ext;
Guido van Rossumfdef2711994-09-14 13:31:04 +0000709
Guido van Rossum82598051997-03-05 00:20:32 +0000710 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000711 if (m == NULL)
712 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000713 d = PyModule_GetDict(m);
Fred Drake8ed02042002-10-17 21:24:58 +0000714 if (PyDict_GetItemString(d, "__file__") == NULL) {
715 PyObject *f = PyString_FromString(filename);
716 if (f == NULL)
717 return -1;
718 if (PyDict_SetItemString(d, "__file__", f) < 0) {
719 Py_DECREF(f);
720 return -1;
721 }
722 Py_DECREF(f);
723 }
Guido van Rossumfdef2711994-09-14 13:31:04 +0000724 ext = filename + strlen(filename) - 4;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000725 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Guido van Rossumfdef2711994-09-14 13:31:04 +0000726 /* Try to run a pyc file. First, re-open in binary */
Guido van Rossum0df002c2000-08-27 19:21:52 +0000727 if (closeit)
728 fclose(fp);
Fred Drake8ed02042002-10-17 21:24:58 +0000729 if ((fp = fopen(filename, "rb")) == NULL) {
Guido van Rossumfdef2711994-09-14 13:31:04 +0000730 fprintf(stderr, "python: Can't reopen .pyc file\n");
731 return -1;
732 }
Guido van Rossum2a7f58d1997-04-02 05:28:38 +0000733 /* Turn on optimization if a .pyo file is given */
734 if (strcmp(ext, ".pyo") == 0)
735 Py_OptimizeFlag = 1;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000736 v = run_pyc_file(fp, filename, d, d, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000737 } else {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000738 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
739 closeit, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000740 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000741 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000742 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000743 return -1;
744 }
Guido van Rossum82598051997-03-05 00:20:32 +0000745 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000746 if (Py_FlushLine())
747 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000748 return 0;
749}
750
751int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000752PyRun_SimpleString(const char *command)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000753{
Guido van Rossum393661d2001-08-31 17:40:15 +0000754 return PyRun_SimpleStringFlags(command, NULL);
755}
756
757int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000758PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +0000759{
Guido van Rossum82598051997-03-05 00:20:32 +0000760 PyObject *m, *d, *v;
761 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000762 if (m == NULL)
763 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000764 d = PyModule_GetDict(m);
Guido van Rossum393661d2001-08-31 17:40:15 +0000765 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000766 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000767 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000768 return -1;
769 }
Guido van Rossum82598051997-03-05 00:20:32 +0000770 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000771 if (Py_FlushLine())
772 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000773 return 0;
774}
775
Barry Warsaw035574d1997-08-29 22:07:17 +0000776static int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000777parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
778 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +0000779{
780 long hold;
781 PyObject *v;
782
783 /* old style errors */
784 if (PyTuple_Check(err))
Neal Norwitz78293352002-04-01 01:41:20 +0000785 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
786 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +0000787
788 /* new style errors. `err' is an instance */
789
790 if (! (v = PyObject_GetAttrString(err, "msg")))
791 goto finally;
792 *message = v;
793
794 if (!(v = PyObject_GetAttrString(err, "filename")))
795 goto finally;
796 if (v == Py_None)
797 *filename = NULL;
798 else if (! (*filename = PyString_AsString(v)))
799 goto finally;
800
801 Py_DECREF(v);
802 if (!(v = PyObject_GetAttrString(err, "lineno")))
803 goto finally;
804 hold = PyInt_AsLong(v);
805 Py_DECREF(v);
806 v = NULL;
807 if (hold < 0 && PyErr_Occurred())
808 goto finally;
809 *lineno = (int)hold;
810
811 if (!(v = PyObject_GetAttrString(err, "offset")))
812 goto finally;
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000813 if (v == Py_None) {
814 *offset = -1;
815 Py_DECREF(v);
816 v = NULL;
817 } else {
818 hold = PyInt_AsLong(v);
819 Py_DECREF(v);
820 v = NULL;
821 if (hold < 0 && PyErr_Occurred())
822 goto finally;
823 *offset = (int)hold;
824 }
Barry Warsaw035574d1997-08-29 22:07:17 +0000825
826 if (!(v = PyObject_GetAttrString(err, "text")))
827 goto finally;
828 if (v == Py_None)
829 *text = NULL;
830 else if (! (*text = PyString_AsString(v)))
831 goto finally;
832 Py_DECREF(v);
833 return 1;
834
835finally:
836 Py_XDECREF(v);
837 return 0;
838}
839
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000840void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000841PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000842{
Guido van Rossuma61691e1998-02-06 22:27:24 +0000843 PyErr_PrintEx(1);
844}
845
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000846static void
Martin v. Löwis95292d62002-12-11 14:04:59 +0000847print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000848{
849 char *nl;
850 if (offset >= 0) {
851 if (offset > 0 && offset == (int)strlen(text))
852 offset--;
853 for (;;) {
854 nl = strchr(text, '\n');
855 if (nl == NULL || nl-text >= offset)
856 break;
857 offset -= (nl+1-text);
858 text = nl+1;
859 }
860 while (*text == ' ' || *text == '\t') {
861 text++;
862 offset--;
863 }
864 }
865 PyFile_WriteString(" ", f);
866 PyFile_WriteString(text, f);
867 if (*text == '\0' || text[strlen(text)-1] != '\n')
868 PyFile_WriteString("\n", f);
869 if (offset == -1)
870 return;
871 PyFile_WriteString(" ", f);
872 offset--;
873 while (offset > 0) {
874 PyFile_WriteString(" ", f);
875 offset--;
876 }
877 PyFile_WriteString("^\n", f);
878}
879
Guido van Rossum66e8e862001-03-23 17:54:43 +0000880static void
881handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000882{
Guido van Rossum66e8e862001-03-23 17:54:43 +0000883 PyObject *exception, *value, *tb;
884 PyErr_Fetch(&exception, &value, &tb);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000885 if (Py_FlushLine())
886 PyErr_Clear();
887 fflush(stdout);
888 if (value == NULL || value == Py_None)
889 Py_Exit(0);
890 if (PyInstance_Check(value)) {
891 /* The error code should be in the `code' attribute. */
892 PyObject *code = PyObject_GetAttrString(value, "code");
893 if (code) {
894 Py_DECREF(value);
895 value = code;
896 if (value == Py_None)
897 Py_Exit(0);
898 }
899 /* If we failed to dig out the 'code' attribute,
900 just let the else clause below print the error. */
901 }
902 if (PyInt_Check(value))
903 Py_Exit((int)PyInt_AsLong(value));
904 else {
905 PyObject_Print(value, stderr, Py_PRINT_RAW);
906 PySys_WriteStderr("\n");
907 Py_Exit(1);
908 }
909}
910
911void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000912PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000913{
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000914 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +0000915
916 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
917 handle_system_exit();
918 }
Guido van Rossum82598051997-03-05 00:20:32 +0000919 PyErr_Fetch(&exception, &v, &tb);
Barry Warsaw035574d1997-08-29 22:07:17 +0000920 PyErr_NormalizeException(&exception, &v, &tb);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000921 if (exception == NULL)
Guido van Rossum296b4751997-05-23 00:19:20 +0000922 return;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000923 if (set_sys_last_vars) {
924 PySys_SetObject("last_type", exception);
925 PySys_SetObject("last_value", v);
926 PySys_SetObject("last_traceback", tb);
927 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000928 hook = PySys_GetObject("excepthook");
929 if (hook) {
930 PyObject *args = Py_BuildValue("(OOO)",
931 exception, v ? v : Py_None, tb ? tb : Py_None);
932 PyObject *result = PyEval_CallObject(hook, args);
933 if (result == NULL) {
934 PyObject *exception2, *v2, *tb2;
Guido van Rossum66e8e862001-03-23 17:54:43 +0000935 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
936 handle_system_exit();
937 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000938 PyErr_Fetch(&exception2, &v2, &tb2);
939 PyErr_NormalizeException(&exception2, &v2, &tb2);
940 if (Py_FlushLine())
941 PyErr_Clear();
942 fflush(stdout);
943 PySys_WriteStderr("Error in sys.excepthook:\n");
944 PyErr_Display(exception2, v2, tb2);
945 PySys_WriteStderr("\nOriginal exception was:\n");
946 PyErr_Display(exception, v, tb);
Jeremy Hylton07028582001-12-07 15:35:35 +0000947 Py_XDECREF(exception2);
948 Py_XDECREF(v2);
949 Py_XDECREF(tb2);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000950 }
951 Py_XDECREF(result);
952 Py_XDECREF(args);
953 } else {
954 PySys_WriteStderr("sys.excepthook is missing\n");
955 PyErr_Display(exception, v, tb);
956 }
957 Py_XDECREF(exception);
958 Py_XDECREF(v);
959 Py_XDECREF(tb);
960}
961
962void PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
963{
964 int err = 0;
965 PyObject *v = value;
966 PyObject *f = PySys_GetObject("stderr");
Guido van Rossum3165fe61992-09-25 21:59:05 +0000967 if (f == NULL)
968 fprintf(stderr, "lost sys.stderr\n");
969 else {
Guido van Rossum0829c751998-02-28 04:31:39 +0000970 if (Py_FlushLine())
971 PyErr_Clear();
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000972 fflush(stdout);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000973 if (tb && tb != Py_None)
974 err = PyTraceBack_Print(tb, f);
Barry Warsaw36b8f941997-08-26 18:09:48 +0000975 if (err == 0 &&
Martin v. Löwiscfeb3b62002-03-03 21:30:27 +0000976 PyObject_HasAttrString(v, "print_file_and_line"))
Barry Warsaw36b8f941997-08-26 18:09:48 +0000977 {
Guido van Rossum82598051997-03-05 00:20:32 +0000978 PyObject *message;
Martin v. Löwis95292d62002-12-11 14:04:59 +0000979 const char *filename, *text;
Guido van Rossuma110aa61994-08-29 12:50:44 +0000980 int lineno, offset;
Barry Warsaw035574d1997-08-29 22:07:17 +0000981 if (!parse_syntax_error(v, &message, &filename,
982 &lineno, &offset, &text))
Guido van Rossum82598051997-03-05 00:20:32 +0000983 PyErr_Clear();
Guido van Rossuma110aa61994-08-29 12:50:44 +0000984 else {
985 char buf[10];
Guido van Rossum82598051997-03-05 00:20:32 +0000986 PyFile_WriteString(" File \"", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000987 if (filename == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +0000988 PyFile_WriteString("<string>", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000989 else
Guido van Rossum82598051997-03-05 00:20:32 +0000990 PyFile_WriteString(filename, f);
991 PyFile_WriteString("\", line ", f);
Jeremy Hylton518ab1c2001-11-28 20:42:20 +0000992 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
Guido van Rossum82598051997-03-05 00:20:32 +0000993 PyFile_WriteString(buf, f);
994 PyFile_WriteString("\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000995 if (text != NULL)
996 print_error_text(f, offset, text);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000997 v = message;
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000998 /* Can't be bothered to check all those
999 PyFile_WriteString() calls */
1000 if (PyErr_Occurred())
1001 err = -1;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001002 }
1003 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001004 if (err) {
1005 /* Don't do anything else */
1006 }
1007 else if (PyClass_Check(exception)) {
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001008 PyClassObject* exc = (PyClassObject*)exception;
1009 PyObject* className = exc->cl_name;
1010 PyObject* moduleName =
1011 PyDict_GetItemString(exc->cl_dict, "__module__");
1012
1013 if (moduleName == NULL)
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001014 err = PyFile_WriteString("<unknown>", f);
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001015 else {
1016 char* modstr = PyString_AsString(moduleName);
1017 if (modstr && strcmp(modstr, "exceptions"))
1018 {
1019 err = PyFile_WriteString(modstr, f);
1020 err += PyFile_WriteString(".", f);
1021 }
1022 }
1023 if (err == 0) {
1024 if (className == NULL)
1025 err = PyFile_WriteString("<unknown>", f);
1026 else
1027 err = PyFile_WriteObject(className, f,
1028 Py_PRINT_RAW);
1029 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001030 }
1031 else
1032 err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
1033 if (err == 0) {
1034 if (v != NULL && v != Py_None) {
Barry Warsaw035574d1997-08-29 22:07:17 +00001035 PyObject *s = PyObject_Str(v);
1036 /* only print colon if the str() of the
1037 object is not the empty string
1038 */
Guido van Rossumd6bf45b1997-09-05 19:11:53 +00001039 if (s == NULL)
1040 err = -1;
1041 else if (!PyString_Check(s) ||
1042 PyString_GET_SIZE(s) != 0)
Barry Warsaw035574d1997-08-29 22:07:17 +00001043 err = PyFile_WriteString(": ", f);
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001044 if (err == 0)
Guido van Rossumd6bf45b1997-09-05 19:11:53 +00001045 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1046 Py_XDECREF(s);
Guido van Rossum262e1241995-02-07 15:30:45 +00001047 }
Guido van Rossum262e1241995-02-07 15:30:45 +00001048 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001049 if (err == 0)
1050 err = PyFile_WriteString("\n", f);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001051 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001052 /* If an error happened here, don't show it.
1053 XXX This is wrong, but too many callers rely on this behavior. */
1054 if (err != 0)
1055 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001056}
1057
Guido van Rossum82598051997-03-05 00:20:32 +00001058PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001059PyRun_String(const char *str, int start, PyObject *globals, PyObject *locals)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001060{
Guido van Rossum82598051997-03-05 00:20:32 +00001061 return run_err_node(PyParser_SimpleParseString(str, start),
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001062 "<string>", globals, locals, NULL);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001063}
1064
Guido van Rossum82598051997-03-05 00:20:32 +00001065PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001066PyRun_File(FILE *fp, const char *filename, int start, PyObject *globals,
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001067 PyObject *locals)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001068{
Tim Peterse8682112000-08-27 20:18:17 +00001069 return PyRun_FileEx(fp, filename, start, globals, locals, 0);
Guido van Rossum0df002c2000-08-27 19:21:52 +00001070}
1071
1072PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001073PyRun_FileEx(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001074 PyObject *locals, int closeit)
Guido van Rossum0df002c2000-08-27 19:21:52 +00001075{
1076 node *n = PyParser_SimpleParseFile(fp, filename, start);
1077 if (closeit)
1078 fclose(fp);
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001079 return run_err_node(n, filename, globals, locals, NULL);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001080}
1081
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001082PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001083PyRun_StringFlags(const char *str, int start, PyObject *globals, PyObject *locals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001084 PyCompilerFlags *flags)
1085{
Guido van Rossuma1b3a472001-07-16 16:51:33 +00001086 return run_err_node(PyParser_SimpleParseStringFlags(
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001087 str, start, PARSER_FLAGS(flags)),
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001088 "<string>", globals, locals, flags);
1089}
1090
1091PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001092PyRun_FileFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001093 PyObject *locals, PyCompilerFlags *flags)
1094{
1095 return PyRun_FileExFlags(fp, filename, start, globals, locals, 0,
1096 flags);
1097}
1098
1099PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001100PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001101 PyObject *locals, int closeit, PyCompilerFlags *flags)
1102{
Tim Petersfe2127d2001-07-16 05:37:24 +00001103 node *n = PyParser_SimpleParseFileFlags(fp, filename, start,
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001104 PARSER_FLAGS(flags));
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001105 if (closeit)
1106 fclose(fp);
1107 return run_err_node(n, filename, globals, locals, flags);
1108}
1109
Guido van Rossum82598051997-03-05 00:20:32 +00001110static PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001111run_err_node(node *n, const char *filename, PyObject *globals, PyObject *locals,
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001112 PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001113{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001114 if (n == NULL)
1115 return NULL;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001116 return run_node(n, filename, globals, locals, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001117}
1118
Guido van Rossum82598051997-03-05 00:20:32 +00001119static PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001120run_node(node *n, const char *filename, PyObject *globals, PyObject *locals,
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001121 PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001122{
Guido van Rossum82598051997-03-05 00:20:32 +00001123 PyCodeObject *co;
1124 PyObject *v;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001125 co = PyNode_CompileFlags(n, filename, flags);
Guido van Rossum82598051997-03-05 00:20:32 +00001126 PyNode_Free(n);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001127 if (co == NULL)
1128 return NULL;
Guido van Rossum82598051997-03-05 00:20:32 +00001129 v = PyEval_EvalCode(co, globals, locals);
1130 Py_DECREF(co);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001131 return v;
1132}
1133
Guido van Rossum82598051997-03-05 00:20:32 +00001134static PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001135run_pyc_file(FILE *fp, const char *filename, PyObject *globals, PyObject *locals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001136 PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001137{
Guido van Rossum82598051997-03-05 00:20:32 +00001138 PyCodeObject *co;
1139 PyObject *v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001140 long magic;
Fred Drakee8de31c2000-08-31 05:38:39 +00001141 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001142
Guido van Rossum82598051997-03-05 00:20:32 +00001143 magic = PyMarshal_ReadLongFromFile(fp);
1144 if (magic != PyImport_GetMagicNumber()) {
1145 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001146 "Bad magic number in .pyc file");
1147 return NULL;
1148 }
Guido van Rossum82598051997-03-05 00:20:32 +00001149 (void) PyMarshal_ReadLongFromFile(fp);
Tim Petersd9b9ac82001-01-28 00:27:39 +00001150 v = PyMarshal_ReadLastObjectFromFile(fp);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001151 fclose(fp);
Guido van Rossum82598051997-03-05 00:20:32 +00001152 if (v == NULL || !PyCode_Check(v)) {
1153 Py_XDECREF(v);
1154 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001155 "Bad code object in .pyc file");
1156 return NULL;
1157 }
Guido van Rossum82598051997-03-05 00:20:32 +00001158 co = (PyCodeObject *)v;
1159 v = PyEval_EvalCode(co, globals, locals);
Jeremy Hyltonb857ba22001-08-10 21:41:33 +00001160 if (v && flags)
1161 flags->cf_flags |= (co->co_flags & PyCF_MASK);
Guido van Rossum82598051997-03-05 00:20:32 +00001162 Py_DECREF(co);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001163 return v;
1164}
1165
Guido van Rossum82598051997-03-05 00:20:32 +00001166PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001167Py_CompileString(const char *str, const char *filename, int start)
Guido van Rossum5b722181993-03-30 17:46:03 +00001168{
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001169 return Py_CompileStringFlags(str, filename, start, NULL);
1170}
1171
1172PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001173Py_CompileStringFlags(const char *str, const char *filename, int start,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001174 PyCompilerFlags *flags)
1175{
Guido van Rossum5b722181993-03-30 17:46:03 +00001176 node *n;
Guido van Rossum82598051997-03-05 00:20:32 +00001177 PyCodeObject *co;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001178
1179 n = PyParser_SimpleParseStringFlagsFilename(str, filename, start,
1180 PARSER_FLAGS(flags));
Guido van Rossuma110aa61994-08-29 12:50:44 +00001181 if (n == NULL)
Guido van Rossum5b722181993-03-30 17:46:03 +00001182 return NULL;
Jeremy Hylton673a4fd2001-03-26 19:53:38 +00001183 co = PyNode_CompileFlags(n, filename, flags);
Guido van Rossum82598051997-03-05 00:20:32 +00001184 PyNode_Free(n);
1185 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001186}
1187
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001188struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001189Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001190{
1191 node *n;
1192 struct symtable *st;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001193 n = PyParser_SimpleParseStringFlagsFilename(str, filename,
1194 start, 0);
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001195 if (n == NULL)
1196 return NULL;
1197 st = PyNode_CompileSymtable(n, filename);
1198 PyNode_Free(n);
1199 return st;
1200}
1201
Guido van Rossuma110aa61994-08-29 12:50:44 +00001202/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001203
Guido van Rossuma110aa61994-08-29 12:50:44 +00001204node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001205PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001206{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001207 node *n;
1208 perrdetail err;
Tim Petersfe2127d2001-07-16 05:37:24 +00001209 n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar, start,
1210 (char *)0, (char *)0, &err, flags);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001211 if (n == NULL)
1212 err_input(&err);
1213 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001214}
1215
Tim Petersfe2127d2001-07-16 05:37:24 +00001216node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001217PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
Tim Petersfe2127d2001-07-16 05:37:24 +00001218{
1219 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
1220}
1221
Guido van Rossuma110aa61994-08-29 12:50:44 +00001222/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001223
Guido van Rossuma110aa61994-08-29 12:50:44 +00001224node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001225PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001226{
1227 node *n;
1228 perrdetail err;
1229 n = PyParser_ParseStringFlags(str, &_PyParser_Grammar, start, &err,
1230 flags);
1231 if (n == NULL)
1232 err_input(&err);
1233 return n;
1234}
1235
1236node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001237PyParser_SimpleParseString(const char *str, int start)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001238{
Tim Petersfe2127d2001-07-16 05:37:24 +00001239 return PyParser_SimpleParseStringFlags(str, start, 0);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001240}
1241
Thomas Heller6b17abf2002-07-09 09:23:27 +00001242node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001243PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Thomas Heller6b17abf2002-07-09 09:23:27 +00001244 int start, int flags)
1245{
1246 node *n;
1247 perrdetail err;
1248
1249 n = PyParser_ParseStringFlagsFilename(str, filename,
1250 &_PyParser_Grammar,
1251 start, &err, flags);
1252 if (n == NULL)
1253 err_input(&err);
1254 return n;
1255}
1256
1257node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001258PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001259{
1260 return PyParser_SimpleParseStringFlagsFilename(str, filename,
1261 start, 0);
1262}
1263
Guido van Rossuma110aa61994-08-29 12:50:44 +00001264/* Set the error appropriate to the given input error code (see errcode.h) */
1265
1266static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001267err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001268{
Fred Drake85f36392000-07-11 17:53:00 +00001269 PyObject *v, *w, *errtype;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001270 PyObject* u = NULL;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001271 char *msg = NULL;
Fred Drake85f36392000-07-11 17:53:00 +00001272 errtype = PyExc_SyntaxError;
Guido van Rossum82598051997-03-05 00:20:32 +00001273 v = Py_BuildValue("(ziiz)", err->filename,
Guido van Rossuma110aa61994-08-29 12:50:44 +00001274 err->lineno, err->offset, err->text);
1275 if (err->text != NULL) {
Guido van Rossumb18618d2000-05-03 23:44:39 +00001276 PyMem_DEL(err->text);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001277 err->text = NULL;
1278 }
1279 switch (err->error) {
1280 case E_SYNTAX:
Fred Drake85f36392000-07-11 17:53:00 +00001281 errtype = PyExc_IndentationError;
1282 if (err->expected == INDENT)
1283 msg = "expected an indented block";
1284 else if (err->token == INDENT)
1285 msg = "unexpected indent";
1286 else if (err->token == DEDENT)
1287 msg = "unexpected unindent";
1288 else {
1289 errtype = PyExc_SyntaxError;
1290 msg = "invalid syntax";
1291 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001292 break;
1293 case E_TOKEN:
1294 msg = "invalid token";
Guido van Rossuma110aa61994-08-29 12:50:44 +00001295 break;
Skip Montanaro118ec702002-08-15 01:20:16 +00001296 case E_EOFS:
1297 msg = "EOF while scanning triple-quoted string";
1298 break;
1299 case E_EOLS:
1300 msg = "EOL while scanning single-quoted string";
1301 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001302 case E_INTR:
Guido van Rossum82598051997-03-05 00:20:32 +00001303 PyErr_SetNone(PyExc_KeyboardInterrupt);
Barry Warsawc80baa31999-01-27 16:39:40 +00001304 Py_XDECREF(v);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001305 return;
1306 case E_NOMEM:
Guido van Rossum82598051997-03-05 00:20:32 +00001307 PyErr_NoMemory();
Barry Warsawc80baa31999-01-27 16:39:40 +00001308 Py_XDECREF(v);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001309 return;
1310 case E_EOF:
1311 msg = "unexpected EOF while parsing";
1312 break;
Fred Drake85f36392000-07-11 17:53:00 +00001313 case E_TABSPACE:
1314 errtype = PyExc_TabError;
Guido van Rossum560e8ad1998-04-10 19:43:42 +00001315 msg = "inconsistent use of tabs and spaces in indentation";
1316 break;
Jeremy Hylton94988062000-06-20 19:10:44 +00001317 case E_OVERFLOW:
1318 msg = "expression too long";
1319 break;
Fred Drake85f36392000-07-11 17:53:00 +00001320 case E_DEDENT:
1321 errtype = PyExc_IndentationError;
1322 msg = "unindent does not match any outer indentation level";
1323 break;
1324 case E_TOODEEP:
1325 errtype = PyExc_IndentationError;
1326 msg = "too many levels of indentation";
1327 break;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001328 case E_DECODE: { /* XXX */
1329 PyThreadState* tstate = PyThreadState_Get();
1330 PyObject* value = tstate->curexc_value;
1331 if (value != NULL) {
1332 u = PyObject_Repr(value);
1333 if (u != NULL) {
1334 msg = PyString_AsString(u);
1335 break;
1336 }
1337 }
1338 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001339 default:
1340 fprintf(stderr, "error=%d\n", err->error);
1341 msg = "unknown parsing error";
1342 break;
1343 }
Guido van Rossum82598051997-03-05 00:20:32 +00001344 w = Py_BuildValue("(sO)", msg, v);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001345 Py_XDECREF(u);
Guido van Rossum41318302001-03-23 04:01:07 +00001346 Py_XDECREF(v);
Fred Drake85f36392000-07-11 17:53:00 +00001347 PyErr_SetObject(errtype, w);
Guido van Rossum82598051997-03-05 00:20:32 +00001348 Py_XDECREF(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001349}
1350
1351/* Print fatal error message and abort */
1352
1353void
Tim Peters7c321a82002-07-09 02:57:01 +00001354Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001355{
Guido van Rossum83dd6c31994-09-29 09:38:33 +00001356 fprintf(stderr, "Fatal Python error: %s\n", msg);
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001357#ifdef MS_WINDOWS
Guido van Rossum23c94461997-05-22 20:21:30 +00001358 OutputDebugString("Fatal Python error: ");
Guido van Rossuma44823b1995-03-14 15:01:17 +00001359 OutputDebugString(msg);
1360 OutputDebugString("\n");
Guido van Rossum0ba35361998-08-13 13:33:16 +00001361#ifdef _DEBUG
1362 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00001363#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001364#endif /* MS_WINDOWS */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001365 abort();
1366}
1367
1368/* Clean up and exit */
1369
Guido van Rossuma110aa61994-08-29 12:50:44 +00001370#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00001371#include "pythread.h"
Guido van Rossum82598051997-03-05 00:20:32 +00001372int _PyThread_Started = 0; /* Set by threadmodule.c and maybe others */
Guido van Rossumf9f2e821992-08-17 08:59:08 +00001373#endif
1374
Guido van Rossum2dcfc961998-10-01 16:01:57 +00001375#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001376static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00001377static int nexitfuncs = 0;
1378
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001379int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00001380{
1381 if (nexitfuncs >= NEXITFUNCS)
1382 return -1;
1383 exitfuncs[nexitfuncs++] = func;
1384 return 0;
1385}
1386
Guido van Rossumcc283f51997-08-05 02:22:03 +00001387static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001388call_sys_exitfunc(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001389{
Guido van Rossum82598051997-03-05 00:20:32 +00001390 PyObject *exitfunc = PySys_GetObject("exitfunc");
Guido van Rossum59bff391992-09-03 20:28:00 +00001391
1392 if (exitfunc) {
Fred Drake6a12d8d2001-03-23 17:34:02 +00001393 PyObject *res;
Guido van Rossum82598051997-03-05 00:20:32 +00001394 Py_INCREF(exitfunc);
1395 PySys_SetObject("exitfunc", (PyObject *)NULL);
1396 res = PyEval_CallObject(exitfunc, (PyObject *)NULL);
Guido van Rossum59bff391992-09-03 20:28:00 +00001397 if (res == NULL) {
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001398 if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
1399 PySys_WriteStderr("Error in sys.exitfunc:\n");
1400 }
Guido van Rossum82598051997-03-05 00:20:32 +00001401 PyErr_Print();
Guido van Rossum59bff391992-09-03 20:28:00 +00001402 }
Guido van Rossum82598051997-03-05 00:20:32 +00001403 Py_DECREF(exitfunc);
Guido van Rossum59bff391992-09-03 20:28:00 +00001404 }
1405
Guido van Rossum0829c751998-02-28 04:31:39 +00001406 if (Py_FlushLine())
1407 PyErr_Clear();
Guido van Rossumcc283f51997-08-05 02:22:03 +00001408}
Guido van Rossum1662dd51994-09-07 14:38:28 +00001409
Guido van Rossumcc283f51997-08-05 02:22:03 +00001410static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001411call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00001412{
Guido van Rossum1662dd51994-09-07 14:38:28 +00001413 while (nexitfuncs > 0)
1414 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00001415
1416 fflush(stdout);
1417 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001418}
1419
1420void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001421Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001422{
Guido van Rossumcc283f51997-08-05 02:22:03 +00001423 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001424
Jack Jansen66a89771995-10-27 13:22:14 +00001425#ifdef macintosh
1426 PyMac_Exit(sts);
1427#else
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001428 exit(sts);
Jack Jansen66a89771995-10-27 13:22:14 +00001429#endif
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001430}
1431
Guido van Rossumf1dc5661993-07-05 10:31:29 +00001432static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001433initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001434{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001435#ifdef HAVE_SIGNAL_H
1436#ifdef SIGPIPE
1437 signal(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001438#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00001439#ifdef SIGXFZ
1440 signal(SIGXFZ, SIG_IGN);
1441#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00001442#ifdef SIGXFSZ
1443 signal(SIGXFSZ, SIG_IGN);
1444#endif
Guido van Rossuma110aa61994-08-29 12:50:44 +00001445#endif /* HAVE_SIGNAL_H */
Guido van Rossum82598051997-03-05 00:20:32 +00001446 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001447}
1448
Guido van Rossuma110aa61994-08-29 12:50:44 +00001449#ifdef MPW
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001450
1451/* Check for file descriptor connected to interactive device.
1452 Pretend that stdin is always interactive, other files never. */
1453
1454int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001455isatty(int fd)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001456{
1457 return fd == fileno(stdin);
1458}
1459
1460#endif
Guido van Rossum7433b121997-02-14 19:45:36 +00001461
1462/*
1463 * The file descriptor fd is considered ``interactive'' if either
1464 * a) isatty(fd) is TRUE, or
1465 * b) the -i flag was given, and the filename associated with
1466 * the descriptor is NULL or "<stdin>" or "???".
1467 */
1468int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001469Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00001470{
1471 if (isatty((int)fileno(fp)))
1472 return 1;
1473 if (!Py_InteractiveFlag)
1474 return 0;
1475 return (filename == NULL) ||
1476 (strcmp(filename, "<stdin>") == 0) ||
1477 (strcmp(filename, "???") == 0);
1478}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001479
1480
1481#if defined(USE_STACKCHECK)
1482#if defined(WIN32) && defined(_MSC_VER)
1483
1484/* Stack checking for Microsoft C */
1485
1486#include <malloc.h>
1487#include <excpt.h>
1488
Fred Drakee8de31c2000-08-31 05:38:39 +00001489/*
1490 * Return non-zero when we run out of memory on the stack; zero otherwise.
1491 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001492int
Fred Drake399739f2000-08-31 05:52:44 +00001493PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001494{
1495 __try {
Tim Peters92e4dd82002-10-05 01:47:34 +00001496 /* alloca throws a stack overflow exception if there's
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001497 not enough space left on the stack */
Tim Peters92e4dd82002-10-05 01:47:34 +00001498 alloca(PYOS_STACK_MARGIN * sizeof(void*));
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001499 return 0;
1500 } __except (EXCEPTION_EXECUTE_HANDLER) {
1501 /* just ignore all errors */
1502 }
1503 return 1;
1504}
1505
1506#endif /* WIN32 && _MSC_VER */
1507
1508/* Alternate implementations can be added here... */
1509
1510#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00001511
1512
1513/* Wrappers around sigaction() or signal(). */
1514
1515PyOS_sighandler_t
1516PyOS_getsig(int sig)
1517{
1518#ifdef HAVE_SIGACTION
1519 struct sigaction context;
Barry Warsawafeb2a42001-11-13 23:08:26 +00001520 /* Initialize context.sa_handler to SIG_ERR which makes about as
1521 * much sense as anything else. It should get overwritten if
1522 * sigaction actually succeeds and otherwise we avoid an
1523 * uninitialized memory read.
1524 */
1525 context.sa_handler = SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00001526 sigaction(sig, NULL, &context);
1527 return context.sa_handler;
1528#else
1529 PyOS_sighandler_t handler;
1530 handler = signal(sig, SIG_IGN);
1531 signal(sig, handler);
1532 return handler;
1533#endif
1534}
1535
1536PyOS_sighandler_t
1537PyOS_setsig(int sig, PyOS_sighandler_t handler)
1538{
1539#ifdef HAVE_SIGACTION
1540 struct sigaction context;
1541 PyOS_sighandler_t oldhandler;
Barry Warsawafeb2a42001-11-13 23:08:26 +00001542 /* Initialize context.sa_handler to SIG_ERR which makes about as
1543 * much sense as anything else. It should get overwritten if
1544 * sigaction actually succeeds and otherwise we avoid an
1545 * uninitialized memory read.
1546 */
1547 context.sa_handler = SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00001548 sigaction(sig, NULL, &context);
1549 oldhandler = context.sa_handler;
1550 context.sa_handler = handler;
1551 sigaction(sig, &context, NULL);
1552 return oldhandler;
1553#else
1554 return signal(sig, handler);
1555#endif
1556}