blob: 917f2be00b0eb61e96d2e8cdb773101a4912b83a [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 Rossuma9e7dc11992-10-18 18:53:57 +000016#include <signal.h>
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000017
Martin v. Löwis73d538b2003-03-05 15:13:47 +000018#ifdef HAVE_LANGINFO_H
19#include <locale.h>
20#include <langinfo.h>
21#endif
22
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000023#ifdef MS_WINDOWS
Guido van Rossuma44823b1995-03-14 15:01:17 +000024#undef BYTE
25#include "windows.h"
26#endif
27
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000028extern char *Py_GetPath(void);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000029
Guido van Rossum82598051997-03-05 00:20:32 +000030extern grammar _PyParser_Grammar; /* From graminit.c */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000031
Guido van Rossumb73cc041993-11-01 16:28:59 +000032/* Forward */
Tim Petersdbd9ba62000-07-09 03:09:57 +000033static void initmain(void);
34static void initsite(void);
Martin v. Löwis95292d62002-12-11 14:04:59 +000035static PyObject *run_err_node(node *, const char *, PyObject *, PyObject *,
Jeremy Hylton9f324e92001-03-01 22:59:14 +000036 PyCompilerFlags *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000037static PyObject *run_node(node *, const char *, PyObject *, PyObject *,
Jeremy Hylton9f324e92001-03-01 22:59:14 +000038 PyCompilerFlags *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000039static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
Jeremy Hyltonbc320242001-03-22 02:47:58 +000040 PyCompilerFlags *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000041static void err_input(perrdetail *);
42static void initsigs(void);
43static void call_sys_exitfunc(void);
44static void call_ll_exitfuncs(void);
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000045extern void _PyUnicode_Init(void);
46extern void _PyUnicode_Fini(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +000047
Mark Hammond8d98d2c2003-04-19 15:41:53 +000048#ifdef WITH_THREAD
49extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
50extern void _PyGILState_Fini(void);
51#endif /* WITH_THREAD */
52
Guido van Rossum82598051997-03-05 00:20:32 +000053int Py_DebugFlag; /* Needed by parser.c */
54int Py_VerboseFlag; /* Needed by import.c */
Guido van Rossum7433b121997-02-14 19:45:36 +000055int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Guido van Rossumdcc0c131997-08-29 22:32:42 +000056int Py_NoSiteFlag; /* Suppress 'import site' */
Barry Warsaw3ce09642000-05-02 19:18:59 +000057int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +000058int Py_FrozenFlag; /* Needed by getpath.c */
Guido van Rossumb16d1972000-05-01 17:55:15 +000059int Py_UnicodeFlag = 0; /* Needed by compile.c */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +000060int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Tim Peters3caca232001-12-06 06:23:26 +000061/* _XXX Py_QnewFlag should go away in 2.3. It's true iff -Qnew is passed,
62 on the command line, and is used in 2.2 by ceval.c to make all "/" divisions
63 true divisions (which they will be in 2.3). */
64int _Py_QnewFlag = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +000065
Mark Hammonda43fd0c2003-02-19 00:33:33 +000066/* Reference to 'warnings' module, to avoid importing it
Mark Hammondedd07732003-07-15 23:03:55 +000067 on the fly when the import lock may be held. See 683658/771097
Mark Hammonda43fd0c2003-02-19 00:33:33 +000068*/
Mark Hammondedd07732003-07-15 23:03:55 +000069static PyObject *warnings_module = NULL;
70
71/* Returns a borrowed reference to the 'warnings' module, or NULL.
72 If the module is returned, it is guaranteed to have been obtained
73 without acquiring the import lock
74*/
Martin v. Löwisa2c17c52003-08-09 09:47:11 +000075PyObject *PyModule_GetWarningsModule(void)
Mark Hammondedd07732003-07-15 23:03:55 +000076{
77 PyObject *typ, *val, *tb;
78 PyObject *all_modules;
79 /* If we managed to get the module at init time, just use it */
80 if (warnings_module)
81 return warnings_module;
82 /* If it wasn't available at init time, it may be available
83 now in sys.modules (common scenario is frozen apps: import
84 at init time fails, but the frozen init code sets up sys.path
85 correctly, then does an implicit import of warnings for us
86 */
87 /* Save and restore any exceptions */
88 PyErr_Fetch(&typ, &val, &tb);
89
Mark Hammond5f4e8ca2003-07-16 01:54:38 +000090 all_modules = PySys_GetObject("modules");
Mark Hammondedd07732003-07-15 23:03:55 +000091 if (all_modules) {
92 warnings_module = PyDict_GetItemString(all_modules, "warnings");
93 /* We keep a ref in the global */
94 Py_XINCREF(warnings_module);
95 }
96 PyErr_Restore(typ, val, tb);
97 return warnings_module;
98}
Mark Hammonda43fd0c2003-02-19 00:33:33 +000099
Guido van Rossum25ce5661997-08-02 03:10:38 +0000100static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000101
Thomas Wouters7e474022000-07-16 12:04:32 +0000102/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000103
104int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000105Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000106{
107 return initialized;
108}
109
Guido van Rossum25ce5661997-08-02 03:10:38 +0000110/* Global initializations. Can be undone by Py_Finalize(). Don't
111 call this twice without an intervening Py_Finalize() call. When
112 initializations fail, a fatal error is issued and the function does
113 not return. On return, the first thread and interpreter state have
114 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000115
Guido van Rossum25ce5661997-08-02 03:10:38 +0000116 Locking: you must hold the interpreter lock while calling this.
117 (If the lock has not yet been initialized, that's equivalent to
118 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000119
Guido van Rossum25ce5661997-08-02 03:10:38 +0000120*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000121
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000122static int
123add_flag(int flag, const char *envs)
124{
125 int env = atoi(envs);
126 if (flag < env)
127 flag = env;
128 if (flag < 1)
129 flag = 1;
130 return flag;
131}
132
Guido van Rossuma027efa1997-05-05 20:56:21 +0000133void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000134Py_InitializeEx(int install_sigs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000135{
Guido van Rossuma027efa1997-05-05 20:56:21 +0000136 PyInterpreterState *interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000137 PyThreadState *tstate;
138 PyObject *bimod, *sysmod;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000139 char *p;
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000140#if defined(Py_USING_UNICODE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
141 char *codeset;
142 char *saved_locale;
143 PyObject *sys_stream, *sys_isatty;
144#endif
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
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000211 if (install_sigs)
212 initsigs(); /* Signal handling stuff, including initintr() */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000213
214 initmain(); /* Module __main__ */
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000215 if (!Py_NoSiteFlag)
216 initsite(); /* Module site */
Just van Rossum5bfba3a2003-02-25 20:25:12 +0000217
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000218 /* auto-thread-state API, if available */
219#ifdef WITH_THREAD
220 _PyGILState_Init(interp, tstate);
221#endif /* WITH_THREAD */
222
Mark Hammondedd07732003-07-15 23:03:55 +0000223 warnings_module = PyImport_ImportModule("warnings");
224 if (!warnings_module)
225 PyErr_Clear();
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000226
227#if defined(Py_USING_UNICODE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
228 /* On Unix, set the file system encoding according to the
229 user's preference, if the CODESET names a well-known
230 Python codec, and Py_FileSystemDefaultEncoding isn't
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000231 initialized by other means. Also set the encoding of
232 stdin and stdout if these are terminals. */
233
Martin v. Löwisf56d0152003-11-13 07:43:21 +0000234 saved_locale = strdup(setlocale(LC_CTYPE, NULL));
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000235 setlocale(LC_CTYPE, "");
236 codeset = nl_langinfo(CODESET);
237 if (codeset && *codeset) {
238 PyObject *enc = PyCodec_Encoder(codeset);
239 if (enc) {
240 codeset = strdup(codeset);
241 Py_DECREF(enc);
242 } else {
243 codeset = NULL;
244 PyErr_Clear();
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000245 }
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000246 } else
247 codeset = NULL;
248 setlocale(LC_CTYPE, saved_locale);
Martin v. Löwisf56d0152003-11-13 07:43:21 +0000249 free(saved_locale);
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000250
251 if (codeset) {
Michael W. Hudson68debc92003-08-11 12:20:24 +0000252 sys_stream = PySys_GetObject("stdin");
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000253 sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
254 if (!sys_isatty)
255 PyErr_Clear();
256 if(sys_isatty && PyObject_IsTrue(sys_isatty)) {
257 if (!PyFile_SetEncoding(sys_stream, codeset))
258 Py_FatalError("Cannot set codeset of stdin");
259 }
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000260 Py_XDECREF(sys_isatty);
261
262 sys_stream = PySys_GetObject("stdout");
263 sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
264 if (!sys_isatty)
265 PyErr_Clear();
266 if(sys_isatty && PyObject_IsTrue(sys_isatty)) {
267 if (!PyFile_SetEncoding(sys_stream, codeset))
268 Py_FatalError("Cannot set codeset of stdout");
269 }
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000270 Py_XDECREF(sys_isatty);
271
272 if (!Py_FileSystemDefaultEncoding)
273 Py_FileSystemDefaultEncoding = codeset;
274 else
275 free(codeset);
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000276 }
277#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000278}
279
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000280void
281Py_Initialize(void)
282{
283 Py_InitializeEx(1);
284}
285
286
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000287#ifdef COUNT_ALLOCS
Tim Petersdbd9ba62000-07-09 03:09:57 +0000288extern void dump_counts(void);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000289#endif
290
Guido van Rossum25ce5661997-08-02 03:10:38 +0000291/* Undo the effect of Py_Initialize().
292
293 Beware: if multiple interpreter and/or thread states exist, these
294 are not wiped out; only the current thread and interpreter state
295 are deleted. But since everything else is deleted, those other
296 interpreter and thread states should no longer be used.
297
298 (XXX We should do better, e.g. wipe out all interpreters and
299 threads.)
300
301 Locking: as above.
302
303*/
304
305void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000306Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000307{
308 PyInterpreterState *interp;
309 PyThreadState *tstate;
310
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000311 if (!initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +0000312 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000313
Tim Peters384fd102001-01-21 03:40:37 +0000314 /* The interpreter is still entirely intact at this point, and the
315 * exit funcs may be relying on that. In particular, if some thread
316 * or exit func is still waiting to do an import, the import machinery
317 * expects Py_IsInitialized() to return true. So don't say the
318 * interpreter is uninitialized until after the exit funcs have run.
319 * Note that Threading.py uses an exit func to do a join on all the
320 * threads created thru it, so this also protects pending imports in
321 * the threads created via Threading.
322 */
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000323 call_sys_exitfunc();
Tim Peters384fd102001-01-21 03:40:37 +0000324 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000325
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000326 /* Get current thread state and interpreter pointer */
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000327 tstate = PyThreadState_GET();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000328 interp = tstate->interp;
329
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000330 /* Disable signal handling */
331 PyOS_FiniInterrupts();
332
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000333 /* drop module references we saved */
Mark Hammondedd07732003-07-15 23:03:55 +0000334 Py_XDECREF(warnings_module);
335 warnings_module = NULL;
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000336
Guido van Rossume13ddc92003-04-17 17:29:22 +0000337 /* Collect garbage. This may call finalizers; it's nice to call these
Tim Peters1d7323e2003-12-01 21:35:27 +0000338 * before all modules are destroyed.
339 * XXX If a __del__ or weakref callback is triggered here, and tries to
340 * XXX import a module, bad things can happen, because Python no
341 * XXX longer believes it's initialized.
342 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
343 * XXX is easy to provoke that way. I've also seen, e.g.,
344 * XXX Exception exceptions.ImportError: 'No module named sha'
345 * XXX in <function callback at 0x008F5718> ignored
346 * XXX but I'm unclear on exactly how that one happens. In any case,
347 * XXX I haven't seen a real-life report of either of these.
348 */
Guido van Rossume13ddc92003-04-17 17:29:22 +0000349 PyGC_Collect();
350
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000351 /* Destroy all modules */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000352 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000353
Guido van Rossume13ddc92003-04-17 17:29:22 +0000354 /* Collect final garbage. This disposes of cycles created by
Tim Peters1d7323e2003-12-01 21:35:27 +0000355 * new-style class definitions, for example.
356 * XXX This is disabled because it caused too many problems. If
357 * XXX a __del__ or weakref callback triggers here, Python code has
358 * XXX a hard time running, because even the sys module has been
359 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
360 * XXX One symptom is a sequence of information-free messages
361 * XXX coming from threads (if a __del__ or callback is invoked,
362 * XXX other threads can execute too, and any exception they encounter
363 * XXX triggers a comedy of errors as subsystem after subsystem
364 * XXX fails to find what it *expects* to find in sys to help report
365 * XXX the exception and consequent unexpected failures). I've also
366 * XXX seen segfaults then, after adding print statements to the
367 * XXX Python code getting called.
368 */
369#if 0
Guido van Rossume13ddc92003-04-17 17:29:22 +0000370 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000371#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000372
Guido van Rossum1707aad1997-12-08 23:43:45 +0000373 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
374 _PyImport_Fini();
375
376 /* Debugging stuff */
377#ifdef COUNT_ALLOCS
378 dump_counts();
379#endif
380
381#ifdef Py_REF_DEBUG
382 fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
383#endif
384
Tim Peters9cf25ce2003-04-17 15:21:01 +0000385#ifdef Py_TRACE_REFS
386 /* Display all objects still alive -- this can invoke arbitrary
387 * __repr__ overrides, so requires a mostly-intact interpreter.
388 * Alas, a lot of stuff may still be alive now that will be cleaned
389 * up later.
390 */
Tim Peters269b2a62003-04-17 19:52:29 +0000391 if (Py_GETENV("PYTHONDUMPREFS"))
Tim Peters9cf25ce2003-04-17 15:21:01 +0000392 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000393#endif /* Py_TRACE_REFS */
394
Barry Warsaw035574d1997-08-29 22:07:17 +0000395 /* Now we decref the exception classes. After this point nothing
396 can raise an exception. That's okay, because each Fini() method
397 below has been checked to make sure no exceptions are ever
398 raised.
399 */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000400 _PyExc_Fini();
Barry Warsawf242aa02000-05-25 23:09:49 +0000401
Mark Hammond6cb90292003-04-22 11:18:00 +0000402 /* Cleanup auto-thread-state */
403#ifdef WITH_THREAD
404 _PyGILState_Fini();
405#endif /* WITH_THREAD */
406
Guido van Rossumd922fa42003-04-15 14:10:09 +0000407 /* Clear interpreter state */
Barry Warsawf242aa02000-05-25 23:09:49 +0000408 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000409
Guido van Rossumd922fa42003-04-15 14:10:09 +0000410 /* Delete current thread */
Barry Warsawf242aa02000-05-25 23:09:49 +0000411 PyThreadState_Swap(NULL);
412 PyInterpreterState_Delete(interp);
413
Guido van Rossumd922fa42003-04-15 14:10:09 +0000414 /* Sundry finalizers */
Guido van Rossumcc283f51997-08-05 02:22:03 +0000415 PyMethod_Fini();
416 PyFrame_Fini();
417 PyCFunction_Fini();
418 PyTuple_Fini();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000419 PyString_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000420 PyInt_Fini();
421 PyFloat_Fini();
422
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000423#ifdef Py_USING_UNICODE
424 /* Cleanup Unicode implementation */
425 _PyUnicode_Fini();
426#endif
427
Guido van Rossumcc283f51997-08-05 02:22:03 +0000428 /* XXX Still allocated:
429 - various static ad-hoc pointers to interned strings
430 - int and float free list blocks
431 - whatever various modules and libraries allocate
432 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000433
434 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000435
Tim Peters269b2a62003-04-17 19:52:29 +0000436#ifdef Py_TRACE_REFS
437 /* Display addresses (& refcnts) of all objects still alive.
438 * An address can be used to find the repr of the object, printed
439 * above by _Py_PrintReferences.
440 */
441 if (Py_GETENV("PYTHONDUMPREFS"))
442 _Py_PrintReferenceAddresses(stderr);
443#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000444#ifdef PYMALLOC_DEBUG
445 if (Py_GETENV("PYTHONMALLOCSTATS"))
446 _PyObject_DebugMallocStats();
447#endif
448
Guido van Rossumcc283f51997-08-05 02:22:03 +0000449 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000450}
451
452/* Create and initialize a new interpreter and thread, and return the
453 new thread. This requires that Py_Initialize() has been called
454 first.
455
456 Unsuccessful initialization yields a NULL pointer. Note that *no*
457 exception information is available even in this case -- the
458 exception information is held in the thread, and there is no
459 thread.
460
461 Locking: as above.
462
463*/
464
465PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000466Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000467{
468 PyInterpreterState *interp;
469 PyThreadState *tstate, *save_tstate;
470 PyObject *bimod, *sysmod;
471
472 if (!initialized)
473 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
474
475 interp = PyInterpreterState_New();
476 if (interp == NULL)
477 return NULL;
478
479 tstate = PyThreadState_New(interp);
480 if (tstate == NULL) {
481 PyInterpreterState_Delete(interp);
482 return NULL;
483 }
484
485 save_tstate = PyThreadState_Swap(tstate);
486
487 /* XXX The following is lax in error checking */
488
489 interp->modules = PyDict_New();
490
491 bimod = _PyImport_FindExtension("__builtin__", "__builtin__");
492 if (bimod != NULL) {
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000493 interp->builtins = PyModule_GetDict(bimod);
494 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000495 }
496 sysmod = _PyImport_FindExtension("sys", "sys");
497 if (bimod != NULL && sysmod != NULL) {
498 interp->sysdict = PyModule_GetDict(sysmod);
499 Py_INCREF(interp->sysdict);
500 PySys_SetPath(Py_GetPath());
501 PyDict_SetItemString(interp->sysdict, "modules",
502 interp->modules);
Martin v. Löwisd7ceb222003-01-22 09:00:38 +0000503 _PyImportHooks_Init();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000504 initmain();
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000505 if (!Py_NoSiteFlag)
506 initsite();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000507 }
508
509 if (!PyErr_Occurred())
510 return tstate;
511
512 /* Oops, it didn't work. Undo it all. */
513
514 PyErr_Print();
515 PyThreadState_Clear(tstate);
516 PyThreadState_Swap(save_tstate);
517 PyThreadState_Delete(tstate);
518 PyInterpreterState_Delete(interp);
519
520 return NULL;
521}
522
523/* Delete an interpreter and its last thread. This requires that the
524 given thread state is current, that the thread has no remaining
525 frames, and that it is its interpreter's only remaining thread.
526 It is a fatal error to violate these constraints.
527
528 (Py_Finalize() doesn't have these constraints -- it zaps
529 everything, regardless.)
530
531 Locking: as above.
532
533*/
534
535void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000536Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000537{
538 PyInterpreterState *interp = tstate->interp;
539
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000540 if (tstate != PyThreadState_GET())
Guido van Rossum25ce5661997-08-02 03:10:38 +0000541 Py_FatalError("Py_EndInterpreter: thread is not current");
542 if (tstate->frame != NULL)
543 Py_FatalError("Py_EndInterpreter: thread still has a frame");
544 if (tstate != interp->tstate_head || tstate->next != NULL)
545 Py_FatalError("Py_EndInterpreter: not the last thread");
546
547 PyImport_Cleanup();
548 PyInterpreterState_Clear(interp);
549 PyThreadState_Swap(NULL);
550 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000551}
552
553static char *progname = "python";
554
555void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000556Py_SetProgramName(char *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000557{
558 if (pn && *pn)
559 progname = pn;
560}
561
562char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000563Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000564{
565 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000566}
567
Guido van Rossuma61691e1998-02-06 22:27:24 +0000568static char *default_home = NULL;
569
570void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000571Py_SetPythonHome(char *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000572{
573 default_home = home;
574}
575
576char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000577Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000578{
579 char *home = default_home;
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000580 if (home == NULL && !Py_IgnoreEnvironmentFlag)
581 home = Py_GETENV("PYTHONHOME");
Guido van Rossuma61691e1998-02-06 22:27:24 +0000582 return home;
583}
584
Guido van Rossum6135a871995-01-09 17:53:26 +0000585/* Create __main__ module */
586
587static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000588initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000589{
Guido van Rossum82598051997-03-05 00:20:32 +0000590 PyObject *m, *d;
591 m = PyImport_AddModule("__main__");
Guido van Rossum6135a871995-01-09 17:53:26 +0000592 if (m == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +0000593 Py_FatalError("can't create __main__ module");
594 d = PyModule_GetDict(m);
595 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
Guido van Rossum858cb731997-11-19 16:15:37 +0000596 PyObject *bimod = PyImport_ImportModule("__builtin__");
597 if (bimod == NULL ||
598 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
Guido van Rossum82598051997-03-05 00:20:32 +0000599 Py_FatalError("can't add __builtins__ to __main__");
Barry Warsaw3d05b1a1999-01-29 21:30:22 +0000600 Py_DECREF(bimod);
Guido van Rossum6135a871995-01-09 17:53:26 +0000601 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000602}
603
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000604/* Import the site module (not into __main__ though) */
605
606static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000607initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000608{
609 PyObject *m, *f;
610 m = PyImport_ImportModule("site");
611 if (m == NULL) {
612 f = PySys_GetObject("stderr");
613 if (Py_VerboseFlag) {
614 PyFile_WriteString(
615 "'import site' failed; traceback:\n", f);
616 PyErr_Print();
617 }
618 else {
619 PyFile_WriteString(
620 "'import site' failed; use -v for traceback\n", f);
621 PyErr_Clear();
622 }
623 }
624 else {
625 Py_DECREF(m);
626 }
627}
628
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000629/* Parse input from a file and execute it */
630
631int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000632PyRun_AnyFile(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000633{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000634 return PyRun_AnyFileExFlags(fp, filename, 0, NULL);
635}
636
637int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000638PyRun_AnyFileFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000639{
640 return PyRun_AnyFileExFlags(fp, filename, 0, flags);
Guido van Rossum0df002c2000-08-27 19:21:52 +0000641}
642
643int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000644PyRun_AnyFileEx(FILE *fp, const char *filename, int closeit)
Guido van Rossum0df002c2000-08-27 19:21:52 +0000645{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000646 return PyRun_AnyFileExFlags(fp, filename, closeit, NULL);
647}
648
649int
Tim Petersd08e3822003-04-17 15:24:21 +0000650PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000651 PyCompilerFlags *flags)
652{
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000653 if (filename == NULL)
654 filename = "???";
Guido van Rossum0df002c2000-08-27 19:21:52 +0000655 if (Py_FdIsInteractive(fp, filename)) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000656 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
Guido van Rossum0df002c2000-08-27 19:21:52 +0000657 if (closeit)
658 fclose(fp);
659 return err;
660 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000661 else
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000662 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000663}
664
665int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000666PyRun_InteractiveLoop(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000667{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000668 return PyRun_InteractiveLoopFlags(fp, filename, NULL);
669}
670
671int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000672PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000673{
Guido van Rossum82598051997-03-05 00:20:32 +0000674 PyObject *v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000675 int ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000676 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000677
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000678 if (flags == NULL) {
679 flags = &local_flags;
Tim Peters5ba58662001-07-16 02:29:45 +0000680 local_flags.cf_flags = 0;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000681 }
Guido van Rossum82598051997-03-05 00:20:32 +0000682 v = PySys_GetObject("ps1");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000683 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000684 PySys_SetObject("ps1", v = PyString_FromString(">>> "));
685 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000686 }
Guido van Rossum82598051997-03-05 00:20:32 +0000687 v = PySys_GetObject("ps2");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000688 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000689 PySys_SetObject("ps2", v = PyString_FromString("... "));
690 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000691 }
692 for (;;) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000693 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
Guido van Rossumaae0d321996-05-22 16:35:33 +0000694#ifdef Py_REF_DEBUG
Guido van Rossum6f9e4331995-03-29 16:57:48 +0000695 fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000696#endif
697 if (ret == E_EOF)
698 return 0;
699 /*
700 if (ret == E_NOMEM)
701 return -1;
702 */
703 }
704}
705
706int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000707PyRun_InteractiveOne(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000708{
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000709 return PyRun_InteractiveOneFlags(fp, filename, NULL);
710}
711
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000712/* compute parser flags based on compiler flags */
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000713#define PARSER_FLAGS(flags) \
Guido van Rossum4b499dd32003-02-13 22:07:59 +0000714 (((flags) && (flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
715 PyPARSE_DONT_IMPLY_DEDENT : 0)
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000716
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000717int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000718PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000719{
Guido van Rossum82598051997-03-05 00:20:32 +0000720 PyObject *m, *d, *v, *w;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000721 node *n;
Guido van Rossuma110aa61994-08-29 12:50:44 +0000722 perrdetail err;
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000723 char *ps1 = "", *ps2 = "";
Tim Petersfe2127d2001-07-16 05:37:24 +0000724
Guido van Rossum82598051997-03-05 00:20:32 +0000725 v = PySys_GetObject("ps1");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000726 if (v != NULL) {
727 v = PyObject_Str(v);
728 if (v == NULL)
729 PyErr_Clear();
730 else if (PyString_Check(v))
731 ps1 = PyString_AsString(v);
732 }
Guido van Rossum82598051997-03-05 00:20:32 +0000733 w = PySys_GetObject("ps2");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000734 if (w != NULL) {
735 w = PyObject_Str(w);
736 if (w == NULL)
737 PyErr_Clear();
738 else if (PyString_Check(w))
739 ps2 = PyString_AsString(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000740 }
Tim Petersfe2127d2001-07-16 05:37:24 +0000741 n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar,
742 Py_single_input, ps1, ps2, &err,
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000743 PARSER_FLAGS(flags));
Guido van Rossum82598051997-03-05 00:20:32 +0000744 Py_XDECREF(v);
745 Py_XDECREF(w);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000746 if (n == NULL) {
747 if (err.error == E_EOF) {
748 if (err.text)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000749 PyMem_DEL(err.text);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000750 return E_EOF;
751 }
752 err_input(&err);
Guido van Rossum82598051997-03-05 00:20:32 +0000753 PyErr_Print();
Guido van Rossuma110aa61994-08-29 12:50:44 +0000754 return err.error;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000755 }
Guido van Rossum82598051997-03-05 00:20:32 +0000756 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000757 if (m == NULL)
758 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000759 d = PyModule_GetDict(m);
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000760 v = run_node(n, filename, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000761 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000762 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000763 return -1;
764 }
Guido van Rossum82598051997-03-05 00:20:32 +0000765 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000766 if (Py_FlushLine())
767 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000768 return 0;
769}
770
771int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000772PyRun_SimpleFile(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000773{
Guido van Rossum0df002c2000-08-27 19:21:52 +0000774 return PyRun_SimpleFileEx(fp, filename, 0);
775}
776
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000777/* Check whether a file maybe a pyc file: Look at the extension,
778 the file type, and, if we may close it, at the first few bytes. */
779
780static int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000781maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000782{
783 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
784 return 1;
785
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000786 /* Only look into the file if we are allowed to close it, since
787 it then should also be seekable. */
788 if (closeit) {
789 /* Read only two bytes of the magic. If the file was opened in
790 text mode, the bytes 3 and 4 of the magic (\r\n) might not
791 be read as they are on disk. */
792 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
793 unsigned char buf[2];
Tim Peters3e876562001-02-11 04:35:39 +0000794 /* Mess: In case of -x, the stream is NOT at its start now,
795 and ungetc() was used to push back the first newline,
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000796 which makes the current stream position formally undefined,
797 and a x-platform nightmare.
798 Unfortunately, we have no direct way to know whether -x
799 was specified. So we use a terrible hack: if the current
800 stream position is not 0, we assume -x was specified, and
801 give up. Bug 132850 on SourceForge spells out the
802 hopelessness of trying anything else (fseek and ftell
803 don't work predictably x-platform for text-mode files).
Tim Peters3e876562001-02-11 04:35:39 +0000804 */
Tim Peters3e876562001-02-11 04:35:39 +0000805 int ispyc = 0;
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000806 if (ftell(fp) == 0) {
807 if (fread(buf, 1, 2, fp) == 2 &&
Tim Petersd08e3822003-04-17 15:24:21 +0000808 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000809 ispyc = 1;
810 rewind(fp);
811 }
Tim Peters3e876562001-02-11 04:35:39 +0000812 return ispyc;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000813 }
814 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +0000815}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000816
Guido van Rossum0df002c2000-08-27 19:21:52 +0000817int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000818PyRun_SimpleFileEx(FILE *fp, const char *filename, int closeit)
Guido van Rossum0df002c2000-08-27 19:21:52 +0000819{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000820 return PyRun_SimpleFileExFlags(fp, filename, closeit, NULL);
821}
822
823int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000824PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000825 PyCompilerFlags *flags)
826{
Guido van Rossum82598051997-03-05 00:20:32 +0000827 PyObject *m, *d, *v;
Martin v. Löwis95292d62002-12-11 14:04:59 +0000828 const char *ext;
Guido van Rossumfdef2711994-09-14 13:31:04 +0000829
Guido van Rossum82598051997-03-05 00:20:32 +0000830 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000831 if (m == NULL)
832 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000833 d = PyModule_GetDict(m);
Fred Drake8ed02042002-10-17 21:24:58 +0000834 if (PyDict_GetItemString(d, "__file__") == NULL) {
835 PyObject *f = PyString_FromString(filename);
836 if (f == NULL)
837 return -1;
838 if (PyDict_SetItemString(d, "__file__", f) < 0) {
839 Py_DECREF(f);
840 return -1;
841 }
842 Py_DECREF(f);
843 }
Guido van Rossumfdef2711994-09-14 13:31:04 +0000844 ext = filename + strlen(filename) - 4;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000845 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Guido van Rossumfdef2711994-09-14 13:31:04 +0000846 /* Try to run a pyc file. First, re-open in binary */
Guido van Rossum0df002c2000-08-27 19:21:52 +0000847 if (closeit)
848 fclose(fp);
Fred Drake8ed02042002-10-17 21:24:58 +0000849 if ((fp = fopen(filename, "rb")) == NULL) {
Guido van Rossumfdef2711994-09-14 13:31:04 +0000850 fprintf(stderr, "python: Can't reopen .pyc file\n");
851 return -1;
852 }
Guido van Rossum2a7f58d1997-04-02 05:28:38 +0000853 /* Turn on optimization if a .pyo file is given */
854 if (strcmp(ext, ".pyo") == 0)
855 Py_OptimizeFlag = 1;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000856 v = run_pyc_file(fp, filename, d, d, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000857 } else {
Tim Petersd08e3822003-04-17 15:24:21 +0000858 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000859 closeit, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000860 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000861 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000862 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000863 return -1;
864 }
Guido van Rossum82598051997-03-05 00:20:32 +0000865 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000866 if (Py_FlushLine())
867 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000868 return 0;
869}
870
871int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000872PyRun_SimpleString(const char *command)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000873{
Guido van Rossum393661d2001-08-31 17:40:15 +0000874 return PyRun_SimpleStringFlags(command, NULL);
875}
876
877int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000878PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +0000879{
Guido van Rossum82598051997-03-05 00:20:32 +0000880 PyObject *m, *d, *v;
881 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000882 if (m == NULL)
883 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000884 d = PyModule_GetDict(m);
Guido van Rossum393661d2001-08-31 17:40:15 +0000885 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000886 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000887 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000888 return -1;
889 }
Guido van Rossum82598051997-03-05 00:20:32 +0000890 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000891 if (Py_FlushLine())
892 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000893 return 0;
894}
895
Barry Warsaw035574d1997-08-29 22:07:17 +0000896static int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000897parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
898 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +0000899{
900 long hold;
901 PyObject *v;
902
903 /* old style errors */
904 if (PyTuple_Check(err))
Neal Norwitz78293352002-04-01 01:41:20 +0000905 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
906 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +0000907
908 /* new style errors. `err' is an instance */
909
910 if (! (v = PyObject_GetAttrString(err, "msg")))
911 goto finally;
912 *message = v;
913
914 if (!(v = PyObject_GetAttrString(err, "filename")))
915 goto finally;
916 if (v == Py_None)
917 *filename = NULL;
918 else if (! (*filename = PyString_AsString(v)))
919 goto finally;
920
921 Py_DECREF(v);
922 if (!(v = PyObject_GetAttrString(err, "lineno")))
923 goto finally;
924 hold = PyInt_AsLong(v);
925 Py_DECREF(v);
926 v = NULL;
927 if (hold < 0 && PyErr_Occurred())
928 goto finally;
929 *lineno = (int)hold;
930
931 if (!(v = PyObject_GetAttrString(err, "offset")))
932 goto finally;
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000933 if (v == Py_None) {
934 *offset = -1;
935 Py_DECREF(v);
936 v = NULL;
937 } else {
938 hold = PyInt_AsLong(v);
939 Py_DECREF(v);
940 v = NULL;
941 if (hold < 0 && PyErr_Occurred())
942 goto finally;
943 *offset = (int)hold;
944 }
Barry Warsaw035574d1997-08-29 22:07:17 +0000945
946 if (!(v = PyObject_GetAttrString(err, "text")))
947 goto finally;
948 if (v == Py_None)
949 *text = NULL;
950 else if (! (*text = PyString_AsString(v)))
951 goto finally;
952 Py_DECREF(v);
953 return 1;
954
955finally:
956 Py_XDECREF(v);
957 return 0;
958}
959
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000960void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000961PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000962{
Guido van Rossuma61691e1998-02-06 22:27:24 +0000963 PyErr_PrintEx(1);
964}
965
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000966static void
Martin v. Löwis95292d62002-12-11 14:04:59 +0000967print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000968{
969 char *nl;
970 if (offset >= 0) {
971 if (offset > 0 && offset == (int)strlen(text))
972 offset--;
973 for (;;) {
974 nl = strchr(text, '\n');
975 if (nl == NULL || nl-text >= offset)
976 break;
977 offset -= (nl+1-text);
978 text = nl+1;
979 }
980 while (*text == ' ' || *text == '\t') {
981 text++;
982 offset--;
983 }
984 }
985 PyFile_WriteString(" ", f);
986 PyFile_WriteString(text, f);
987 if (*text == '\0' || text[strlen(text)-1] != '\n')
988 PyFile_WriteString("\n", f);
989 if (offset == -1)
990 return;
991 PyFile_WriteString(" ", f);
992 offset--;
993 while (offset > 0) {
994 PyFile_WriteString(" ", f);
995 offset--;
996 }
997 PyFile_WriteString("^\n", f);
998}
999
Guido van Rossum66e8e862001-03-23 17:54:43 +00001000static void
1001handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001002{
Guido van Rossum66e8e862001-03-23 17:54:43 +00001003 PyObject *exception, *value, *tb;
Tim Peterscf615b52003-04-19 18:47:02 +00001004 int exitcode = 0;
1005
Guido van Rossum66e8e862001-03-23 17:54:43 +00001006 PyErr_Fetch(&exception, &value, &tb);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001007 if (Py_FlushLine())
1008 PyErr_Clear();
1009 fflush(stdout);
1010 if (value == NULL || value == Py_None)
Tim Peterscf615b52003-04-19 18:47:02 +00001011 goto done;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001012 if (PyInstance_Check(value)) {
1013 /* The error code should be in the `code' attribute. */
1014 PyObject *code = PyObject_GetAttrString(value, "code");
1015 if (code) {
1016 Py_DECREF(value);
1017 value = code;
1018 if (value == Py_None)
Tim Peterscf615b52003-04-19 18:47:02 +00001019 goto done;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001020 }
1021 /* If we failed to dig out the 'code' attribute,
1022 just let the else clause below print the error. */
1023 }
1024 if (PyInt_Check(value))
Tim Peterscf615b52003-04-19 18:47:02 +00001025 exitcode = (int)PyInt_AsLong(value);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001026 else {
1027 PyObject_Print(value, stderr, Py_PRINT_RAW);
1028 PySys_WriteStderr("\n");
Tim Peterscf615b52003-04-19 18:47:02 +00001029 exitcode = 1;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001030 }
Tim Peterscf615b52003-04-19 18:47:02 +00001031 done:
1032 /* Restore and clear the exception info, in order to properly decref
1033 * the exception, value, and traceback. If we just exit instead,
1034 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1035 * some finalizers from running.
1036 */
1037 PyErr_Restore(exception, value, tb);
1038 PyErr_Clear();
1039 Py_Exit(exitcode);
1040 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001041}
1042
1043void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001044PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001045{
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001046 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001047
1048 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1049 handle_system_exit();
1050 }
Guido van Rossum82598051997-03-05 00:20:32 +00001051 PyErr_Fetch(&exception, &v, &tb);
Barry Warsaw035574d1997-08-29 22:07:17 +00001052 PyErr_NormalizeException(&exception, &v, &tb);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001053 if (exception == NULL)
Guido van Rossum296b4751997-05-23 00:19:20 +00001054 return;
Guido van Rossuma61691e1998-02-06 22:27:24 +00001055 if (set_sys_last_vars) {
1056 PySys_SetObject("last_type", exception);
1057 PySys_SetObject("last_value", v);
1058 PySys_SetObject("last_traceback", tb);
1059 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001060 hook = PySys_GetObject("excepthook");
1061 if (hook) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001062 PyObject *args = PyTuple_Pack(3,
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001063 exception, v ? v : Py_None, tb ? tb : Py_None);
1064 PyObject *result = PyEval_CallObject(hook, args);
1065 if (result == NULL) {
1066 PyObject *exception2, *v2, *tb2;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001067 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1068 handle_system_exit();
1069 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001070 PyErr_Fetch(&exception2, &v2, &tb2);
1071 PyErr_NormalizeException(&exception2, &v2, &tb2);
1072 if (Py_FlushLine())
1073 PyErr_Clear();
1074 fflush(stdout);
1075 PySys_WriteStderr("Error in sys.excepthook:\n");
1076 PyErr_Display(exception2, v2, tb2);
1077 PySys_WriteStderr("\nOriginal exception was:\n");
1078 PyErr_Display(exception, v, tb);
Jeremy Hylton07028582001-12-07 15:35:35 +00001079 Py_XDECREF(exception2);
1080 Py_XDECREF(v2);
1081 Py_XDECREF(tb2);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001082 }
1083 Py_XDECREF(result);
1084 Py_XDECREF(args);
1085 } else {
1086 PySys_WriteStderr("sys.excepthook is missing\n");
1087 PyErr_Display(exception, v, tb);
1088 }
1089 Py_XDECREF(exception);
1090 Py_XDECREF(v);
1091 Py_XDECREF(tb);
1092}
1093
1094void PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
1095{
1096 int err = 0;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001097 PyObject *f = PySys_GetObject("stderr");
Armin Rigo5d2c6832004-03-22 20:16:58 +00001098 Py_INCREF(value);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001099 if (f == NULL)
1100 fprintf(stderr, "lost sys.stderr\n");
1101 else {
Guido van Rossum0829c751998-02-28 04:31:39 +00001102 if (Py_FlushLine())
1103 PyErr_Clear();
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001104 fflush(stdout);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001105 if (tb && tb != Py_None)
1106 err = PyTraceBack_Print(tb, f);
Barry Warsaw36b8f941997-08-26 18:09:48 +00001107 if (err == 0 &&
Armin Rigo5d2c6832004-03-22 20:16:58 +00001108 PyObject_HasAttrString(value, "print_file_and_line"))
Barry Warsaw36b8f941997-08-26 18:09:48 +00001109 {
Guido van Rossum82598051997-03-05 00:20:32 +00001110 PyObject *message;
Martin v. Löwis95292d62002-12-11 14:04:59 +00001111 const char *filename, *text;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001112 int lineno, offset;
Armin Rigo5d2c6832004-03-22 20:16:58 +00001113 if (!parse_syntax_error(value, &message, &filename,
Barry Warsaw035574d1997-08-29 22:07:17 +00001114 &lineno, &offset, &text))
Guido van Rossum82598051997-03-05 00:20:32 +00001115 PyErr_Clear();
Guido van Rossuma110aa61994-08-29 12:50:44 +00001116 else {
1117 char buf[10];
Guido van Rossum82598051997-03-05 00:20:32 +00001118 PyFile_WriteString(" File \"", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001119 if (filename == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +00001120 PyFile_WriteString("<string>", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001121 else
Guido van Rossum82598051997-03-05 00:20:32 +00001122 PyFile_WriteString(filename, f);
1123 PyFile_WriteString("\", line ", f);
Jeremy Hylton518ab1c2001-11-28 20:42:20 +00001124 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
Guido van Rossum82598051997-03-05 00:20:32 +00001125 PyFile_WriteString(buf, f);
1126 PyFile_WriteString("\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001127 if (text != NULL)
1128 print_error_text(f, offset, text);
Armin Rigo5d2c6832004-03-22 20:16:58 +00001129 Py_DECREF(value);
1130 value = message;
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001131 /* Can't be bothered to check all those
1132 PyFile_WriteString() calls */
1133 if (PyErr_Occurred())
1134 err = -1;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001135 }
1136 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001137 if (err) {
1138 /* Don't do anything else */
1139 }
1140 else if (PyClass_Check(exception)) {
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001141 PyClassObject* exc = (PyClassObject*)exception;
1142 PyObject* className = exc->cl_name;
1143 PyObject* moduleName =
1144 PyDict_GetItemString(exc->cl_dict, "__module__");
1145
1146 if (moduleName == NULL)
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001147 err = PyFile_WriteString("<unknown>", f);
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001148 else {
1149 char* modstr = PyString_AsString(moduleName);
Tim Petersd08e3822003-04-17 15:24:21 +00001150 if (modstr && strcmp(modstr, "exceptions"))
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001151 {
1152 err = PyFile_WriteString(modstr, f);
1153 err += PyFile_WriteString(".", f);
1154 }
1155 }
1156 if (err == 0) {
1157 if (className == NULL)
1158 err = PyFile_WriteString("<unknown>", f);
1159 else
1160 err = PyFile_WriteObject(className, f,
1161 Py_PRINT_RAW);
1162 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001163 }
1164 else
1165 err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
1166 if (err == 0) {
Armin Rigo5d2c6832004-03-22 20:16:58 +00001167 if (value != Py_None) {
1168 PyObject *s = PyObject_Str(value);
Barry Warsaw035574d1997-08-29 22:07:17 +00001169 /* only print colon if the str() of the
1170 object is not the empty string
1171 */
Guido van Rossumd6bf45b1997-09-05 19:11:53 +00001172 if (s == NULL)
1173 err = -1;
1174 else if (!PyString_Check(s) ||
1175 PyString_GET_SIZE(s) != 0)
Barry Warsaw035574d1997-08-29 22:07:17 +00001176 err = PyFile_WriteString(": ", f);
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001177 if (err == 0)
Guido van Rossumd6bf45b1997-09-05 19:11:53 +00001178 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1179 Py_XDECREF(s);
Guido van Rossum262e1241995-02-07 15:30:45 +00001180 }
Guido van Rossum262e1241995-02-07 15:30:45 +00001181 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001182 if (err == 0)
1183 err = PyFile_WriteString("\n", f);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001184 }
Armin Rigo5d2c6832004-03-22 20:16:58 +00001185 Py_DECREF(value);
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001186 /* If an error happened here, don't show it.
1187 XXX This is wrong, but too many callers rely on this behavior. */
1188 if (err != 0)
1189 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001190}
1191
Guido van Rossum82598051997-03-05 00:20:32 +00001192PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001193PyRun_String(const char *str, int start, PyObject *globals, PyObject *locals)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001194{
Guido van Rossum82598051997-03-05 00:20:32 +00001195 return run_err_node(PyParser_SimpleParseString(str, start),
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001196 "<string>", globals, locals, NULL);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001197}
1198
Guido van Rossum82598051997-03-05 00:20:32 +00001199PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001200PyRun_File(FILE *fp, const char *filename, int start, PyObject *globals,
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001201 PyObject *locals)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001202{
Tim Peterse8682112000-08-27 20:18:17 +00001203 return PyRun_FileEx(fp, filename, start, globals, locals, 0);
Guido van Rossum0df002c2000-08-27 19:21:52 +00001204}
1205
1206PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001207PyRun_FileEx(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001208 PyObject *locals, int closeit)
Guido van Rossum0df002c2000-08-27 19:21:52 +00001209{
1210 node *n = PyParser_SimpleParseFile(fp, filename, start);
1211 if (closeit)
1212 fclose(fp);
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001213 return run_err_node(n, filename, globals, locals, NULL);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001214}
1215
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001216PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001217PyRun_StringFlags(const char *str, int start, PyObject *globals, PyObject *locals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001218 PyCompilerFlags *flags)
1219{
Guido van Rossuma1b3a472001-07-16 16:51:33 +00001220 return run_err_node(PyParser_SimpleParseStringFlags(
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001221 str, start, PARSER_FLAGS(flags)),
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001222 "<string>", globals, locals, flags);
1223}
1224
1225PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001226PyRun_FileFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001227 PyObject *locals, PyCompilerFlags *flags)
1228{
1229 return PyRun_FileExFlags(fp, filename, start, globals, locals, 0,
Tim Petersd08e3822003-04-17 15:24:21 +00001230 flags);
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001231}
1232
1233PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001234PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001235 PyObject *locals, int closeit, PyCompilerFlags *flags)
1236{
Tim Petersfe2127d2001-07-16 05:37:24 +00001237 node *n = PyParser_SimpleParseFileFlags(fp, filename, start,
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001238 PARSER_FLAGS(flags));
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001239 if (closeit)
1240 fclose(fp);
1241 return run_err_node(n, filename, globals, locals, flags);
1242}
1243
Guido van Rossum82598051997-03-05 00:20:32 +00001244static PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001245run_err_node(node *n, const char *filename, PyObject *globals, PyObject *locals,
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001246 PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001247{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001248 if (n == NULL)
1249 return NULL;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001250 return run_node(n, filename, globals, locals, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001251}
1252
Guido van Rossum82598051997-03-05 00:20:32 +00001253static PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001254run_node(node *n, const char *filename, PyObject *globals, PyObject *locals,
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001255 PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001256{
Guido van Rossum82598051997-03-05 00:20:32 +00001257 PyCodeObject *co;
1258 PyObject *v;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001259 co = PyNode_CompileFlags(n, filename, flags);
Guido van Rossum82598051997-03-05 00:20:32 +00001260 PyNode_Free(n);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001261 if (co == NULL)
1262 return NULL;
Guido van Rossum82598051997-03-05 00:20:32 +00001263 v = PyEval_EvalCode(co, globals, locals);
1264 Py_DECREF(co);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001265 return v;
1266}
1267
Guido van Rossum82598051997-03-05 00:20:32 +00001268static PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001269run_pyc_file(FILE *fp, const char *filename, PyObject *globals, PyObject *locals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001270 PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001271{
Guido van Rossum82598051997-03-05 00:20:32 +00001272 PyCodeObject *co;
1273 PyObject *v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001274 long magic;
Fred Drakee8de31c2000-08-31 05:38:39 +00001275 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001276
Guido van Rossum82598051997-03-05 00:20:32 +00001277 magic = PyMarshal_ReadLongFromFile(fp);
1278 if (magic != PyImport_GetMagicNumber()) {
1279 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001280 "Bad magic number in .pyc file");
1281 return NULL;
1282 }
Guido van Rossum82598051997-03-05 00:20:32 +00001283 (void) PyMarshal_ReadLongFromFile(fp);
Tim Petersd9b9ac82001-01-28 00:27:39 +00001284 v = PyMarshal_ReadLastObjectFromFile(fp);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001285 fclose(fp);
Guido van Rossum82598051997-03-05 00:20:32 +00001286 if (v == NULL || !PyCode_Check(v)) {
1287 Py_XDECREF(v);
1288 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001289 "Bad code object in .pyc file");
1290 return NULL;
1291 }
Guido van Rossum82598051997-03-05 00:20:32 +00001292 co = (PyCodeObject *)v;
1293 v = PyEval_EvalCode(co, globals, locals);
Jeremy Hyltonb857ba22001-08-10 21:41:33 +00001294 if (v && flags)
1295 flags->cf_flags |= (co->co_flags & PyCF_MASK);
Guido van Rossum82598051997-03-05 00:20:32 +00001296 Py_DECREF(co);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001297 return v;
1298}
1299
Guido van Rossum82598051997-03-05 00:20:32 +00001300PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001301Py_CompileString(const char *str, const char *filename, int start)
Guido van Rossum5b722181993-03-30 17:46:03 +00001302{
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001303 return Py_CompileStringFlags(str, filename, start, NULL);
1304}
1305
1306PyObject *
Tim Petersd08e3822003-04-17 15:24:21 +00001307Py_CompileStringFlags(const char *str, const char *filename, int start,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001308 PyCompilerFlags *flags)
1309{
Guido van Rossum5b722181993-03-30 17:46:03 +00001310 node *n;
Guido van Rossum82598051997-03-05 00:20:32 +00001311 PyCodeObject *co;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001312
1313 n = PyParser_SimpleParseStringFlagsFilename(str, filename, start,
1314 PARSER_FLAGS(flags));
Guido van Rossuma110aa61994-08-29 12:50:44 +00001315 if (n == NULL)
Guido van Rossum5b722181993-03-30 17:46:03 +00001316 return NULL;
Jeremy Hylton673a4fd2001-03-26 19:53:38 +00001317 co = PyNode_CompileFlags(n, filename, flags);
Guido van Rossum82598051997-03-05 00:20:32 +00001318 PyNode_Free(n);
1319 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001320}
1321
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001322struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001323Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001324{
1325 node *n;
1326 struct symtable *st;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001327 n = PyParser_SimpleParseStringFlagsFilename(str, filename,
1328 start, 0);
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001329 if (n == NULL)
1330 return NULL;
1331 st = PyNode_CompileSymtable(n, filename);
1332 PyNode_Free(n);
1333 return st;
1334}
1335
Guido van Rossuma110aa61994-08-29 12:50:44 +00001336/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001337
Guido van Rossuma110aa61994-08-29 12:50:44 +00001338node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001339PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001340{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001341 node *n;
1342 perrdetail err;
Tim Petersfe2127d2001-07-16 05:37:24 +00001343 n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar, start,
1344 (char *)0, (char *)0, &err, flags);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001345 if (n == NULL)
1346 err_input(&err);
1347 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001348}
1349
Tim Petersfe2127d2001-07-16 05:37:24 +00001350node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001351PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
Tim Petersfe2127d2001-07-16 05:37:24 +00001352{
1353 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
1354}
1355
Guido van Rossuma110aa61994-08-29 12:50:44 +00001356/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001357
Guido van Rossuma110aa61994-08-29 12:50:44 +00001358node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001359PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001360{
1361 node *n;
1362 perrdetail err;
1363 n = PyParser_ParseStringFlags(str, &_PyParser_Grammar, start, &err,
1364 flags);
1365 if (n == NULL)
1366 err_input(&err);
1367 return n;
1368}
1369
1370node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001371PyParser_SimpleParseString(const char *str, int start)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001372{
Tim Petersfe2127d2001-07-16 05:37:24 +00001373 return PyParser_SimpleParseStringFlags(str, start, 0);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001374}
1375
Thomas Heller6b17abf2002-07-09 09:23:27 +00001376node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001377PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Thomas Heller6b17abf2002-07-09 09:23:27 +00001378 int start, int flags)
1379{
1380 node *n;
1381 perrdetail err;
1382
Tim Petersd08e3822003-04-17 15:24:21 +00001383 n = PyParser_ParseStringFlagsFilename(str, filename,
Thomas Heller6b17abf2002-07-09 09:23:27 +00001384 &_PyParser_Grammar,
1385 start, &err, flags);
1386 if (n == NULL)
1387 err_input(&err);
1388 return n;
1389}
1390
1391node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001392PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001393{
1394 return PyParser_SimpleParseStringFlagsFilename(str, filename,
1395 start, 0);
1396}
1397
Guido van Rossum66ebd912003-04-17 16:02:26 +00001398/* May want to move a more generalized form of this to parsetok.c or
1399 even parser modules. */
1400
1401void
1402PyParser_SetError(perrdetail *err)
1403{
1404 err_input(err);
1405}
1406
Guido van Rossuma110aa61994-08-29 12:50:44 +00001407/* Set the error appropriate to the given input error code (see errcode.h) */
1408
1409static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001410err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001411{
Fred Drake85f36392000-07-11 17:53:00 +00001412 PyObject *v, *w, *errtype;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001413 PyObject* u = NULL;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001414 char *msg = NULL;
Fred Drake85f36392000-07-11 17:53:00 +00001415 errtype = PyExc_SyntaxError;
Guido van Rossum82598051997-03-05 00:20:32 +00001416 v = Py_BuildValue("(ziiz)", err->filename,
Guido van Rossuma110aa61994-08-29 12:50:44 +00001417 err->lineno, err->offset, err->text);
1418 if (err->text != NULL) {
Guido van Rossumb18618d2000-05-03 23:44:39 +00001419 PyMem_DEL(err->text);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001420 err->text = NULL;
1421 }
1422 switch (err->error) {
1423 case E_SYNTAX:
Fred Drake85f36392000-07-11 17:53:00 +00001424 errtype = PyExc_IndentationError;
1425 if (err->expected == INDENT)
1426 msg = "expected an indented block";
1427 else if (err->token == INDENT)
1428 msg = "unexpected indent";
1429 else if (err->token == DEDENT)
1430 msg = "unexpected unindent";
1431 else {
1432 errtype = PyExc_SyntaxError;
1433 msg = "invalid syntax";
1434 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001435 break;
1436 case E_TOKEN:
1437 msg = "invalid token";
Guido van Rossuma110aa61994-08-29 12:50:44 +00001438 break;
Skip Montanaro118ec702002-08-15 01:20:16 +00001439 case E_EOFS:
1440 msg = "EOF while scanning triple-quoted string";
1441 break;
1442 case E_EOLS:
1443 msg = "EOL while scanning single-quoted string";
1444 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001445 case E_INTR:
Michael W. Hudson30ea2f22004-07-07 17:44:12 +00001446 if (!PyErr_Occurred())
1447 PyErr_SetNone(PyExc_KeyboardInterrupt);
Barry Warsawc80baa31999-01-27 16:39:40 +00001448 Py_XDECREF(v);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001449 return;
1450 case E_NOMEM:
Guido van Rossum82598051997-03-05 00:20:32 +00001451 PyErr_NoMemory();
Barry Warsawc80baa31999-01-27 16:39:40 +00001452 Py_XDECREF(v);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001453 return;
1454 case E_EOF:
1455 msg = "unexpected EOF while parsing";
1456 break;
Fred Drake85f36392000-07-11 17:53:00 +00001457 case E_TABSPACE:
1458 errtype = PyExc_TabError;
Guido van Rossum560e8ad1998-04-10 19:43:42 +00001459 msg = "inconsistent use of tabs and spaces in indentation";
1460 break;
Jeremy Hylton94988062000-06-20 19:10:44 +00001461 case E_OVERFLOW:
1462 msg = "expression too long";
1463 break;
Fred Drake85f36392000-07-11 17:53:00 +00001464 case E_DEDENT:
1465 errtype = PyExc_IndentationError;
1466 msg = "unindent does not match any outer indentation level";
1467 break;
1468 case E_TOODEEP:
1469 errtype = PyExc_IndentationError;
1470 msg = "too many levels of indentation";
1471 break;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001472 case E_DECODE: { /* XXX */
Nicholas Bastine5662ae2004-03-24 22:22:12 +00001473 PyThreadState* tstate = PyThreadState_GET();
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001474 PyObject* value = tstate->curexc_value;
1475 if (value != NULL) {
1476 u = PyObject_Repr(value);
1477 if (u != NULL) {
1478 msg = PyString_AsString(u);
1479 break;
1480 }
1481 }
Martin v. Löwisc2632a52004-07-21 05:35:02 +00001482 if (msg == NULL)
1483 msg = "unknown decode error";
1484 break;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001485 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001486 default:
1487 fprintf(stderr, "error=%d\n", err->error);
1488 msg = "unknown parsing error";
1489 break;
1490 }
Guido van Rossum82598051997-03-05 00:20:32 +00001491 w = Py_BuildValue("(sO)", msg, v);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001492 Py_XDECREF(u);
Guido van Rossum41318302001-03-23 04:01:07 +00001493 Py_XDECREF(v);
Fred Drake85f36392000-07-11 17:53:00 +00001494 PyErr_SetObject(errtype, w);
Guido van Rossum82598051997-03-05 00:20:32 +00001495 Py_XDECREF(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001496}
1497
1498/* Print fatal error message and abort */
1499
1500void
Tim Peters7c321a82002-07-09 02:57:01 +00001501Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001502{
Guido van Rossum83dd6c31994-09-29 09:38:33 +00001503 fprintf(stderr, "Fatal Python error: %s\n", msg);
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001504#ifdef MS_WINDOWS
Guido van Rossum23c94461997-05-22 20:21:30 +00001505 OutputDebugString("Fatal Python error: ");
Guido van Rossuma44823b1995-03-14 15:01:17 +00001506 OutputDebugString(msg);
1507 OutputDebugString("\n");
Guido van Rossum0ba35361998-08-13 13:33:16 +00001508#ifdef _DEBUG
1509 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00001510#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001511#endif /* MS_WINDOWS */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001512 abort();
1513}
1514
1515/* Clean up and exit */
1516
Guido van Rossuma110aa61994-08-29 12:50:44 +00001517#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00001518#include "pythread.h"
Guido van Rossum82598051997-03-05 00:20:32 +00001519int _PyThread_Started = 0; /* Set by threadmodule.c and maybe others */
Guido van Rossumf9f2e821992-08-17 08:59:08 +00001520#endif
1521
Guido van Rossum2dcfc961998-10-01 16:01:57 +00001522#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001523static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00001524static int nexitfuncs = 0;
1525
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001526int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00001527{
1528 if (nexitfuncs >= NEXITFUNCS)
1529 return -1;
1530 exitfuncs[nexitfuncs++] = func;
1531 return 0;
1532}
1533
Guido van Rossumcc283f51997-08-05 02:22:03 +00001534static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001535call_sys_exitfunc(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001536{
Guido van Rossum82598051997-03-05 00:20:32 +00001537 PyObject *exitfunc = PySys_GetObject("exitfunc");
Guido van Rossum59bff391992-09-03 20:28:00 +00001538
1539 if (exitfunc) {
Fred Drake6a12d8d2001-03-23 17:34:02 +00001540 PyObject *res;
Guido van Rossum82598051997-03-05 00:20:32 +00001541 Py_INCREF(exitfunc);
1542 PySys_SetObject("exitfunc", (PyObject *)NULL);
1543 res = PyEval_CallObject(exitfunc, (PyObject *)NULL);
Guido van Rossum59bff391992-09-03 20:28:00 +00001544 if (res == NULL) {
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001545 if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
1546 PySys_WriteStderr("Error in sys.exitfunc:\n");
1547 }
Guido van Rossum82598051997-03-05 00:20:32 +00001548 PyErr_Print();
Guido van Rossum59bff391992-09-03 20:28:00 +00001549 }
Guido van Rossum82598051997-03-05 00:20:32 +00001550 Py_DECREF(exitfunc);
Guido van Rossum59bff391992-09-03 20:28:00 +00001551 }
1552
Guido van Rossum0829c751998-02-28 04:31:39 +00001553 if (Py_FlushLine())
1554 PyErr_Clear();
Guido van Rossumcc283f51997-08-05 02:22:03 +00001555}
Guido van Rossum1662dd51994-09-07 14:38:28 +00001556
Guido van Rossumcc283f51997-08-05 02:22:03 +00001557static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001558call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00001559{
Guido van Rossum1662dd51994-09-07 14:38:28 +00001560 while (nexitfuncs > 0)
1561 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00001562
1563 fflush(stdout);
1564 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001565}
1566
1567void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001568Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001569{
Guido van Rossumcc283f51997-08-05 02:22:03 +00001570 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001571
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001572 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001573}
1574
Guido van Rossumf1dc5661993-07-05 10:31:29 +00001575static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001576initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001577{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001578#ifdef SIGPIPE
1579 signal(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001580#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00001581#ifdef SIGXFZ
1582 signal(SIGXFZ, SIG_IGN);
1583#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00001584#ifdef SIGXFSZ
1585 signal(SIGXFSZ, SIG_IGN);
1586#endif
Guido van Rossum82598051997-03-05 00:20:32 +00001587 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001588}
1589
Guido van Rossum7433b121997-02-14 19:45:36 +00001590
1591/*
1592 * The file descriptor fd is considered ``interactive'' if either
1593 * a) isatty(fd) is TRUE, or
1594 * b) the -i flag was given, and the filename associated with
1595 * the descriptor is NULL or "<stdin>" or "???".
1596 */
1597int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001598Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00001599{
1600 if (isatty((int)fileno(fp)))
1601 return 1;
1602 if (!Py_InteractiveFlag)
1603 return 0;
1604 return (filename == NULL) ||
1605 (strcmp(filename, "<stdin>") == 0) ||
1606 (strcmp(filename, "???") == 0);
1607}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001608
1609
Tim Petersd08e3822003-04-17 15:24:21 +00001610#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001611#if defined(WIN32) && defined(_MSC_VER)
1612
1613/* Stack checking for Microsoft C */
1614
1615#include <malloc.h>
1616#include <excpt.h>
1617
Fred Drakee8de31c2000-08-31 05:38:39 +00001618/*
1619 * Return non-zero when we run out of memory on the stack; zero otherwise.
1620 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001621int
Fred Drake399739f2000-08-31 05:52:44 +00001622PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001623{
1624 __try {
Tim Peters92e4dd82002-10-05 01:47:34 +00001625 /* alloca throws a stack overflow exception if there's
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001626 not enough space left on the stack */
Tim Peters92e4dd82002-10-05 01:47:34 +00001627 alloca(PYOS_STACK_MARGIN * sizeof(void*));
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001628 return 0;
1629 } __except (EXCEPTION_EXECUTE_HANDLER) {
1630 /* just ignore all errors */
1631 }
1632 return 1;
1633}
1634
1635#endif /* WIN32 && _MSC_VER */
1636
1637/* Alternate implementations can be added here... */
1638
1639#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00001640
1641
1642/* Wrappers around sigaction() or signal(). */
1643
1644PyOS_sighandler_t
1645PyOS_getsig(int sig)
1646{
1647#ifdef HAVE_SIGACTION
1648 struct sigaction context;
Barry Warsawafeb2a42001-11-13 23:08:26 +00001649 /* Initialize context.sa_handler to SIG_ERR which makes about as
1650 * much sense as anything else. It should get overwritten if
1651 * sigaction actually succeeds and otherwise we avoid an
1652 * uninitialized memory read.
1653 */
1654 context.sa_handler = SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00001655 sigaction(sig, NULL, &context);
1656 return context.sa_handler;
1657#else
1658 PyOS_sighandler_t handler;
1659 handler = signal(sig, SIG_IGN);
1660 signal(sig, handler);
1661 return handler;
1662#endif
1663}
1664
1665PyOS_sighandler_t
1666PyOS_setsig(int sig, PyOS_sighandler_t handler)
1667{
1668#ifdef HAVE_SIGACTION
1669 struct sigaction context;
1670 PyOS_sighandler_t oldhandler;
Barry Warsawafeb2a42001-11-13 23:08:26 +00001671 /* Initialize context.sa_handler to SIG_ERR which makes about as
1672 * much sense as anything else. It should get overwritten if
1673 * sigaction actually succeeds and otherwise we avoid an
1674 * uninitialized memory read.
1675 */
1676 context.sa_handler = SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00001677 sigaction(sig, NULL, &context);
1678 oldhandler = context.sa_handler;
1679 context.sa_handler = handler;
1680 sigaction(sig, &context, NULL);
1681 return oldhandler;
1682#else
1683 return signal(sig, handler);
1684#endif
1685}