blob: a8dedde7c11d877b2f93df684d0210d0c1094a6b [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
Mark Hammond8d98d2c2003-04-19 15:41:53 +000053#ifdef WITH_THREAD
54extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
55extern void _PyGILState_Fini(void);
56#endif /* WITH_THREAD */
57
Guido van Rossum82598051997-03-05 00:20:32 +000058int Py_DebugFlag; /* Needed by parser.c */
59int Py_VerboseFlag; /* Needed by import.c */
Guido van Rossum7433b121997-02-14 19:45:36 +000060int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Guido van Rossumdcc0c131997-08-29 22:32:42 +000061int Py_NoSiteFlag; /* Suppress 'import site' */
Barry Warsaw3ce09642000-05-02 19:18:59 +000062int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +000063int Py_FrozenFlag; /* Needed by getpath.c */
Guido van Rossumb16d1972000-05-01 17:55:15 +000064int Py_UnicodeFlag = 0; /* Needed by compile.c */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +000065int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Tim Peters3caca232001-12-06 06:23:26 +000066/* _XXX Py_QnewFlag should go away in 2.3. It's true iff -Qnew is passed,
67 on the command line, and is used in 2.2 by ceval.c to make all "/" divisions
68 true divisions (which they will be in 2.3). */
69int _Py_QnewFlag = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +000070
Mark Hammonda43fd0c2003-02-19 00:33:33 +000071/* Reference to 'warnings' module, to avoid importing it
72 on the fly when the import lock may be held. See 683658
73*/
74PyObject *PyModule_WarningsModule = NULL;
75
Guido van Rossum25ce5661997-08-02 03:10:38 +000076static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +000077
Thomas Wouters7e474022000-07-16 12:04:32 +000078/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +000079
80int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000081Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +000082{
83 return initialized;
84}
85
Guido van Rossum25ce5661997-08-02 03:10:38 +000086/* Global initializations. Can be undone by Py_Finalize(). Don't
87 call this twice without an intervening Py_Finalize() call. When
88 initializations fail, a fatal error is issued and the function does
89 not return. On return, the first thread and interpreter state have
90 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +000091
Guido van Rossum25ce5661997-08-02 03:10:38 +000092 Locking: you must hold the interpreter lock while calling this.
93 (If the lock has not yet been initialized, that's equivalent to
94 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000095
Guido van Rossum25ce5661997-08-02 03:10:38 +000096*/
Guido van Rossuma027efa1997-05-05 20:56:21 +000097
Guido van Rossum9abaf4d2001-10-12 22:17:56 +000098static int
99add_flag(int flag, const char *envs)
100{
101 int env = atoi(envs);
102 if (flag < env)
103 flag = env;
104 if (flag < 1)
105 flag = 1;
106 return flag;
107}
108
Guido van Rossuma027efa1997-05-05 20:56:21 +0000109void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000110Py_Initialize(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000111{
Guido van Rossuma027efa1997-05-05 20:56:21 +0000112 PyInterpreterState *interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000113 PyThreadState *tstate;
114 PyObject *bimod, *sysmod;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000115 char *p;
Guido van Rossum70d893a2001-08-16 08:21:42 +0000116 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000117
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000118 if (initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +0000119 return;
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000120 initialized = 1;
Tim Petersd08e3822003-04-17 15:24:21 +0000121
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000122 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000123 Py_DebugFlag = add_flag(Py_DebugFlag, p);
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000124 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000125 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000126 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000127 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000128
Guido van Rossuma027efa1997-05-05 20:56:21 +0000129 interp = PyInterpreterState_New();
130 if (interp == NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000131 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000132
Guido van Rossuma027efa1997-05-05 20:56:21 +0000133 tstate = PyThreadState_New(interp);
134 if (tstate == NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000135 Py_FatalError("Py_Initialize: can't make first thread");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000136 (void) PyThreadState_Swap(tstate);
137
Guido van Rossum70d893a2001-08-16 08:21:42 +0000138 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000139
Neal Norwitzb2501f42002-12-31 03:42:13 +0000140 if (!_PyFrame_Init())
Neal Norwitzc91ed402002-12-30 22:29:22 +0000141 Py_FatalError("Py_Initialize: can't init frames");
142
Neal Norwitzb2501f42002-12-31 03:42:13 +0000143 if (!_PyInt_Init())
Neal Norwitzc91ed402002-12-30 22:29:22 +0000144 Py_FatalError("Py_Initialize: can't init ints");
145
Guido van Rossum25ce5661997-08-02 03:10:38 +0000146 interp->modules = PyDict_New();
147 if (interp->modules == NULL)
148 Py_FatalError("Py_Initialize: can't make modules dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000149
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000150#ifdef Py_USING_UNICODE
Guido van Rossumc94044c2000-03-10 23:03:54 +0000151 /* Init Unicode implementation; relies on the codec registry */
152 _PyUnicode_Init();
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000153#endif
Guido van Rossumc94044c2000-03-10 23:03:54 +0000154
Barry Warsawf242aa02000-05-25 23:09:49 +0000155 bimod = _PyBuiltin_Init();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000156 if (bimod == NULL)
157 Py_FatalError("Py_Initialize: can't initialize __builtin__");
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000158 interp->builtins = PyModule_GetDict(bimod);
159 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000160
161 sysmod = _PySys_Init();
162 if (sysmod == NULL)
163 Py_FatalError("Py_Initialize: can't initialize sys");
164 interp->sysdict = PyModule_GetDict(sysmod);
165 Py_INCREF(interp->sysdict);
166 _PyImport_FixupExtension("sys", "sys");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000167 PySys_SetPath(Py_GetPath());
Guido van Rossum25ce5661997-08-02 03:10:38 +0000168 PyDict_SetItemString(interp->sysdict, "modules",
169 interp->modules);
170
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000171 _PyImport_Init();
172
Barry Warsawf242aa02000-05-25 23:09:49 +0000173 /* initialize builtin exceptions */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000174 _PyExc_Init();
Barry Warsaw5821bc52001-08-13 23:04:56 +0000175 _PyImport_FixupExtension("exceptions", "exceptions");
Barry Warsawf242aa02000-05-25 23:09:49 +0000176
Barry Warsaw035574d1997-08-29 22:07:17 +0000177 /* phase 2 of builtins */
Barry Warsaw963b8711997-09-18 16:42:02 +0000178 _PyImport_FixupExtension("__builtin__", "__builtin__");
Barry Warsaw035574d1997-08-29 22:07:17 +0000179
Just van Rossum52e14d62002-12-30 22:08:05 +0000180 _PyImportHooks_Init();
181
Guido van Rossum25ce5661997-08-02 03:10:38 +0000182 initsigs(); /* Signal handling stuff, including initintr() */
183
184 initmain(); /* Module __main__ */
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000185 if (!Py_NoSiteFlag)
186 initsite(); /* Module site */
Just van Rossum5bfba3a2003-02-25 20:25:12 +0000187
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000188 /* auto-thread-state API, if available */
189#ifdef WITH_THREAD
190 _PyGILState_Init(interp, tstate);
191#endif /* WITH_THREAD */
192
Just van Rossum5bfba3a2003-02-25 20:25:12 +0000193 PyModule_WarningsModule = PyImport_ImportModule("warnings");
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000194
195#if defined(Py_USING_UNICODE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
196 /* On Unix, set the file system encoding according to the
197 user's preference, if the CODESET names a well-known
198 Python codec, and Py_FileSystemDefaultEncoding isn't
199 initialized by other means. */
200 if (!Py_FileSystemDefaultEncoding) {
201 char *saved_locale = setlocale(LC_CTYPE, NULL);
202 char *codeset;
203 setlocale(LC_CTYPE, "");
204 codeset = nl_langinfo(CODESET);
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000205 if (*codeset) {
Neal Norwitz5c16c7b2003-04-10 21:53:14 +0000206 PyObject *enc = PyCodec_Encoder(codeset);
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000207 if (enc) {
208 Py_FileSystemDefaultEncoding = strdup(codeset);
209 Py_DECREF(enc);
210 } else
211 PyErr_Clear();
212 }
213 setlocale(LC_CTYPE, saved_locale);
214 }
215#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000216}
217
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000218#ifdef COUNT_ALLOCS
Tim Petersdbd9ba62000-07-09 03:09:57 +0000219extern void dump_counts(void);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000220#endif
221
Guido van Rossum25ce5661997-08-02 03:10:38 +0000222/* Undo the effect of Py_Initialize().
223
224 Beware: if multiple interpreter and/or thread states exist, these
225 are not wiped out; only the current thread and interpreter state
226 are deleted. But since everything else is deleted, those other
227 interpreter and thread states should no longer be used.
228
229 (XXX We should do better, e.g. wipe out all interpreters and
230 threads.)
231
232 Locking: as above.
233
234*/
235
236void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000237Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000238{
239 PyInterpreterState *interp;
240 PyThreadState *tstate;
241
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000242 if (!initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +0000243 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000244
Tim Peters384fd102001-01-21 03:40:37 +0000245 /* The interpreter is still entirely intact at this point, and the
246 * exit funcs may be relying on that. In particular, if some thread
247 * or exit func is still waiting to do an import, the import machinery
248 * expects Py_IsInitialized() to return true. So don't say the
249 * interpreter is uninitialized until after the exit funcs have run.
250 * Note that Threading.py uses an exit func to do a join on all the
251 * threads created thru it, so this also protects pending imports in
252 * the threads created via Threading.
253 */
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000254 call_sys_exitfunc();
Tim Peters384fd102001-01-21 03:40:37 +0000255 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000256
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000257 /* Get current thread state and interpreter pointer */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000258 tstate = PyThreadState_Get();
259 interp = tstate->interp;
260
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000261 /* Disable signal handling */
262 PyOS_FiniInterrupts();
263
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000264 /* drop module references we saved */
265 Py_XDECREF(PyModule_WarningsModule);
266 PyModule_WarningsModule = NULL;
267
Guido van Rossume13ddc92003-04-17 17:29:22 +0000268 /* Collect garbage. This may call finalizers; it's nice to call these
269 before all modules are destroyed. */
270 PyGC_Collect();
271
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000272 /* Destroy all modules */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000273 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000274
Guido van Rossume13ddc92003-04-17 17:29:22 +0000275 /* Collect final garbage. This disposes of cycles created by
276 new-style class definitions, for example. */
277 PyGC_Collect();
278
Guido van Rossum1707aad1997-12-08 23:43:45 +0000279 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
280 _PyImport_Fini();
281
282 /* Debugging stuff */
283#ifdef COUNT_ALLOCS
284 dump_counts();
285#endif
286
287#ifdef Py_REF_DEBUG
288 fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
289#endif
290
Tim Peters9cf25ce2003-04-17 15:21:01 +0000291#ifdef Py_TRACE_REFS
292 /* Display all objects still alive -- this can invoke arbitrary
293 * __repr__ overrides, so requires a mostly-intact interpreter.
294 * Alas, a lot of stuff may still be alive now that will be cleaned
295 * up later.
296 */
Tim Peters269b2a62003-04-17 19:52:29 +0000297 if (Py_GETENV("PYTHONDUMPREFS"))
Tim Peters9cf25ce2003-04-17 15:21:01 +0000298 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000299#endif /* Py_TRACE_REFS */
300
Barry Warsaw035574d1997-08-29 22:07:17 +0000301 /* Now we decref the exception classes. After this point nothing
302 can raise an exception. That's okay, because each Fini() method
303 below has been checked to make sure no exceptions are ever
304 raised.
305 */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000306 _PyExc_Fini();
Barry Warsawf242aa02000-05-25 23:09:49 +0000307
Mark Hammond6cb90292003-04-22 11:18:00 +0000308 /* Cleanup auto-thread-state */
309#ifdef WITH_THREAD
310 _PyGILState_Fini();
311#endif /* WITH_THREAD */
312
Guido van Rossumd922fa42003-04-15 14:10:09 +0000313 /* Clear interpreter state */
Barry Warsawf242aa02000-05-25 23:09:49 +0000314 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000315
Guido van Rossumd922fa42003-04-15 14:10:09 +0000316 /* Delete current thread */
Barry Warsawf242aa02000-05-25 23:09:49 +0000317 PyThreadState_Swap(NULL);
318 PyInterpreterState_Delete(interp);
319
Guido van Rossumd922fa42003-04-15 14:10:09 +0000320 /* Sundry finalizers */
Guido van Rossumcc283f51997-08-05 02:22:03 +0000321 PyMethod_Fini();
322 PyFrame_Fini();
323 PyCFunction_Fini();
324 PyTuple_Fini();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000325 PyString_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000326 PyInt_Fini();
327 PyFloat_Fini();
328
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000329#ifdef Py_USING_UNICODE
330 /* Cleanup Unicode implementation */
331 _PyUnicode_Fini();
332#endif
333
Guido van Rossumcc283f51997-08-05 02:22:03 +0000334 /* XXX Still allocated:
335 - various static ad-hoc pointers to interned strings
336 - int and float free list blocks
337 - whatever various modules and libraries allocate
338 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000339
340 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000341
Tim Peters269b2a62003-04-17 19:52:29 +0000342#ifdef Py_TRACE_REFS
343 /* Display addresses (& refcnts) of all objects still alive.
344 * An address can be used to find the repr of the object, printed
345 * above by _Py_PrintReferences.
346 */
347 if (Py_GETENV("PYTHONDUMPREFS"))
348 _Py_PrintReferenceAddresses(stderr);
349#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000350#ifdef PYMALLOC_DEBUG
351 if (Py_GETENV("PYTHONMALLOCSTATS"))
352 _PyObject_DebugMallocStats();
353#endif
354
Guido van Rossumcc283f51997-08-05 02:22:03 +0000355 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000356}
357
358/* Create and initialize a new interpreter and thread, and return the
359 new thread. This requires that Py_Initialize() has been called
360 first.
361
362 Unsuccessful initialization yields a NULL pointer. Note that *no*
363 exception information is available even in this case -- the
364 exception information is held in the thread, and there is no
365 thread.
366
367 Locking: as above.
368
369*/
370
371PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000372Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000373{
374 PyInterpreterState *interp;
375 PyThreadState *tstate, *save_tstate;
376 PyObject *bimod, *sysmod;
377
378 if (!initialized)
379 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
380
381 interp = PyInterpreterState_New();
382 if (interp == NULL)
383 return NULL;
384
385 tstate = PyThreadState_New(interp);
386 if (tstate == NULL) {
387 PyInterpreterState_Delete(interp);
388 return NULL;
389 }
390
391 save_tstate = PyThreadState_Swap(tstate);
392
393 /* XXX The following is lax in error checking */
394
395 interp->modules = PyDict_New();
396
397 bimod = _PyImport_FindExtension("__builtin__", "__builtin__");
398 if (bimod != NULL) {
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000399 interp->builtins = PyModule_GetDict(bimod);
400 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000401 }
402 sysmod = _PyImport_FindExtension("sys", "sys");
403 if (bimod != NULL && sysmod != NULL) {
404 interp->sysdict = PyModule_GetDict(sysmod);
405 Py_INCREF(interp->sysdict);
406 PySys_SetPath(Py_GetPath());
407 PyDict_SetItemString(interp->sysdict, "modules",
408 interp->modules);
Martin v. Löwisd7ceb222003-01-22 09:00:38 +0000409 _PyImportHooks_Init();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000410 initmain();
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000411 if (!Py_NoSiteFlag)
412 initsite();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000413 }
414
415 if (!PyErr_Occurred())
416 return tstate;
417
418 /* Oops, it didn't work. Undo it all. */
419
420 PyErr_Print();
421 PyThreadState_Clear(tstate);
422 PyThreadState_Swap(save_tstate);
423 PyThreadState_Delete(tstate);
424 PyInterpreterState_Delete(interp);
425
426 return NULL;
427}
428
429/* Delete an interpreter and its last thread. This requires that the
430 given thread state is current, that the thread has no remaining
431 frames, and that it is its interpreter's only remaining thread.
432 It is a fatal error to violate these constraints.
433
434 (Py_Finalize() doesn't have these constraints -- it zaps
435 everything, regardless.)
436
437 Locking: as above.
438
439*/
440
441void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000442Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000443{
444 PyInterpreterState *interp = tstate->interp;
445
446 if (tstate != PyThreadState_Get())
447 Py_FatalError("Py_EndInterpreter: thread is not current");
448 if (tstate->frame != NULL)
449 Py_FatalError("Py_EndInterpreter: thread still has a frame");
450 if (tstate != interp->tstate_head || tstate->next != NULL)
451 Py_FatalError("Py_EndInterpreter: not the last thread");
452
453 PyImport_Cleanup();
454 PyInterpreterState_Clear(interp);
455 PyThreadState_Swap(NULL);
456 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000457}
458
459static char *progname = "python";
460
461void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000462Py_SetProgramName(char *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000463{
464 if (pn && *pn)
465 progname = pn;
466}
467
468char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000469Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000470{
471 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000472}
473
Guido van Rossuma61691e1998-02-06 22:27:24 +0000474static char *default_home = NULL;
475
476void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000477Py_SetPythonHome(char *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000478{
479 default_home = home;
480}
481
482char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000483Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000484{
485 char *home = default_home;
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000486 if (home == NULL && !Py_IgnoreEnvironmentFlag)
487 home = Py_GETENV("PYTHONHOME");
Guido van Rossuma61691e1998-02-06 22:27:24 +0000488 return home;
489}
490
Guido van Rossum6135a871995-01-09 17:53:26 +0000491/* Create __main__ module */
492
493static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000494initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000495{
Guido van Rossum82598051997-03-05 00:20:32 +0000496 PyObject *m, *d;
497 m = PyImport_AddModule("__main__");
Guido van Rossum6135a871995-01-09 17:53:26 +0000498 if (m == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +0000499 Py_FatalError("can't create __main__ module");
500 d = PyModule_GetDict(m);
501 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
Guido van Rossum858cb731997-11-19 16:15:37 +0000502 PyObject *bimod = PyImport_ImportModule("__builtin__");
503 if (bimod == NULL ||
504 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
Guido van Rossum82598051997-03-05 00:20:32 +0000505 Py_FatalError("can't add __builtins__ to __main__");
Barry Warsaw3d05b1a1999-01-29 21:30:22 +0000506 Py_DECREF(bimod);
Guido van Rossum6135a871995-01-09 17:53:26 +0000507 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000508}
509
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000510/* Import the site module (not into __main__ though) */
511
512static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000513initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000514{
515 PyObject *m, *f;
516 m = PyImport_ImportModule("site");
517 if (m == NULL) {
518 f = PySys_GetObject("stderr");
519 if (Py_VerboseFlag) {
520 PyFile_WriteString(
521 "'import site' failed; traceback:\n", f);
522 PyErr_Print();
523 }
524 else {
525 PyFile_WriteString(
526 "'import site' failed; use -v for traceback\n", f);
527 PyErr_Clear();
528 }
529 }
530 else {
531 Py_DECREF(m);
532 }
533}
534
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000535/* Parse input from a file and execute it */
536
537int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000538PyRun_AnyFile(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000539{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000540 return PyRun_AnyFileExFlags(fp, filename, 0, NULL);
541}
542
543int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000544PyRun_AnyFileFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000545{
546 return PyRun_AnyFileExFlags(fp, filename, 0, flags);
Guido van Rossum0df002c2000-08-27 19:21:52 +0000547}
548
549int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000550PyRun_AnyFileEx(FILE *fp, const char *filename, int closeit)
Guido van Rossum0df002c2000-08-27 19:21:52 +0000551{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000552 return PyRun_AnyFileExFlags(fp, filename, closeit, NULL);
553}
554
555int
Tim Petersd08e3822003-04-17 15:24:21 +0000556PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000557 PyCompilerFlags *flags)
558{
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000559 if (filename == NULL)
560 filename = "???";
Guido van Rossum0df002c2000-08-27 19:21:52 +0000561 if (Py_FdIsInteractive(fp, filename)) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000562 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
Guido van Rossum0df002c2000-08-27 19:21:52 +0000563 if (closeit)
564 fclose(fp);
565 return err;
566 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000567 else
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000568 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000569}
570
571int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000572PyRun_InteractiveLoop(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000573{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000574 return PyRun_InteractiveLoopFlags(fp, filename, NULL);
575}
576
577int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000578PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000579{
Guido van Rossum82598051997-03-05 00:20:32 +0000580 PyObject *v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000581 int ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000582 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000583
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000584 if (flags == NULL) {
585 flags = &local_flags;
Tim Peters5ba58662001-07-16 02:29:45 +0000586 local_flags.cf_flags = 0;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000587 }
Guido van Rossum82598051997-03-05 00:20:32 +0000588 v = PySys_GetObject("ps1");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000589 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000590 PySys_SetObject("ps1", v = PyString_FromString(">>> "));
591 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000592 }
Guido van Rossum82598051997-03-05 00:20:32 +0000593 v = PySys_GetObject("ps2");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000594 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000595 PySys_SetObject("ps2", v = PyString_FromString("... "));
596 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000597 }
598 for (;;) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000599 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
Guido van Rossumaae0d321996-05-22 16:35:33 +0000600#ifdef Py_REF_DEBUG
Guido van Rossum6f9e4331995-03-29 16:57:48 +0000601 fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000602#endif
603 if (ret == E_EOF)
604 return 0;
605 /*
606 if (ret == E_NOMEM)
607 return -1;
608 */
609 }
610}
611
612int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000613PyRun_InteractiveOne(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000614{
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000615 return PyRun_InteractiveOneFlags(fp, filename, NULL);
616}
617
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000618/* compute parser flags based on compiler flags */
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000619#define PARSER_FLAGS(flags) \
Guido van Rossum4b499dd32003-02-13 22:07:59 +0000620 (((flags) && (flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
621 PyPARSE_DONT_IMPLY_DEDENT : 0)
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000622
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000623int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000624PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000625{
Guido van Rossum82598051997-03-05 00:20:32 +0000626 PyObject *m, *d, *v, *w;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000627 node *n;
Guido van Rossuma110aa61994-08-29 12:50:44 +0000628 perrdetail err;
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000629 char *ps1 = "", *ps2 = "";
Tim Petersfe2127d2001-07-16 05:37:24 +0000630
Guido van Rossum82598051997-03-05 00:20:32 +0000631 v = PySys_GetObject("ps1");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000632 if (v != NULL) {
633 v = PyObject_Str(v);
634 if (v == NULL)
635 PyErr_Clear();
636 else if (PyString_Check(v))
637 ps1 = PyString_AsString(v);
638 }
Guido van Rossum82598051997-03-05 00:20:32 +0000639 w = PySys_GetObject("ps2");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000640 if (w != NULL) {
641 w = PyObject_Str(w);
642 if (w == NULL)
643 PyErr_Clear();
644 else if (PyString_Check(w))
645 ps2 = PyString_AsString(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000646 }
Tim Petersfe2127d2001-07-16 05:37:24 +0000647 n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar,
648 Py_single_input, ps1, ps2, &err,
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000649 PARSER_FLAGS(flags));
Guido van Rossum82598051997-03-05 00:20:32 +0000650 Py_XDECREF(v);
651 Py_XDECREF(w);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000652 if (n == NULL) {
653 if (err.error == E_EOF) {
654 if (err.text)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000655 PyMem_DEL(err.text);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000656 return E_EOF;
657 }
658 err_input(&err);
Guido van Rossum82598051997-03-05 00:20:32 +0000659 PyErr_Print();
Guido van Rossuma110aa61994-08-29 12:50:44 +0000660 return err.error;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000661 }
Guido van Rossum82598051997-03-05 00:20:32 +0000662 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000663 if (m == NULL)
664 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000665 d = PyModule_GetDict(m);
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000666 v = run_node(n, filename, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000667 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000668 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000669 return -1;
670 }
Guido van Rossum82598051997-03-05 00:20:32 +0000671 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000672 if (Py_FlushLine())
673 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000674 return 0;
675}
676
677int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000678PyRun_SimpleFile(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000679{
Guido van Rossum0df002c2000-08-27 19:21:52 +0000680 return PyRun_SimpleFileEx(fp, filename, 0);
681}
682
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000683/* Check whether a file maybe a pyc file: Look at the extension,
684 the file type, and, if we may close it, at the first few bytes. */
685
686static int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000687maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000688{
689 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
690 return 1;
691
692#ifdef macintosh
693 /* On a mac, we also assume a pyc file for types 'PYC ' and 'APPL' */
Jack Jansen72f3b7a2002-12-13 15:23:10 +0000694 if (PyMac_getfiletype((char *)filename) == 'PYC '
695 || PyMac_getfiletype((char *)filename) == 'APPL')
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000696 return 1;
697#endif /* macintosh */
698
699 /* Only look into the file if we are allowed to close it, since
700 it then should also be seekable. */
701 if (closeit) {
702 /* Read only two bytes of the magic. If the file was opened in
703 text mode, the bytes 3 and 4 of the magic (\r\n) might not
704 be read as they are on disk. */
705 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
706 unsigned char buf[2];
Tim Peters3e876562001-02-11 04:35:39 +0000707 /* Mess: In case of -x, the stream is NOT at its start now,
708 and ungetc() was used to push back the first newline,
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000709 which makes the current stream position formally undefined,
710 and a x-platform nightmare.
711 Unfortunately, we have no direct way to know whether -x
712 was specified. So we use a terrible hack: if the current
713 stream position is not 0, we assume -x was specified, and
714 give up. Bug 132850 on SourceForge spells out the
715 hopelessness of trying anything else (fseek and ftell
716 don't work predictably x-platform for text-mode files).
Tim Peters3e876562001-02-11 04:35:39 +0000717 */
Tim Peters3e876562001-02-11 04:35:39 +0000718 int ispyc = 0;
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000719 if (ftell(fp) == 0) {
720 if (fread(buf, 1, 2, fp) == 2 &&
Tim Petersd08e3822003-04-17 15:24:21 +0000721 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000722 ispyc = 1;
723 rewind(fp);
724 }
Tim Peters3e876562001-02-11 04:35:39 +0000725 return ispyc;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000726 }
727 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +0000728}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000729
Guido van Rossum0df002c2000-08-27 19:21:52 +0000730int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000731PyRun_SimpleFileEx(FILE *fp, const char *filename, int closeit)
Guido van Rossum0df002c2000-08-27 19:21:52 +0000732{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000733 return PyRun_SimpleFileExFlags(fp, filename, closeit, NULL);
734}
735
736int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000737PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000738 PyCompilerFlags *flags)
739{
Guido van Rossum82598051997-03-05 00:20:32 +0000740 PyObject *m, *d, *v;
Martin v. Löwis95292d62002-12-11 14:04:59 +0000741 const char *ext;
Guido van Rossumfdef2711994-09-14 13:31:04 +0000742
Guido van Rossum82598051997-03-05 00:20:32 +0000743 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000744 if (m == NULL)
745 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000746 d = PyModule_GetDict(m);
Fred Drake8ed02042002-10-17 21:24:58 +0000747 if (PyDict_GetItemString(d, "__file__") == NULL) {
748 PyObject *f = PyString_FromString(filename);
749 if (f == NULL)
750 return -1;
751 if (PyDict_SetItemString(d, "__file__", f) < 0) {
752 Py_DECREF(f);
753 return -1;
754 }
755 Py_DECREF(f);
756 }
Guido van Rossumfdef2711994-09-14 13:31:04 +0000757 ext = filename + strlen(filename) - 4;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000758 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Guido van Rossumfdef2711994-09-14 13:31:04 +0000759 /* Try to run a pyc file. First, re-open in binary */
Guido van Rossum0df002c2000-08-27 19:21:52 +0000760 if (closeit)
761 fclose(fp);
Fred Drake8ed02042002-10-17 21:24:58 +0000762 if ((fp = fopen(filename, "rb")) == NULL) {
Guido van Rossumfdef2711994-09-14 13:31:04 +0000763 fprintf(stderr, "python: Can't reopen .pyc file\n");
764 return -1;
765 }
Guido van Rossum2a7f58d1997-04-02 05:28:38 +0000766 /* Turn on optimization if a .pyo file is given */
767 if (strcmp(ext, ".pyo") == 0)
768 Py_OptimizeFlag = 1;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000769 v = run_pyc_file(fp, filename, d, d, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000770 } else {
Tim Petersd08e3822003-04-17 15:24:21 +0000771 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000772 closeit, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000773 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000774 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000775 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000776 return -1;
777 }
Guido van Rossum82598051997-03-05 00:20:32 +0000778 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000779 if (Py_FlushLine())
780 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000781 return 0;
782}
783
784int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000785PyRun_SimpleString(const char *command)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000786{
Guido van Rossum393661d2001-08-31 17:40:15 +0000787 return PyRun_SimpleStringFlags(command, NULL);
788}
789
790int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000791PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +0000792{
Guido van Rossum82598051997-03-05 00:20:32 +0000793 PyObject *m, *d, *v;
794 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000795 if (m == NULL)
796 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000797 d = PyModule_GetDict(m);
Guido van Rossum393661d2001-08-31 17:40:15 +0000798 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000799 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000800 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000801 return -1;
802 }
Guido van Rossum82598051997-03-05 00:20:32 +0000803 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000804 if (Py_FlushLine())
805 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000806 return 0;
807}
808
Barry Warsaw035574d1997-08-29 22:07:17 +0000809static int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000810parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
811 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +0000812{
813 long hold;
814 PyObject *v;
815
816 /* old style errors */
817 if (PyTuple_Check(err))
Neal Norwitz78293352002-04-01 01:41:20 +0000818 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
819 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +0000820
821 /* new style errors. `err' is an instance */
822
823 if (! (v = PyObject_GetAttrString(err, "msg")))
824 goto finally;
825 *message = v;
826
827 if (!(v = PyObject_GetAttrString(err, "filename")))
828 goto finally;
829 if (v == Py_None)
830 *filename = NULL;
831 else if (! (*filename = PyString_AsString(v)))
832 goto finally;
833
834 Py_DECREF(v);
835 if (!(v = PyObject_GetAttrString(err, "lineno")))
836 goto finally;
837 hold = PyInt_AsLong(v);
838 Py_DECREF(v);
839 v = NULL;
840 if (hold < 0 && PyErr_Occurred())
841 goto finally;
842 *lineno = (int)hold;
843
844 if (!(v = PyObject_GetAttrString(err, "offset")))
845 goto finally;
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000846 if (v == Py_None) {
847 *offset = -1;
848 Py_DECREF(v);
849 v = NULL;
850 } else {
851 hold = PyInt_AsLong(v);
852 Py_DECREF(v);
853 v = NULL;
854 if (hold < 0 && PyErr_Occurred())
855 goto finally;
856 *offset = (int)hold;
857 }
Barry Warsaw035574d1997-08-29 22:07:17 +0000858
859 if (!(v = PyObject_GetAttrString(err, "text")))
860 goto finally;
861 if (v == Py_None)
862 *text = NULL;
863 else if (! (*text = PyString_AsString(v)))
864 goto finally;
865 Py_DECREF(v);
866 return 1;
867
868finally:
869 Py_XDECREF(v);
870 return 0;
871}
872
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000873void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000874PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000875{
Guido van Rossuma61691e1998-02-06 22:27:24 +0000876 PyErr_PrintEx(1);
877}
878
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000879static void
Martin v. Löwis95292d62002-12-11 14:04:59 +0000880print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000881{
882 char *nl;
883 if (offset >= 0) {
884 if (offset > 0 && offset == (int)strlen(text))
885 offset--;
886 for (;;) {
887 nl = strchr(text, '\n');
888 if (nl == NULL || nl-text >= offset)
889 break;
890 offset -= (nl+1-text);
891 text = nl+1;
892 }
893 while (*text == ' ' || *text == '\t') {
894 text++;
895 offset--;
896 }
897 }
898 PyFile_WriteString(" ", f);
899 PyFile_WriteString(text, f);
900 if (*text == '\0' || text[strlen(text)-1] != '\n')
901 PyFile_WriteString("\n", f);
902 if (offset == -1)
903 return;
904 PyFile_WriteString(" ", f);
905 offset--;
906 while (offset > 0) {
907 PyFile_WriteString(" ", f);
908 offset--;
909 }
910 PyFile_WriteString("^\n", f);
911}
912
Guido van Rossum66e8e862001-03-23 17:54:43 +0000913static void
914handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000915{
Guido van Rossum66e8e862001-03-23 17:54:43 +0000916 PyObject *exception, *value, *tb;
Tim Peterscf615b52003-04-19 18:47:02 +0000917 int exitcode = 0;
918
Guido van Rossum66e8e862001-03-23 17:54:43 +0000919 PyErr_Fetch(&exception, &value, &tb);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000920 if (Py_FlushLine())
921 PyErr_Clear();
922 fflush(stdout);
923 if (value == NULL || value == Py_None)
Tim Peterscf615b52003-04-19 18:47:02 +0000924 goto done;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000925 if (PyInstance_Check(value)) {
926 /* The error code should be in the `code' attribute. */
927 PyObject *code = PyObject_GetAttrString(value, "code");
928 if (code) {
929 Py_DECREF(value);
930 value = code;
931 if (value == Py_None)
Tim Peterscf615b52003-04-19 18:47:02 +0000932 goto done;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000933 }
934 /* If we failed to dig out the 'code' attribute,
935 just let the else clause below print the error. */
936 }
937 if (PyInt_Check(value))
Tim Peterscf615b52003-04-19 18:47:02 +0000938 exitcode = (int)PyInt_AsLong(value);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000939 else {
940 PyObject_Print(value, stderr, Py_PRINT_RAW);
941 PySys_WriteStderr("\n");
Tim Peterscf615b52003-04-19 18:47:02 +0000942 exitcode = 1;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000943 }
Tim Peterscf615b52003-04-19 18:47:02 +0000944 done:
945 /* Restore and clear the exception info, in order to properly decref
946 * the exception, value, and traceback. If we just exit instead,
947 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
948 * some finalizers from running.
949 */
950 PyErr_Restore(exception, value, tb);
951 PyErr_Clear();
952 Py_Exit(exitcode);
953 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000954}
955
956void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000957PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000958{
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000959 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +0000960
961 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
962 handle_system_exit();
963 }
Guido van Rossum82598051997-03-05 00:20:32 +0000964 PyErr_Fetch(&exception, &v, &tb);
Barry Warsaw035574d1997-08-29 22:07:17 +0000965 PyErr_NormalizeException(&exception, &v, &tb);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000966 if (exception == NULL)
Guido van Rossum296b4751997-05-23 00:19:20 +0000967 return;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000968 if (set_sys_last_vars) {
969 PySys_SetObject("last_type", exception);
970 PySys_SetObject("last_value", v);
971 PySys_SetObject("last_traceback", tb);
972 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000973 hook = PySys_GetObject("excepthook");
974 if (hook) {
975 PyObject *args = Py_BuildValue("(OOO)",
976 exception, v ? v : Py_None, tb ? tb : Py_None);
977 PyObject *result = PyEval_CallObject(hook, args);
978 if (result == NULL) {
979 PyObject *exception2, *v2, *tb2;
Guido van Rossum66e8e862001-03-23 17:54:43 +0000980 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
981 handle_system_exit();
982 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000983 PyErr_Fetch(&exception2, &v2, &tb2);
984 PyErr_NormalizeException(&exception2, &v2, &tb2);
985 if (Py_FlushLine())
986 PyErr_Clear();
987 fflush(stdout);
988 PySys_WriteStderr("Error in sys.excepthook:\n");
989 PyErr_Display(exception2, v2, tb2);
990 PySys_WriteStderr("\nOriginal exception was:\n");
991 PyErr_Display(exception, v, tb);
Jeremy Hylton07028582001-12-07 15:35:35 +0000992 Py_XDECREF(exception2);
993 Py_XDECREF(v2);
994 Py_XDECREF(tb2);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000995 }
996 Py_XDECREF(result);
997 Py_XDECREF(args);
998 } else {
999 PySys_WriteStderr("sys.excepthook is missing\n");
1000 PyErr_Display(exception, v, tb);
1001 }
1002 Py_XDECREF(exception);
1003 Py_XDECREF(v);
1004 Py_XDECREF(tb);
1005}
1006
1007void PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
1008{
1009 int err = 0;
1010 PyObject *v = value;
1011 PyObject *f = PySys_GetObject("stderr");
Guido van Rossum3165fe61992-09-25 21:59:05 +00001012 if (f == NULL)
1013 fprintf(stderr, "lost sys.stderr\n");
1014 else {
Guido van Rossum0829c751998-02-28 04:31:39 +00001015 if (Py_FlushLine())
1016 PyErr_Clear();
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001017 fflush(stdout);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001018 if (tb && tb != Py_None)
1019 err = PyTraceBack_Print(tb, f);
Barry Warsaw36b8f941997-08-26 18:09:48 +00001020 if (err == 0 &&
Martin v. Löwiscfeb3b62002-03-03 21:30:27 +00001021 PyObject_HasAttrString(v, "print_file_and_line"))
Barry Warsaw36b8f941997-08-26 18:09:48 +00001022 {
Guido van Rossum82598051997-03-05 00:20:32 +00001023 PyObject *message;
Martin v. Löwis95292d62002-12-11 14:04:59 +00001024 const char *filename, *text;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001025 int lineno, offset;
Barry Warsaw035574d1997-08-29 22:07:17 +00001026 if (!parse_syntax_error(v, &message, &filename,
1027 &lineno, &offset, &text))
Guido van Rossum82598051997-03-05 00:20:32 +00001028 PyErr_Clear();
Guido van Rossuma110aa61994-08-29 12:50:44 +00001029 else {
1030 char buf[10];
Guido van Rossum82598051997-03-05 00:20:32 +00001031 PyFile_WriteString(" File \"", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001032 if (filename == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +00001033 PyFile_WriteString("<string>", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001034 else
Guido van Rossum82598051997-03-05 00:20:32 +00001035 PyFile_WriteString(filename, f);
1036 PyFile_WriteString("\", line ", f);
Jeremy Hylton518ab1c2001-11-28 20:42:20 +00001037 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
Guido van Rossum82598051997-03-05 00:20:32 +00001038 PyFile_WriteString(buf, f);
1039 PyFile_WriteString("\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001040 if (text != NULL)
1041 print_error_text(f, offset, text);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001042 v = message;
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001043 /* Can't be bothered to check all those
1044 PyFile_WriteString() calls */
1045 if (PyErr_Occurred())
1046 err = -1;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001047 }
1048 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001049 if (err) {
1050 /* Don't do anything else */
1051 }
1052 else if (PyClass_Check(exception)) {
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001053 PyClassObject* exc = (PyClassObject*)exception;
1054 PyObject* className = exc->cl_name;
1055 PyObject* moduleName =
1056 PyDict_GetItemString(exc->cl_dict, "__module__");
1057
1058 if (moduleName == NULL)
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001059 err = PyFile_WriteString("<unknown>", f);
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001060 else {
1061 char* modstr = PyString_AsString(moduleName);
Tim Petersd08e3822003-04-17 15:24:21 +00001062 if (modstr && strcmp(modstr, "exceptions"))
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001063 {
1064 err = PyFile_WriteString(modstr, f);
1065 err += PyFile_WriteString(".", f);
1066 }
1067 }
1068 if (err == 0) {
1069 if (className == NULL)
1070 err = PyFile_WriteString("<unknown>", f);
1071 else
1072 err = PyFile_WriteObject(className, f,
1073 Py_PRINT_RAW);
1074 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001075 }
1076 else
1077 err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
1078 if (err == 0) {
1079 if (v != NULL && v != Py_None) {
Barry Warsaw035574d1997-08-29 22:07:17 +00001080 PyObject *s = PyObject_Str(v);
1081 /* only print colon if the str() of the
1082 object is not the empty string
1083 */
Guido van Rossumd6bf45b1997-09-05 19:11:53 +00001084 if (s == NULL)
1085 err = -1;
1086 else if (!PyString_Check(s) ||
1087 PyString_GET_SIZE(s) != 0)
Barry Warsaw035574d1997-08-29 22:07:17 +00001088 err = PyFile_WriteString(": ", f);
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001089 if (err == 0)
Guido van Rossumd6bf45b1997-09-05 19:11:53 +00001090 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1091 Py_XDECREF(s);
Guido van Rossum262e1241995-02-07 15:30:45 +00001092 }
Guido van Rossum262e1241995-02-07 15:30:45 +00001093 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001094 if (err == 0)
1095 err = PyFile_WriteString("\n", f);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001096 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001097 /* If an error happened here, don't show it.
1098 XXX This is wrong, but too many callers rely on this behavior. */
1099 if (err != 0)
1100 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001101}
1102
Guido van Rossum82598051997-03-05 00:20:32 +00001103PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001104PyRun_String(const char *str, int start, PyObject *globals, PyObject *locals)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001105{
Guido van Rossum82598051997-03-05 00:20:32 +00001106 return run_err_node(PyParser_SimpleParseString(str, start),
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001107 "<string>", globals, locals, NULL);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001108}
1109
Guido van Rossum82598051997-03-05 00:20:32 +00001110PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001111PyRun_File(FILE *fp, const char *filename, int start, PyObject *globals,
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001112 PyObject *locals)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001113{
Tim Peterse8682112000-08-27 20:18:17 +00001114 return PyRun_FileEx(fp, filename, start, globals, locals, 0);
Guido van Rossum0df002c2000-08-27 19:21:52 +00001115}
1116
1117PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001118PyRun_FileEx(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001119 PyObject *locals, int closeit)
Guido van Rossum0df002c2000-08-27 19:21:52 +00001120{
1121 node *n = PyParser_SimpleParseFile(fp, filename, start);
1122 if (closeit)
1123 fclose(fp);
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001124 return run_err_node(n, filename, globals, locals, NULL);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001125}
1126
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001127PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001128PyRun_StringFlags(const char *str, int start, PyObject *globals, PyObject *locals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001129 PyCompilerFlags *flags)
1130{
Guido van Rossuma1b3a472001-07-16 16:51:33 +00001131 return run_err_node(PyParser_SimpleParseStringFlags(
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001132 str, start, PARSER_FLAGS(flags)),
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001133 "<string>", globals, locals, flags);
1134}
1135
1136PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001137PyRun_FileFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001138 PyObject *locals, PyCompilerFlags *flags)
1139{
1140 return PyRun_FileExFlags(fp, filename, start, globals, locals, 0,
Tim Petersd08e3822003-04-17 15:24:21 +00001141 flags);
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001142}
1143
1144PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001145PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001146 PyObject *locals, int closeit, PyCompilerFlags *flags)
1147{
Tim Petersfe2127d2001-07-16 05:37:24 +00001148 node *n = PyParser_SimpleParseFileFlags(fp, filename, start,
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001149 PARSER_FLAGS(flags));
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001150 if (closeit)
1151 fclose(fp);
1152 return run_err_node(n, filename, globals, locals, flags);
1153}
1154
Guido van Rossum82598051997-03-05 00:20:32 +00001155static PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001156run_err_node(node *n, const char *filename, PyObject *globals, PyObject *locals,
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001157 PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001158{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001159 if (n == NULL)
1160 return NULL;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001161 return run_node(n, filename, globals, locals, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001162}
1163
Guido van Rossum82598051997-03-05 00:20:32 +00001164static PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001165run_node(node *n, const char *filename, PyObject *globals, PyObject *locals,
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001166 PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001167{
Guido van Rossum82598051997-03-05 00:20:32 +00001168 PyCodeObject *co;
1169 PyObject *v;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001170 co = PyNode_CompileFlags(n, filename, flags);
Guido van Rossum82598051997-03-05 00:20:32 +00001171 PyNode_Free(n);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001172 if (co == NULL)
1173 return NULL;
Guido van Rossum82598051997-03-05 00:20:32 +00001174 v = PyEval_EvalCode(co, globals, locals);
1175 Py_DECREF(co);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001176 return v;
1177}
1178
Guido van Rossum82598051997-03-05 00:20:32 +00001179static PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001180run_pyc_file(FILE *fp, const char *filename, PyObject *globals, PyObject *locals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001181 PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001182{
Guido van Rossum82598051997-03-05 00:20:32 +00001183 PyCodeObject *co;
1184 PyObject *v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001185 long magic;
Fred Drakee8de31c2000-08-31 05:38:39 +00001186 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001187
Guido van Rossum82598051997-03-05 00:20:32 +00001188 magic = PyMarshal_ReadLongFromFile(fp);
1189 if (magic != PyImport_GetMagicNumber()) {
1190 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001191 "Bad magic number in .pyc file");
1192 return NULL;
1193 }
Guido van Rossum82598051997-03-05 00:20:32 +00001194 (void) PyMarshal_ReadLongFromFile(fp);
Tim Petersd9b9ac82001-01-28 00:27:39 +00001195 v = PyMarshal_ReadLastObjectFromFile(fp);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001196 fclose(fp);
Guido van Rossum82598051997-03-05 00:20:32 +00001197 if (v == NULL || !PyCode_Check(v)) {
1198 Py_XDECREF(v);
1199 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001200 "Bad code object in .pyc file");
1201 return NULL;
1202 }
Guido van Rossum82598051997-03-05 00:20:32 +00001203 co = (PyCodeObject *)v;
1204 v = PyEval_EvalCode(co, globals, locals);
Jeremy Hyltonb857ba22001-08-10 21:41:33 +00001205 if (v && flags)
1206 flags->cf_flags |= (co->co_flags & PyCF_MASK);
Guido van Rossum82598051997-03-05 00:20:32 +00001207 Py_DECREF(co);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001208 return v;
1209}
1210
Guido van Rossum82598051997-03-05 00:20:32 +00001211PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001212Py_CompileString(const char *str, const char *filename, int start)
Guido van Rossum5b722181993-03-30 17:46:03 +00001213{
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001214 return Py_CompileStringFlags(str, filename, start, NULL);
1215}
1216
1217PyObject *
Tim Petersd08e3822003-04-17 15:24:21 +00001218Py_CompileStringFlags(const char *str, const char *filename, int start,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001219 PyCompilerFlags *flags)
1220{
Guido van Rossum5b722181993-03-30 17:46:03 +00001221 node *n;
Guido van Rossum82598051997-03-05 00:20:32 +00001222 PyCodeObject *co;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001223
1224 n = PyParser_SimpleParseStringFlagsFilename(str, filename, start,
1225 PARSER_FLAGS(flags));
Guido van Rossuma110aa61994-08-29 12:50:44 +00001226 if (n == NULL)
Guido van Rossum5b722181993-03-30 17:46:03 +00001227 return NULL;
Jeremy Hylton673a4fd2001-03-26 19:53:38 +00001228 co = PyNode_CompileFlags(n, filename, flags);
Guido van Rossum82598051997-03-05 00:20:32 +00001229 PyNode_Free(n);
1230 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001231}
1232
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001233struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001234Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001235{
1236 node *n;
1237 struct symtable *st;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001238 n = PyParser_SimpleParseStringFlagsFilename(str, filename,
1239 start, 0);
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001240 if (n == NULL)
1241 return NULL;
1242 st = PyNode_CompileSymtable(n, filename);
1243 PyNode_Free(n);
1244 return st;
1245}
1246
Guido van Rossuma110aa61994-08-29 12:50:44 +00001247/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001248
Guido van Rossuma110aa61994-08-29 12:50:44 +00001249node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001250PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001251{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001252 node *n;
1253 perrdetail err;
Tim Petersfe2127d2001-07-16 05:37:24 +00001254 n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar, start,
1255 (char *)0, (char *)0, &err, flags);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001256 if (n == NULL)
1257 err_input(&err);
1258 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001259}
1260
Tim Petersfe2127d2001-07-16 05:37:24 +00001261node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001262PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
Tim Petersfe2127d2001-07-16 05:37:24 +00001263{
1264 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
1265}
1266
Guido van Rossuma110aa61994-08-29 12:50:44 +00001267/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001268
Guido van Rossuma110aa61994-08-29 12:50:44 +00001269node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001270PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001271{
1272 node *n;
1273 perrdetail err;
1274 n = PyParser_ParseStringFlags(str, &_PyParser_Grammar, start, &err,
1275 flags);
1276 if (n == NULL)
1277 err_input(&err);
1278 return n;
1279}
1280
1281node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001282PyParser_SimpleParseString(const char *str, int start)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001283{
Tim Petersfe2127d2001-07-16 05:37:24 +00001284 return PyParser_SimpleParseStringFlags(str, start, 0);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001285}
1286
Thomas Heller6b17abf2002-07-09 09:23:27 +00001287node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001288PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Thomas Heller6b17abf2002-07-09 09:23:27 +00001289 int start, int flags)
1290{
1291 node *n;
1292 perrdetail err;
1293
Tim Petersd08e3822003-04-17 15:24:21 +00001294 n = PyParser_ParseStringFlagsFilename(str, filename,
Thomas Heller6b17abf2002-07-09 09:23:27 +00001295 &_PyParser_Grammar,
1296 start, &err, flags);
1297 if (n == NULL)
1298 err_input(&err);
1299 return n;
1300}
1301
1302node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001303PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001304{
1305 return PyParser_SimpleParseStringFlagsFilename(str, filename,
1306 start, 0);
1307}
1308
Guido van Rossum66ebd912003-04-17 16:02:26 +00001309/* May want to move a more generalized form of this to parsetok.c or
1310 even parser modules. */
1311
1312void
1313PyParser_SetError(perrdetail *err)
1314{
1315 err_input(err);
1316}
1317
Guido van Rossuma110aa61994-08-29 12:50:44 +00001318/* Set the error appropriate to the given input error code (see errcode.h) */
1319
1320static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001321err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001322{
Fred Drake85f36392000-07-11 17:53:00 +00001323 PyObject *v, *w, *errtype;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001324 PyObject* u = NULL;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001325 char *msg = NULL;
Fred Drake85f36392000-07-11 17:53:00 +00001326 errtype = PyExc_SyntaxError;
Guido van Rossum82598051997-03-05 00:20:32 +00001327 v = Py_BuildValue("(ziiz)", err->filename,
Guido van Rossuma110aa61994-08-29 12:50:44 +00001328 err->lineno, err->offset, err->text);
1329 if (err->text != NULL) {
Guido van Rossumb18618d2000-05-03 23:44:39 +00001330 PyMem_DEL(err->text);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001331 err->text = NULL;
1332 }
1333 switch (err->error) {
1334 case E_SYNTAX:
Fred Drake85f36392000-07-11 17:53:00 +00001335 errtype = PyExc_IndentationError;
1336 if (err->expected == INDENT)
1337 msg = "expected an indented block";
1338 else if (err->token == INDENT)
1339 msg = "unexpected indent";
1340 else if (err->token == DEDENT)
1341 msg = "unexpected unindent";
1342 else {
1343 errtype = PyExc_SyntaxError;
1344 msg = "invalid syntax";
1345 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001346 break;
1347 case E_TOKEN:
1348 msg = "invalid token";
Guido van Rossuma110aa61994-08-29 12:50:44 +00001349 break;
Skip Montanaro118ec702002-08-15 01:20:16 +00001350 case E_EOFS:
1351 msg = "EOF while scanning triple-quoted string";
1352 break;
1353 case E_EOLS:
1354 msg = "EOL while scanning single-quoted string";
1355 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001356 case E_INTR:
Guido van Rossum82598051997-03-05 00:20:32 +00001357 PyErr_SetNone(PyExc_KeyboardInterrupt);
Barry Warsawc80baa31999-01-27 16:39:40 +00001358 Py_XDECREF(v);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001359 return;
1360 case E_NOMEM:
Guido van Rossum82598051997-03-05 00:20:32 +00001361 PyErr_NoMemory();
Barry Warsawc80baa31999-01-27 16:39:40 +00001362 Py_XDECREF(v);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001363 return;
1364 case E_EOF:
1365 msg = "unexpected EOF while parsing";
1366 break;
Fred Drake85f36392000-07-11 17:53:00 +00001367 case E_TABSPACE:
1368 errtype = PyExc_TabError;
Guido van Rossum560e8ad1998-04-10 19:43:42 +00001369 msg = "inconsistent use of tabs and spaces in indentation";
1370 break;
Jeremy Hylton94988062000-06-20 19:10:44 +00001371 case E_OVERFLOW:
1372 msg = "expression too long";
1373 break;
Fred Drake85f36392000-07-11 17:53:00 +00001374 case E_DEDENT:
1375 errtype = PyExc_IndentationError;
1376 msg = "unindent does not match any outer indentation level";
1377 break;
1378 case E_TOODEEP:
1379 errtype = PyExc_IndentationError;
1380 msg = "too many levels of indentation";
1381 break;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001382 case E_DECODE: { /* XXX */
1383 PyThreadState* tstate = PyThreadState_Get();
1384 PyObject* value = tstate->curexc_value;
1385 if (value != NULL) {
1386 u = PyObject_Repr(value);
1387 if (u != NULL) {
1388 msg = PyString_AsString(u);
1389 break;
1390 }
1391 }
1392 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001393 default:
1394 fprintf(stderr, "error=%d\n", err->error);
1395 msg = "unknown parsing error";
1396 break;
1397 }
Guido van Rossum82598051997-03-05 00:20:32 +00001398 w = Py_BuildValue("(sO)", msg, v);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001399 Py_XDECREF(u);
Guido van Rossum41318302001-03-23 04:01:07 +00001400 Py_XDECREF(v);
Fred Drake85f36392000-07-11 17:53:00 +00001401 PyErr_SetObject(errtype, w);
Guido van Rossum82598051997-03-05 00:20:32 +00001402 Py_XDECREF(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001403}
1404
1405/* Print fatal error message and abort */
1406
1407void
Tim Peters7c321a82002-07-09 02:57:01 +00001408Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001409{
Guido van Rossum83dd6c31994-09-29 09:38:33 +00001410 fprintf(stderr, "Fatal Python error: %s\n", msg);
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001411#ifdef MS_WINDOWS
Guido van Rossum23c94461997-05-22 20:21:30 +00001412 OutputDebugString("Fatal Python error: ");
Guido van Rossuma44823b1995-03-14 15:01:17 +00001413 OutputDebugString(msg);
1414 OutputDebugString("\n");
Guido van Rossum0ba35361998-08-13 13:33:16 +00001415#ifdef _DEBUG
1416 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00001417#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001418#endif /* MS_WINDOWS */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001419 abort();
1420}
1421
1422/* Clean up and exit */
1423
Guido van Rossuma110aa61994-08-29 12:50:44 +00001424#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00001425#include "pythread.h"
Guido van Rossum82598051997-03-05 00:20:32 +00001426int _PyThread_Started = 0; /* Set by threadmodule.c and maybe others */
Guido van Rossumf9f2e821992-08-17 08:59:08 +00001427#endif
1428
Guido van Rossum2dcfc961998-10-01 16:01:57 +00001429#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001430static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00001431static int nexitfuncs = 0;
1432
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001433int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00001434{
1435 if (nexitfuncs >= NEXITFUNCS)
1436 return -1;
1437 exitfuncs[nexitfuncs++] = func;
1438 return 0;
1439}
1440
Guido van Rossumcc283f51997-08-05 02:22:03 +00001441static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001442call_sys_exitfunc(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001443{
Guido van Rossum82598051997-03-05 00:20:32 +00001444 PyObject *exitfunc = PySys_GetObject("exitfunc");
Guido van Rossum59bff391992-09-03 20:28:00 +00001445
1446 if (exitfunc) {
Fred Drake6a12d8d2001-03-23 17:34:02 +00001447 PyObject *res;
Guido van Rossum82598051997-03-05 00:20:32 +00001448 Py_INCREF(exitfunc);
1449 PySys_SetObject("exitfunc", (PyObject *)NULL);
1450 res = PyEval_CallObject(exitfunc, (PyObject *)NULL);
Guido van Rossum59bff391992-09-03 20:28:00 +00001451 if (res == NULL) {
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001452 if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
1453 PySys_WriteStderr("Error in sys.exitfunc:\n");
1454 }
Guido van Rossum82598051997-03-05 00:20:32 +00001455 PyErr_Print();
Guido van Rossum59bff391992-09-03 20:28:00 +00001456 }
Guido van Rossum82598051997-03-05 00:20:32 +00001457 Py_DECREF(exitfunc);
Guido van Rossum59bff391992-09-03 20:28:00 +00001458 }
1459
Guido van Rossum0829c751998-02-28 04:31:39 +00001460 if (Py_FlushLine())
1461 PyErr_Clear();
Guido van Rossumcc283f51997-08-05 02:22:03 +00001462}
Guido van Rossum1662dd51994-09-07 14:38:28 +00001463
Guido van Rossumcc283f51997-08-05 02:22:03 +00001464static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001465call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00001466{
Guido van Rossum1662dd51994-09-07 14:38:28 +00001467 while (nexitfuncs > 0)
1468 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00001469
1470 fflush(stdout);
1471 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001472}
1473
1474void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001475Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001476{
Guido van Rossumcc283f51997-08-05 02:22:03 +00001477 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001478
Jack Jansen66a89771995-10-27 13:22:14 +00001479#ifdef macintosh
1480 PyMac_Exit(sts);
1481#else
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001482 exit(sts);
Jack Jansen66a89771995-10-27 13:22:14 +00001483#endif
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001484}
1485
Guido van Rossumf1dc5661993-07-05 10:31:29 +00001486static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001487initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001488{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001489#ifdef HAVE_SIGNAL_H
1490#ifdef SIGPIPE
1491 signal(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001492#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00001493#ifdef SIGXFZ
1494 signal(SIGXFZ, SIG_IGN);
1495#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00001496#ifdef SIGXFSZ
1497 signal(SIGXFSZ, SIG_IGN);
1498#endif
Guido van Rossuma110aa61994-08-29 12:50:44 +00001499#endif /* HAVE_SIGNAL_H */
Guido van Rossum82598051997-03-05 00:20:32 +00001500 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001501}
1502
Guido van Rossuma110aa61994-08-29 12:50:44 +00001503#ifdef MPW
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001504
1505/* Check for file descriptor connected to interactive device.
1506 Pretend that stdin is always interactive, other files never. */
1507
1508int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001509isatty(int fd)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001510{
1511 return fd == fileno(stdin);
1512}
1513
1514#endif
Guido van Rossum7433b121997-02-14 19:45:36 +00001515
1516/*
1517 * The file descriptor fd is considered ``interactive'' if either
1518 * a) isatty(fd) is TRUE, or
1519 * b) the -i flag was given, and the filename associated with
1520 * the descriptor is NULL or "<stdin>" or "???".
1521 */
1522int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001523Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00001524{
1525 if (isatty((int)fileno(fp)))
1526 return 1;
1527 if (!Py_InteractiveFlag)
1528 return 0;
1529 return (filename == NULL) ||
1530 (strcmp(filename, "<stdin>") == 0) ||
1531 (strcmp(filename, "???") == 0);
1532}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001533
1534
Tim Petersd08e3822003-04-17 15:24:21 +00001535#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001536#if defined(WIN32) && defined(_MSC_VER)
1537
1538/* Stack checking for Microsoft C */
1539
1540#include <malloc.h>
1541#include <excpt.h>
1542
Fred Drakee8de31c2000-08-31 05:38:39 +00001543/*
1544 * Return non-zero when we run out of memory on the stack; zero otherwise.
1545 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001546int
Fred Drake399739f2000-08-31 05:52:44 +00001547PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001548{
1549 __try {
Tim Peters92e4dd82002-10-05 01:47:34 +00001550 /* alloca throws a stack overflow exception if there's
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001551 not enough space left on the stack */
Tim Peters92e4dd82002-10-05 01:47:34 +00001552 alloca(PYOS_STACK_MARGIN * sizeof(void*));
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001553 return 0;
1554 } __except (EXCEPTION_EXECUTE_HANDLER) {
1555 /* just ignore all errors */
1556 }
1557 return 1;
1558}
1559
1560#endif /* WIN32 && _MSC_VER */
1561
1562/* Alternate implementations can be added here... */
1563
1564#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00001565
1566
1567/* Wrappers around sigaction() or signal(). */
1568
1569PyOS_sighandler_t
1570PyOS_getsig(int sig)
1571{
1572#ifdef HAVE_SIGACTION
1573 struct sigaction context;
Barry Warsawafeb2a42001-11-13 23:08:26 +00001574 /* Initialize context.sa_handler to SIG_ERR which makes about as
1575 * much sense as anything else. It should get overwritten if
1576 * sigaction actually succeeds and otherwise we avoid an
1577 * uninitialized memory read.
1578 */
1579 context.sa_handler = SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00001580 sigaction(sig, NULL, &context);
1581 return context.sa_handler;
1582#else
1583 PyOS_sighandler_t handler;
1584 handler = signal(sig, SIG_IGN);
1585 signal(sig, handler);
1586 return handler;
1587#endif
1588}
1589
1590PyOS_sighandler_t
1591PyOS_setsig(int sig, PyOS_sighandler_t handler)
1592{
1593#ifdef HAVE_SIGACTION
1594 struct sigaction context;
1595 PyOS_sighandler_t oldhandler;
Barry Warsawafeb2a42001-11-13 23:08:26 +00001596 /* Initialize context.sa_handler to SIG_ERR which makes about as
1597 * much sense as anything else. It should get overwritten if
1598 * sigaction actually succeeds and otherwise we avoid an
1599 * uninitialized memory read.
1600 */
1601 context.sa_handler = SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00001602 sigaction(sig, NULL, &context);
1603 oldhandler = context.sa_handler;
1604 context.sa_handler = handler;
1605 sigaction(sig, &context, NULL);
1606 return oldhandler;
1607#else
1608 return signal(sig, handler);
1609#endif
1610}