blob: a84186c88846e4249704500bc7cefbd4b5b96778 [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;
Tim Petersd08e3822003-04-17 15:24:21 +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
Tim Peters9cf25ce2003-04-17 15:21:01 +0000273#ifdef Py_TRACE_REFS
274 /* Display all objects still alive -- this can invoke arbitrary
275 * __repr__ overrides, so requires a mostly-intact interpreter.
276 * Alas, a lot of stuff may still be alive now that will be cleaned
277 * up later.
278 */
279 if (Py_GETENV("PYTHONDUMPREFS")) {
280 _Py_PrintReferences(stderr);
281 }
282#endif /* Py_TRACE_REFS */
283
Barry Warsaw035574d1997-08-29 22:07:17 +0000284 /* Now we decref the exception classes. After this point nothing
285 can raise an exception. That's okay, because each Fini() method
286 below has been checked to make sure no exceptions are ever
287 raised.
288 */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000289 _PyExc_Fini();
Barry Warsawf242aa02000-05-25 23:09:49 +0000290
Guido van Rossumd922fa42003-04-15 14:10:09 +0000291 /* Clear interpreter state */
Barry Warsawf242aa02000-05-25 23:09:49 +0000292 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000293
Guido van Rossumd922fa42003-04-15 14:10:09 +0000294 /* Delete current thread */
Barry Warsawf242aa02000-05-25 23:09:49 +0000295 PyThreadState_Swap(NULL);
296 PyInterpreterState_Delete(interp);
297
Guido van Rossumd922fa42003-04-15 14:10:09 +0000298 /* Sundry finalizers */
Guido van Rossumcc283f51997-08-05 02:22:03 +0000299 PyMethod_Fini();
300 PyFrame_Fini();
301 PyCFunction_Fini();
302 PyTuple_Fini();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000303 PyString_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000304 PyInt_Fini();
305 PyFloat_Fini();
306
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000307#ifdef Py_USING_UNICODE
308 /* Cleanup Unicode implementation */
309 _PyUnicode_Fini();
310#endif
311
Guido van Rossumcc283f51997-08-05 02:22:03 +0000312 /* XXX Still allocated:
313 - various static ad-hoc pointers to interned strings
314 - int and float free list blocks
315 - whatever various modules and libraries allocate
316 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000317
318 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000319
Tim Peters0e871182002-04-13 08:29:14 +0000320#ifdef PYMALLOC_DEBUG
321 if (Py_GETENV("PYTHONMALLOCSTATS"))
322 _PyObject_DebugMallocStats();
323#endif
324
Guido van Rossumcc283f51997-08-05 02:22:03 +0000325 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000326}
327
328/* Create and initialize a new interpreter and thread, and return the
329 new thread. This requires that Py_Initialize() has been called
330 first.
331
332 Unsuccessful initialization yields a NULL pointer. Note that *no*
333 exception information is available even in this case -- the
334 exception information is held in the thread, and there is no
335 thread.
336
337 Locking: as above.
338
339*/
340
341PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000342Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000343{
344 PyInterpreterState *interp;
345 PyThreadState *tstate, *save_tstate;
346 PyObject *bimod, *sysmod;
347
348 if (!initialized)
349 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
350
351 interp = PyInterpreterState_New();
352 if (interp == NULL)
353 return NULL;
354
355 tstate = PyThreadState_New(interp);
356 if (tstate == NULL) {
357 PyInterpreterState_Delete(interp);
358 return NULL;
359 }
360
361 save_tstate = PyThreadState_Swap(tstate);
362
363 /* XXX The following is lax in error checking */
364
365 interp->modules = PyDict_New();
366
367 bimod = _PyImport_FindExtension("__builtin__", "__builtin__");
368 if (bimod != NULL) {
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000369 interp->builtins = PyModule_GetDict(bimod);
370 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000371 }
372 sysmod = _PyImport_FindExtension("sys", "sys");
373 if (bimod != NULL && sysmod != NULL) {
374 interp->sysdict = PyModule_GetDict(sysmod);
375 Py_INCREF(interp->sysdict);
376 PySys_SetPath(Py_GetPath());
377 PyDict_SetItemString(interp->sysdict, "modules",
378 interp->modules);
Martin v. Löwisd7ceb222003-01-22 09:00:38 +0000379 _PyImportHooks_Init();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000380 initmain();
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000381 if (!Py_NoSiteFlag)
382 initsite();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000383 }
384
385 if (!PyErr_Occurred())
386 return tstate;
387
388 /* Oops, it didn't work. Undo it all. */
389
390 PyErr_Print();
391 PyThreadState_Clear(tstate);
392 PyThreadState_Swap(save_tstate);
393 PyThreadState_Delete(tstate);
394 PyInterpreterState_Delete(interp);
395
396 return NULL;
397}
398
399/* Delete an interpreter and its last thread. This requires that the
400 given thread state is current, that the thread has no remaining
401 frames, and that it is its interpreter's only remaining thread.
402 It is a fatal error to violate these constraints.
403
404 (Py_Finalize() doesn't have these constraints -- it zaps
405 everything, regardless.)
406
407 Locking: as above.
408
409*/
410
411void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000412Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000413{
414 PyInterpreterState *interp = tstate->interp;
415
416 if (tstate != PyThreadState_Get())
417 Py_FatalError("Py_EndInterpreter: thread is not current");
418 if (tstate->frame != NULL)
419 Py_FatalError("Py_EndInterpreter: thread still has a frame");
420 if (tstate != interp->tstate_head || tstate->next != NULL)
421 Py_FatalError("Py_EndInterpreter: not the last thread");
422
423 PyImport_Cleanup();
424 PyInterpreterState_Clear(interp);
425 PyThreadState_Swap(NULL);
426 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000427}
428
429static char *progname = "python";
430
431void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000432Py_SetProgramName(char *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000433{
434 if (pn && *pn)
435 progname = pn;
436}
437
438char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000439Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000440{
441 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000442}
443
Guido van Rossuma61691e1998-02-06 22:27:24 +0000444static char *default_home = NULL;
445
446void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000447Py_SetPythonHome(char *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000448{
449 default_home = home;
450}
451
452char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000453Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000454{
455 char *home = default_home;
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000456 if (home == NULL && !Py_IgnoreEnvironmentFlag)
457 home = Py_GETENV("PYTHONHOME");
Guido van Rossuma61691e1998-02-06 22:27:24 +0000458 return home;
459}
460
Guido van Rossum6135a871995-01-09 17:53:26 +0000461/* Create __main__ module */
462
463static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000464initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000465{
Guido van Rossum82598051997-03-05 00:20:32 +0000466 PyObject *m, *d;
467 m = PyImport_AddModule("__main__");
Guido van Rossum6135a871995-01-09 17:53:26 +0000468 if (m == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +0000469 Py_FatalError("can't create __main__ module");
470 d = PyModule_GetDict(m);
471 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
Guido van Rossum858cb731997-11-19 16:15:37 +0000472 PyObject *bimod = PyImport_ImportModule("__builtin__");
473 if (bimod == NULL ||
474 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
Guido van Rossum82598051997-03-05 00:20:32 +0000475 Py_FatalError("can't add __builtins__ to __main__");
Barry Warsaw3d05b1a1999-01-29 21:30:22 +0000476 Py_DECREF(bimod);
Guido van Rossum6135a871995-01-09 17:53:26 +0000477 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000478}
479
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000480/* Import the site module (not into __main__ though) */
481
482static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000483initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000484{
485 PyObject *m, *f;
486 m = PyImport_ImportModule("site");
487 if (m == NULL) {
488 f = PySys_GetObject("stderr");
489 if (Py_VerboseFlag) {
490 PyFile_WriteString(
491 "'import site' failed; traceback:\n", f);
492 PyErr_Print();
493 }
494 else {
495 PyFile_WriteString(
496 "'import site' failed; use -v for traceback\n", f);
497 PyErr_Clear();
498 }
499 }
500 else {
501 Py_DECREF(m);
502 }
503}
504
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000505/* Parse input from a file and execute it */
506
507int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000508PyRun_AnyFile(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000509{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000510 return PyRun_AnyFileExFlags(fp, filename, 0, NULL);
511}
512
513int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000514PyRun_AnyFileFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000515{
516 return PyRun_AnyFileExFlags(fp, filename, 0, flags);
Guido van Rossum0df002c2000-08-27 19:21:52 +0000517}
518
519int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000520PyRun_AnyFileEx(FILE *fp, const char *filename, int closeit)
Guido van Rossum0df002c2000-08-27 19:21:52 +0000521{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000522 return PyRun_AnyFileExFlags(fp, filename, closeit, NULL);
523}
524
525int
Tim Petersd08e3822003-04-17 15:24:21 +0000526PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000527 PyCompilerFlags *flags)
528{
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000529 if (filename == NULL)
530 filename = "???";
Guido van Rossum0df002c2000-08-27 19:21:52 +0000531 if (Py_FdIsInteractive(fp, filename)) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000532 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
Guido van Rossum0df002c2000-08-27 19:21:52 +0000533 if (closeit)
534 fclose(fp);
535 return err;
536 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000537 else
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000538 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000539}
540
541int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000542PyRun_InteractiveLoop(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000543{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000544 return PyRun_InteractiveLoopFlags(fp, filename, NULL);
545}
546
547int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000548PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000549{
Guido van Rossum82598051997-03-05 00:20:32 +0000550 PyObject *v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000551 int ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000552 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000553
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000554 if (flags == NULL) {
555 flags = &local_flags;
Tim Peters5ba58662001-07-16 02:29:45 +0000556 local_flags.cf_flags = 0;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000557 }
Guido van Rossum82598051997-03-05 00:20:32 +0000558 v = PySys_GetObject("ps1");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000559 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000560 PySys_SetObject("ps1", v = PyString_FromString(">>> "));
561 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000562 }
Guido van Rossum82598051997-03-05 00:20:32 +0000563 v = PySys_GetObject("ps2");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000564 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000565 PySys_SetObject("ps2", v = PyString_FromString("... "));
566 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000567 }
568 for (;;) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000569 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
Guido van Rossumaae0d321996-05-22 16:35:33 +0000570#ifdef Py_REF_DEBUG
Guido van Rossum6f9e4331995-03-29 16:57:48 +0000571 fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000572#endif
573 if (ret == E_EOF)
574 return 0;
575 /*
576 if (ret == E_NOMEM)
577 return -1;
578 */
579 }
580}
581
582int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000583PyRun_InteractiveOne(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000584{
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000585 return PyRun_InteractiveOneFlags(fp, filename, NULL);
586}
587
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000588/* compute parser flags based on compiler flags */
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000589#define PARSER_FLAGS(flags) \
Guido van Rossum4b499dd32003-02-13 22:07:59 +0000590 (((flags) && (flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
591 PyPARSE_DONT_IMPLY_DEDENT : 0)
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000592
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000593int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000594PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000595{
Guido van Rossum82598051997-03-05 00:20:32 +0000596 PyObject *m, *d, *v, *w;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000597 node *n;
Guido van Rossuma110aa61994-08-29 12:50:44 +0000598 perrdetail err;
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000599 char *ps1 = "", *ps2 = "";
Tim Petersfe2127d2001-07-16 05:37:24 +0000600
Guido van Rossum82598051997-03-05 00:20:32 +0000601 v = PySys_GetObject("ps1");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000602 if (v != NULL) {
603 v = PyObject_Str(v);
604 if (v == NULL)
605 PyErr_Clear();
606 else if (PyString_Check(v))
607 ps1 = PyString_AsString(v);
608 }
Guido van Rossum82598051997-03-05 00:20:32 +0000609 w = PySys_GetObject("ps2");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000610 if (w != NULL) {
611 w = PyObject_Str(w);
612 if (w == NULL)
613 PyErr_Clear();
614 else if (PyString_Check(w))
615 ps2 = PyString_AsString(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000616 }
Tim Petersfe2127d2001-07-16 05:37:24 +0000617 n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar,
618 Py_single_input, ps1, ps2, &err,
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000619 PARSER_FLAGS(flags));
Guido van Rossum82598051997-03-05 00:20:32 +0000620 Py_XDECREF(v);
621 Py_XDECREF(w);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000622 if (n == NULL) {
623 if (err.error == E_EOF) {
624 if (err.text)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000625 PyMem_DEL(err.text);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000626 return E_EOF;
627 }
628 err_input(&err);
Guido van Rossum82598051997-03-05 00:20:32 +0000629 PyErr_Print();
Guido van Rossuma110aa61994-08-29 12:50:44 +0000630 return err.error;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000631 }
Guido van Rossum82598051997-03-05 00:20:32 +0000632 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000633 if (m == NULL)
634 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000635 d = PyModule_GetDict(m);
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000636 v = run_node(n, filename, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000637 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000638 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000639 return -1;
640 }
Guido van Rossum82598051997-03-05 00:20:32 +0000641 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000642 if (Py_FlushLine())
643 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000644 return 0;
645}
646
647int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000648PyRun_SimpleFile(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000649{
Guido van Rossum0df002c2000-08-27 19:21:52 +0000650 return PyRun_SimpleFileEx(fp, filename, 0);
651}
652
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000653/* Check whether a file maybe a pyc file: Look at the extension,
654 the file type, and, if we may close it, at the first few bytes. */
655
656static int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000657maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000658{
659 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
660 return 1;
661
662#ifdef macintosh
663 /* On a mac, we also assume a pyc file for types 'PYC ' and 'APPL' */
Jack Jansen72f3b7a2002-12-13 15:23:10 +0000664 if (PyMac_getfiletype((char *)filename) == 'PYC '
665 || PyMac_getfiletype((char *)filename) == 'APPL')
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000666 return 1;
667#endif /* macintosh */
668
669 /* Only look into the file if we are allowed to close it, since
670 it then should also be seekable. */
671 if (closeit) {
672 /* Read only two bytes of the magic. If the file was opened in
673 text mode, the bytes 3 and 4 of the magic (\r\n) might not
674 be read as they are on disk. */
675 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
676 unsigned char buf[2];
Tim Peters3e876562001-02-11 04:35:39 +0000677 /* Mess: In case of -x, the stream is NOT at its start now,
678 and ungetc() was used to push back the first newline,
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000679 which makes the current stream position formally undefined,
680 and a x-platform nightmare.
681 Unfortunately, we have no direct way to know whether -x
682 was specified. So we use a terrible hack: if the current
683 stream position is not 0, we assume -x was specified, and
684 give up. Bug 132850 on SourceForge spells out the
685 hopelessness of trying anything else (fseek and ftell
686 don't work predictably x-platform for text-mode files).
Tim Peters3e876562001-02-11 04:35:39 +0000687 */
Tim Peters3e876562001-02-11 04:35:39 +0000688 int ispyc = 0;
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000689 if (ftell(fp) == 0) {
690 if (fread(buf, 1, 2, fp) == 2 &&
Tim Petersd08e3822003-04-17 15:24:21 +0000691 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000692 ispyc = 1;
693 rewind(fp);
694 }
Tim Peters3e876562001-02-11 04:35:39 +0000695 return ispyc;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000696 }
697 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +0000698}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000699
Guido van Rossum0df002c2000-08-27 19:21:52 +0000700int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000701PyRun_SimpleFileEx(FILE *fp, const char *filename, int closeit)
Guido van Rossum0df002c2000-08-27 19:21:52 +0000702{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000703 return PyRun_SimpleFileExFlags(fp, filename, closeit, NULL);
704}
705
706int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000707PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000708 PyCompilerFlags *flags)
709{
Guido van Rossum82598051997-03-05 00:20:32 +0000710 PyObject *m, *d, *v;
Martin v. Löwis95292d62002-12-11 14:04:59 +0000711 const char *ext;
Guido van Rossumfdef2711994-09-14 13:31:04 +0000712
Guido van Rossum82598051997-03-05 00:20:32 +0000713 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000714 if (m == NULL)
715 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000716 d = PyModule_GetDict(m);
Fred Drake8ed02042002-10-17 21:24:58 +0000717 if (PyDict_GetItemString(d, "__file__") == NULL) {
718 PyObject *f = PyString_FromString(filename);
719 if (f == NULL)
720 return -1;
721 if (PyDict_SetItemString(d, "__file__", f) < 0) {
722 Py_DECREF(f);
723 return -1;
724 }
725 Py_DECREF(f);
726 }
Guido van Rossumfdef2711994-09-14 13:31:04 +0000727 ext = filename + strlen(filename) - 4;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000728 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Guido van Rossumfdef2711994-09-14 13:31:04 +0000729 /* Try to run a pyc file. First, re-open in binary */
Guido van Rossum0df002c2000-08-27 19:21:52 +0000730 if (closeit)
731 fclose(fp);
Fred Drake8ed02042002-10-17 21:24:58 +0000732 if ((fp = fopen(filename, "rb")) == NULL) {
Guido van Rossumfdef2711994-09-14 13:31:04 +0000733 fprintf(stderr, "python: Can't reopen .pyc file\n");
734 return -1;
735 }
Guido van Rossum2a7f58d1997-04-02 05:28:38 +0000736 /* Turn on optimization if a .pyo file is given */
737 if (strcmp(ext, ".pyo") == 0)
738 Py_OptimizeFlag = 1;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000739 v = run_pyc_file(fp, filename, d, d, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000740 } else {
Tim Petersd08e3822003-04-17 15:24:21 +0000741 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000742 closeit, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000743 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000744 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000745 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000746 return -1;
747 }
Guido van Rossum82598051997-03-05 00:20:32 +0000748 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000749 if (Py_FlushLine())
750 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000751 return 0;
752}
753
754int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000755PyRun_SimpleString(const char *command)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000756{
Guido van Rossum393661d2001-08-31 17:40:15 +0000757 return PyRun_SimpleStringFlags(command, NULL);
758}
759
760int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000761PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +0000762{
Guido van Rossum82598051997-03-05 00:20:32 +0000763 PyObject *m, *d, *v;
764 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000765 if (m == NULL)
766 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000767 d = PyModule_GetDict(m);
Guido van Rossum393661d2001-08-31 17:40:15 +0000768 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000769 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000770 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000771 return -1;
772 }
Guido van Rossum82598051997-03-05 00:20:32 +0000773 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000774 if (Py_FlushLine())
775 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000776 return 0;
777}
778
Barry Warsaw035574d1997-08-29 22:07:17 +0000779static int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000780parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
781 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +0000782{
783 long hold;
784 PyObject *v;
785
786 /* old style errors */
787 if (PyTuple_Check(err))
Neal Norwitz78293352002-04-01 01:41:20 +0000788 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
789 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +0000790
791 /* new style errors. `err' is an instance */
792
793 if (! (v = PyObject_GetAttrString(err, "msg")))
794 goto finally;
795 *message = v;
796
797 if (!(v = PyObject_GetAttrString(err, "filename")))
798 goto finally;
799 if (v == Py_None)
800 *filename = NULL;
801 else if (! (*filename = PyString_AsString(v)))
802 goto finally;
803
804 Py_DECREF(v);
805 if (!(v = PyObject_GetAttrString(err, "lineno")))
806 goto finally;
807 hold = PyInt_AsLong(v);
808 Py_DECREF(v);
809 v = NULL;
810 if (hold < 0 && PyErr_Occurred())
811 goto finally;
812 *lineno = (int)hold;
813
814 if (!(v = PyObject_GetAttrString(err, "offset")))
815 goto finally;
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000816 if (v == Py_None) {
817 *offset = -1;
818 Py_DECREF(v);
819 v = NULL;
820 } else {
821 hold = PyInt_AsLong(v);
822 Py_DECREF(v);
823 v = NULL;
824 if (hold < 0 && PyErr_Occurred())
825 goto finally;
826 *offset = (int)hold;
827 }
Barry Warsaw035574d1997-08-29 22:07:17 +0000828
829 if (!(v = PyObject_GetAttrString(err, "text")))
830 goto finally;
831 if (v == Py_None)
832 *text = NULL;
833 else if (! (*text = PyString_AsString(v)))
834 goto finally;
835 Py_DECREF(v);
836 return 1;
837
838finally:
839 Py_XDECREF(v);
840 return 0;
841}
842
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000843void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000844PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000845{
Guido van Rossuma61691e1998-02-06 22:27:24 +0000846 PyErr_PrintEx(1);
847}
848
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000849static void
Martin v. Löwis95292d62002-12-11 14:04:59 +0000850print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000851{
852 char *nl;
853 if (offset >= 0) {
854 if (offset > 0 && offset == (int)strlen(text))
855 offset--;
856 for (;;) {
857 nl = strchr(text, '\n');
858 if (nl == NULL || nl-text >= offset)
859 break;
860 offset -= (nl+1-text);
861 text = nl+1;
862 }
863 while (*text == ' ' || *text == '\t') {
864 text++;
865 offset--;
866 }
867 }
868 PyFile_WriteString(" ", f);
869 PyFile_WriteString(text, f);
870 if (*text == '\0' || text[strlen(text)-1] != '\n')
871 PyFile_WriteString("\n", f);
872 if (offset == -1)
873 return;
874 PyFile_WriteString(" ", f);
875 offset--;
876 while (offset > 0) {
877 PyFile_WriteString(" ", f);
878 offset--;
879 }
880 PyFile_WriteString("^\n", f);
881}
882
Guido van Rossum66e8e862001-03-23 17:54:43 +0000883static void
884handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000885{
Guido van Rossum66e8e862001-03-23 17:54:43 +0000886 PyObject *exception, *value, *tb;
887 PyErr_Fetch(&exception, &value, &tb);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000888 if (Py_FlushLine())
889 PyErr_Clear();
890 fflush(stdout);
891 if (value == NULL || value == Py_None)
892 Py_Exit(0);
893 if (PyInstance_Check(value)) {
894 /* The error code should be in the `code' attribute. */
895 PyObject *code = PyObject_GetAttrString(value, "code");
896 if (code) {
897 Py_DECREF(value);
898 value = code;
899 if (value == Py_None)
900 Py_Exit(0);
901 }
902 /* If we failed to dig out the 'code' attribute,
903 just let the else clause below print the error. */
904 }
905 if (PyInt_Check(value))
906 Py_Exit((int)PyInt_AsLong(value));
907 else {
908 PyObject_Print(value, stderr, Py_PRINT_RAW);
909 PySys_WriteStderr("\n");
910 Py_Exit(1);
911 }
912}
913
914void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000915PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000916{
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000917 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +0000918
919 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
920 handle_system_exit();
921 }
Guido van Rossum82598051997-03-05 00:20:32 +0000922 PyErr_Fetch(&exception, &v, &tb);
Barry Warsaw035574d1997-08-29 22:07:17 +0000923 PyErr_NormalizeException(&exception, &v, &tb);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000924 if (exception == NULL)
Guido van Rossum296b4751997-05-23 00:19:20 +0000925 return;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000926 if (set_sys_last_vars) {
927 PySys_SetObject("last_type", exception);
928 PySys_SetObject("last_value", v);
929 PySys_SetObject("last_traceback", tb);
930 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000931 hook = PySys_GetObject("excepthook");
932 if (hook) {
933 PyObject *args = Py_BuildValue("(OOO)",
934 exception, v ? v : Py_None, tb ? tb : Py_None);
935 PyObject *result = PyEval_CallObject(hook, args);
936 if (result == NULL) {
937 PyObject *exception2, *v2, *tb2;
Guido van Rossum66e8e862001-03-23 17:54:43 +0000938 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
939 handle_system_exit();
940 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000941 PyErr_Fetch(&exception2, &v2, &tb2);
942 PyErr_NormalizeException(&exception2, &v2, &tb2);
943 if (Py_FlushLine())
944 PyErr_Clear();
945 fflush(stdout);
946 PySys_WriteStderr("Error in sys.excepthook:\n");
947 PyErr_Display(exception2, v2, tb2);
948 PySys_WriteStderr("\nOriginal exception was:\n");
949 PyErr_Display(exception, v, tb);
Jeremy Hylton07028582001-12-07 15:35:35 +0000950 Py_XDECREF(exception2);
951 Py_XDECREF(v2);
952 Py_XDECREF(tb2);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000953 }
954 Py_XDECREF(result);
955 Py_XDECREF(args);
956 } else {
957 PySys_WriteStderr("sys.excepthook is missing\n");
958 PyErr_Display(exception, v, tb);
959 }
960 Py_XDECREF(exception);
961 Py_XDECREF(v);
962 Py_XDECREF(tb);
963}
964
965void PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
966{
967 int err = 0;
968 PyObject *v = value;
969 PyObject *f = PySys_GetObject("stderr");
Guido van Rossum3165fe61992-09-25 21:59:05 +0000970 if (f == NULL)
971 fprintf(stderr, "lost sys.stderr\n");
972 else {
Guido van Rossum0829c751998-02-28 04:31:39 +0000973 if (Py_FlushLine())
974 PyErr_Clear();
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000975 fflush(stdout);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000976 if (tb && tb != Py_None)
977 err = PyTraceBack_Print(tb, f);
Barry Warsaw36b8f941997-08-26 18:09:48 +0000978 if (err == 0 &&
Martin v. Löwiscfeb3b62002-03-03 21:30:27 +0000979 PyObject_HasAttrString(v, "print_file_and_line"))
Barry Warsaw36b8f941997-08-26 18:09:48 +0000980 {
Guido van Rossum82598051997-03-05 00:20:32 +0000981 PyObject *message;
Martin v. Löwis95292d62002-12-11 14:04:59 +0000982 const char *filename, *text;
Guido van Rossuma110aa61994-08-29 12:50:44 +0000983 int lineno, offset;
Barry Warsaw035574d1997-08-29 22:07:17 +0000984 if (!parse_syntax_error(v, &message, &filename,
985 &lineno, &offset, &text))
Guido van Rossum82598051997-03-05 00:20:32 +0000986 PyErr_Clear();
Guido van Rossuma110aa61994-08-29 12:50:44 +0000987 else {
988 char buf[10];
Guido van Rossum82598051997-03-05 00:20:32 +0000989 PyFile_WriteString(" File \"", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000990 if (filename == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +0000991 PyFile_WriteString("<string>", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000992 else
Guido van Rossum82598051997-03-05 00:20:32 +0000993 PyFile_WriteString(filename, f);
994 PyFile_WriteString("\", line ", f);
Jeremy Hylton518ab1c2001-11-28 20:42:20 +0000995 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
Guido van Rossum82598051997-03-05 00:20:32 +0000996 PyFile_WriteString(buf, f);
997 PyFile_WriteString("\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000998 if (text != NULL)
999 print_error_text(f, offset, text);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001000 v = message;
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001001 /* Can't be bothered to check all those
1002 PyFile_WriteString() calls */
1003 if (PyErr_Occurred())
1004 err = -1;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001005 }
1006 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001007 if (err) {
1008 /* Don't do anything else */
1009 }
1010 else if (PyClass_Check(exception)) {
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001011 PyClassObject* exc = (PyClassObject*)exception;
1012 PyObject* className = exc->cl_name;
1013 PyObject* moduleName =
1014 PyDict_GetItemString(exc->cl_dict, "__module__");
1015
1016 if (moduleName == NULL)
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001017 err = PyFile_WriteString("<unknown>", f);
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001018 else {
1019 char* modstr = PyString_AsString(moduleName);
Tim Petersd08e3822003-04-17 15:24:21 +00001020 if (modstr && strcmp(modstr, "exceptions"))
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001021 {
1022 err = PyFile_WriteString(modstr, f);
1023 err += PyFile_WriteString(".", f);
1024 }
1025 }
1026 if (err == 0) {
1027 if (className == NULL)
1028 err = PyFile_WriteString("<unknown>", f);
1029 else
1030 err = PyFile_WriteObject(className, f,
1031 Py_PRINT_RAW);
1032 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001033 }
1034 else
1035 err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
1036 if (err == 0) {
1037 if (v != NULL && v != Py_None) {
Barry Warsaw035574d1997-08-29 22:07:17 +00001038 PyObject *s = PyObject_Str(v);
1039 /* only print colon if the str() of the
1040 object is not the empty string
1041 */
Guido van Rossumd6bf45b1997-09-05 19:11:53 +00001042 if (s == NULL)
1043 err = -1;
1044 else if (!PyString_Check(s) ||
1045 PyString_GET_SIZE(s) != 0)
Barry Warsaw035574d1997-08-29 22:07:17 +00001046 err = PyFile_WriteString(": ", f);
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001047 if (err == 0)
Guido van Rossumd6bf45b1997-09-05 19:11:53 +00001048 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1049 Py_XDECREF(s);
Guido van Rossum262e1241995-02-07 15:30:45 +00001050 }
Guido van Rossum262e1241995-02-07 15:30:45 +00001051 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001052 if (err == 0)
1053 err = PyFile_WriteString("\n", f);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001054 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001055 /* If an error happened here, don't show it.
1056 XXX This is wrong, but too many callers rely on this behavior. */
1057 if (err != 0)
1058 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001059}
1060
Guido van Rossum82598051997-03-05 00:20:32 +00001061PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001062PyRun_String(const char *str, int start, PyObject *globals, PyObject *locals)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001063{
Guido van Rossum82598051997-03-05 00:20:32 +00001064 return run_err_node(PyParser_SimpleParseString(str, start),
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001065 "<string>", globals, locals, NULL);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001066}
1067
Guido van Rossum82598051997-03-05 00:20:32 +00001068PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001069PyRun_File(FILE *fp, const char *filename, int start, PyObject *globals,
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001070 PyObject *locals)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001071{
Tim Peterse8682112000-08-27 20:18:17 +00001072 return PyRun_FileEx(fp, filename, start, globals, locals, 0);
Guido van Rossum0df002c2000-08-27 19:21:52 +00001073}
1074
1075PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001076PyRun_FileEx(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001077 PyObject *locals, int closeit)
Guido van Rossum0df002c2000-08-27 19:21:52 +00001078{
1079 node *n = PyParser_SimpleParseFile(fp, filename, start);
1080 if (closeit)
1081 fclose(fp);
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001082 return run_err_node(n, filename, globals, locals, NULL);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001083}
1084
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001085PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001086PyRun_StringFlags(const char *str, int start, PyObject *globals, PyObject *locals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001087 PyCompilerFlags *flags)
1088{
Guido van Rossuma1b3a472001-07-16 16:51:33 +00001089 return run_err_node(PyParser_SimpleParseStringFlags(
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001090 str, start, PARSER_FLAGS(flags)),
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001091 "<string>", globals, locals, flags);
1092}
1093
1094PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001095PyRun_FileFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001096 PyObject *locals, PyCompilerFlags *flags)
1097{
1098 return PyRun_FileExFlags(fp, filename, start, globals, locals, 0,
Tim Petersd08e3822003-04-17 15:24:21 +00001099 flags);
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001100}
1101
1102PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001103PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001104 PyObject *locals, int closeit, PyCompilerFlags *flags)
1105{
Tim Petersfe2127d2001-07-16 05:37:24 +00001106 node *n = PyParser_SimpleParseFileFlags(fp, filename, start,
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001107 PARSER_FLAGS(flags));
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001108 if (closeit)
1109 fclose(fp);
1110 return run_err_node(n, filename, globals, locals, flags);
1111}
1112
Guido van Rossum82598051997-03-05 00:20:32 +00001113static PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001114run_err_node(node *n, const char *filename, PyObject *globals, PyObject *locals,
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001115 PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001116{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001117 if (n == NULL)
1118 return NULL;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001119 return run_node(n, filename, globals, locals, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001120}
1121
Guido van Rossum82598051997-03-05 00:20:32 +00001122static PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001123run_node(node *n, const char *filename, PyObject *globals, PyObject *locals,
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001124 PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001125{
Guido van Rossum82598051997-03-05 00:20:32 +00001126 PyCodeObject *co;
1127 PyObject *v;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001128 co = PyNode_CompileFlags(n, filename, flags);
Guido van Rossum82598051997-03-05 00:20:32 +00001129 PyNode_Free(n);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001130 if (co == NULL)
1131 return NULL;
Guido van Rossum82598051997-03-05 00:20:32 +00001132 v = PyEval_EvalCode(co, globals, locals);
1133 Py_DECREF(co);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001134 return v;
1135}
1136
Guido van Rossum82598051997-03-05 00:20:32 +00001137static PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001138run_pyc_file(FILE *fp, const char *filename, PyObject *globals, PyObject *locals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001139 PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001140{
Guido van Rossum82598051997-03-05 00:20:32 +00001141 PyCodeObject *co;
1142 PyObject *v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001143 long magic;
Fred Drakee8de31c2000-08-31 05:38:39 +00001144 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001145
Guido van Rossum82598051997-03-05 00:20:32 +00001146 magic = PyMarshal_ReadLongFromFile(fp);
1147 if (magic != PyImport_GetMagicNumber()) {
1148 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001149 "Bad magic number in .pyc file");
1150 return NULL;
1151 }
Guido van Rossum82598051997-03-05 00:20:32 +00001152 (void) PyMarshal_ReadLongFromFile(fp);
Tim Petersd9b9ac82001-01-28 00:27:39 +00001153 v = PyMarshal_ReadLastObjectFromFile(fp);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001154 fclose(fp);
Guido van Rossum82598051997-03-05 00:20:32 +00001155 if (v == NULL || !PyCode_Check(v)) {
1156 Py_XDECREF(v);
1157 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001158 "Bad code object in .pyc file");
1159 return NULL;
1160 }
Guido van Rossum82598051997-03-05 00:20:32 +00001161 co = (PyCodeObject *)v;
1162 v = PyEval_EvalCode(co, globals, locals);
Jeremy Hyltonb857ba22001-08-10 21:41:33 +00001163 if (v && flags)
1164 flags->cf_flags |= (co->co_flags & PyCF_MASK);
Guido van Rossum82598051997-03-05 00:20:32 +00001165 Py_DECREF(co);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001166 return v;
1167}
1168
Guido van Rossum82598051997-03-05 00:20:32 +00001169PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001170Py_CompileString(const char *str, const char *filename, int start)
Guido van Rossum5b722181993-03-30 17:46:03 +00001171{
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001172 return Py_CompileStringFlags(str, filename, start, NULL);
1173}
1174
1175PyObject *
Tim Petersd08e3822003-04-17 15:24:21 +00001176Py_CompileStringFlags(const char *str, const char *filename, int start,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001177 PyCompilerFlags *flags)
1178{
Guido van Rossum5b722181993-03-30 17:46:03 +00001179 node *n;
Guido van Rossum82598051997-03-05 00:20:32 +00001180 PyCodeObject *co;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001181
1182 n = PyParser_SimpleParseStringFlagsFilename(str, filename, start,
1183 PARSER_FLAGS(flags));
Guido van Rossuma110aa61994-08-29 12:50:44 +00001184 if (n == NULL)
Guido van Rossum5b722181993-03-30 17:46:03 +00001185 return NULL;
Jeremy Hylton673a4fd2001-03-26 19:53:38 +00001186 co = PyNode_CompileFlags(n, filename, flags);
Guido van Rossum82598051997-03-05 00:20:32 +00001187 PyNode_Free(n);
1188 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001189}
1190
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001191struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001192Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001193{
1194 node *n;
1195 struct symtable *st;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001196 n = PyParser_SimpleParseStringFlagsFilename(str, filename,
1197 start, 0);
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001198 if (n == NULL)
1199 return NULL;
1200 st = PyNode_CompileSymtable(n, filename);
1201 PyNode_Free(n);
1202 return st;
1203}
1204
Guido van Rossuma110aa61994-08-29 12:50:44 +00001205/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001206
Guido van Rossuma110aa61994-08-29 12:50:44 +00001207node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001208PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001209{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001210 node *n;
1211 perrdetail err;
Tim Petersfe2127d2001-07-16 05:37:24 +00001212 n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar, start,
1213 (char *)0, (char *)0, &err, flags);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001214 if (n == NULL)
1215 err_input(&err);
1216 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001217}
1218
Tim Petersfe2127d2001-07-16 05:37:24 +00001219node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001220PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
Tim Petersfe2127d2001-07-16 05:37:24 +00001221{
1222 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
1223}
1224
Guido van Rossuma110aa61994-08-29 12:50:44 +00001225/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001226
Guido van Rossuma110aa61994-08-29 12:50:44 +00001227node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001228PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001229{
1230 node *n;
1231 perrdetail err;
1232 n = PyParser_ParseStringFlags(str, &_PyParser_Grammar, start, &err,
1233 flags);
1234 if (n == NULL)
1235 err_input(&err);
1236 return n;
1237}
1238
1239node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001240PyParser_SimpleParseString(const char *str, int start)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001241{
Tim Petersfe2127d2001-07-16 05:37:24 +00001242 return PyParser_SimpleParseStringFlags(str, start, 0);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001243}
1244
Thomas Heller6b17abf2002-07-09 09:23:27 +00001245node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001246PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Thomas Heller6b17abf2002-07-09 09:23:27 +00001247 int start, int flags)
1248{
1249 node *n;
1250 perrdetail err;
1251
Tim Petersd08e3822003-04-17 15:24:21 +00001252 n = PyParser_ParseStringFlagsFilename(str, filename,
Thomas Heller6b17abf2002-07-09 09:23:27 +00001253 &_PyParser_Grammar,
1254 start, &err, flags);
1255 if (n == NULL)
1256 err_input(&err);
1257 return n;
1258}
1259
1260node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001261PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001262{
1263 return PyParser_SimpleParseStringFlagsFilename(str, filename,
1264 start, 0);
1265}
1266
Guido van Rossum66ebd912003-04-17 16:02:26 +00001267/* May want to move a more generalized form of this to parsetok.c or
1268 even parser modules. */
1269
1270void
1271PyParser_SetError(perrdetail *err)
1272{
1273 err_input(err);
1274}
1275
Guido van Rossuma110aa61994-08-29 12:50:44 +00001276/* Set the error appropriate to the given input error code (see errcode.h) */
1277
1278static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001279err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001280{
Fred Drake85f36392000-07-11 17:53:00 +00001281 PyObject *v, *w, *errtype;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001282 PyObject* u = NULL;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001283 char *msg = NULL;
Fred Drake85f36392000-07-11 17:53:00 +00001284 errtype = PyExc_SyntaxError;
Guido van Rossum82598051997-03-05 00:20:32 +00001285 v = Py_BuildValue("(ziiz)", err->filename,
Guido van Rossuma110aa61994-08-29 12:50:44 +00001286 err->lineno, err->offset, err->text);
1287 if (err->text != NULL) {
Guido van Rossumb18618d2000-05-03 23:44:39 +00001288 PyMem_DEL(err->text);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001289 err->text = NULL;
1290 }
1291 switch (err->error) {
1292 case E_SYNTAX:
Fred Drake85f36392000-07-11 17:53:00 +00001293 errtype = PyExc_IndentationError;
1294 if (err->expected == INDENT)
1295 msg = "expected an indented block";
1296 else if (err->token == INDENT)
1297 msg = "unexpected indent";
1298 else if (err->token == DEDENT)
1299 msg = "unexpected unindent";
1300 else {
1301 errtype = PyExc_SyntaxError;
1302 msg = "invalid syntax";
1303 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001304 break;
1305 case E_TOKEN:
1306 msg = "invalid token";
Guido van Rossuma110aa61994-08-29 12:50:44 +00001307 break;
Skip Montanaro118ec702002-08-15 01:20:16 +00001308 case E_EOFS:
1309 msg = "EOF while scanning triple-quoted string";
1310 break;
1311 case E_EOLS:
1312 msg = "EOL while scanning single-quoted string";
1313 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001314 case E_INTR:
Guido van Rossum82598051997-03-05 00:20:32 +00001315 PyErr_SetNone(PyExc_KeyboardInterrupt);
Barry Warsawc80baa31999-01-27 16:39:40 +00001316 Py_XDECREF(v);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001317 return;
1318 case E_NOMEM:
Guido van Rossum82598051997-03-05 00:20:32 +00001319 PyErr_NoMemory();
Barry Warsawc80baa31999-01-27 16:39:40 +00001320 Py_XDECREF(v);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001321 return;
1322 case E_EOF:
1323 msg = "unexpected EOF while parsing";
1324 break;
Fred Drake85f36392000-07-11 17:53:00 +00001325 case E_TABSPACE:
1326 errtype = PyExc_TabError;
Guido van Rossum560e8ad1998-04-10 19:43:42 +00001327 msg = "inconsistent use of tabs and spaces in indentation";
1328 break;
Jeremy Hylton94988062000-06-20 19:10:44 +00001329 case E_OVERFLOW:
1330 msg = "expression too long";
1331 break;
Fred Drake85f36392000-07-11 17:53:00 +00001332 case E_DEDENT:
1333 errtype = PyExc_IndentationError;
1334 msg = "unindent does not match any outer indentation level";
1335 break;
1336 case E_TOODEEP:
1337 errtype = PyExc_IndentationError;
1338 msg = "too many levels of indentation";
1339 break;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001340 case E_DECODE: { /* XXX */
1341 PyThreadState* tstate = PyThreadState_Get();
1342 PyObject* value = tstate->curexc_value;
1343 if (value != NULL) {
1344 u = PyObject_Repr(value);
1345 if (u != NULL) {
1346 msg = PyString_AsString(u);
1347 break;
1348 }
1349 }
1350 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001351 default:
1352 fprintf(stderr, "error=%d\n", err->error);
1353 msg = "unknown parsing error";
1354 break;
1355 }
Guido van Rossum82598051997-03-05 00:20:32 +00001356 w = Py_BuildValue("(sO)", msg, v);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001357 Py_XDECREF(u);
Guido van Rossum41318302001-03-23 04:01:07 +00001358 Py_XDECREF(v);
Fred Drake85f36392000-07-11 17:53:00 +00001359 PyErr_SetObject(errtype, w);
Guido van Rossum82598051997-03-05 00:20:32 +00001360 Py_XDECREF(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001361}
1362
1363/* Print fatal error message and abort */
1364
1365void
Tim Peters7c321a82002-07-09 02:57:01 +00001366Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001367{
Guido van Rossum83dd6c31994-09-29 09:38:33 +00001368 fprintf(stderr, "Fatal Python error: %s\n", msg);
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001369#ifdef MS_WINDOWS
Guido van Rossum23c94461997-05-22 20:21:30 +00001370 OutputDebugString("Fatal Python error: ");
Guido van Rossuma44823b1995-03-14 15:01:17 +00001371 OutputDebugString(msg);
1372 OutputDebugString("\n");
Guido van Rossum0ba35361998-08-13 13:33:16 +00001373#ifdef _DEBUG
1374 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00001375#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001376#endif /* MS_WINDOWS */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001377 abort();
1378}
1379
1380/* Clean up and exit */
1381
Guido van Rossuma110aa61994-08-29 12:50:44 +00001382#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00001383#include "pythread.h"
Guido van Rossum82598051997-03-05 00:20:32 +00001384int _PyThread_Started = 0; /* Set by threadmodule.c and maybe others */
Guido van Rossumf9f2e821992-08-17 08:59:08 +00001385#endif
1386
Guido van Rossum2dcfc961998-10-01 16:01:57 +00001387#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001388static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00001389static int nexitfuncs = 0;
1390
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001391int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00001392{
1393 if (nexitfuncs >= NEXITFUNCS)
1394 return -1;
1395 exitfuncs[nexitfuncs++] = func;
1396 return 0;
1397}
1398
Guido van Rossumcc283f51997-08-05 02:22:03 +00001399static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001400call_sys_exitfunc(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001401{
Guido van Rossum82598051997-03-05 00:20:32 +00001402 PyObject *exitfunc = PySys_GetObject("exitfunc");
Guido van Rossum59bff391992-09-03 20:28:00 +00001403
1404 if (exitfunc) {
Fred Drake6a12d8d2001-03-23 17:34:02 +00001405 PyObject *res;
Guido van Rossum82598051997-03-05 00:20:32 +00001406 Py_INCREF(exitfunc);
1407 PySys_SetObject("exitfunc", (PyObject *)NULL);
1408 res = PyEval_CallObject(exitfunc, (PyObject *)NULL);
Guido van Rossum59bff391992-09-03 20:28:00 +00001409 if (res == NULL) {
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001410 if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
1411 PySys_WriteStderr("Error in sys.exitfunc:\n");
1412 }
Guido van Rossum82598051997-03-05 00:20:32 +00001413 PyErr_Print();
Guido van Rossum59bff391992-09-03 20:28:00 +00001414 }
Guido van Rossum82598051997-03-05 00:20:32 +00001415 Py_DECREF(exitfunc);
Guido van Rossum59bff391992-09-03 20:28:00 +00001416 }
1417
Guido van Rossum0829c751998-02-28 04:31:39 +00001418 if (Py_FlushLine())
1419 PyErr_Clear();
Guido van Rossumcc283f51997-08-05 02:22:03 +00001420}
Guido van Rossum1662dd51994-09-07 14:38:28 +00001421
Guido van Rossumcc283f51997-08-05 02:22:03 +00001422static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001423call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00001424{
Guido van Rossum1662dd51994-09-07 14:38:28 +00001425 while (nexitfuncs > 0)
1426 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00001427
1428 fflush(stdout);
1429 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001430}
1431
1432void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001433Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001434{
Guido van Rossumcc283f51997-08-05 02:22:03 +00001435 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001436
Jack Jansen66a89771995-10-27 13:22:14 +00001437#ifdef macintosh
1438 PyMac_Exit(sts);
1439#else
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001440 exit(sts);
Jack Jansen66a89771995-10-27 13:22:14 +00001441#endif
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001442}
1443
Guido van Rossumf1dc5661993-07-05 10:31:29 +00001444static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001445initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001446{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001447#ifdef HAVE_SIGNAL_H
1448#ifdef SIGPIPE
1449 signal(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001450#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00001451#ifdef SIGXFZ
1452 signal(SIGXFZ, SIG_IGN);
1453#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00001454#ifdef SIGXFSZ
1455 signal(SIGXFSZ, SIG_IGN);
1456#endif
Guido van Rossuma110aa61994-08-29 12:50:44 +00001457#endif /* HAVE_SIGNAL_H */
Guido van Rossum82598051997-03-05 00:20:32 +00001458 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001459}
1460
Guido van Rossuma110aa61994-08-29 12:50:44 +00001461#ifdef MPW
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001462
1463/* Check for file descriptor connected to interactive device.
1464 Pretend that stdin is always interactive, other files never. */
1465
1466int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001467isatty(int fd)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001468{
1469 return fd == fileno(stdin);
1470}
1471
1472#endif
Guido van Rossum7433b121997-02-14 19:45:36 +00001473
1474/*
1475 * The file descriptor fd is considered ``interactive'' if either
1476 * a) isatty(fd) is TRUE, or
1477 * b) the -i flag was given, and the filename associated with
1478 * the descriptor is NULL or "<stdin>" or "???".
1479 */
1480int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001481Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00001482{
1483 if (isatty((int)fileno(fp)))
1484 return 1;
1485 if (!Py_InteractiveFlag)
1486 return 0;
1487 return (filename == NULL) ||
1488 (strcmp(filename, "<stdin>") == 0) ||
1489 (strcmp(filename, "???") == 0);
1490}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001491
1492
Tim Petersd08e3822003-04-17 15:24:21 +00001493#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001494#if defined(WIN32) && defined(_MSC_VER)
1495
1496/* Stack checking for Microsoft C */
1497
1498#include <malloc.h>
1499#include <excpt.h>
1500
Fred Drakee8de31c2000-08-31 05:38:39 +00001501/*
1502 * Return non-zero when we run out of memory on the stack; zero otherwise.
1503 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001504int
Fred Drake399739f2000-08-31 05:52:44 +00001505PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001506{
1507 __try {
Tim Peters92e4dd82002-10-05 01:47:34 +00001508 /* alloca throws a stack overflow exception if there's
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001509 not enough space left on the stack */
Tim Peters92e4dd82002-10-05 01:47:34 +00001510 alloca(PYOS_STACK_MARGIN * sizeof(void*));
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001511 return 0;
1512 } __except (EXCEPTION_EXECUTE_HANDLER) {
1513 /* just ignore all errors */
1514 }
1515 return 1;
1516}
1517
1518#endif /* WIN32 && _MSC_VER */
1519
1520/* Alternate implementations can be added here... */
1521
1522#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00001523
1524
1525/* Wrappers around sigaction() or signal(). */
1526
1527PyOS_sighandler_t
1528PyOS_getsig(int sig)
1529{
1530#ifdef HAVE_SIGACTION
1531 struct sigaction context;
Barry Warsawafeb2a42001-11-13 23:08:26 +00001532 /* Initialize context.sa_handler to SIG_ERR which makes about as
1533 * much sense as anything else. It should get overwritten if
1534 * sigaction actually succeeds and otherwise we avoid an
1535 * uninitialized memory read.
1536 */
1537 context.sa_handler = SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00001538 sigaction(sig, NULL, &context);
1539 return context.sa_handler;
1540#else
1541 PyOS_sighandler_t handler;
1542 handler = signal(sig, SIG_IGN);
1543 signal(sig, handler);
1544 return handler;
1545#endif
1546}
1547
1548PyOS_sighandler_t
1549PyOS_setsig(int sig, PyOS_sighandler_t handler)
1550{
1551#ifdef HAVE_SIGACTION
1552 struct sigaction context;
1553 PyOS_sighandler_t oldhandler;
Barry Warsawafeb2a42001-11-13 23:08:26 +00001554 /* Initialize context.sa_handler to SIG_ERR which makes about as
1555 * much sense as anything else. It should get overwritten if
1556 * sigaction actually succeeds and otherwise we avoid an
1557 * uninitialized memory read.
1558 */
1559 context.sa_handler = SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00001560 sigaction(sig, NULL, &context);
1561 oldhandler = context.sa_handler;
1562 context.sa_handler = handler;
1563 sigaction(sig, &context, NULL);
1564 return oldhandler;
1565#else
1566 return signal(sig, handler);
1567#endif
1568}