blob: 0a9a63723c2f87cf41822f703a869747cd19de50 [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 Rossume13ddc92003-04-17 17:29:22 +0000258 /* Collect garbage. This may call finalizers; it's nice to call these
259 before all modules are destroyed. */
260 PyGC_Collect();
261
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000262 /* Destroy all modules */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000263 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000264
Guido van Rossume13ddc92003-04-17 17:29:22 +0000265 /* Collect final garbage. This disposes of cycles created by
266 new-style class definitions, for example. */
267 PyGC_Collect();
268
Guido van Rossum1707aad1997-12-08 23:43:45 +0000269 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
270 _PyImport_Fini();
271
272 /* Debugging stuff */
273#ifdef COUNT_ALLOCS
274 dump_counts();
275#endif
276
277#ifdef Py_REF_DEBUG
278 fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
279#endif
280
Tim Peters9cf25ce2003-04-17 15:21:01 +0000281#ifdef Py_TRACE_REFS
282 /* Display all objects still alive -- this can invoke arbitrary
283 * __repr__ overrides, so requires a mostly-intact interpreter.
284 * Alas, a lot of stuff may still be alive now that will be cleaned
285 * up later.
286 */
Tim Peters269b2a62003-04-17 19:52:29 +0000287 if (Py_GETENV("PYTHONDUMPREFS"))
Tim Peters9cf25ce2003-04-17 15:21:01 +0000288 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000289#endif /* Py_TRACE_REFS */
290
Barry Warsaw035574d1997-08-29 22:07:17 +0000291 /* Now we decref the exception classes. After this point nothing
292 can raise an exception. That's okay, because each Fini() method
293 below has been checked to make sure no exceptions are ever
294 raised.
295 */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000296 _PyExc_Fini();
Barry Warsawf242aa02000-05-25 23:09:49 +0000297
Guido van Rossumd922fa42003-04-15 14:10:09 +0000298 /* Clear interpreter state */
Barry Warsawf242aa02000-05-25 23:09:49 +0000299 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000300
Guido van Rossumd922fa42003-04-15 14:10:09 +0000301 /* Delete current thread */
Barry Warsawf242aa02000-05-25 23:09:49 +0000302 PyThreadState_Swap(NULL);
303 PyInterpreterState_Delete(interp);
304
Guido van Rossumd922fa42003-04-15 14:10:09 +0000305 /* Sundry finalizers */
Guido van Rossumcc283f51997-08-05 02:22:03 +0000306 PyMethod_Fini();
307 PyFrame_Fini();
308 PyCFunction_Fini();
309 PyTuple_Fini();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000310 PyString_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000311 PyInt_Fini();
312 PyFloat_Fini();
313
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000314#ifdef Py_USING_UNICODE
315 /* Cleanup Unicode implementation */
316 _PyUnicode_Fini();
317#endif
318
Guido van Rossumcc283f51997-08-05 02:22:03 +0000319 /* XXX Still allocated:
320 - various static ad-hoc pointers to interned strings
321 - int and float free list blocks
322 - whatever various modules and libraries allocate
323 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000324
325 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000326
Tim Peters269b2a62003-04-17 19:52:29 +0000327#ifdef Py_TRACE_REFS
328 /* Display addresses (& refcnts) of all objects still alive.
329 * An address can be used to find the repr of the object, printed
330 * above by _Py_PrintReferences.
331 */
332 if (Py_GETENV("PYTHONDUMPREFS"))
333 _Py_PrintReferenceAddresses(stderr);
334#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000335#ifdef PYMALLOC_DEBUG
336 if (Py_GETENV("PYTHONMALLOCSTATS"))
337 _PyObject_DebugMallocStats();
338#endif
339
Guido van Rossumcc283f51997-08-05 02:22:03 +0000340 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000341}
342
343/* Create and initialize a new interpreter and thread, and return the
344 new thread. This requires that Py_Initialize() has been called
345 first.
346
347 Unsuccessful initialization yields a NULL pointer. Note that *no*
348 exception information is available even in this case -- the
349 exception information is held in the thread, and there is no
350 thread.
351
352 Locking: as above.
353
354*/
355
356PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000357Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000358{
359 PyInterpreterState *interp;
360 PyThreadState *tstate, *save_tstate;
361 PyObject *bimod, *sysmod;
362
363 if (!initialized)
364 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
365
366 interp = PyInterpreterState_New();
367 if (interp == NULL)
368 return NULL;
369
370 tstate = PyThreadState_New(interp);
371 if (tstate == NULL) {
372 PyInterpreterState_Delete(interp);
373 return NULL;
374 }
375
376 save_tstate = PyThreadState_Swap(tstate);
377
378 /* XXX The following is lax in error checking */
379
380 interp->modules = PyDict_New();
381
382 bimod = _PyImport_FindExtension("__builtin__", "__builtin__");
383 if (bimod != NULL) {
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000384 interp->builtins = PyModule_GetDict(bimod);
385 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000386 }
387 sysmod = _PyImport_FindExtension("sys", "sys");
388 if (bimod != NULL && sysmod != NULL) {
389 interp->sysdict = PyModule_GetDict(sysmod);
390 Py_INCREF(interp->sysdict);
391 PySys_SetPath(Py_GetPath());
392 PyDict_SetItemString(interp->sysdict, "modules",
393 interp->modules);
Martin v. Löwisd7ceb222003-01-22 09:00:38 +0000394 _PyImportHooks_Init();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000395 initmain();
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000396 if (!Py_NoSiteFlag)
397 initsite();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000398 }
399
400 if (!PyErr_Occurred())
401 return tstate;
402
403 /* Oops, it didn't work. Undo it all. */
404
405 PyErr_Print();
406 PyThreadState_Clear(tstate);
407 PyThreadState_Swap(save_tstate);
408 PyThreadState_Delete(tstate);
409 PyInterpreterState_Delete(interp);
410
411 return NULL;
412}
413
414/* Delete an interpreter and its last thread. This requires that the
415 given thread state is current, that the thread has no remaining
416 frames, and that it is its interpreter's only remaining thread.
417 It is a fatal error to violate these constraints.
418
419 (Py_Finalize() doesn't have these constraints -- it zaps
420 everything, regardless.)
421
422 Locking: as above.
423
424*/
425
426void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000427Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000428{
429 PyInterpreterState *interp = tstate->interp;
430
431 if (tstate != PyThreadState_Get())
432 Py_FatalError("Py_EndInterpreter: thread is not current");
433 if (tstate->frame != NULL)
434 Py_FatalError("Py_EndInterpreter: thread still has a frame");
435 if (tstate != interp->tstate_head || tstate->next != NULL)
436 Py_FatalError("Py_EndInterpreter: not the last thread");
437
438 PyImport_Cleanup();
439 PyInterpreterState_Clear(interp);
440 PyThreadState_Swap(NULL);
441 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000442}
443
444static char *progname = "python";
445
446void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000447Py_SetProgramName(char *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000448{
449 if (pn && *pn)
450 progname = pn;
451}
452
453char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000454Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000455{
456 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000457}
458
Guido van Rossuma61691e1998-02-06 22:27:24 +0000459static char *default_home = NULL;
460
461void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000462Py_SetPythonHome(char *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000463{
464 default_home = home;
465}
466
467char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000468Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000469{
470 char *home = default_home;
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000471 if (home == NULL && !Py_IgnoreEnvironmentFlag)
472 home = Py_GETENV("PYTHONHOME");
Guido van Rossuma61691e1998-02-06 22:27:24 +0000473 return home;
474}
475
Guido van Rossum6135a871995-01-09 17:53:26 +0000476/* Create __main__ module */
477
478static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000479initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000480{
Guido van Rossum82598051997-03-05 00:20:32 +0000481 PyObject *m, *d;
482 m = PyImport_AddModule("__main__");
Guido van Rossum6135a871995-01-09 17:53:26 +0000483 if (m == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +0000484 Py_FatalError("can't create __main__ module");
485 d = PyModule_GetDict(m);
486 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
Guido van Rossum858cb731997-11-19 16:15:37 +0000487 PyObject *bimod = PyImport_ImportModule("__builtin__");
488 if (bimod == NULL ||
489 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
Guido van Rossum82598051997-03-05 00:20:32 +0000490 Py_FatalError("can't add __builtins__ to __main__");
Barry Warsaw3d05b1a1999-01-29 21:30:22 +0000491 Py_DECREF(bimod);
Guido van Rossum6135a871995-01-09 17:53:26 +0000492 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000493}
494
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000495/* Import the site module (not into __main__ though) */
496
497static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000498initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000499{
500 PyObject *m, *f;
501 m = PyImport_ImportModule("site");
502 if (m == NULL) {
503 f = PySys_GetObject("stderr");
504 if (Py_VerboseFlag) {
505 PyFile_WriteString(
506 "'import site' failed; traceback:\n", f);
507 PyErr_Print();
508 }
509 else {
510 PyFile_WriteString(
511 "'import site' failed; use -v for traceback\n", f);
512 PyErr_Clear();
513 }
514 }
515 else {
516 Py_DECREF(m);
517 }
518}
519
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000520/* Parse input from a file and execute it */
521
522int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000523PyRun_AnyFile(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000524{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000525 return PyRun_AnyFileExFlags(fp, filename, 0, NULL);
526}
527
528int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000529PyRun_AnyFileFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000530{
531 return PyRun_AnyFileExFlags(fp, filename, 0, flags);
Guido van Rossum0df002c2000-08-27 19:21:52 +0000532}
533
534int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000535PyRun_AnyFileEx(FILE *fp, const char *filename, int closeit)
Guido van Rossum0df002c2000-08-27 19:21:52 +0000536{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000537 return PyRun_AnyFileExFlags(fp, filename, closeit, NULL);
538}
539
540int
Tim Petersd08e3822003-04-17 15:24:21 +0000541PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000542 PyCompilerFlags *flags)
543{
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000544 if (filename == NULL)
545 filename = "???";
Guido van Rossum0df002c2000-08-27 19:21:52 +0000546 if (Py_FdIsInteractive(fp, filename)) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000547 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
Guido van Rossum0df002c2000-08-27 19:21:52 +0000548 if (closeit)
549 fclose(fp);
550 return err;
551 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000552 else
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000553 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000554}
555
556int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000557PyRun_InteractiveLoop(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000558{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000559 return PyRun_InteractiveLoopFlags(fp, filename, NULL);
560}
561
562int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000563PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000564{
Guido van Rossum82598051997-03-05 00:20:32 +0000565 PyObject *v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000566 int ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000567 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000568
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000569 if (flags == NULL) {
570 flags = &local_flags;
Tim Peters5ba58662001-07-16 02:29:45 +0000571 local_flags.cf_flags = 0;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000572 }
Guido van Rossum82598051997-03-05 00:20:32 +0000573 v = PySys_GetObject("ps1");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000574 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000575 PySys_SetObject("ps1", v = PyString_FromString(">>> "));
576 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000577 }
Guido van Rossum82598051997-03-05 00:20:32 +0000578 v = PySys_GetObject("ps2");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000579 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000580 PySys_SetObject("ps2", v = PyString_FromString("... "));
581 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000582 }
583 for (;;) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000584 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
Guido van Rossumaae0d321996-05-22 16:35:33 +0000585#ifdef Py_REF_DEBUG
Guido van Rossum6f9e4331995-03-29 16:57:48 +0000586 fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000587#endif
588 if (ret == E_EOF)
589 return 0;
590 /*
591 if (ret == E_NOMEM)
592 return -1;
593 */
594 }
595}
596
597int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000598PyRun_InteractiveOne(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000599{
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000600 return PyRun_InteractiveOneFlags(fp, filename, NULL);
601}
602
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000603/* compute parser flags based on compiler flags */
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000604#define PARSER_FLAGS(flags) \
Guido van Rossum4b499dd32003-02-13 22:07:59 +0000605 (((flags) && (flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
606 PyPARSE_DONT_IMPLY_DEDENT : 0)
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000607
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000608int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000609PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000610{
Guido van Rossum82598051997-03-05 00:20:32 +0000611 PyObject *m, *d, *v, *w;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000612 node *n;
Guido van Rossuma110aa61994-08-29 12:50:44 +0000613 perrdetail err;
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000614 char *ps1 = "", *ps2 = "";
Tim Petersfe2127d2001-07-16 05:37:24 +0000615
Guido van Rossum82598051997-03-05 00:20:32 +0000616 v = PySys_GetObject("ps1");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000617 if (v != NULL) {
618 v = PyObject_Str(v);
619 if (v == NULL)
620 PyErr_Clear();
621 else if (PyString_Check(v))
622 ps1 = PyString_AsString(v);
623 }
Guido van Rossum82598051997-03-05 00:20:32 +0000624 w = PySys_GetObject("ps2");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000625 if (w != NULL) {
626 w = PyObject_Str(w);
627 if (w == NULL)
628 PyErr_Clear();
629 else if (PyString_Check(w))
630 ps2 = PyString_AsString(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000631 }
Tim Petersfe2127d2001-07-16 05:37:24 +0000632 n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar,
633 Py_single_input, ps1, ps2, &err,
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000634 PARSER_FLAGS(flags));
Guido van Rossum82598051997-03-05 00:20:32 +0000635 Py_XDECREF(v);
636 Py_XDECREF(w);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000637 if (n == NULL) {
638 if (err.error == E_EOF) {
639 if (err.text)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000640 PyMem_DEL(err.text);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000641 return E_EOF;
642 }
643 err_input(&err);
Guido van Rossum82598051997-03-05 00:20:32 +0000644 PyErr_Print();
Guido van Rossuma110aa61994-08-29 12:50:44 +0000645 return err.error;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000646 }
Guido van Rossum82598051997-03-05 00:20:32 +0000647 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000648 if (m == NULL)
649 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000650 d = PyModule_GetDict(m);
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000651 v = run_node(n, filename, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000652 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000653 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000654 return -1;
655 }
Guido van Rossum82598051997-03-05 00:20:32 +0000656 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000657 if (Py_FlushLine())
658 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000659 return 0;
660}
661
662int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000663PyRun_SimpleFile(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000664{
Guido van Rossum0df002c2000-08-27 19:21:52 +0000665 return PyRun_SimpleFileEx(fp, filename, 0);
666}
667
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000668/* Check whether a file maybe a pyc file: Look at the extension,
669 the file type, and, if we may close it, at the first few bytes. */
670
671static int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000672maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000673{
674 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
675 return 1;
676
677#ifdef macintosh
678 /* On a mac, we also assume a pyc file for types 'PYC ' and 'APPL' */
Jack Jansen72f3b7a2002-12-13 15:23:10 +0000679 if (PyMac_getfiletype((char *)filename) == 'PYC '
680 || PyMac_getfiletype((char *)filename) == 'APPL')
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000681 return 1;
682#endif /* macintosh */
683
684 /* Only look into the file if we are allowed to close it, since
685 it then should also be seekable. */
686 if (closeit) {
687 /* Read only two bytes of the magic. If the file was opened in
688 text mode, the bytes 3 and 4 of the magic (\r\n) might not
689 be read as they are on disk. */
690 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
691 unsigned char buf[2];
Tim Peters3e876562001-02-11 04:35:39 +0000692 /* Mess: In case of -x, the stream is NOT at its start now,
693 and ungetc() was used to push back the first newline,
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000694 which makes the current stream position formally undefined,
695 and a x-platform nightmare.
696 Unfortunately, we have no direct way to know whether -x
697 was specified. So we use a terrible hack: if the current
698 stream position is not 0, we assume -x was specified, and
699 give up. Bug 132850 on SourceForge spells out the
700 hopelessness of trying anything else (fseek and ftell
701 don't work predictably x-platform for text-mode files).
Tim Peters3e876562001-02-11 04:35:39 +0000702 */
Tim Peters3e876562001-02-11 04:35:39 +0000703 int ispyc = 0;
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000704 if (ftell(fp) == 0) {
705 if (fread(buf, 1, 2, fp) == 2 &&
Tim Petersd08e3822003-04-17 15:24:21 +0000706 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000707 ispyc = 1;
708 rewind(fp);
709 }
Tim Peters3e876562001-02-11 04:35:39 +0000710 return ispyc;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000711 }
712 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +0000713}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000714
Guido van Rossum0df002c2000-08-27 19:21:52 +0000715int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000716PyRun_SimpleFileEx(FILE *fp, const char *filename, int closeit)
Guido van Rossum0df002c2000-08-27 19:21:52 +0000717{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000718 return PyRun_SimpleFileExFlags(fp, filename, closeit, NULL);
719}
720
721int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000722PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000723 PyCompilerFlags *flags)
724{
Guido van Rossum82598051997-03-05 00:20:32 +0000725 PyObject *m, *d, *v;
Martin v. Löwis95292d62002-12-11 14:04:59 +0000726 const char *ext;
Guido van Rossumfdef2711994-09-14 13:31:04 +0000727
Guido van Rossum82598051997-03-05 00:20:32 +0000728 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000729 if (m == NULL)
730 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000731 d = PyModule_GetDict(m);
Fred Drake8ed02042002-10-17 21:24:58 +0000732 if (PyDict_GetItemString(d, "__file__") == NULL) {
733 PyObject *f = PyString_FromString(filename);
734 if (f == NULL)
735 return -1;
736 if (PyDict_SetItemString(d, "__file__", f) < 0) {
737 Py_DECREF(f);
738 return -1;
739 }
740 Py_DECREF(f);
741 }
Guido van Rossumfdef2711994-09-14 13:31:04 +0000742 ext = filename + strlen(filename) - 4;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000743 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Guido van Rossumfdef2711994-09-14 13:31:04 +0000744 /* Try to run a pyc file. First, re-open in binary */
Guido van Rossum0df002c2000-08-27 19:21:52 +0000745 if (closeit)
746 fclose(fp);
Fred Drake8ed02042002-10-17 21:24:58 +0000747 if ((fp = fopen(filename, "rb")) == NULL) {
Guido van Rossumfdef2711994-09-14 13:31:04 +0000748 fprintf(stderr, "python: Can't reopen .pyc file\n");
749 return -1;
750 }
Guido van Rossum2a7f58d1997-04-02 05:28:38 +0000751 /* Turn on optimization if a .pyo file is given */
752 if (strcmp(ext, ".pyo") == 0)
753 Py_OptimizeFlag = 1;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000754 v = run_pyc_file(fp, filename, d, d, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000755 } else {
Tim Petersd08e3822003-04-17 15:24:21 +0000756 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000757 closeit, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000758 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000759 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000760 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000761 return -1;
762 }
Guido van Rossum82598051997-03-05 00:20:32 +0000763 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000764 if (Py_FlushLine())
765 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000766 return 0;
767}
768
769int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000770PyRun_SimpleString(const char *command)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000771{
Guido van Rossum393661d2001-08-31 17:40:15 +0000772 return PyRun_SimpleStringFlags(command, NULL);
773}
774
775int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000776PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +0000777{
Guido van Rossum82598051997-03-05 00:20:32 +0000778 PyObject *m, *d, *v;
779 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000780 if (m == NULL)
781 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000782 d = PyModule_GetDict(m);
Guido van Rossum393661d2001-08-31 17:40:15 +0000783 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000784 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000785 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000786 return -1;
787 }
Guido van Rossum82598051997-03-05 00:20:32 +0000788 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000789 if (Py_FlushLine())
790 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000791 return 0;
792}
793
Barry Warsaw035574d1997-08-29 22:07:17 +0000794static int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000795parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
796 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +0000797{
798 long hold;
799 PyObject *v;
800
801 /* old style errors */
802 if (PyTuple_Check(err))
Neal Norwitz78293352002-04-01 01:41:20 +0000803 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
804 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +0000805
806 /* new style errors. `err' is an instance */
807
808 if (! (v = PyObject_GetAttrString(err, "msg")))
809 goto finally;
810 *message = v;
811
812 if (!(v = PyObject_GetAttrString(err, "filename")))
813 goto finally;
814 if (v == Py_None)
815 *filename = NULL;
816 else if (! (*filename = PyString_AsString(v)))
817 goto finally;
818
819 Py_DECREF(v);
820 if (!(v = PyObject_GetAttrString(err, "lineno")))
821 goto finally;
822 hold = PyInt_AsLong(v);
823 Py_DECREF(v);
824 v = NULL;
825 if (hold < 0 && PyErr_Occurred())
826 goto finally;
827 *lineno = (int)hold;
828
829 if (!(v = PyObject_GetAttrString(err, "offset")))
830 goto finally;
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000831 if (v == Py_None) {
832 *offset = -1;
833 Py_DECREF(v);
834 v = NULL;
835 } else {
836 hold = PyInt_AsLong(v);
837 Py_DECREF(v);
838 v = NULL;
839 if (hold < 0 && PyErr_Occurred())
840 goto finally;
841 *offset = (int)hold;
842 }
Barry Warsaw035574d1997-08-29 22:07:17 +0000843
844 if (!(v = PyObject_GetAttrString(err, "text")))
845 goto finally;
846 if (v == Py_None)
847 *text = NULL;
848 else if (! (*text = PyString_AsString(v)))
849 goto finally;
850 Py_DECREF(v);
851 return 1;
852
853finally:
854 Py_XDECREF(v);
855 return 0;
856}
857
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000858void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000859PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000860{
Guido van Rossuma61691e1998-02-06 22:27:24 +0000861 PyErr_PrintEx(1);
862}
863
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000864static void
Martin v. Löwis95292d62002-12-11 14:04:59 +0000865print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000866{
867 char *nl;
868 if (offset >= 0) {
869 if (offset > 0 && offset == (int)strlen(text))
870 offset--;
871 for (;;) {
872 nl = strchr(text, '\n');
873 if (nl == NULL || nl-text >= offset)
874 break;
875 offset -= (nl+1-text);
876 text = nl+1;
877 }
878 while (*text == ' ' || *text == '\t') {
879 text++;
880 offset--;
881 }
882 }
883 PyFile_WriteString(" ", f);
884 PyFile_WriteString(text, f);
885 if (*text == '\0' || text[strlen(text)-1] != '\n')
886 PyFile_WriteString("\n", f);
887 if (offset == -1)
888 return;
889 PyFile_WriteString(" ", f);
890 offset--;
891 while (offset > 0) {
892 PyFile_WriteString(" ", f);
893 offset--;
894 }
895 PyFile_WriteString("^\n", f);
896}
897
Guido van Rossum66e8e862001-03-23 17:54:43 +0000898static void
899handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000900{
Guido van Rossum66e8e862001-03-23 17:54:43 +0000901 PyObject *exception, *value, *tb;
902 PyErr_Fetch(&exception, &value, &tb);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000903 if (Py_FlushLine())
904 PyErr_Clear();
905 fflush(stdout);
906 if (value == NULL || value == Py_None)
907 Py_Exit(0);
908 if (PyInstance_Check(value)) {
909 /* The error code should be in the `code' attribute. */
910 PyObject *code = PyObject_GetAttrString(value, "code");
911 if (code) {
912 Py_DECREF(value);
913 value = code;
914 if (value == Py_None)
915 Py_Exit(0);
916 }
917 /* If we failed to dig out the 'code' attribute,
918 just let the else clause below print the error. */
919 }
920 if (PyInt_Check(value))
921 Py_Exit((int)PyInt_AsLong(value));
922 else {
923 PyObject_Print(value, stderr, Py_PRINT_RAW);
924 PySys_WriteStderr("\n");
925 Py_Exit(1);
926 }
927}
928
929void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000930PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000931{
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000932 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +0000933
934 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
935 handle_system_exit();
936 }
Guido van Rossum82598051997-03-05 00:20:32 +0000937 PyErr_Fetch(&exception, &v, &tb);
Barry Warsaw035574d1997-08-29 22:07:17 +0000938 PyErr_NormalizeException(&exception, &v, &tb);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000939 if (exception == NULL)
Guido van Rossum296b4751997-05-23 00:19:20 +0000940 return;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000941 if (set_sys_last_vars) {
942 PySys_SetObject("last_type", exception);
943 PySys_SetObject("last_value", v);
944 PySys_SetObject("last_traceback", tb);
945 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000946 hook = PySys_GetObject("excepthook");
947 if (hook) {
948 PyObject *args = Py_BuildValue("(OOO)",
949 exception, v ? v : Py_None, tb ? tb : Py_None);
950 PyObject *result = PyEval_CallObject(hook, args);
951 if (result == NULL) {
952 PyObject *exception2, *v2, *tb2;
Guido van Rossum66e8e862001-03-23 17:54:43 +0000953 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
954 handle_system_exit();
955 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000956 PyErr_Fetch(&exception2, &v2, &tb2);
957 PyErr_NormalizeException(&exception2, &v2, &tb2);
958 if (Py_FlushLine())
959 PyErr_Clear();
960 fflush(stdout);
961 PySys_WriteStderr("Error in sys.excepthook:\n");
962 PyErr_Display(exception2, v2, tb2);
963 PySys_WriteStderr("\nOriginal exception was:\n");
964 PyErr_Display(exception, v, tb);
Jeremy Hylton07028582001-12-07 15:35:35 +0000965 Py_XDECREF(exception2);
966 Py_XDECREF(v2);
967 Py_XDECREF(tb2);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000968 }
969 Py_XDECREF(result);
970 Py_XDECREF(args);
971 } else {
972 PySys_WriteStderr("sys.excepthook is missing\n");
973 PyErr_Display(exception, v, tb);
974 }
975 Py_XDECREF(exception);
976 Py_XDECREF(v);
977 Py_XDECREF(tb);
978}
979
980void PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
981{
982 int err = 0;
983 PyObject *v = value;
984 PyObject *f = PySys_GetObject("stderr");
Guido van Rossum3165fe61992-09-25 21:59:05 +0000985 if (f == NULL)
986 fprintf(stderr, "lost sys.stderr\n");
987 else {
Guido van Rossum0829c751998-02-28 04:31:39 +0000988 if (Py_FlushLine())
989 PyErr_Clear();
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000990 fflush(stdout);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000991 if (tb && tb != Py_None)
992 err = PyTraceBack_Print(tb, f);
Barry Warsaw36b8f941997-08-26 18:09:48 +0000993 if (err == 0 &&
Martin v. Löwiscfeb3b62002-03-03 21:30:27 +0000994 PyObject_HasAttrString(v, "print_file_and_line"))
Barry Warsaw36b8f941997-08-26 18:09:48 +0000995 {
Guido van Rossum82598051997-03-05 00:20:32 +0000996 PyObject *message;
Martin v. Löwis95292d62002-12-11 14:04:59 +0000997 const char *filename, *text;
Guido van Rossuma110aa61994-08-29 12:50:44 +0000998 int lineno, offset;
Barry Warsaw035574d1997-08-29 22:07:17 +0000999 if (!parse_syntax_error(v, &message, &filename,
1000 &lineno, &offset, &text))
Guido van Rossum82598051997-03-05 00:20:32 +00001001 PyErr_Clear();
Guido van Rossuma110aa61994-08-29 12:50:44 +00001002 else {
1003 char buf[10];
Guido van Rossum82598051997-03-05 00:20:32 +00001004 PyFile_WriteString(" File \"", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001005 if (filename == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +00001006 PyFile_WriteString("<string>", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001007 else
Guido van Rossum82598051997-03-05 00:20:32 +00001008 PyFile_WriteString(filename, f);
1009 PyFile_WriteString("\", line ", f);
Jeremy Hylton518ab1c2001-11-28 20:42:20 +00001010 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
Guido van Rossum82598051997-03-05 00:20:32 +00001011 PyFile_WriteString(buf, f);
1012 PyFile_WriteString("\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001013 if (text != NULL)
1014 print_error_text(f, offset, text);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001015 v = message;
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001016 /* Can't be bothered to check all those
1017 PyFile_WriteString() calls */
1018 if (PyErr_Occurred())
1019 err = -1;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001020 }
1021 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001022 if (err) {
1023 /* Don't do anything else */
1024 }
1025 else if (PyClass_Check(exception)) {
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001026 PyClassObject* exc = (PyClassObject*)exception;
1027 PyObject* className = exc->cl_name;
1028 PyObject* moduleName =
1029 PyDict_GetItemString(exc->cl_dict, "__module__");
1030
1031 if (moduleName == NULL)
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001032 err = PyFile_WriteString("<unknown>", f);
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001033 else {
1034 char* modstr = PyString_AsString(moduleName);
Tim Petersd08e3822003-04-17 15:24:21 +00001035 if (modstr && strcmp(modstr, "exceptions"))
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001036 {
1037 err = PyFile_WriteString(modstr, f);
1038 err += PyFile_WriteString(".", f);
1039 }
1040 }
1041 if (err == 0) {
1042 if (className == NULL)
1043 err = PyFile_WriteString("<unknown>", f);
1044 else
1045 err = PyFile_WriteObject(className, f,
1046 Py_PRINT_RAW);
1047 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001048 }
1049 else
1050 err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
1051 if (err == 0) {
1052 if (v != NULL && v != Py_None) {
Barry Warsaw035574d1997-08-29 22:07:17 +00001053 PyObject *s = PyObject_Str(v);
1054 /* only print colon if the str() of the
1055 object is not the empty string
1056 */
Guido van Rossumd6bf45b1997-09-05 19:11:53 +00001057 if (s == NULL)
1058 err = -1;
1059 else if (!PyString_Check(s) ||
1060 PyString_GET_SIZE(s) != 0)
Barry Warsaw035574d1997-08-29 22:07:17 +00001061 err = PyFile_WriteString(": ", f);
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001062 if (err == 0)
Guido van Rossumd6bf45b1997-09-05 19:11:53 +00001063 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1064 Py_XDECREF(s);
Guido van Rossum262e1241995-02-07 15:30:45 +00001065 }
Guido van Rossum262e1241995-02-07 15:30:45 +00001066 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001067 if (err == 0)
1068 err = PyFile_WriteString("\n", f);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001069 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001070 /* If an error happened here, don't show it.
1071 XXX This is wrong, but too many callers rely on this behavior. */
1072 if (err != 0)
1073 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001074}
1075
Guido van Rossum82598051997-03-05 00:20:32 +00001076PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001077PyRun_String(const char *str, int start, PyObject *globals, PyObject *locals)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001078{
Guido van Rossum82598051997-03-05 00:20:32 +00001079 return run_err_node(PyParser_SimpleParseString(str, start),
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001080 "<string>", globals, locals, NULL);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001081}
1082
Guido van Rossum82598051997-03-05 00:20:32 +00001083PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001084PyRun_File(FILE *fp, const char *filename, int start, PyObject *globals,
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001085 PyObject *locals)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001086{
Tim Peterse8682112000-08-27 20:18:17 +00001087 return PyRun_FileEx(fp, filename, start, globals, locals, 0);
Guido van Rossum0df002c2000-08-27 19:21:52 +00001088}
1089
1090PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001091PyRun_FileEx(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001092 PyObject *locals, int closeit)
Guido van Rossum0df002c2000-08-27 19:21:52 +00001093{
1094 node *n = PyParser_SimpleParseFile(fp, filename, start);
1095 if (closeit)
1096 fclose(fp);
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001097 return run_err_node(n, filename, globals, locals, NULL);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001098}
1099
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001100PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001101PyRun_StringFlags(const char *str, int start, PyObject *globals, PyObject *locals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001102 PyCompilerFlags *flags)
1103{
Guido van Rossuma1b3a472001-07-16 16:51:33 +00001104 return run_err_node(PyParser_SimpleParseStringFlags(
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001105 str, start, PARSER_FLAGS(flags)),
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001106 "<string>", globals, locals, flags);
1107}
1108
1109PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001110PyRun_FileFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001111 PyObject *locals, PyCompilerFlags *flags)
1112{
1113 return PyRun_FileExFlags(fp, filename, start, globals, locals, 0,
Tim Petersd08e3822003-04-17 15:24:21 +00001114 flags);
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001115}
1116
1117PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001118PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001119 PyObject *locals, int closeit, PyCompilerFlags *flags)
1120{
Tim Petersfe2127d2001-07-16 05:37:24 +00001121 node *n = PyParser_SimpleParseFileFlags(fp, filename, start,
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001122 PARSER_FLAGS(flags));
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001123 if (closeit)
1124 fclose(fp);
1125 return run_err_node(n, filename, globals, locals, flags);
1126}
1127
Guido van Rossum82598051997-03-05 00:20:32 +00001128static PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001129run_err_node(node *n, const char *filename, PyObject *globals, PyObject *locals,
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001130 PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001131{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001132 if (n == NULL)
1133 return NULL;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001134 return run_node(n, filename, globals, locals, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001135}
1136
Guido van Rossum82598051997-03-05 00:20:32 +00001137static PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001138run_node(node *n, const char *filename, PyObject *globals, PyObject *locals,
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001139 PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001140{
Guido van Rossum82598051997-03-05 00:20:32 +00001141 PyCodeObject *co;
1142 PyObject *v;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001143 co = PyNode_CompileFlags(n, filename, flags);
Guido van Rossum82598051997-03-05 00:20:32 +00001144 PyNode_Free(n);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001145 if (co == NULL)
1146 return NULL;
Guido van Rossum82598051997-03-05 00:20:32 +00001147 v = PyEval_EvalCode(co, globals, locals);
1148 Py_DECREF(co);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001149 return v;
1150}
1151
Guido van Rossum82598051997-03-05 00:20:32 +00001152static PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001153run_pyc_file(FILE *fp, const char *filename, PyObject *globals, PyObject *locals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001154 PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001155{
Guido van Rossum82598051997-03-05 00:20:32 +00001156 PyCodeObject *co;
1157 PyObject *v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001158 long magic;
Fred Drakee8de31c2000-08-31 05:38:39 +00001159 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001160
Guido van Rossum82598051997-03-05 00:20:32 +00001161 magic = PyMarshal_ReadLongFromFile(fp);
1162 if (magic != PyImport_GetMagicNumber()) {
1163 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001164 "Bad magic number in .pyc file");
1165 return NULL;
1166 }
Guido van Rossum82598051997-03-05 00:20:32 +00001167 (void) PyMarshal_ReadLongFromFile(fp);
Tim Petersd9b9ac82001-01-28 00:27:39 +00001168 v = PyMarshal_ReadLastObjectFromFile(fp);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001169 fclose(fp);
Guido van Rossum82598051997-03-05 00:20:32 +00001170 if (v == NULL || !PyCode_Check(v)) {
1171 Py_XDECREF(v);
1172 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001173 "Bad code object in .pyc file");
1174 return NULL;
1175 }
Guido van Rossum82598051997-03-05 00:20:32 +00001176 co = (PyCodeObject *)v;
1177 v = PyEval_EvalCode(co, globals, locals);
Jeremy Hyltonb857ba22001-08-10 21:41:33 +00001178 if (v && flags)
1179 flags->cf_flags |= (co->co_flags & PyCF_MASK);
Guido van Rossum82598051997-03-05 00:20:32 +00001180 Py_DECREF(co);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001181 return v;
1182}
1183
Guido van Rossum82598051997-03-05 00:20:32 +00001184PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001185Py_CompileString(const char *str, const char *filename, int start)
Guido van Rossum5b722181993-03-30 17:46:03 +00001186{
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001187 return Py_CompileStringFlags(str, filename, start, NULL);
1188}
1189
1190PyObject *
Tim Petersd08e3822003-04-17 15:24:21 +00001191Py_CompileStringFlags(const char *str, const char *filename, int start,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001192 PyCompilerFlags *flags)
1193{
Guido van Rossum5b722181993-03-30 17:46:03 +00001194 node *n;
Guido van Rossum82598051997-03-05 00:20:32 +00001195 PyCodeObject *co;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001196
1197 n = PyParser_SimpleParseStringFlagsFilename(str, filename, start,
1198 PARSER_FLAGS(flags));
Guido van Rossuma110aa61994-08-29 12:50:44 +00001199 if (n == NULL)
Guido van Rossum5b722181993-03-30 17:46:03 +00001200 return NULL;
Jeremy Hylton673a4fd2001-03-26 19:53:38 +00001201 co = PyNode_CompileFlags(n, filename, flags);
Guido van Rossum82598051997-03-05 00:20:32 +00001202 PyNode_Free(n);
1203 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001204}
1205
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001206struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001207Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001208{
1209 node *n;
1210 struct symtable *st;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001211 n = PyParser_SimpleParseStringFlagsFilename(str, filename,
1212 start, 0);
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001213 if (n == NULL)
1214 return NULL;
1215 st = PyNode_CompileSymtable(n, filename);
1216 PyNode_Free(n);
1217 return st;
1218}
1219
Guido van Rossuma110aa61994-08-29 12:50:44 +00001220/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001221
Guido van Rossuma110aa61994-08-29 12:50:44 +00001222node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001223PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001224{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001225 node *n;
1226 perrdetail err;
Tim Petersfe2127d2001-07-16 05:37:24 +00001227 n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar, start,
1228 (char *)0, (char *)0, &err, flags);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001229 if (n == NULL)
1230 err_input(&err);
1231 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001232}
1233
Tim Petersfe2127d2001-07-16 05:37:24 +00001234node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001235PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
Tim Petersfe2127d2001-07-16 05:37:24 +00001236{
1237 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
1238}
1239
Guido van Rossuma110aa61994-08-29 12:50:44 +00001240/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001241
Guido van Rossuma110aa61994-08-29 12:50:44 +00001242node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001243PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001244{
1245 node *n;
1246 perrdetail err;
1247 n = PyParser_ParseStringFlags(str, &_PyParser_Grammar, start, &err,
1248 flags);
1249 if (n == NULL)
1250 err_input(&err);
1251 return n;
1252}
1253
1254node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001255PyParser_SimpleParseString(const char *str, int start)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001256{
Tim Petersfe2127d2001-07-16 05:37:24 +00001257 return PyParser_SimpleParseStringFlags(str, start, 0);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001258}
1259
Thomas Heller6b17abf2002-07-09 09:23:27 +00001260node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001261PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Thomas Heller6b17abf2002-07-09 09:23:27 +00001262 int start, int flags)
1263{
1264 node *n;
1265 perrdetail err;
1266
Tim Petersd08e3822003-04-17 15:24:21 +00001267 n = PyParser_ParseStringFlagsFilename(str, filename,
Thomas Heller6b17abf2002-07-09 09:23:27 +00001268 &_PyParser_Grammar,
1269 start, &err, flags);
1270 if (n == NULL)
1271 err_input(&err);
1272 return n;
1273}
1274
1275node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001276PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001277{
1278 return PyParser_SimpleParseStringFlagsFilename(str, filename,
1279 start, 0);
1280}
1281
Guido van Rossum66ebd912003-04-17 16:02:26 +00001282/* May want to move a more generalized form of this to parsetok.c or
1283 even parser modules. */
1284
1285void
1286PyParser_SetError(perrdetail *err)
1287{
1288 err_input(err);
1289}
1290
Guido van Rossuma110aa61994-08-29 12:50:44 +00001291/* Set the error appropriate to the given input error code (see errcode.h) */
1292
1293static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001294err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001295{
Fred Drake85f36392000-07-11 17:53:00 +00001296 PyObject *v, *w, *errtype;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001297 PyObject* u = NULL;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001298 char *msg = NULL;
Fred Drake85f36392000-07-11 17:53:00 +00001299 errtype = PyExc_SyntaxError;
Guido van Rossum82598051997-03-05 00:20:32 +00001300 v = Py_BuildValue("(ziiz)", err->filename,
Guido van Rossuma110aa61994-08-29 12:50:44 +00001301 err->lineno, err->offset, err->text);
1302 if (err->text != NULL) {
Guido van Rossumb18618d2000-05-03 23:44:39 +00001303 PyMem_DEL(err->text);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001304 err->text = NULL;
1305 }
1306 switch (err->error) {
1307 case E_SYNTAX:
Fred Drake85f36392000-07-11 17:53:00 +00001308 errtype = PyExc_IndentationError;
1309 if (err->expected == INDENT)
1310 msg = "expected an indented block";
1311 else if (err->token == INDENT)
1312 msg = "unexpected indent";
1313 else if (err->token == DEDENT)
1314 msg = "unexpected unindent";
1315 else {
1316 errtype = PyExc_SyntaxError;
1317 msg = "invalid syntax";
1318 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001319 break;
1320 case E_TOKEN:
1321 msg = "invalid token";
Guido van Rossuma110aa61994-08-29 12:50:44 +00001322 break;
Skip Montanaro118ec702002-08-15 01:20:16 +00001323 case E_EOFS:
1324 msg = "EOF while scanning triple-quoted string";
1325 break;
1326 case E_EOLS:
1327 msg = "EOL while scanning single-quoted string";
1328 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001329 case E_INTR:
Guido van Rossum82598051997-03-05 00:20:32 +00001330 PyErr_SetNone(PyExc_KeyboardInterrupt);
Barry Warsawc80baa31999-01-27 16:39:40 +00001331 Py_XDECREF(v);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001332 return;
1333 case E_NOMEM:
Guido van Rossum82598051997-03-05 00:20:32 +00001334 PyErr_NoMemory();
Barry Warsawc80baa31999-01-27 16:39:40 +00001335 Py_XDECREF(v);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001336 return;
1337 case E_EOF:
1338 msg = "unexpected EOF while parsing";
1339 break;
Fred Drake85f36392000-07-11 17:53:00 +00001340 case E_TABSPACE:
1341 errtype = PyExc_TabError;
Guido van Rossum560e8ad1998-04-10 19:43:42 +00001342 msg = "inconsistent use of tabs and spaces in indentation";
1343 break;
Jeremy Hylton94988062000-06-20 19:10:44 +00001344 case E_OVERFLOW:
1345 msg = "expression too long";
1346 break;
Fred Drake85f36392000-07-11 17:53:00 +00001347 case E_DEDENT:
1348 errtype = PyExc_IndentationError;
1349 msg = "unindent does not match any outer indentation level";
1350 break;
1351 case E_TOODEEP:
1352 errtype = PyExc_IndentationError;
1353 msg = "too many levels of indentation";
1354 break;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001355 case E_DECODE: { /* XXX */
1356 PyThreadState* tstate = PyThreadState_Get();
1357 PyObject* value = tstate->curexc_value;
1358 if (value != NULL) {
1359 u = PyObject_Repr(value);
1360 if (u != NULL) {
1361 msg = PyString_AsString(u);
1362 break;
1363 }
1364 }
1365 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001366 default:
1367 fprintf(stderr, "error=%d\n", err->error);
1368 msg = "unknown parsing error";
1369 break;
1370 }
Guido van Rossum82598051997-03-05 00:20:32 +00001371 w = Py_BuildValue("(sO)", msg, v);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001372 Py_XDECREF(u);
Guido van Rossum41318302001-03-23 04:01:07 +00001373 Py_XDECREF(v);
Fred Drake85f36392000-07-11 17:53:00 +00001374 PyErr_SetObject(errtype, w);
Guido van Rossum82598051997-03-05 00:20:32 +00001375 Py_XDECREF(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001376}
1377
1378/* Print fatal error message and abort */
1379
1380void
Tim Peters7c321a82002-07-09 02:57:01 +00001381Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001382{
Guido van Rossum83dd6c31994-09-29 09:38:33 +00001383 fprintf(stderr, "Fatal Python error: %s\n", msg);
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001384#ifdef MS_WINDOWS
Guido van Rossum23c94461997-05-22 20:21:30 +00001385 OutputDebugString("Fatal Python error: ");
Guido van Rossuma44823b1995-03-14 15:01:17 +00001386 OutputDebugString(msg);
1387 OutputDebugString("\n");
Guido van Rossum0ba35361998-08-13 13:33:16 +00001388#ifdef _DEBUG
1389 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00001390#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001391#endif /* MS_WINDOWS */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001392 abort();
1393}
1394
1395/* Clean up and exit */
1396
Guido van Rossuma110aa61994-08-29 12:50:44 +00001397#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00001398#include "pythread.h"
Guido van Rossum82598051997-03-05 00:20:32 +00001399int _PyThread_Started = 0; /* Set by threadmodule.c and maybe others */
Guido van Rossumf9f2e821992-08-17 08:59:08 +00001400#endif
1401
Guido van Rossum2dcfc961998-10-01 16:01:57 +00001402#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001403static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00001404static int nexitfuncs = 0;
1405
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001406int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00001407{
1408 if (nexitfuncs >= NEXITFUNCS)
1409 return -1;
1410 exitfuncs[nexitfuncs++] = func;
1411 return 0;
1412}
1413
Guido van Rossumcc283f51997-08-05 02:22:03 +00001414static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001415call_sys_exitfunc(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001416{
Guido van Rossum82598051997-03-05 00:20:32 +00001417 PyObject *exitfunc = PySys_GetObject("exitfunc");
Guido van Rossum59bff391992-09-03 20:28:00 +00001418
1419 if (exitfunc) {
Fred Drake6a12d8d2001-03-23 17:34:02 +00001420 PyObject *res;
Guido van Rossum82598051997-03-05 00:20:32 +00001421 Py_INCREF(exitfunc);
1422 PySys_SetObject("exitfunc", (PyObject *)NULL);
1423 res = PyEval_CallObject(exitfunc, (PyObject *)NULL);
Guido van Rossum59bff391992-09-03 20:28:00 +00001424 if (res == NULL) {
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001425 if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
1426 PySys_WriteStderr("Error in sys.exitfunc:\n");
1427 }
Guido van Rossum82598051997-03-05 00:20:32 +00001428 PyErr_Print();
Guido van Rossum59bff391992-09-03 20:28:00 +00001429 }
Guido van Rossum82598051997-03-05 00:20:32 +00001430 Py_DECREF(exitfunc);
Guido van Rossum59bff391992-09-03 20:28:00 +00001431 }
1432
Guido van Rossum0829c751998-02-28 04:31:39 +00001433 if (Py_FlushLine())
1434 PyErr_Clear();
Guido van Rossumcc283f51997-08-05 02:22:03 +00001435}
Guido van Rossum1662dd51994-09-07 14:38:28 +00001436
Guido van Rossumcc283f51997-08-05 02:22:03 +00001437static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001438call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00001439{
Guido van Rossum1662dd51994-09-07 14:38:28 +00001440 while (nexitfuncs > 0)
1441 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00001442
1443 fflush(stdout);
1444 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001445}
1446
1447void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001448Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001449{
Guido van Rossumcc283f51997-08-05 02:22:03 +00001450 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001451
Jack Jansen66a89771995-10-27 13:22:14 +00001452#ifdef macintosh
1453 PyMac_Exit(sts);
1454#else
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001455 exit(sts);
Jack Jansen66a89771995-10-27 13:22:14 +00001456#endif
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001457}
1458
Guido van Rossumf1dc5661993-07-05 10:31:29 +00001459static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001460initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001461{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001462#ifdef HAVE_SIGNAL_H
1463#ifdef SIGPIPE
1464 signal(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001465#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00001466#ifdef SIGXFZ
1467 signal(SIGXFZ, SIG_IGN);
1468#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00001469#ifdef SIGXFSZ
1470 signal(SIGXFSZ, SIG_IGN);
1471#endif
Guido van Rossuma110aa61994-08-29 12:50:44 +00001472#endif /* HAVE_SIGNAL_H */
Guido van Rossum82598051997-03-05 00:20:32 +00001473 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001474}
1475
Guido van Rossuma110aa61994-08-29 12:50:44 +00001476#ifdef MPW
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001477
1478/* Check for file descriptor connected to interactive device.
1479 Pretend that stdin is always interactive, other files never. */
1480
1481int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001482isatty(int fd)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001483{
1484 return fd == fileno(stdin);
1485}
1486
1487#endif
Guido van Rossum7433b121997-02-14 19:45:36 +00001488
1489/*
1490 * The file descriptor fd is considered ``interactive'' if either
1491 * a) isatty(fd) is TRUE, or
1492 * b) the -i flag was given, and the filename associated with
1493 * the descriptor is NULL or "<stdin>" or "???".
1494 */
1495int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001496Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00001497{
1498 if (isatty((int)fileno(fp)))
1499 return 1;
1500 if (!Py_InteractiveFlag)
1501 return 0;
1502 return (filename == NULL) ||
1503 (strcmp(filename, "<stdin>") == 0) ||
1504 (strcmp(filename, "???") == 0);
1505}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001506
1507
Tim Petersd08e3822003-04-17 15:24:21 +00001508#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001509#if defined(WIN32) && defined(_MSC_VER)
1510
1511/* Stack checking for Microsoft C */
1512
1513#include <malloc.h>
1514#include <excpt.h>
1515
Fred Drakee8de31c2000-08-31 05:38:39 +00001516/*
1517 * Return non-zero when we run out of memory on the stack; zero otherwise.
1518 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001519int
Fred Drake399739f2000-08-31 05:52:44 +00001520PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001521{
1522 __try {
Tim Peters92e4dd82002-10-05 01:47:34 +00001523 /* alloca throws a stack overflow exception if there's
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001524 not enough space left on the stack */
Tim Peters92e4dd82002-10-05 01:47:34 +00001525 alloca(PYOS_STACK_MARGIN * sizeof(void*));
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001526 return 0;
1527 } __except (EXCEPTION_EXECUTE_HANDLER) {
1528 /* just ignore all errors */
1529 }
1530 return 1;
1531}
1532
1533#endif /* WIN32 && _MSC_VER */
1534
1535/* Alternate implementations can be added here... */
1536
1537#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00001538
1539
1540/* Wrappers around sigaction() or signal(). */
1541
1542PyOS_sighandler_t
1543PyOS_getsig(int sig)
1544{
1545#ifdef HAVE_SIGACTION
1546 struct sigaction context;
Barry Warsawafeb2a42001-11-13 23:08:26 +00001547 /* Initialize context.sa_handler to SIG_ERR which makes about as
1548 * much sense as anything else. It should get overwritten if
1549 * sigaction actually succeeds and otherwise we avoid an
1550 * uninitialized memory read.
1551 */
1552 context.sa_handler = SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00001553 sigaction(sig, NULL, &context);
1554 return context.sa_handler;
1555#else
1556 PyOS_sighandler_t handler;
1557 handler = signal(sig, SIG_IGN);
1558 signal(sig, handler);
1559 return handler;
1560#endif
1561}
1562
1563PyOS_sighandler_t
1564PyOS_setsig(int sig, PyOS_sighandler_t handler)
1565{
1566#ifdef HAVE_SIGACTION
1567 struct sigaction context;
1568 PyOS_sighandler_t oldhandler;
Barry Warsawafeb2a42001-11-13 23:08:26 +00001569 /* Initialize context.sa_handler to SIG_ERR which makes about as
1570 * much sense as anything else. It should get overwritten if
1571 * sigaction actually succeeds and otherwise we avoid an
1572 * uninitialized memory read.
1573 */
1574 context.sa_handler = SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00001575 sigaction(sig, NULL, &context);
1576 oldhandler = context.sa_handler;
1577 context.sa_handler = handler;
1578 sigaction(sig, &context, NULL);
1579 return oldhandler;
1580#else
1581 return signal(sig, handler);
1582#endif
1583}