blob: fb40e8f22ea410dae1eb9b3db7d59366aeddc935 [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
Mark Hammondedd07732003-07-15 23:03:55 +000072 on the fly when the import lock may be held. See 683658/771097
Mark Hammonda43fd0c2003-02-19 00:33:33 +000073*/
Mark Hammondedd07732003-07-15 23:03:55 +000074static PyObject *warnings_module = NULL;
75
76/* Returns a borrowed reference to the 'warnings' module, or NULL.
77 If the module is returned, it is guaranteed to have been obtained
78 without acquiring the import lock
79*/
80PyObject *PyModule_GetWarningsModule()
81{
82 PyObject *typ, *val, *tb;
83 PyObject *all_modules;
84 /* If we managed to get the module at init time, just use it */
85 if (warnings_module)
86 return warnings_module;
87 /* If it wasn't available at init time, it may be available
88 now in sys.modules (common scenario is frozen apps: import
89 at init time fails, but the frozen init code sets up sys.path
90 correctly, then does an implicit import of warnings for us
91 */
92 /* Save and restore any exceptions */
93 PyErr_Fetch(&typ, &val, &tb);
94
95 all_modules = PySys_GetObject("__modules__");
96 if (all_modules) {
97 warnings_module = PyDict_GetItemString(all_modules, "warnings");
98 /* We keep a ref in the global */
99 Py_XINCREF(warnings_module);
100 }
101 PyErr_Restore(typ, val, tb);
102 return warnings_module;
103}
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000104
Guido van Rossum25ce5661997-08-02 03:10:38 +0000105static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000106
Thomas Wouters7e474022000-07-16 12:04:32 +0000107/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000108
109int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000110Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000111{
112 return initialized;
113}
114
Guido van Rossum25ce5661997-08-02 03:10:38 +0000115/* Global initializations. Can be undone by Py_Finalize(). Don't
116 call this twice without an intervening Py_Finalize() call. When
117 initializations fail, a fatal error is issued and the function does
118 not return. On return, the first thread and interpreter state have
119 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000120
Guido van Rossum25ce5661997-08-02 03:10:38 +0000121 Locking: you must hold the interpreter lock while calling this.
122 (If the lock has not yet been initialized, that's equivalent to
123 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000124
Guido van Rossum25ce5661997-08-02 03:10:38 +0000125*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000126
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000127static int
128add_flag(int flag, const char *envs)
129{
130 int env = atoi(envs);
131 if (flag < env)
132 flag = env;
133 if (flag < 1)
134 flag = 1;
135 return flag;
136}
137
Guido van Rossuma027efa1997-05-05 20:56:21 +0000138void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000139Py_Initialize(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000140{
Guido van Rossuma027efa1997-05-05 20:56:21 +0000141 PyInterpreterState *interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000142 PyThreadState *tstate;
143 PyObject *bimod, *sysmod;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000144 char *p;
Guido van Rossum70d893a2001-08-16 08:21:42 +0000145 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000146
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000147 if (initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +0000148 return;
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000149 initialized = 1;
Tim Petersd08e3822003-04-17 15:24:21 +0000150
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000151 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000152 Py_DebugFlag = add_flag(Py_DebugFlag, p);
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000153 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000154 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000155 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000156 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000157
Guido van Rossuma027efa1997-05-05 20:56:21 +0000158 interp = PyInterpreterState_New();
159 if (interp == NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000160 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000161
Guido van Rossuma027efa1997-05-05 20:56:21 +0000162 tstate = PyThreadState_New(interp);
163 if (tstate == NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000164 Py_FatalError("Py_Initialize: can't make first thread");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000165 (void) PyThreadState_Swap(tstate);
166
Guido van Rossum70d893a2001-08-16 08:21:42 +0000167 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000168
Neal Norwitzb2501f42002-12-31 03:42:13 +0000169 if (!_PyFrame_Init())
Neal Norwitzc91ed402002-12-30 22:29:22 +0000170 Py_FatalError("Py_Initialize: can't init frames");
171
Neal Norwitzb2501f42002-12-31 03:42:13 +0000172 if (!_PyInt_Init())
Neal Norwitzc91ed402002-12-30 22:29:22 +0000173 Py_FatalError("Py_Initialize: can't init ints");
174
Guido van Rossum25ce5661997-08-02 03:10:38 +0000175 interp->modules = PyDict_New();
176 if (interp->modules == NULL)
177 Py_FatalError("Py_Initialize: can't make modules dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000178
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000179#ifdef Py_USING_UNICODE
Guido van Rossumc94044c2000-03-10 23:03:54 +0000180 /* Init Unicode implementation; relies on the codec registry */
181 _PyUnicode_Init();
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000182#endif
Guido van Rossumc94044c2000-03-10 23:03:54 +0000183
Barry Warsawf242aa02000-05-25 23:09:49 +0000184 bimod = _PyBuiltin_Init();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000185 if (bimod == NULL)
186 Py_FatalError("Py_Initialize: can't initialize __builtin__");
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000187 interp->builtins = PyModule_GetDict(bimod);
188 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000189
190 sysmod = _PySys_Init();
191 if (sysmod == NULL)
192 Py_FatalError("Py_Initialize: can't initialize sys");
193 interp->sysdict = PyModule_GetDict(sysmod);
194 Py_INCREF(interp->sysdict);
195 _PyImport_FixupExtension("sys", "sys");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000196 PySys_SetPath(Py_GetPath());
Guido van Rossum25ce5661997-08-02 03:10:38 +0000197 PyDict_SetItemString(interp->sysdict, "modules",
198 interp->modules);
199
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000200 _PyImport_Init();
201
Barry Warsawf242aa02000-05-25 23:09:49 +0000202 /* initialize builtin exceptions */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000203 _PyExc_Init();
Barry Warsaw5821bc52001-08-13 23:04:56 +0000204 _PyImport_FixupExtension("exceptions", "exceptions");
Barry Warsawf242aa02000-05-25 23:09:49 +0000205
Barry Warsaw035574d1997-08-29 22:07:17 +0000206 /* phase 2 of builtins */
Barry Warsaw963b8711997-09-18 16:42:02 +0000207 _PyImport_FixupExtension("__builtin__", "__builtin__");
Barry Warsaw035574d1997-08-29 22:07:17 +0000208
Just van Rossum52e14d62002-12-30 22:08:05 +0000209 _PyImportHooks_Init();
210
Guido van Rossum25ce5661997-08-02 03:10:38 +0000211 initsigs(); /* Signal handling stuff, including initintr() */
212
213 initmain(); /* Module __main__ */
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000214 if (!Py_NoSiteFlag)
215 initsite(); /* Module site */
Just van Rossum5bfba3a2003-02-25 20:25:12 +0000216
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000217 /* auto-thread-state API, if available */
218#ifdef WITH_THREAD
219 _PyGILState_Init(interp, tstate);
220#endif /* WITH_THREAD */
221
Mark Hammondedd07732003-07-15 23:03:55 +0000222 warnings_module = PyImport_ImportModule("warnings");
223 if (!warnings_module)
224 PyErr_Clear();
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000225
226#if defined(Py_USING_UNICODE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
227 /* On Unix, set the file system encoding according to the
228 user's preference, if the CODESET names a well-known
229 Python codec, and Py_FileSystemDefaultEncoding isn't
230 initialized by other means. */
231 if (!Py_FileSystemDefaultEncoding) {
232 char *saved_locale = setlocale(LC_CTYPE, NULL);
233 char *codeset;
234 setlocale(LC_CTYPE, "");
235 codeset = nl_langinfo(CODESET);
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000236 if (*codeset) {
Neal Norwitz5c16c7b2003-04-10 21:53:14 +0000237 PyObject *enc = PyCodec_Encoder(codeset);
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000238 if (enc) {
239 Py_FileSystemDefaultEncoding = strdup(codeset);
240 Py_DECREF(enc);
241 } else
242 PyErr_Clear();
243 }
244 setlocale(LC_CTYPE, saved_locale);
245 }
246#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000247}
248
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000249#ifdef COUNT_ALLOCS
Tim Petersdbd9ba62000-07-09 03:09:57 +0000250extern void dump_counts(void);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000251#endif
252
Guido van Rossum25ce5661997-08-02 03:10:38 +0000253/* Undo the effect of Py_Initialize().
254
255 Beware: if multiple interpreter and/or thread states exist, these
256 are not wiped out; only the current thread and interpreter state
257 are deleted. But since everything else is deleted, those other
258 interpreter and thread states should no longer be used.
259
260 (XXX We should do better, e.g. wipe out all interpreters and
261 threads.)
262
263 Locking: as above.
264
265*/
266
267void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000268Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000269{
270 PyInterpreterState *interp;
271 PyThreadState *tstate;
272
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000273 if (!initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +0000274 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000275
Tim Peters384fd102001-01-21 03:40:37 +0000276 /* The interpreter is still entirely intact at this point, and the
277 * exit funcs may be relying on that. In particular, if some thread
278 * or exit func is still waiting to do an import, the import machinery
279 * expects Py_IsInitialized() to return true. So don't say the
280 * interpreter is uninitialized until after the exit funcs have run.
281 * Note that Threading.py uses an exit func to do a join on all the
282 * threads created thru it, so this also protects pending imports in
283 * the threads created via Threading.
284 */
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000285 call_sys_exitfunc();
Tim Peters384fd102001-01-21 03:40:37 +0000286 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000287
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000288 /* Get current thread state and interpreter pointer */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000289 tstate = PyThreadState_Get();
290 interp = tstate->interp;
291
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000292 /* Disable signal handling */
293 PyOS_FiniInterrupts();
294
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000295 /* drop module references we saved */
Mark Hammondedd07732003-07-15 23:03:55 +0000296 Py_XDECREF(warnings_module);
297 warnings_module = NULL;
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000298
Guido van Rossume13ddc92003-04-17 17:29:22 +0000299 /* Collect garbage. This may call finalizers; it's nice to call these
300 before all modules are destroyed. */
301 PyGC_Collect();
302
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000303 /* Destroy all modules */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000304 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000305
Guido van Rossume13ddc92003-04-17 17:29:22 +0000306 /* Collect final garbage. This disposes of cycles created by
307 new-style class definitions, for example. */
308 PyGC_Collect();
309
Guido van Rossum1707aad1997-12-08 23:43:45 +0000310 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
311 _PyImport_Fini();
312
313 /* Debugging stuff */
314#ifdef COUNT_ALLOCS
315 dump_counts();
316#endif
317
318#ifdef Py_REF_DEBUG
319 fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
320#endif
321
Tim Peters9cf25ce2003-04-17 15:21:01 +0000322#ifdef Py_TRACE_REFS
323 /* Display all objects still alive -- this can invoke arbitrary
324 * __repr__ overrides, so requires a mostly-intact interpreter.
325 * Alas, a lot of stuff may still be alive now that will be cleaned
326 * up later.
327 */
Tim Peters269b2a62003-04-17 19:52:29 +0000328 if (Py_GETENV("PYTHONDUMPREFS"))
Tim Peters9cf25ce2003-04-17 15:21:01 +0000329 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000330#endif /* Py_TRACE_REFS */
331
Barry Warsaw035574d1997-08-29 22:07:17 +0000332 /* Now we decref the exception classes. After this point nothing
333 can raise an exception. That's okay, because each Fini() method
334 below has been checked to make sure no exceptions are ever
335 raised.
336 */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000337 _PyExc_Fini();
Barry Warsawf242aa02000-05-25 23:09:49 +0000338
Mark Hammond6cb90292003-04-22 11:18:00 +0000339 /* Cleanup auto-thread-state */
340#ifdef WITH_THREAD
341 _PyGILState_Fini();
342#endif /* WITH_THREAD */
343
Guido van Rossumd922fa42003-04-15 14:10:09 +0000344 /* Clear interpreter state */
Barry Warsawf242aa02000-05-25 23:09:49 +0000345 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000346
Guido van Rossumd922fa42003-04-15 14:10:09 +0000347 /* Delete current thread */
Barry Warsawf242aa02000-05-25 23:09:49 +0000348 PyThreadState_Swap(NULL);
349 PyInterpreterState_Delete(interp);
350
Guido van Rossumd922fa42003-04-15 14:10:09 +0000351 /* Sundry finalizers */
Guido van Rossumcc283f51997-08-05 02:22:03 +0000352 PyMethod_Fini();
353 PyFrame_Fini();
354 PyCFunction_Fini();
355 PyTuple_Fini();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000356 PyString_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000357 PyInt_Fini();
358 PyFloat_Fini();
359
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000360#ifdef Py_USING_UNICODE
361 /* Cleanup Unicode implementation */
362 _PyUnicode_Fini();
363#endif
364
Guido van Rossumcc283f51997-08-05 02:22:03 +0000365 /* XXX Still allocated:
366 - various static ad-hoc pointers to interned strings
367 - int and float free list blocks
368 - whatever various modules and libraries allocate
369 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000370
371 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000372
Tim Peters269b2a62003-04-17 19:52:29 +0000373#ifdef Py_TRACE_REFS
374 /* Display addresses (& refcnts) of all objects still alive.
375 * An address can be used to find the repr of the object, printed
376 * above by _Py_PrintReferences.
377 */
378 if (Py_GETENV("PYTHONDUMPREFS"))
379 _Py_PrintReferenceAddresses(stderr);
380#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000381#ifdef PYMALLOC_DEBUG
382 if (Py_GETENV("PYTHONMALLOCSTATS"))
383 _PyObject_DebugMallocStats();
384#endif
385
Guido van Rossumcc283f51997-08-05 02:22:03 +0000386 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000387}
388
389/* Create and initialize a new interpreter and thread, and return the
390 new thread. This requires that Py_Initialize() has been called
391 first.
392
393 Unsuccessful initialization yields a NULL pointer. Note that *no*
394 exception information is available even in this case -- the
395 exception information is held in the thread, and there is no
396 thread.
397
398 Locking: as above.
399
400*/
401
402PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000403Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000404{
405 PyInterpreterState *interp;
406 PyThreadState *tstate, *save_tstate;
407 PyObject *bimod, *sysmod;
408
409 if (!initialized)
410 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
411
412 interp = PyInterpreterState_New();
413 if (interp == NULL)
414 return NULL;
415
416 tstate = PyThreadState_New(interp);
417 if (tstate == NULL) {
418 PyInterpreterState_Delete(interp);
419 return NULL;
420 }
421
422 save_tstate = PyThreadState_Swap(tstate);
423
424 /* XXX The following is lax in error checking */
425
426 interp->modules = PyDict_New();
427
428 bimod = _PyImport_FindExtension("__builtin__", "__builtin__");
429 if (bimod != NULL) {
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000430 interp->builtins = PyModule_GetDict(bimod);
431 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000432 }
433 sysmod = _PyImport_FindExtension("sys", "sys");
434 if (bimod != NULL && sysmod != NULL) {
435 interp->sysdict = PyModule_GetDict(sysmod);
436 Py_INCREF(interp->sysdict);
437 PySys_SetPath(Py_GetPath());
438 PyDict_SetItemString(interp->sysdict, "modules",
439 interp->modules);
Martin v. Löwisd7ceb222003-01-22 09:00:38 +0000440 _PyImportHooks_Init();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000441 initmain();
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000442 if (!Py_NoSiteFlag)
443 initsite();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000444 }
445
446 if (!PyErr_Occurred())
447 return tstate;
448
449 /* Oops, it didn't work. Undo it all. */
450
451 PyErr_Print();
452 PyThreadState_Clear(tstate);
453 PyThreadState_Swap(save_tstate);
454 PyThreadState_Delete(tstate);
455 PyInterpreterState_Delete(interp);
456
457 return NULL;
458}
459
460/* Delete an interpreter and its last thread. This requires that the
461 given thread state is current, that the thread has no remaining
462 frames, and that it is its interpreter's only remaining thread.
463 It is a fatal error to violate these constraints.
464
465 (Py_Finalize() doesn't have these constraints -- it zaps
466 everything, regardless.)
467
468 Locking: as above.
469
470*/
471
472void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000473Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000474{
475 PyInterpreterState *interp = tstate->interp;
476
477 if (tstate != PyThreadState_Get())
478 Py_FatalError("Py_EndInterpreter: thread is not current");
479 if (tstate->frame != NULL)
480 Py_FatalError("Py_EndInterpreter: thread still has a frame");
481 if (tstate != interp->tstate_head || tstate->next != NULL)
482 Py_FatalError("Py_EndInterpreter: not the last thread");
483
484 PyImport_Cleanup();
485 PyInterpreterState_Clear(interp);
486 PyThreadState_Swap(NULL);
487 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000488}
489
490static char *progname = "python";
491
492void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000493Py_SetProgramName(char *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000494{
495 if (pn && *pn)
496 progname = pn;
497}
498
499char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000500Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000501{
502 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000503}
504
Guido van Rossuma61691e1998-02-06 22:27:24 +0000505static char *default_home = NULL;
506
507void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000508Py_SetPythonHome(char *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000509{
510 default_home = home;
511}
512
513char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000514Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000515{
516 char *home = default_home;
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000517 if (home == NULL && !Py_IgnoreEnvironmentFlag)
518 home = Py_GETENV("PYTHONHOME");
Guido van Rossuma61691e1998-02-06 22:27:24 +0000519 return home;
520}
521
Guido van Rossum6135a871995-01-09 17:53:26 +0000522/* Create __main__ module */
523
524static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000525initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000526{
Guido van Rossum82598051997-03-05 00:20:32 +0000527 PyObject *m, *d;
528 m = PyImport_AddModule("__main__");
Guido van Rossum6135a871995-01-09 17:53:26 +0000529 if (m == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +0000530 Py_FatalError("can't create __main__ module");
531 d = PyModule_GetDict(m);
532 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
Guido van Rossum858cb731997-11-19 16:15:37 +0000533 PyObject *bimod = PyImport_ImportModule("__builtin__");
534 if (bimod == NULL ||
535 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
Guido van Rossum82598051997-03-05 00:20:32 +0000536 Py_FatalError("can't add __builtins__ to __main__");
Barry Warsaw3d05b1a1999-01-29 21:30:22 +0000537 Py_DECREF(bimod);
Guido van Rossum6135a871995-01-09 17:53:26 +0000538 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000539}
540
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000541/* Import the site module (not into __main__ though) */
542
543static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000544initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000545{
546 PyObject *m, *f;
547 m = PyImport_ImportModule("site");
548 if (m == NULL) {
549 f = PySys_GetObject("stderr");
550 if (Py_VerboseFlag) {
551 PyFile_WriteString(
552 "'import site' failed; traceback:\n", f);
553 PyErr_Print();
554 }
555 else {
556 PyFile_WriteString(
557 "'import site' failed; use -v for traceback\n", f);
558 PyErr_Clear();
559 }
560 }
561 else {
562 Py_DECREF(m);
563 }
564}
565
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000566/* Parse input from a file and execute it */
567
568int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000569PyRun_AnyFile(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000570{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000571 return PyRun_AnyFileExFlags(fp, filename, 0, NULL);
572}
573
574int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000575PyRun_AnyFileFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000576{
577 return PyRun_AnyFileExFlags(fp, filename, 0, flags);
Guido van Rossum0df002c2000-08-27 19:21:52 +0000578}
579
580int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000581PyRun_AnyFileEx(FILE *fp, const char *filename, int closeit)
Guido van Rossum0df002c2000-08-27 19:21:52 +0000582{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000583 return PyRun_AnyFileExFlags(fp, filename, closeit, NULL);
584}
585
586int
Tim Petersd08e3822003-04-17 15:24:21 +0000587PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000588 PyCompilerFlags *flags)
589{
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000590 if (filename == NULL)
591 filename = "???";
Guido van Rossum0df002c2000-08-27 19:21:52 +0000592 if (Py_FdIsInteractive(fp, filename)) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000593 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
Guido van Rossum0df002c2000-08-27 19:21:52 +0000594 if (closeit)
595 fclose(fp);
596 return err;
597 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000598 else
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000599 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000600}
601
602int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000603PyRun_InteractiveLoop(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000604{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000605 return PyRun_InteractiveLoopFlags(fp, filename, NULL);
606}
607
608int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000609PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000610{
Guido van Rossum82598051997-03-05 00:20:32 +0000611 PyObject *v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000612 int ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000613 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000614
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000615 if (flags == NULL) {
616 flags = &local_flags;
Tim Peters5ba58662001-07-16 02:29:45 +0000617 local_flags.cf_flags = 0;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000618 }
Guido van Rossum82598051997-03-05 00:20:32 +0000619 v = PySys_GetObject("ps1");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000620 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000621 PySys_SetObject("ps1", v = PyString_FromString(">>> "));
622 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000623 }
Guido van Rossum82598051997-03-05 00:20:32 +0000624 v = PySys_GetObject("ps2");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000625 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000626 PySys_SetObject("ps2", v = PyString_FromString("... "));
627 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000628 }
629 for (;;) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000630 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
Guido van Rossumaae0d321996-05-22 16:35:33 +0000631#ifdef Py_REF_DEBUG
Guido van Rossum6f9e4331995-03-29 16:57:48 +0000632 fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000633#endif
634 if (ret == E_EOF)
635 return 0;
636 /*
637 if (ret == E_NOMEM)
638 return -1;
639 */
640 }
641}
642
643int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000644PyRun_InteractiveOne(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000645{
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000646 return PyRun_InteractiveOneFlags(fp, filename, NULL);
647}
648
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000649/* compute parser flags based on compiler flags */
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000650#define PARSER_FLAGS(flags) \
Guido van Rossum4b499dd32003-02-13 22:07:59 +0000651 (((flags) && (flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
652 PyPARSE_DONT_IMPLY_DEDENT : 0)
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000653
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000654int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000655PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000656{
Guido van Rossum82598051997-03-05 00:20:32 +0000657 PyObject *m, *d, *v, *w;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000658 node *n;
Guido van Rossuma110aa61994-08-29 12:50:44 +0000659 perrdetail err;
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000660 char *ps1 = "", *ps2 = "";
Tim Petersfe2127d2001-07-16 05:37:24 +0000661
Guido van Rossum82598051997-03-05 00:20:32 +0000662 v = PySys_GetObject("ps1");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000663 if (v != NULL) {
664 v = PyObject_Str(v);
665 if (v == NULL)
666 PyErr_Clear();
667 else if (PyString_Check(v))
668 ps1 = PyString_AsString(v);
669 }
Guido van Rossum82598051997-03-05 00:20:32 +0000670 w = PySys_GetObject("ps2");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000671 if (w != NULL) {
672 w = PyObject_Str(w);
673 if (w == NULL)
674 PyErr_Clear();
675 else if (PyString_Check(w))
676 ps2 = PyString_AsString(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000677 }
Tim Petersfe2127d2001-07-16 05:37:24 +0000678 n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar,
679 Py_single_input, ps1, ps2, &err,
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000680 PARSER_FLAGS(flags));
Guido van Rossum82598051997-03-05 00:20:32 +0000681 Py_XDECREF(v);
682 Py_XDECREF(w);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000683 if (n == NULL) {
684 if (err.error == E_EOF) {
685 if (err.text)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000686 PyMem_DEL(err.text);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000687 return E_EOF;
688 }
689 err_input(&err);
Guido van Rossum82598051997-03-05 00:20:32 +0000690 PyErr_Print();
Guido van Rossuma110aa61994-08-29 12:50:44 +0000691 return err.error;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000692 }
Guido van Rossum82598051997-03-05 00:20:32 +0000693 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000694 if (m == NULL)
695 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000696 d = PyModule_GetDict(m);
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000697 v = run_node(n, filename, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000698 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000699 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000700 return -1;
701 }
Guido van Rossum82598051997-03-05 00:20:32 +0000702 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000703 if (Py_FlushLine())
704 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000705 return 0;
706}
707
708int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000709PyRun_SimpleFile(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000710{
Guido van Rossum0df002c2000-08-27 19:21:52 +0000711 return PyRun_SimpleFileEx(fp, filename, 0);
712}
713
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000714/* Check whether a file maybe a pyc file: Look at the extension,
715 the file type, and, if we may close it, at the first few bytes. */
716
717static int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000718maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000719{
720 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
721 return 1;
722
723#ifdef macintosh
724 /* On a mac, we also assume a pyc file for types 'PYC ' and 'APPL' */
Jack Jansen72f3b7a2002-12-13 15:23:10 +0000725 if (PyMac_getfiletype((char *)filename) == 'PYC '
726 || PyMac_getfiletype((char *)filename) == 'APPL')
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000727 return 1;
728#endif /* macintosh */
729
730 /* Only look into the file if we are allowed to close it, since
731 it then should also be seekable. */
732 if (closeit) {
733 /* Read only two bytes of the magic. If the file was opened in
734 text mode, the bytes 3 and 4 of the magic (\r\n) might not
735 be read as they are on disk. */
736 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
737 unsigned char buf[2];
Tim Peters3e876562001-02-11 04:35:39 +0000738 /* Mess: In case of -x, the stream is NOT at its start now,
739 and ungetc() was used to push back the first newline,
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000740 which makes the current stream position formally undefined,
741 and a x-platform nightmare.
742 Unfortunately, we have no direct way to know whether -x
743 was specified. So we use a terrible hack: if the current
744 stream position is not 0, we assume -x was specified, and
745 give up. Bug 132850 on SourceForge spells out the
746 hopelessness of trying anything else (fseek and ftell
747 don't work predictably x-platform for text-mode files).
Tim Peters3e876562001-02-11 04:35:39 +0000748 */
Tim Peters3e876562001-02-11 04:35:39 +0000749 int ispyc = 0;
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000750 if (ftell(fp) == 0) {
751 if (fread(buf, 1, 2, fp) == 2 &&
Tim Petersd08e3822003-04-17 15:24:21 +0000752 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000753 ispyc = 1;
754 rewind(fp);
755 }
Tim Peters3e876562001-02-11 04:35:39 +0000756 return ispyc;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000757 }
758 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +0000759}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000760
Guido van Rossum0df002c2000-08-27 19:21:52 +0000761int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000762PyRun_SimpleFileEx(FILE *fp, const char *filename, int closeit)
Guido van Rossum0df002c2000-08-27 19:21:52 +0000763{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000764 return PyRun_SimpleFileExFlags(fp, filename, closeit, NULL);
765}
766
767int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000768PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000769 PyCompilerFlags *flags)
770{
Guido van Rossum82598051997-03-05 00:20:32 +0000771 PyObject *m, *d, *v;
Martin v. Löwis95292d62002-12-11 14:04:59 +0000772 const char *ext;
Guido van Rossumfdef2711994-09-14 13:31:04 +0000773
Guido van Rossum82598051997-03-05 00:20:32 +0000774 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000775 if (m == NULL)
776 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000777 d = PyModule_GetDict(m);
Fred Drake8ed02042002-10-17 21:24:58 +0000778 if (PyDict_GetItemString(d, "__file__") == NULL) {
779 PyObject *f = PyString_FromString(filename);
780 if (f == NULL)
781 return -1;
782 if (PyDict_SetItemString(d, "__file__", f) < 0) {
783 Py_DECREF(f);
784 return -1;
785 }
786 Py_DECREF(f);
787 }
Guido van Rossumfdef2711994-09-14 13:31:04 +0000788 ext = filename + strlen(filename) - 4;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000789 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Guido van Rossumfdef2711994-09-14 13:31:04 +0000790 /* Try to run a pyc file. First, re-open in binary */
Guido van Rossum0df002c2000-08-27 19:21:52 +0000791 if (closeit)
792 fclose(fp);
Fred Drake8ed02042002-10-17 21:24:58 +0000793 if ((fp = fopen(filename, "rb")) == NULL) {
Guido van Rossumfdef2711994-09-14 13:31:04 +0000794 fprintf(stderr, "python: Can't reopen .pyc file\n");
795 return -1;
796 }
Guido van Rossum2a7f58d1997-04-02 05:28:38 +0000797 /* Turn on optimization if a .pyo file is given */
798 if (strcmp(ext, ".pyo") == 0)
799 Py_OptimizeFlag = 1;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000800 v = run_pyc_file(fp, filename, d, d, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000801 } else {
Tim Petersd08e3822003-04-17 15:24:21 +0000802 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000803 closeit, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000804 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000805 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000806 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000807 return -1;
808 }
Guido van Rossum82598051997-03-05 00:20:32 +0000809 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000810 if (Py_FlushLine())
811 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000812 return 0;
813}
814
815int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000816PyRun_SimpleString(const char *command)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000817{
Guido van Rossum393661d2001-08-31 17:40:15 +0000818 return PyRun_SimpleStringFlags(command, NULL);
819}
820
821int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000822PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +0000823{
Guido van Rossum82598051997-03-05 00:20:32 +0000824 PyObject *m, *d, *v;
825 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000826 if (m == NULL)
827 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000828 d = PyModule_GetDict(m);
Guido van Rossum393661d2001-08-31 17:40:15 +0000829 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000830 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000831 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000832 return -1;
833 }
Guido van Rossum82598051997-03-05 00:20:32 +0000834 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000835 if (Py_FlushLine())
836 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000837 return 0;
838}
839
Barry Warsaw035574d1997-08-29 22:07:17 +0000840static int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000841parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
842 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +0000843{
844 long hold;
845 PyObject *v;
846
847 /* old style errors */
848 if (PyTuple_Check(err))
Neal Norwitz78293352002-04-01 01:41:20 +0000849 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
850 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +0000851
852 /* new style errors. `err' is an instance */
853
854 if (! (v = PyObject_GetAttrString(err, "msg")))
855 goto finally;
856 *message = v;
857
858 if (!(v = PyObject_GetAttrString(err, "filename")))
859 goto finally;
860 if (v == Py_None)
861 *filename = NULL;
862 else if (! (*filename = PyString_AsString(v)))
863 goto finally;
864
865 Py_DECREF(v);
866 if (!(v = PyObject_GetAttrString(err, "lineno")))
867 goto finally;
868 hold = PyInt_AsLong(v);
869 Py_DECREF(v);
870 v = NULL;
871 if (hold < 0 && PyErr_Occurred())
872 goto finally;
873 *lineno = (int)hold;
874
875 if (!(v = PyObject_GetAttrString(err, "offset")))
876 goto finally;
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000877 if (v == Py_None) {
878 *offset = -1;
879 Py_DECREF(v);
880 v = NULL;
881 } else {
882 hold = PyInt_AsLong(v);
883 Py_DECREF(v);
884 v = NULL;
885 if (hold < 0 && PyErr_Occurred())
886 goto finally;
887 *offset = (int)hold;
888 }
Barry Warsaw035574d1997-08-29 22:07:17 +0000889
890 if (!(v = PyObject_GetAttrString(err, "text")))
891 goto finally;
892 if (v == Py_None)
893 *text = NULL;
894 else if (! (*text = PyString_AsString(v)))
895 goto finally;
896 Py_DECREF(v);
897 return 1;
898
899finally:
900 Py_XDECREF(v);
901 return 0;
902}
903
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000904void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000905PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000906{
Guido van Rossuma61691e1998-02-06 22:27:24 +0000907 PyErr_PrintEx(1);
908}
909
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000910static void
Martin v. Löwis95292d62002-12-11 14:04:59 +0000911print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000912{
913 char *nl;
914 if (offset >= 0) {
915 if (offset > 0 && offset == (int)strlen(text))
916 offset--;
917 for (;;) {
918 nl = strchr(text, '\n');
919 if (nl == NULL || nl-text >= offset)
920 break;
921 offset -= (nl+1-text);
922 text = nl+1;
923 }
924 while (*text == ' ' || *text == '\t') {
925 text++;
926 offset--;
927 }
928 }
929 PyFile_WriteString(" ", f);
930 PyFile_WriteString(text, f);
931 if (*text == '\0' || text[strlen(text)-1] != '\n')
932 PyFile_WriteString("\n", f);
933 if (offset == -1)
934 return;
935 PyFile_WriteString(" ", f);
936 offset--;
937 while (offset > 0) {
938 PyFile_WriteString(" ", f);
939 offset--;
940 }
941 PyFile_WriteString("^\n", f);
942}
943
Guido van Rossum66e8e862001-03-23 17:54:43 +0000944static void
945handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000946{
Guido van Rossum66e8e862001-03-23 17:54:43 +0000947 PyObject *exception, *value, *tb;
Tim Peterscf615b52003-04-19 18:47:02 +0000948 int exitcode = 0;
949
Guido van Rossum66e8e862001-03-23 17:54:43 +0000950 PyErr_Fetch(&exception, &value, &tb);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000951 if (Py_FlushLine())
952 PyErr_Clear();
953 fflush(stdout);
954 if (value == NULL || value == Py_None)
Tim Peterscf615b52003-04-19 18:47:02 +0000955 goto done;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000956 if (PyInstance_Check(value)) {
957 /* The error code should be in the `code' attribute. */
958 PyObject *code = PyObject_GetAttrString(value, "code");
959 if (code) {
960 Py_DECREF(value);
961 value = code;
962 if (value == Py_None)
Tim Peterscf615b52003-04-19 18:47:02 +0000963 goto done;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000964 }
965 /* If we failed to dig out the 'code' attribute,
966 just let the else clause below print the error. */
967 }
968 if (PyInt_Check(value))
Tim Peterscf615b52003-04-19 18:47:02 +0000969 exitcode = (int)PyInt_AsLong(value);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000970 else {
971 PyObject_Print(value, stderr, Py_PRINT_RAW);
972 PySys_WriteStderr("\n");
Tim Peterscf615b52003-04-19 18:47:02 +0000973 exitcode = 1;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000974 }
Tim Peterscf615b52003-04-19 18:47:02 +0000975 done:
976 /* Restore and clear the exception info, in order to properly decref
977 * the exception, value, and traceback. If we just exit instead,
978 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
979 * some finalizers from running.
980 */
981 PyErr_Restore(exception, value, tb);
982 PyErr_Clear();
983 Py_Exit(exitcode);
984 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000985}
986
987void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000988PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000989{
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000990 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +0000991
992 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
993 handle_system_exit();
994 }
Guido van Rossum82598051997-03-05 00:20:32 +0000995 PyErr_Fetch(&exception, &v, &tb);
Barry Warsaw035574d1997-08-29 22:07:17 +0000996 PyErr_NormalizeException(&exception, &v, &tb);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000997 if (exception == NULL)
Guido van Rossum296b4751997-05-23 00:19:20 +0000998 return;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000999 if (set_sys_last_vars) {
1000 PySys_SetObject("last_type", exception);
1001 PySys_SetObject("last_value", v);
1002 PySys_SetObject("last_traceback", tb);
1003 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001004 hook = PySys_GetObject("excepthook");
1005 if (hook) {
1006 PyObject *args = Py_BuildValue("(OOO)",
1007 exception, v ? v : Py_None, tb ? tb : Py_None);
1008 PyObject *result = PyEval_CallObject(hook, args);
1009 if (result == NULL) {
1010 PyObject *exception2, *v2, *tb2;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001011 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1012 handle_system_exit();
1013 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001014 PyErr_Fetch(&exception2, &v2, &tb2);
1015 PyErr_NormalizeException(&exception2, &v2, &tb2);
1016 if (Py_FlushLine())
1017 PyErr_Clear();
1018 fflush(stdout);
1019 PySys_WriteStderr("Error in sys.excepthook:\n");
1020 PyErr_Display(exception2, v2, tb2);
1021 PySys_WriteStderr("\nOriginal exception was:\n");
1022 PyErr_Display(exception, v, tb);
Jeremy Hylton07028582001-12-07 15:35:35 +00001023 Py_XDECREF(exception2);
1024 Py_XDECREF(v2);
1025 Py_XDECREF(tb2);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001026 }
1027 Py_XDECREF(result);
1028 Py_XDECREF(args);
1029 } else {
1030 PySys_WriteStderr("sys.excepthook is missing\n");
1031 PyErr_Display(exception, v, tb);
1032 }
1033 Py_XDECREF(exception);
1034 Py_XDECREF(v);
1035 Py_XDECREF(tb);
1036}
1037
1038void PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
1039{
1040 int err = 0;
1041 PyObject *v = value;
1042 PyObject *f = PySys_GetObject("stderr");
Guido van Rossum3165fe61992-09-25 21:59:05 +00001043 if (f == NULL)
1044 fprintf(stderr, "lost sys.stderr\n");
1045 else {
Guido van Rossum0829c751998-02-28 04:31:39 +00001046 if (Py_FlushLine())
1047 PyErr_Clear();
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001048 fflush(stdout);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001049 if (tb && tb != Py_None)
1050 err = PyTraceBack_Print(tb, f);
Barry Warsaw36b8f941997-08-26 18:09:48 +00001051 if (err == 0 &&
Martin v. Löwiscfeb3b62002-03-03 21:30:27 +00001052 PyObject_HasAttrString(v, "print_file_and_line"))
Barry Warsaw36b8f941997-08-26 18:09:48 +00001053 {
Guido van Rossum82598051997-03-05 00:20:32 +00001054 PyObject *message;
Martin v. Löwis95292d62002-12-11 14:04:59 +00001055 const char *filename, *text;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001056 int lineno, offset;
Barry Warsaw035574d1997-08-29 22:07:17 +00001057 if (!parse_syntax_error(v, &message, &filename,
1058 &lineno, &offset, &text))
Guido van Rossum82598051997-03-05 00:20:32 +00001059 PyErr_Clear();
Guido van Rossuma110aa61994-08-29 12:50:44 +00001060 else {
1061 char buf[10];
Guido van Rossum82598051997-03-05 00:20:32 +00001062 PyFile_WriteString(" File \"", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001063 if (filename == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +00001064 PyFile_WriteString("<string>", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001065 else
Guido van Rossum82598051997-03-05 00:20:32 +00001066 PyFile_WriteString(filename, f);
1067 PyFile_WriteString("\", line ", f);
Jeremy Hylton518ab1c2001-11-28 20:42:20 +00001068 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
Guido van Rossum82598051997-03-05 00:20:32 +00001069 PyFile_WriteString(buf, f);
1070 PyFile_WriteString("\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001071 if (text != NULL)
1072 print_error_text(f, offset, text);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001073 v = message;
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001074 /* Can't be bothered to check all those
1075 PyFile_WriteString() calls */
1076 if (PyErr_Occurred())
1077 err = -1;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001078 }
1079 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001080 if (err) {
1081 /* Don't do anything else */
1082 }
1083 else if (PyClass_Check(exception)) {
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001084 PyClassObject* exc = (PyClassObject*)exception;
1085 PyObject* className = exc->cl_name;
1086 PyObject* moduleName =
1087 PyDict_GetItemString(exc->cl_dict, "__module__");
1088
1089 if (moduleName == NULL)
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001090 err = PyFile_WriteString("<unknown>", f);
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001091 else {
1092 char* modstr = PyString_AsString(moduleName);
Tim Petersd08e3822003-04-17 15:24:21 +00001093 if (modstr && strcmp(modstr, "exceptions"))
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001094 {
1095 err = PyFile_WriteString(modstr, f);
1096 err += PyFile_WriteString(".", f);
1097 }
1098 }
1099 if (err == 0) {
1100 if (className == NULL)
1101 err = PyFile_WriteString("<unknown>", f);
1102 else
1103 err = PyFile_WriteObject(className, f,
1104 Py_PRINT_RAW);
1105 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001106 }
1107 else
1108 err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
1109 if (err == 0) {
1110 if (v != NULL && v != Py_None) {
Barry Warsaw035574d1997-08-29 22:07:17 +00001111 PyObject *s = PyObject_Str(v);
1112 /* only print colon if the str() of the
1113 object is not the empty string
1114 */
Guido van Rossumd6bf45b1997-09-05 19:11:53 +00001115 if (s == NULL)
1116 err = -1;
1117 else if (!PyString_Check(s) ||
1118 PyString_GET_SIZE(s) != 0)
Barry Warsaw035574d1997-08-29 22:07:17 +00001119 err = PyFile_WriteString(": ", f);
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001120 if (err == 0)
Guido van Rossumd6bf45b1997-09-05 19:11:53 +00001121 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1122 Py_XDECREF(s);
Guido van Rossum262e1241995-02-07 15:30:45 +00001123 }
Guido van Rossum262e1241995-02-07 15:30:45 +00001124 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001125 if (err == 0)
1126 err = PyFile_WriteString("\n", f);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001127 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001128 /* If an error happened here, don't show it.
1129 XXX This is wrong, but too many callers rely on this behavior. */
1130 if (err != 0)
1131 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001132}
1133
Guido van Rossum82598051997-03-05 00:20:32 +00001134PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001135PyRun_String(const char *str, int start, PyObject *globals, PyObject *locals)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001136{
Guido van Rossum82598051997-03-05 00:20:32 +00001137 return run_err_node(PyParser_SimpleParseString(str, start),
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001138 "<string>", globals, locals, NULL);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001139}
1140
Guido van Rossum82598051997-03-05 00:20:32 +00001141PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001142PyRun_File(FILE *fp, const char *filename, int start, PyObject *globals,
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001143 PyObject *locals)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001144{
Tim Peterse8682112000-08-27 20:18:17 +00001145 return PyRun_FileEx(fp, filename, start, globals, locals, 0);
Guido van Rossum0df002c2000-08-27 19:21:52 +00001146}
1147
1148PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001149PyRun_FileEx(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001150 PyObject *locals, int closeit)
Guido van Rossum0df002c2000-08-27 19:21:52 +00001151{
1152 node *n = PyParser_SimpleParseFile(fp, filename, start);
1153 if (closeit)
1154 fclose(fp);
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001155 return run_err_node(n, filename, globals, locals, NULL);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001156}
1157
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001158PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001159PyRun_StringFlags(const char *str, int start, PyObject *globals, PyObject *locals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001160 PyCompilerFlags *flags)
1161{
Guido van Rossuma1b3a472001-07-16 16:51:33 +00001162 return run_err_node(PyParser_SimpleParseStringFlags(
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001163 str, start, PARSER_FLAGS(flags)),
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001164 "<string>", globals, locals, flags);
1165}
1166
1167PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001168PyRun_FileFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001169 PyObject *locals, PyCompilerFlags *flags)
1170{
1171 return PyRun_FileExFlags(fp, filename, start, globals, locals, 0,
Tim Petersd08e3822003-04-17 15:24:21 +00001172 flags);
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001173}
1174
1175PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001176PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001177 PyObject *locals, int closeit, PyCompilerFlags *flags)
1178{
Tim Petersfe2127d2001-07-16 05:37:24 +00001179 node *n = PyParser_SimpleParseFileFlags(fp, filename, start,
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001180 PARSER_FLAGS(flags));
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001181 if (closeit)
1182 fclose(fp);
1183 return run_err_node(n, filename, globals, locals, flags);
1184}
1185
Guido van Rossum82598051997-03-05 00:20:32 +00001186static PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001187run_err_node(node *n, const char *filename, PyObject *globals, PyObject *locals,
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001188 PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001189{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001190 if (n == NULL)
1191 return NULL;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001192 return run_node(n, filename, globals, locals, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001193}
1194
Guido van Rossum82598051997-03-05 00:20:32 +00001195static PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001196run_node(node *n, const char *filename, PyObject *globals, PyObject *locals,
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001197 PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001198{
Guido van Rossum82598051997-03-05 00:20:32 +00001199 PyCodeObject *co;
1200 PyObject *v;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001201 co = PyNode_CompileFlags(n, filename, flags);
Guido van Rossum82598051997-03-05 00:20:32 +00001202 PyNode_Free(n);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001203 if (co == NULL)
1204 return NULL;
Guido van Rossum82598051997-03-05 00:20:32 +00001205 v = PyEval_EvalCode(co, globals, locals);
1206 Py_DECREF(co);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001207 return v;
1208}
1209
Guido van Rossum82598051997-03-05 00:20:32 +00001210static PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001211run_pyc_file(FILE *fp, const char *filename, PyObject *globals, PyObject *locals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001212 PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001213{
Guido van Rossum82598051997-03-05 00:20:32 +00001214 PyCodeObject *co;
1215 PyObject *v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001216 long magic;
Fred Drakee8de31c2000-08-31 05:38:39 +00001217 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001218
Guido van Rossum82598051997-03-05 00:20:32 +00001219 magic = PyMarshal_ReadLongFromFile(fp);
1220 if (magic != PyImport_GetMagicNumber()) {
1221 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001222 "Bad magic number in .pyc file");
1223 return NULL;
1224 }
Guido van Rossum82598051997-03-05 00:20:32 +00001225 (void) PyMarshal_ReadLongFromFile(fp);
Tim Petersd9b9ac82001-01-28 00:27:39 +00001226 v = PyMarshal_ReadLastObjectFromFile(fp);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001227 fclose(fp);
Guido van Rossum82598051997-03-05 00:20:32 +00001228 if (v == NULL || !PyCode_Check(v)) {
1229 Py_XDECREF(v);
1230 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001231 "Bad code object in .pyc file");
1232 return NULL;
1233 }
Guido van Rossum82598051997-03-05 00:20:32 +00001234 co = (PyCodeObject *)v;
1235 v = PyEval_EvalCode(co, globals, locals);
Jeremy Hyltonb857ba22001-08-10 21:41:33 +00001236 if (v && flags)
1237 flags->cf_flags |= (co->co_flags & PyCF_MASK);
Guido van Rossum82598051997-03-05 00:20:32 +00001238 Py_DECREF(co);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001239 return v;
1240}
1241
Guido van Rossum82598051997-03-05 00:20:32 +00001242PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001243Py_CompileString(const char *str, const char *filename, int start)
Guido van Rossum5b722181993-03-30 17:46:03 +00001244{
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001245 return Py_CompileStringFlags(str, filename, start, NULL);
1246}
1247
1248PyObject *
Tim Petersd08e3822003-04-17 15:24:21 +00001249Py_CompileStringFlags(const char *str, const char *filename, int start,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001250 PyCompilerFlags *flags)
1251{
Guido van Rossum5b722181993-03-30 17:46:03 +00001252 node *n;
Guido van Rossum82598051997-03-05 00:20:32 +00001253 PyCodeObject *co;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001254
1255 n = PyParser_SimpleParseStringFlagsFilename(str, filename, start,
1256 PARSER_FLAGS(flags));
Guido van Rossuma110aa61994-08-29 12:50:44 +00001257 if (n == NULL)
Guido van Rossum5b722181993-03-30 17:46:03 +00001258 return NULL;
Jeremy Hylton673a4fd2001-03-26 19:53:38 +00001259 co = PyNode_CompileFlags(n, filename, flags);
Guido van Rossum82598051997-03-05 00:20:32 +00001260 PyNode_Free(n);
1261 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001262}
1263
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001264struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001265Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001266{
1267 node *n;
1268 struct symtable *st;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001269 n = PyParser_SimpleParseStringFlagsFilename(str, filename,
1270 start, 0);
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001271 if (n == NULL)
1272 return NULL;
1273 st = PyNode_CompileSymtable(n, filename);
1274 PyNode_Free(n);
1275 return st;
1276}
1277
Guido van Rossuma110aa61994-08-29 12:50:44 +00001278/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001279
Guido van Rossuma110aa61994-08-29 12:50:44 +00001280node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001281PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001282{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001283 node *n;
1284 perrdetail err;
Tim Petersfe2127d2001-07-16 05:37:24 +00001285 n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar, start,
1286 (char *)0, (char *)0, &err, flags);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001287 if (n == NULL)
1288 err_input(&err);
1289 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001290}
1291
Tim Petersfe2127d2001-07-16 05:37:24 +00001292node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001293PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
Tim Petersfe2127d2001-07-16 05:37:24 +00001294{
1295 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
1296}
1297
Guido van Rossuma110aa61994-08-29 12:50:44 +00001298/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001299
Guido van Rossuma110aa61994-08-29 12:50:44 +00001300node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001301PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001302{
1303 node *n;
1304 perrdetail err;
1305 n = PyParser_ParseStringFlags(str, &_PyParser_Grammar, start, &err,
1306 flags);
1307 if (n == NULL)
1308 err_input(&err);
1309 return n;
1310}
1311
1312node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001313PyParser_SimpleParseString(const char *str, int start)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001314{
Tim Petersfe2127d2001-07-16 05:37:24 +00001315 return PyParser_SimpleParseStringFlags(str, start, 0);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001316}
1317
Thomas Heller6b17abf2002-07-09 09:23:27 +00001318node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001319PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Thomas Heller6b17abf2002-07-09 09:23:27 +00001320 int start, int flags)
1321{
1322 node *n;
1323 perrdetail err;
1324
Tim Petersd08e3822003-04-17 15:24:21 +00001325 n = PyParser_ParseStringFlagsFilename(str, filename,
Thomas Heller6b17abf2002-07-09 09:23:27 +00001326 &_PyParser_Grammar,
1327 start, &err, flags);
1328 if (n == NULL)
1329 err_input(&err);
1330 return n;
1331}
1332
1333node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001334PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001335{
1336 return PyParser_SimpleParseStringFlagsFilename(str, filename,
1337 start, 0);
1338}
1339
Guido van Rossum66ebd912003-04-17 16:02:26 +00001340/* May want to move a more generalized form of this to parsetok.c or
1341 even parser modules. */
1342
1343void
1344PyParser_SetError(perrdetail *err)
1345{
1346 err_input(err);
1347}
1348
Guido van Rossuma110aa61994-08-29 12:50:44 +00001349/* Set the error appropriate to the given input error code (see errcode.h) */
1350
1351static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001352err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001353{
Fred Drake85f36392000-07-11 17:53:00 +00001354 PyObject *v, *w, *errtype;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001355 PyObject* u = NULL;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001356 char *msg = NULL;
Fred Drake85f36392000-07-11 17:53:00 +00001357 errtype = PyExc_SyntaxError;
Guido van Rossum82598051997-03-05 00:20:32 +00001358 v = Py_BuildValue("(ziiz)", err->filename,
Guido van Rossuma110aa61994-08-29 12:50:44 +00001359 err->lineno, err->offset, err->text);
1360 if (err->text != NULL) {
Guido van Rossumb18618d2000-05-03 23:44:39 +00001361 PyMem_DEL(err->text);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001362 err->text = NULL;
1363 }
1364 switch (err->error) {
1365 case E_SYNTAX:
Fred Drake85f36392000-07-11 17:53:00 +00001366 errtype = PyExc_IndentationError;
1367 if (err->expected == INDENT)
1368 msg = "expected an indented block";
1369 else if (err->token == INDENT)
1370 msg = "unexpected indent";
1371 else if (err->token == DEDENT)
1372 msg = "unexpected unindent";
1373 else {
1374 errtype = PyExc_SyntaxError;
1375 msg = "invalid syntax";
1376 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001377 break;
1378 case E_TOKEN:
1379 msg = "invalid token";
Guido van Rossuma110aa61994-08-29 12:50:44 +00001380 break;
Skip Montanaro118ec702002-08-15 01:20:16 +00001381 case E_EOFS:
1382 msg = "EOF while scanning triple-quoted string";
1383 break;
1384 case E_EOLS:
1385 msg = "EOL while scanning single-quoted string";
1386 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001387 case E_INTR:
Guido van Rossum82598051997-03-05 00:20:32 +00001388 PyErr_SetNone(PyExc_KeyboardInterrupt);
Barry Warsawc80baa31999-01-27 16:39:40 +00001389 Py_XDECREF(v);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001390 return;
1391 case E_NOMEM:
Guido van Rossum82598051997-03-05 00:20:32 +00001392 PyErr_NoMemory();
Barry Warsawc80baa31999-01-27 16:39:40 +00001393 Py_XDECREF(v);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001394 return;
1395 case E_EOF:
1396 msg = "unexpected EOF while parsing";
1397 break;
Fred Drake85f36392000-07-11 17:53:00 +00001398 case E_TABSPACE:
1399 errtype = PyExc_TabError;
Guido van Rossum560e8ad1998-04-10 19:43:42 +00001400 msg = "inconsistent use of tabs and spaces in indentation";
1401 break;
Jeremy Hylton94988062000-06-20 19:10:44 +00001402 case E_OVERFLOW:
1403 msg = "expression too long";
1404 break;
Fred Drake85f36392000-07-11 17:53:00 +00001405 case E_DEDENT:
1406 errtype = PyExc_IndentationError;
1407 msg = "unindent does not match any outer indentation level";
1408 break;
1409 case E_TOODEEP:
1410 errtype = PyExc_IndentationError;
1411 msg = "too many levels of indentation";
1412 break;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001413 case E_DECODE: { /* XXX */
1414 PyThreadState* tstate = PyThreadState_Get();
1415 PyObject* value = tstate->curexc_value;
1416 if (value != NULL) {
1417 u = PyObject_Repr(value);
1418 if (u != NULL) {
1419 msg = PyString_AsString(u);
1420 break;
1421 }
1422 }
1423 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001424 default:
1425 fprintf(stderr, "error=%d\n", err->error);
1426 msg = "unknown parsing error";
1427 break;
1428 }
Guido van Rossum82598051997-03-05 00:20:32 +00001429 w = Py_BuildValue("(sO)", msg, v);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001430 Py_XDECREF(u);
Guido van Rossum41318302001-03-23 04:01:07 +00001431 Py_XDECREF(v);
Fred Drake85f36392000-07-11 17:53:00 +00001432 PyErr_SetObject(errtype, w);
Guido van Rossum82598051997-03-05 00:20:32 +00001433 Py_XDECREF(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001434}
1435
1436/* Print fatal error message and abort */
1437
1438void
Tim Peters7c321a82002-07-09 02:57:01 +00001439Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001440{
Guido van Rossum83dd6c31994-09-29 09:38:33 +00001441 fprintf(stderr, "Fatal Python error: %s\n", msg);
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001442#ifdef MS_WINDOWS
Guido van Rossum23c94461997-05-22 20:21:30 +00001443 OutputDebugString("Fatal Python error: ");
Guido van Rossuma44823b1995-03-14 15:01:17 +00001444 OutputDebugString(msg);
1445 OutputDebugString("\n");
Guido van Rossum0ba35361998-08-13 13:33:16 +00001446#ifdef _DEBUG
1447 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00001448#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001449#endif /* MS_WINDOWS */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001450 abort();
1451}
1452
1453/* Clean up and exit */
1454
Guido van Rossuma110aa61994-08-29 12:50:44 +00001455#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00001456#include "pythread.h"
Guido van Rossum82598051997-03-05 00:20:32 +00001457int _PyThread_Started = 0; /* Set by threadmodule.c and maybe others */
Guido van Rossumf9f2e821992-08-17 08:59:08 +00001458#endif
1459
Guido van Rossum2dcfc961998-10-01 16:01:57 +00001460#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001461static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00001462static int nexitfuncs = 0;
1463
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001464int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00001465{
1466 if (nexitfuncs >= NEXITFUNCS)
1467 return -1;
1468 exitfuncs[nexitfuncs++] = func;
1469 return 0;
1470}
1471
Guido van Rossumcc283f51997-08-05 02:22:03 +00001472static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001473call_sys_exitfunc(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001474{
Guido van Rossum82598051997-03-05 00:20:32 +00001475 PyObject *exitfunc = PySys_GetObject("exitfunc");
Guido van Rossum59bff391992-09-03 20:28:00 +00001476
1477 if (exitfunc) {
Fred Drake6a12d8d2001-03-23 17:34:02 +00001478 PyObject *res;
Guido van Rossum82598051997-03-05 00:20:32 +00001479 Py_INCREF(exitfunc);
1480 PySys_SetObject("exitfunc", (PyObject *)NULL);
1481 res = PyEval_CallObject(exitfunc, (PyObject *)NULL);
Guido van Rossum59bff391992-09-03 20:28:00 +00001482 if (res == NULL) {
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001483 if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
1484 PySys_WriteStderr("Error in sys.exitfunc:\n");
1485 }
Guido van Rossum82598051997-03-05 00:20:32 +00001486 PyErr_Print();
Guido van Rossum59bff391992-09-03 20:28:00 +00001487 }
Guido van Rossum82598051997-03-05 00:20:32 +00001488 Py_DECREF(exitfunc);
Guido van Rossum59bff391992-09-03 20:28:00 +00001489 }
1490
Guido van Rossum0829c751998-02-28 04:31:39 +00001491 if (Py_FlushLine())
1492 PyErr_Clear();
Guido van Rossumcc283f51997-08-05 02:22:03 +00001493}
Guido van Rossum1662dd51994-09-07 14:38:28 +00001494
Guido van Rossumcc283f51997-08-05 02:22:03 +00001495static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001496call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00001497{
Guido van Rossum1662dd51994-09-07 14:38:28 +00001498 while (nexitfuncs > 0)
1499 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00001500
1501 fflush(stdout);
1502 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001503}
1504
1505void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001506Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001507{
Guido van Rossumcc283f51997-08-05 02:22:03 +00001508 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001509
Jack Jansen66a89771995-10-27 13:22:14 +00001510#ifdef macintosh
1511 PyMac_Exit(sts);
1512#else
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001513 exit(sts);
Jack Jansen66a89771995-10-27 13:22:14 +00001514#endif
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001515}
1516
Guido van Rossumf1dc5661993-07-05 10:31:29 +00001517static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001518initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001519{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001520#ifdef HAVE_SIGNAL_H
1521#ifdef SIGPIPE
1522 signal(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001523#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00001524#ifdef SIGXFZ
1525 signal(SIGXFZ, SIG_IGN);
1526#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00001527#ifdef SIGXFSZ
1528 signal(SIGXFSZ, SIG_IGN);
1529#endif
Guido van Rossuma110aa61994-08-29 12:50:44 +00001530#endif /* HAVE_SIGNAL_H */
Guido van Rossum82598051997-03-05 00:20:32 +00001531 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001532}
1533
Guido van Rossuma110aa61994-08-29 12:50:44 +00001534#ifdef MPW
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001535
1536/* Check for file descriptor connected to interactive device.
1537 Pretend that stdin is always interactive, other files never. */
1538
1539int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001540isatty(int fd)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001541{
1542 return fd == fileno(stdin);
1543}
1544
1545#endif
Guido van Rossum7433b121997-02-14 19:45:36 +00001546
1547/*
1548 * The file descriptor fd is considered ``interactive'' if either
1549 * a) isatty(fd) is TRUE, or
1550 * b) the -i flag was given, and the filename associated with
1551 * the descriptor is NULL or "<stdin>" or "???".
1552 */
1553int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001554Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00001555{
1556 if (isatty((int)fileno(fp)))
1557 return 1;
1558 if (!Py_InteractiveFlag)
1559 return 0;
1560 return (filename == NULL) ||
1561 (strcmp(filename, "<stdin>") == 0) ||
1562 (strcmp(filename, "???") == 0);
1563}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001564
1565
Tim Petersd08e3822003-04-17 15:24:21 +00001566#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001567#if defined(WIN32) && defined(_MSC_VER)
1568
1569/* Stack checking for Microsoft C */
1570
1571#include <malloc.h>
1572#include <excpt.h>
1573
Fred Drakee8de31c2000-08-31 05:38:39 +00001574/*
1575 * Return non-zero when we run out of memory on the stack; zero otherwise.
1576 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001577int
Fred Drake399739f2000-08-31 05:52:44 +00001578PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001579{
1580 __try {
Tim Peters92e4dd82002-10-05 01:47:34 +00001581 /* alloca throws a stack overflow exception if there's
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001582 not enough space left on the stack */
Tim Peters92e4dd82002-10-05 01:47:34 +00001583 alloca(PYOS_STACK_MARGIN * sizeof(void*));
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001584 return 0;
1585 } __except (EXCEPTION_EXECUTE_HANDLER) {
1586 /* just ignore all errors */
1587 }
1588 return 1;
1589}
1590
1591#endif /* WIN32 && _MSC_VER */
1592
1593/* Alternate implementations can be added here... */
1594
1595#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00001596
1597
1598/* Wrappers around sigaction() or signal(). */
1599
1600PyOS_sighandler_t
1601PyOS_getsig(int sig)
1602{
1603#ifdef HAVE_SIGACTION
1604 struct sigaction context;
Barry Warsawafeb2a42001-11-13 23:08:26 +00001605 /* Initialize context.sa_handler to SIG_ERR which makes about as
1606 * much sense as anything else. It should get overwritten if
1607 * sigaction actually succeeds and otherwise we avoid an
1608 * uninitialized memory read.
1609 */
1610 context.sa_handler = SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00001611 sigaction(sig, NULL, &context);
1612 return context.sa_handler;
1613#else
1614 PyOS_sighandler_t handler;
1615 handler = signal(sig, SIG_IGN);
1616 signal(sig, handler);
1617 return handler;
1618#endif
1619}
1620
1621PyOS_sighandler_t
1622PyOS_setsig(int sig, PyOS_sighandler_t handler)
1623{
1624#ifdef HAVE_SIGACTION
1625 struct sigaction context;
1626 PyOS_sighandler_t oldhandler;
Barry Warsawafeb2a42001-11-13 23:08:26 +00001627 /* Initialize context.sa_handler to SIG_ERR which makes about as
1628 * much sense as anything else. It should get overwritten if
1629 * sigaction actually succeeds and otherwise we avoid an
1630 * uninitialized memory read.
1631 */
1632 context.sa_handler = SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00001633 sigaction(sig, NULL, &context);
1634 oldhandler = context.sa_handler;
1635 context.sa_handler = handler;
1636 sigaction(sig, &context, NULL);
1637 return oldhandler;
1638#else
1639 return signal(sig, handler);
1640#endif
1641}