blob: 614e65de12d91984d71d59d8fd29eec622303abd [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
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000134Py_Initialize(void)
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
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
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000230 initialized by other means. Also set the encoding of
231 stdin and stdout if these are terminals. */
232
Martin v. Löwisf56d0152003-11-13 07:43:21 +0000233 saved_locale = strdup(setlocale(LC_CTYPE, NULL));
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000234 setlocale(LC_CTYPE, "");
235 codeset = nl_langinfo(CODESET);
236 if (codeset && *codeset) {
237 PyObject *enc = PyCodec_Encoder(codeset);
238 if (enc) {
239 codeset = strdup(codeset);
240 Py_DECREF(enc);
241 } else {
242 codeset = NULL;
243 PyErr_Clear();
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000244 }
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000245 } else
246 codeset = NULL;
247 setlocale(LC_CTYPE, saved_locale);
Martin v. Löwisf56d0152003-11-13 07:43:21 +0000248 free(saved_locale);
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000249
250 if (codeset) {
Michael W. Hudson68debc92003-08-11 12:20:24 +0000251 sys_stream = PySys_GetObject("stdin");
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000252 sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
253 if (!sys_isatty)
254 PyErr_Clear();
255 if(sys_isatty && PyObject_IsTrue(sys_isatty)) {
256 if (!PyFile_SetEncoding(sys_stream, codeset))
257 Py_FatalError("Cannot set codeset of stdin");
258 }
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000259 Py_XDECREF(sys_isatty);
260
261 sys_stream = PySys_GetObject("stdout");
262 sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
263 if (!sys_isatty)
264 PyErr_Clear();
265 if(sys_isatty && PyObject_IsTrue(sys_isatty)) {
266 if (!PyFile_SetEncoding(sys_stream, codeset))
267 Py_FatalError("Cannot set codeset of stdout");
268 }
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000269 Py_XDECREF(sys_isatty);
270
271 if (!Py_FileSystemDefaultEncoding)
272 Py_FileSystemDefaultEncoding = codeset;
273 else
274 free(codeset);
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000275 }
276#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000277}
278
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000279#ifdef COUNT_ALLOCS
Tim Petersdbd9ba62000-07-09 03:09:57 +0000280extern void dump_counts(void);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000281#endif
282
Guido van Rossum25ce5661997-08-02 03:10:38 +0000283/* Undo the effect of Py_Initialize().
284
285 Beware: if multiple interpreter and/or thread states exist, these
286 are not wiped out; only the current thread and interpreter state
287 are deleted. But since everything else is deleted, those other
288 interpreter and thread states should no longer be used.
289
290 (XXX We should do better, e.g. wipe out all interpreters and
291 threads.)
292
293 Locking: as above.
294
295*/
296
297void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000298Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000299{
300 PyInterpreterState *interp;
301 PyThreadState *tstate;
302
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000303 if (!initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +0000304 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000305
Tim Peters384fd102001-01-21 03:40:37 +0000306 /* The interpreter is still entirely intact at this point, and the
307 * exit funcs may be relying on that. In particular, if some thread
308 * or exit func is still waiting to do an import, the import machinery
309 * expects Py_IsInitialized() to return true. So don't say the
310 * interpreter is uninitialized until after the exit funcs have run.
311 * Note that Threading.py uses an exit func to do a join on all the
312 * threads created thru it, so this also protects pending imports in
313 * the threads created via Threading.
314 */
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000315 call_sys_exitfunc();
Tim Peters384fd102001-01-21 03:40:37 +0000316 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000317
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000318 /* Get current thread state and interpreter pointer */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000319 tstate = PyThreadState_Get();
320 interp = tstate->interp;
321
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000322 /* Disable signal handling */
323 PyOS_FiniInterrupts();
324
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000325 /* drop module references we saved */
Mark Hammondedd07732003-07-15 23:03:55 +0000326 Py_XDECREF(warnings_module);
327 warnings_module = NULL;
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000328
Guido van Rossume13ddc92003-04-17 17:29:22 +0000329 /* Collect garbage. This may call finalizers; it's nice to call these
Tim Peters1d7323e2003-12-01 21:35:27 +0000330 * before all modules are destroyed.
331 * XXX If a __del__ or weakref callback is triggered here, and tries to
332 * XXX import a module, bad things can happen, because Python no
333 * XXX longer believes it's initialized.
334 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
335 * XXX is easy to provoke that way. I've also seen, e.g.,
336 * XXX Exception exceptions.ImportError: 'No module named sha'
337 * XXX in <function callback at 0x008F5718> ignored
338 * XXX but I'm unclear on exactly how that one happens. In any case,
339 * XXX I haven't seen a real-life report of either of these.
340 */
Guido van Rossume13ddc92003-04-17 17:29:22 +0000341 PyGC_Collect();
342
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000343 /* Destroy all modules */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000344 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000345
Guido van Rossume13ddc92003-04-17 17:29:22 +0000346 /* Collect final garbage. This disposes of cycles created by
Tim Peters1d7323e2003-12-01 21:35:27 +0000347 * new-style class definitions, for example.
348 * XXX This is disabled because it caused too many problems. If
349 * XXX a __del__ or weakref callback triggers here, Python code has
350 * XXX a hard time running, because even the sys module has been
351 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
352 * XXX One symptom is a sequence of information-free messages
353 * XXX coming from threads (if a __del__ or callback is invoked,
354 * XXX other threads can execute too, and any exception they encounter
355 * XXX triggers a comedy of errors as subsystem after subsystem
356 * XXX fails to find what it *expects* to find in sys to help report
357 * XXX the exception and consequent unexpected failures). I've also
358 * XXX seen segfaults then, after adding print statements to the
359 * XXX Python code getting called.
360 */
361#if 0
Guido van Rossume13ddc92003-04-17 17:29:22 +0000362 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000363#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000364
Guido van Rossum1707aad1997-12-08 23:43:45 +0000365 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
366 _PyImport_Fini();
367
368 /* Debugging stuff */
369#ifdef COUNT_ALLOCS
370 dump_counts();
371#endif
372
373#ifdef Py_REF_DEBUG
374 fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
375#endif
376
Tim Peters9cf25ce2003-04-17 15:21:01 +0000377#ifdef Py_TRACE_REFS
378 /* Display all objects still alive -- this can invoke arbitrary
379 * __repr__ overrides, so requires a mostly-intact interpreter.
380 * Alas, a lot of stuff may still be alive now that will be cleaned
381 * up later.
382 */
Tim Peters269b2a62003-04-17 19:52:29 +0000383 if (Py_GETENV("PYTHONDUMPREFS"))
Tim Peters9cf25ce2003-04-17 15:21:01 +0000384 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000385#endif /* Py_TRACE_REFS */
386
Barry Warsaw035574d1997-08-29 22:07:17 +0000387 /* Now we decref the exception classes. After this point nothing
388 can raise an exception. That's okay, because each Fini() method
389 below has been checked to make sure no exceptions are ever
390 raised.
391 */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000392 _PyExc_Fini();
Barry Warsawf242aa02000-05-25 23:09:49 +0000393
Mark Hammond6cb90292003-04-22 11:18:00 +0000394 /* Cleanup auto-thread-state */
395#ifdef WITH_THREAD
396 _PyGILState_Fini();
397#endif /* WITH_THREAD */
398
Guido van Rossumd922fa42003-04-15 14:10:09 +0000399 /* Clear interpreter state */
Barry Warsawf242aa02000-05-25 23:09:49 +0000400 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000401
Guido van Rossumd922fa42003-04-15 14:10:09 +0000402 /* Delete current thread */
Barry Warsawf242aa02000-05-25 23:09:49 +0000403 PyThreadState_Swap(NULL);
404 PyInterpreterState_Delete(interp);
405
Guido van Rossumd922fa42003-04-15 14:10:09 +0000406 /* Sundry finalizers */
Guido van Rossumcc283f51997-08-05 02:22:03 +0000407 PyMethod_Fini();
408 PyFrame_Fini();
409 PyCFunction_Fini();
410 PyTuple_Fini();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000411 PyString_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000412 PyInt_Fini();
413 PyFloat_Fini();
414
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000415#ifdef Py_USING_UNICODE
416 /* Cleanup Unicode implementation */
417 _PyUnicode_Fini();
418#endif
419
Guido van Rossumcc283f51997-08-05 02:22:03 +0000420 /* XXX Still allocated:
421 - various static ad-hoc pointers to interned strings
422 - int and float free list blocks
423 - whatever various modules and libraries allocate
424 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000425
426 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000427
Tim Peters269b2a62003-04-17 19:52:29 +0000428#ifdef Py_TRACE_REFS
429 /* Display addresses (& refcnts) of all objects still alive.
430 * An address can be used to find the repr of the object, printed
431 * above by _Py_PrintReferences.
432 */
433 if (Py_GETENV("PYTHONDUMPREFS"))
434 _Py_PrintReferenceAddresses(stderr);
435#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000436#ifdef PYMALLOC_DEBUG
437 if (Py_GETENV("PYTHONMALLOCSTATS"))
438 _PyObject_DebugMallocStats();
439#endif
440
Guido van Rossumcc283f51997-08-05 02:22:03 +0000441 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000442}
443
444/* Create and initialize a new interpreter and thread, and return the
445 new thread. This requires that Py_Initialize() has been called
446 first.
447
448 Unsuccessful initialization yields a NULL pointer. Note that *no*
449 exception information is available even in this case -- the
450 exception information is held in the thread, and there is no
451 thread.
452
453 Locking: as above.
454
455*/
456
457PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000458Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000459{
460 PyInterpreterState *interp;
461 PyThreadState *tstate, *save_tstate;
462 PyObject *bimod, *sysmod;
463
464 if (!initialized)
465 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
466
467 interp = PyInterpreterState_New();
468 if (interp == NULL)
469 return NULL;
470
471 tstate = PyThreadState_New(interp);
472 if (tstate == NULL) {
473 PyInterpreterState_Delete(interp);
474 return NULL;
475 }
476
477 save_tstate = PyThreadState_Swap(tstate);
478
479 /* XXX The following is lax in error checking */
480
481 interp->modules = PyDict_New();
482
483 bimod = _PyImport_FindExtension("__builtin__", "__builtin__");
484 if (bimod != NULL) {
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000485 interp->builtins = PyModule_GetDict(bimod);
486 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000487 }
488 sysmod = _PyImport_FindExtension("sys", "sys");
489 if (bimod != NULL && sysmod != NULL) {
490 interp->sysdict = PyModule_GetDict(sysmod);
491 Py_INCREF(interp->sysdict);
492 PySys_SetPath(Py_GetPath());
493 PyDict_SetItemString(interp->sysdict, "modules",
494 interp->modules);
Martin v. Löwisd7ceb222003-01-22 09:00:38 +0000495 _PyImportHooks_Init();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000496 initmain();
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000497 if (!Py_NoSiteFlag)
498 initsite();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000499 }
500
501 if (!PyErr_Occurred())
502 return tstate;
503
504 /* Oops, it didn't work. Undo it all. */
505
506 PyErr_Print();
507 PyThreadState_Clear(tstate);
508 PyThreadState_Swap(save_tstate);
509 PyThreadState_Delete(tstate);
510 PyInterpreterState_Delete(interp);
511
512 return NULL;
513}
514
515/* Delete an interpreter and its last thread. This requires that the
516 given thread state is current, that the thread has no remaining
517 frames, and that it is its interpreter's only remaining thread.
518 It is a fatal error to violate these constraints.
519
520 (Py_Finalize() doesn't have these constraints -- it zaps
521 everything, regardless.)
522
523 Locking: as above.
524
525*/
526
527void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000528Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000529{
530 PyInterpreterState *interp = tstate->interp;
531
532 if (tstate != PyThreadState_Get())
533 Py_FatalError("Py_EndInterpreter: thread is not current");
534 if (tstate->frame != NULL)
535 Py_FatalError("Py_EndInterpreter: thread still has a frame");
536 if (tstate != interp->tstate_head || tstate->next != NULL)
537 Py_FatalError("Py_EndInterpreter: not the last thread");
538
539 PyImport_Cleanup();
540 PyInterpreterState_Clear(interp);
541 PyThreadState_Swap(NULL);
542 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000543}
544
545static char *progname = "python";
546
547void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000548Py_SetProgramName(char *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000549{
550 if (pn && *pn)
551 progname = pn;
552}
553
554char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000555Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000556{
557 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000558}
559
Guido van Rossuma61691e1998-02-06 22:27:24 +0000560static char *default_home = NULL;
561
562void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000563Py_SetPythonHome(char *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000564{
565 default_home = home;
566}
567
568char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000569Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000570{
571 char *home = default_home;
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000572 if (home == NULL && !Py_IgnoreEnvironmentFlag)
573 home = Py_GETENV("PYTHONHOME");
Guido van Rossuma61691e1998-02-06 22:27:24 +0000574 return home;
575}
576
Guido van Rossum6135a871995-01-09 17:53:26 +0000577/* Create __main__ module */
578
579static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000580initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000581{
Guido van Rossum82598051997-03-05 00:20:32 +0000582 PyObject *m, *d;
583 m = PyImport_AddModule("__main__");
Guido van Rossum6135a871995-01-09 17:53:26 +0000584 if (m == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +0000585 Py_FatalError("can't create __main__ module");
586 d = PyModule_GetDict(m);
587 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
Guido van Rossum858cb731997-11-19 16:15:37 +0000588 PyObject *bimod = PyImport_ImportModule("__builtin__");
589 if (bimod == NULL ||
590 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
Guido van Rossum82598051997-03-05 00:20:32 +0000591 Py_FatalError("can't add __builtins__ to __main__");
Barry Warsaw3d05b1a1999-01-29 21:30:22 +0000592 Py_DECREF(bimod);
Guido van Rossum6135a871995-01-09 17:53:26 +0000593 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000594}
595
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000596/* Import the site module (not into __main__ though) */
597
598static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000599initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000600{
601 PyObject *m, *f;
602 m = PyImport_ImportModule("site");
603 if (m == NULL) {
604 f = PySys_GetObject("stderr");
605 if (Py_VerboseFlag) {
606 PyFile_WriteString(
607 "'import site' failed; traceback:\n", f);
608 PyErr_Print();
609 }
610 else {
611 PyFile_WriteString(
612 "'import site' failed; use -v for traceback\n", f);
613 PyErr_Clear();
614 }
615 }
616 else {
617 Py_DECREF(m);
618 }
619}
620
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000621/* Parse input from a file and execute it */
622
623int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000624PyRun_AnyFile(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000625{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000626 return PyRun_AnyFileExFlags(fp, filename, 0, NULL);
627}
628
629int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000630PyRun_AnyFileFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000631{
632 return PyRun_AnyFileExFlags(fp, filename, 0, flags);
Guido van Rossum0df002c2000-08-27 19:21:52 +0000633}
634
635int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000636PyRun_AnyFileEx(FILE *fp, const char *filename, int closeit)
Guido van Rossum0df002c2000-08-27 19:21:52 +0000637{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000638 return PyRun_AnyFileExFlags(fp, filename, closeit, NULL);
639}
640
641int
Tim Petersd08e3822003-04-17 15:24:21 +0000642PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000643 PyCompilerFlags *flags)
644{
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000645 if (filename == NULL)
646 filename = "???";
Guido van Rossum0df002c2000-08-27 19:21:52 +0000647 if (Py_FdIsInteractive(fp, filename)) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000648 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
Guido van Rossum0df002c2000-08-27 19:21:52 +0000649 if (closeit)
650 fclose(fp);
651 return err;
652 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000653 else
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000654 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000655}
656
657int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000658PyRun_InteractiveLoop(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000659{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000660 return PyRun_InteractiveLoopFlags(fp, filename, NULL);
661}
662
663int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000664PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000665{
Guido van Rossum82598051997-03-05 00:20:32 +0000666 PyObject *v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000667 int ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000668 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000669
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000670 if (flags == NULL) {
671 flags = &local_flags;
Tim Peters5ba58662001-07-16 02:29:45 +0000672 local_flags.cf_flags = 0;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000673 }
Guido van Rossum82598051997-03-05 00:20:32 +0000674 v = PySys_GetObject("ps1");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000675 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000676 PySys_SetObject("ps1", v = PyString_FromString(">>> "));
677 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000678 }
Guido van Rossum82598051997-03-05 00:20:32 +0000679 v = PySys_GetObject("ps2");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000680 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000681 PySys_SetObject("ps2", v = PyString_FromString("... "));
682 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000683 }
684 for (;;) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000685 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
Guido van Rossumaae0d321996-05-22 16:35:33 +0000686#ifdef Py_REF_DEBUG
Guido van Rossum6f9e4331995-03-29 16:57:48 +0000687 fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000688#endif
689 if (ret == E_EOF)
690 return 0;
691 /*
692 if (ret == E_NOMEM)
693 return -1;
694 */
695 }
696}
697
698int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000699PyRun_InteractiveOne(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000700{
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000701 return PyRun_InteractiveOneFlags(fp, filename, NULL);
702}
703
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000704/* compute parser flags based on compiler flags */
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000705#define PARSER_FLAGS(flags) \
Guido van Rossum4b499dd32003-02-13 22:07:59 +0000706 (((flags) && (flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
707 PyPARSE_DONT_IMPLY_DEDENT : 0)
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000708
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000709int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000710PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000711{
Guido van Rossum82598051997-03-05 00:20:32 +0000712 PyObject *m, *d, *v, *w;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000713 node *n;
Guido van Rossuma110aa61994-08-29 12:50:44 +0000714 perrdetail err;
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000715 char *ps1 = "", *ps2 = "";
Tim Petersfe2127d2001-07-16 05:37:24 +0000716
Guido van Rossum82598051997-03-05 00:20:32 +0000717 v = PySys_GetObject("ps1");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000718 if (v != NULL) {
719 v = PyObject_Str(v);
720 if (v == NULL)
721 PyErr_Clear();
722 else if (PyString_Check(v))
723 ps1 = PyString_AsString(v);
724 }
Guido van Rossum82598051997-03-05 00:20:32 +0000725 w = PySys_GetObject("ps2");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000726 if (w != NULL) {
727 w = PyObject_Str(w);
728 if (w == NULL)
729 PyErr_Clear();
730 else if (PyString_Check(w))
731 ps2 = PyString_AsString(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000732 }
Tim Petersfe2127d2001-07-16 05:37:24 +0000733 n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar,
734 Py_single_input, ps1, ps2, &err,
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000735 PARSER_FLAGS(flags));
Guido van Rossum82598051997-03-05 00:20:32 +0000736 Py_XDECREF(v);
737 Py_XDECREF(w);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000738 if (n == NULL) {
739 if (err.error == E_EOF) {
740 if (err.text)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000741 PyMem_DEL(err.text);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000742 return E_EOF;
743 }
744 err_input(&err);
Guido van Rossum82598051997-03-05 00:20:32 +0000745 PyErr_Print();
Guido van Rossuma110aa61994-08-29 12:50:44 +0000746 return err.error;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000747 }
Guido van Rossum82598051997-03-05 00:20:32 +0000748 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000749 if (m == NULL)
750 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000751 d = PyModule_GetDict(m);
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000752 v = run_node(n, filename, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000753 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000754 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000755 return -1;
756 }
Guido van Rossum82598051997-03-05 00:20:32 +0000757 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000758 if (Py_FlushLine())
759 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000760 return 0;
761}
762
763int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000764PyRun_SimpleFile(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000765{
Guido van Rossum0df002c2000-08-27 19:21:52 +0000766 return PyRun_SimpleFileEx(fp, filename, 0);
767}
768
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000769/* Check whether a file maybe a pyc file: Look at the extension,
770 the file type, and, if we may close it, at the first few bytes. */
771
772static int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000773maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000774{
775 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
776 return 1;
777
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000778 /* Only look into the file if we are allowed to close it, since
779 it then should also be seekable. */
780 if (closeit) {
781 /* Read only two bytes of the magic. If the file was opened in
782 text mode, the bytes 3 and 4 of the magic (\r\n) might not
783 be read as they are on disk. */
784 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
785 unsigned char buf[2];
Tim Peters3e876562001-02-11 04:35:39 +0000786 /* Mess: In case of -x, the stream is NOT at its start now,
787 and ungetc() was used to push back the first newline,
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000788 which makes the current stream position formally undefined,
789 and a x-platform nightmare.
790 Unfortunately, we have no direct way to know whether -x
791 was specified. So we use a terrible hack: if the current
792 stream position is not 0, we assume -x was specified, and
793 give up. Bug 132850 on SourceForge spells out the
794 hopelessness of trying anything else (fseek and ftell
795 don't work predictably x-platform for text-mode files).
Tim Peters3e876562001-02-11 04:35:39 +0000796 */
Tim Peters3e876562001-02-11 04:35:39 +0000797 int ispyc = 0;
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000798 if (ftell(fp) == 0) {
799 if (fread(buf, 1, 2, fp) == 2 &&
Tim Petersd08e3822003-04-17 15:24:21 +0000800 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000801 ispyc = 1;
802 rewind(fp);
803 }
Tim Peters3e876562001-02-11 04:35:39 +0000804 return ispyc;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000805 }
806 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +0000807}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000808
Guido van Rossum0df002c2000-08-27 19:21:52 +0000809int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000810PyRun_SimpleFileEx(FILE *fp, const char *filename, int closeit)
Guido van Rossum0df002c2000-08-27 19:21:52 +0000811{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000812 return PyRun_SimpleFileExFlags(fp, filename, closeit, NULL);
813}
814
815int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000816PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000817 PyCompilerFlags *flags)
818{
Guido van Rossum82598051997-03-05 00:20:32 +0000819 PyObject *m, *d, *v;
Martin v. Löwis95292d62002-12-11 14:04:59 +0000820 const char *ext;
Guido van Rossumfdef2711994-09-14 13:31:04 +0000821
Guido van Rossum82598051997-03-05 00:20:32 +0000822 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000823 if (m == NULL)
824 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000825 d = PyModule_GetDict(m);
Fred Drake8ed02042002-10-17 21:24:58 +0000826 if (PyDict_GetItemString(d, "__file__") == NULL) {
827 PyObject *f = PyString_FromString(filename);
828 if (f == NULL)
829 return -1;
830 if (PyDict_SetItemString(d, "__file__", f) < 0) {
831 Py_DECREF(f);
832 return -1;
833 }
834 Py_DECREF(f);
835 }
Guido van Rossumfdef2711994-09-14 13:31:04 +0000836 ext = filename + strlen(filename) - 4;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000837 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Guido van Rossumfdef2711994-09-14 13:31:04 +0000838 /* Try to run a pyc file. First, re-open in binary */
Guido van Rossum0df002c2000-08-27 19:21:52 +0000839 if (closeit)
840 fclose(fp);
Fred Drake8ed02042002-10-17 21:24:58 +0000841 if ((fp = fopen(filename, "rb")) == NULL) {
Guido van Rossumfdef2711994-09-14 13:31:04 +0000842 fprintf(stderr, "python: Can't reopen .pyc file\n");
843 return -1;
844 }
Guido van Rossum2a7f58d1997-04-02 05:28:38 +0000845 /* Turn on optimization if a .pyo file is given */
846 if (strcmp(ext, ".pyo") == 0)
847 Py_OptimizeFlag = 1;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000848 v = run_pyc_file(fp, filename, d, d, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000849 } else {
Tim Petersd08e3822003-04-17 15:24:21 +0000850 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000851 closeit, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000852 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000853 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000854 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000855 return -1;
856 }
Guido van Rossum82598051997-03-05 00:20:32 +0000857 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000858 if (Py_FlushLine())
859 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000860 return 0;
861}
862
863int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000864PyRun_SimpleString(const char *command)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000865{
Guido van Rossum393661d2001-08-31 17:40:15 +0000866 return PyRun_SimpleStringFlags(command, NULL);
867}
868
869int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000870PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +0000871{
Guido van Rossum82598051997-03-05 00:20:32 +0000872 PyObject *m, *d, *v;
873 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000874 if (m == NULL)
875 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000876 d = PyModule_GetDict(m);
Guido van Rossum393661d2001-08-31 17:40:15 +0000877 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000878 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000879 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000880 return -1;
881 }
Guido van Rossum82598051997-03-05 00:20:32 +0000882 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000883 if (Py_FlushLine())
884 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000885 return 0;
886}
887
Barry Warsaw035574d1997-08-29 22:07:17 +0000888static int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000889parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
890 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +0000891{
892 long hold;
893 PyObject *v;
894
895 /* old style errors */
896 if (PyTuple_Check(err))
Neal Norwitz78293352002-04-01 01:41:20 +0000897 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
898 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +0000899
900 /* new style errors. `err' is an instance */
901
902 if (! (v = PyObject_GetAttrString(err, "msg")))
903 goto finally;
904 *message = v;
905
906 if (!(v = PyObject_GetAttrString(err, "filename")))
907 goto finally;
908 if (v == Py_None)
909 *filename = NULL;
910 else if (! (*filename = PyString_AsString(v)))
911 goto finally;
912
913 Py_DECREF(v);
914 if (!(v = PyObject_GetAttrString(err, "lineno")))
915 goto finally;
916 hold = PyInt_AsLong(v);
917 Py_DECREF(v);
918 v = NULL;
919 if (hold < 0 && PyErr_Occurred())
920 goto finally;
921 *lineno = (int)hold;
922
923 if (!(v = PyObject_GetAttrString(err, "offset")))
924 goto finally;
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000925 if (v == Py_None) {
926 *offset = -1;
927 Py_DECREF(v);
928 v = NULL;
929 } else {
930 hold = PyInt_AsLong(v);
931 Py_DECREF(v);
932 v = NULL;
933 if (hold < 0 && PyErr_Occurred())
934 goto finally;
935 *offset = (int)hold;
936 }
Barry Warsaw035574d1997-08-29 22:07:17 +0000937
938 if (!(v = PyObject_GetAttrString(err, "text")))
939 goto finally;
940 if (v == Py_None)
941 *text = NULL;
942 else if (! (*text = PyString_AsString(v)))
943 goto finally;
944 Py_DECREF(v);
945 return 1;
946
947finally:
948 Py_XDECREF(v);
949 return 0;
950}
951
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000952void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000953PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000954{
Guido van Rossuma61691e1998-02-06 22:27:24 +0000955 PyErr_PrintEx(1);
956}
957
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000958static void
Martin v. Löwis95292d62002-12-11 14:04:59 +0000959print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000960{
961 char *nl;
962 if (offset >= 0) {
963 if (offset > 0 && offset == (int)strlen(text))
964 offset--;
965 for (;;) {
966 nl = strchr(text, '\n');
967 if (nl == NULL || nl-text >= offset)
968 break;
969 offset -= (nl+1-text);
970 text = nl+1;
971 }
972 while (*text == ' ' || *text == '\t') {
973 text++;
974 offset--;
975 }
976 }
977 PyFile_WriteString(" ", f);
978 PyFile_WriteString(text, f);
979 if (*text == '\0' || text[strlen(text)-1] != '\n')
980 PyFile_WriteString("\n", f);
981 if (offset == -1)
982 return;
983 PyFile_WriteString(" ", f);
984 offset--;
985 while (offset > 0) {
986 PyFile_WriteString(" ", f);
987 offset--;
988 }
989 PyFile_WriteString("^\n", f);
990}
991
Guido van Rossum66e8e862001-03-23 17:54:43 +0000992static void
993handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000994{
Guido van Rossum66e8e862001-03-23 17:54:43 +0000995 PyObject *exception, *value, *tb;
Tim Peterscf615b52003-04-19 18:47:02 +0000996 int exitcode = 0;
997
Guido van Rossum66e8e862001-03-23 17:54:43 +0000998 PyErr_Fetch(&exception, &value, &tb);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000999 if (Py_FlushLine())
1000 PyErr_Clear();
1001 fflush(stdout);
1002 if (value == NULL || value == Py_None)
Tim Peterscf615b52003-04-19 18:47:02 +00001003 goto done;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001004 if (PyInstance_Check(value)) {
1005 /* The error code should be in the `code' attribute. */
1006 PyObject *code = PyObject_GetAttrString(value, "code");
1007 if (code) {
1008 Py_DECREF(value);
1009 value = code;
1010 if (value == Py_None)
Tim Peterscf615b52003-04-19 18:47:02 +00001011 goto done;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001012 }
1013 /* If we failed to dig out the 'code' attribute,
1014 just let the else clause below print the error. */
1015 }
1016 if (PyInt_Check(value))
Tim Peterscf615b52003-04-19 18:47:02 +00001017 exitcode = (int)PyInt_AsLong(value);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001018 else {
1019 PyObject_Print(value, stderr, Py_PRINT_RAW);
1020 PySys_WriteStderr("\n");
Tim Peterscf615b52003-04-19 18:47:02 +00001021 exitcode = 1;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001022 }
Tim Peterscf615b52003-04-19 18:47:02 +00001023 done:
1024 /* Restore and clear the exception info, in order to properly decref
1025 * the exception, value, and traceback. If we just exit instead,
1026 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1027 * some finalizers from running.
1028 */
1029 PyErr_Restore(exception, value, tb);
1030 PyErr_Clear();
1031 Py_Exit(exitcode);
1032 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001033}
1034
1035void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001036PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001037{
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001038 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001039
1040 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1041 handle_system_exit();
1042 }
Guido van Rossum82598051997-03-05 00:20:32 +00001043 PyErr_Fetch(&exception, &v, &tb);
Barry Warsaw035574d1997-08-29 22:07:17 +00001044 PyErr_NormalizeException(&exception, &v, &tb);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001045 if (exception == NULL)
Guido van Rossum296b4751997-05-23 00:19:20 +00001046 return;
Guido van Rossuma61691e1998-02-06 22:27:24 +00001047 if (set_sys_last_vars) {
1048 PySys_SetObject("last_type", exception);
1049 PySys_SetObject("last_value", v);
1050 PySys_SetObject("last_traceback", tb);
1051 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001052 hook = PySys_GetObject("excepthook");
1053 if (hook) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001054 PyObject *args = PyTuple_Pack(3,
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001055 exception, v ? v : Py_None, tb ? tb : Py_None);
1056 PyObject *result = PyEval_CallObject(hook, args);
1057 if (result == NULL) {
1058 PyObject *exception2, *v2, *tb2;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001059 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1060 handle_system_exit();
1061 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001062 PyErr_Fetch(&exception2, &v2, &tb2);
1063 PyErr_NormalizeException(&exception2, &v2, &tb2);
1064 if (Py_FlushLine())
1065 PyErr_Clear();
1066 fflush(stdout);
1067 PySys_WriteStderr("Error in sys.excepthook:\n");
1068 PyErr_Display(exception2, v2, tb2);
1069 PySys_WriteStderr("\nOriginal exception was:\n");
1070 PyErr_Display(exception, v, tb);
Jeremy Hylton07028582001-12-07 15:35:35 +00001071 Py_XDECREF(exception2);
1072 Py_XDECREF(v2);
1073 Py_XDECREF(tb2);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001074 }
1075 Py_XDECREF(result);
1076 Py_XDECREF(args);
1077 } else {
1078 PySys_WriteStderr("sys.excepthook is missing\n");
1079 PyErr_Display(exception, v, tb);
1080 }
1081 Py_XDECREF(exception);
1082 Py_XDECREF(v);
1083 Py_XDECREF(tb);
1084}
1085
1086void PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
1087{
1088 int err = 0;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001089 PyObject *f = PySys_GetObject("stderr");
Armin Rigo5d2c6832004-03-22 20:16:58 +00001090 Py_INCREF(value);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001091 if (f == NULL)
1092 fprintf(stderr, "lost sys.stderr\n");
1093 else {
Guido van Rossum0829c751998-02-28 04:31:39 +00001094 if (Py_FlushLine())
1095 PyErr_Clear();
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001096 fflush(stdout);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001097 if (tb && tb != Py_None)
1098 err = PyTraceBack_Print(tb, f);
Barry Warsaw36b8f941997-08-26 18:09:48 +00001099 if (err == 0 &&
Armin Rigo5d2c6832004-03-22 20:16:58 +00001100 PyObject_HasAttrString(value, "print_file_and_line"))
Barry Warsaw36b8f941997-08-26 18:09:48 +00001101 {
Guido van Rossum82598051997-03-05 00:20:32 +00001102 PyObject *message;
Martin v. Löwis95292d62002-12-11 14:04:59 +00001103 const char *filename, *text;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001104 int lineno, offset;
Armin Rigo5d2c6832004-03-22 20:16:58 +00001105 if (!parse_syntax_error(value, &message, &filename,
Barry Warsaw035574d1997-08-29 22:07:17 +00001106 &lineno, &offset, &text))
Guido van Rossum82598051997-03-05 00:20:32 +00001107 PyErr_Clear();
Guido van Rossuma110aa61994-08-29 12:50:44 +00001108 else {
1109 char buf[10];
Guido van Rossum82598051997-03-05 00:20:32 +00001110 PyFile_WriteString(" File \"", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001111 if (filename == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +00001112 PyFile_WriteString("<string>", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001113 else
Guido van Rossum82598051997-03-05 00:20:32 +00001114 PyFile_WriteString(filename, f);
1115 PyFile_WriteString("\", line ", f);
Jeremy Hylton518ab1c2001-11-28 20:42:20 +00001116 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
Guido van Rossum82598051997-03-05 00:20:32 +00001117 PyFile_WriteString(buf, f);
1118 PyFile_WriteString("\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001119 if (text != NULL)
1120 print_error_text(f, offset, text);
Armin Rigo5d2c6832004-03-22 20:16:58 +00001121 Py_DECREF(value);
1122 value = message;
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001123 /* Can't be bothered to check all those
1124 PyFile_WriteString() calls */
1125 if (PyErr_Occurred())
1126 err = -1;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001127 }
1128 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001129 if (err) {
1130 /* Don't do anything else */
1131 }
1132 else if (PyClass_Check(exception)) {
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001133 PyClassObject* exc = (PyClassObject*)exception;
1134 PyObject* className = exc->cl_name;
1135 PyObject* moduleName =
1136 PyDict_GetItemString(exc->cl_dict, "__module__");
1137
1138 if (moduleName == NULL)
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001139 err = PyFile_WriteString("<unknown>", f);
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001140 else {
1141 char* modstr = PyString_AsString(moduleName);
Tim Petersd08e3822003-04-17 15:24:21 +00001142 if (modstr && strcmp(modstr, "exceptions"))
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001143 {
1144 err = PyFile_WriteString(modstr, f);
1145 err += PyFile_WriteString(".", f);
1146 }
1147 }
1148 if (err == 0) {
1149 if (className == NULL)
1150 err = PyFile_WriteString("<unknown>", f);
1151 else
1152 err = PyFile_WriteObject(className, f,
1153 Py_PRINT_RAW);
1154 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001155 }
1156 else
1157 err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
1158 if (err == 0) {
Armin Rigo5d2c6832004-03-22 20:16:58 +00001159 if (value != Py_None) {
1160 PyObject *s = PyObject_Str(value);
Barry Warsaw035574d1997-08-29 22:07:17 +00001161 /* only print colon if the str() of the
1162 object is not the empty string
1163 */
Guido van Rossumd6bf45b1997-09-05 19:11:53 +00001164 if (s == NULL)
1165 err = -1;
1166 else if (!PyString_Check(s) ||
1167 PyString_GET_SIZE(s) != 0)
Barry Warsaw035574d1997-08-29 22:07:17 +00001168 err = PyFile_WriteString(": ", f);
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001169 if (err == 0)
Guido van Rossumd6bf45b1997-09-05 19:11:53 +00001170 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1171 Py_XDECREF(s);
Guido van Rossum262e1241995-02-07 15:30:45 +00001172 }
Guido van Rossum262e1241995-02-07 15:30:45 +00001173 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001174 if (err == 0)
1175 err = PyFile_WriteString("\n", f);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001176 }
Armin Rigo5d2c6832004-03-22 20:16:58 +00001177 Py_DECREF(value);
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001178 /* If an error happened here, don't show it.
1179 XXX This is wrong, but too many callers rely on this behavior. */
1180 if (err != 0)
1181 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001182}
1183
Guido van Rossum82598051997-03-05 00:20:32 +00001184PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001185PyRun_String(const char *str, int start, PyObject *globals, PyObject *locals)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001186{
Guido van Rossum82598051997-03-05 00:20:32 +00001187 return run_err_node(PyParser_SimpleParseString(str, start),
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001188 "<string>", globals, locals, NULL);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001189}
1190
Guido van Rossum82598051997-03-05 00:20:32 +00001191PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001192PyRun_File(FILE *fp, const char *filename, int start, PyObject *globals,
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001193 PyObject *locals)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001194{
Tim Peterse8682112000-08-27 20:18:17 +00001195 return PyRun_FileEx(fp, filename, start, globals, locals, 0);
Guido van Rossum0df002c2000-08-27 19:21:52 +00001196}
1197
1198PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001199PyRun_FileEx(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001200 PyObject *locals, int closeit)
Guido van Rossum0df002c2000-08-27 19:21:52 +00001201{
1202 node *n = PyParser_SimpleParseFile(fp, filename, start);
1203 if (closeit)
1204 fclose(fp);
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001205 return run_err_node(n, filename, globals, locals, NULL);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001206}
1207
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001208PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001209PyRun_StringFlags(const char *str, int start, PyObject *globals, PyObject *locals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001210 PyCompilerFlags *flags)
1211{
Guido van Rossuma1b3a472001-07-16 16:51:33 +00001212 return run_err_node(PyParser_SimpleParseStringFlags(
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001213 str, start, PARSER_FLAGS(flags)),
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001214 "<string>", globals, locals, flags);
1215}
1216
1217PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001218PyRun_FileFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001219 PyObject *locals, PyCompilerFlags *flags)
1220{
1221 return PyRun_FileExFlags(fp, filename, start, globals, locals, 0,
Tim Petersd08e3822003-04-17 15:24:21 +00001222 flags);
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001223}
1224
1225PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001226PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001227 PyObject *locals, int closeit, PyCompilerFlags *flags)
1228{
Tim Petersfe2127d2001-07-16 05:37:24 +00001229 node *n = PyParser_SimpleParseFileFlags(fp, filename, start,
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001230 PARSER_FLAGS(flags));
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001231 if (closeit)
1232 fclose(fp);
1233 return run_err_node(n, filename, globals, locals, flags);
1234}
1235
Guido van Rossum82598051997-03-05 00:20:32 +00001236static PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001237run_err_node(node *n, const char *filename, PyObject *globals, PyObject *locals,
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001238 PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001239{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001240 if (n == NULL)
1241 return NULL;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001242 return run_node(n, filename, globals, locals, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001243}
1244
Guido van Rossum82598051997-03-05 00:20:32 +00001245static PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001246run_node(node *n, const char *filename, PyObject *globals, PyObject *locals,
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001247 PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001248{
Guido van Rossum82598051997-03-05 00:20:32 +00001249 PyCodeObject *co;
1250 PyObject *v;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001251 co = PyNode_CompileFlags(n, filename, flags);
Guido van Rossum82598051997-03-05 00:20:32 +00001252 PyNode_Free(n);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001253 if (co == NULL)
1254 return NULL;
Guido van Rossum82598051997-03-05 00:20:32 +00001255 v = PyEval_EvalCode(co, globals, locals);
1256 Py_DECREF(co);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001257 return v;
1258}
1259
Guido van Rossum82598051997-03-05 00:20:32 +00001260static PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001261run_pyc_file(FILE *fp, const char *filename, PyObject *globals, PyObject *locals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001262 PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001263{
Guido van Rossum82598051997-03-05 00:20:32 +00001264 PyCodeObject *co;
1265 PyObject *v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001266 long magic;
Fred Drakee8de31c2000-08-31 05:38:39 +00001267 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001268
Guido van Rossum82598051997-03-05 00:20:32 +00001269 magic = PyMarshal_ReadLongFromFile(fp);
1270 if (magic != PyImport_GetMagicNumber()) {
1271 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001272 "Bad magic number in .pyc file");
1273 return NULL;
1274 }
Guido van Rossum82598051997-03-05 00:20:32 +00001275 (void) PyMarshal_ReadLongFromFile(fp);
Tim Petersd9b9ac82001-01-28 00:27:39 +00001276 v = PyMarshal_ReadLastObjectFromFile(fp);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001277 fclose(fp);
Guido van Rossum82598051997-03-05 00:20:32 +00001278 if (v == NULL || !PyCode_Check(v)) {
1279 Py_XDECREF(v);
1280 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001281 "Bad code object in .pyc file");
1282 return NULL;
1283 }
Guido van Rossum82598051997-03-05 00:20:32 +00001284 co = (PyCodeObject *)v;
1285 v = PyEval_EvalCode(co, globals, locals);
Jeremy Hyltonb857ba22001-08-10 21:41:33 +00001286 if (v && flags)
1287 flags->cf_flags |= (co->co_flags & PyCF_MASK);
Guido van Rossum82598051997-03-05 00:20:32 +00001288 Py_DECREF(co);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001289 return v;
1290}
1291
Guido van Rossum82598051997-03-05 00:20:32 +00001292PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001293Py_CompileString(const char *str, const char *filename, int start)
Guido van Rossum5b722181993-03-30 17:46:03 +00001294{
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001295 return Py_CompileStringFlags(str, filename, start, NULL);
1296}
1297
1298PyObject *
Tim Petersd08e3822003-04-17 15:24:21 +00001299Py_CompileStringFlags(const char *str, const char *filename, int start,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001300 PyCompilerFlags *flags)
1301{
Guido van Rossum5b722181993-03-30 17:46:03 +00001302 node *n;
Guido van Rossum82598051997-03-05 00:20:32 +00001303 PyCodeObject *co;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001304
1305 n = PyParser_SimpleParseStringFlagsFilename(str, filename, start,
1306 PARSER_FLAGS(flags));
Guido van Rossuma110aa61994-08-29 12:50:44 +00001307 if (n == NULL)
Guido van Rossum5b722181993-03-30 17:46:03 +00001308 return NULL;
Jeremy Hylton673a4fd2001-03-26 19:53:38 +00001309 co = PyNode_CompileFlags(n, filename, flags);
Guido van Rossum82598051997-03-05 00:20:32 +00001310 PyNode_Free(n);
1311 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001312}
1313
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001314struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001315Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001316{
1317 node *n;
1318 struct symtable *st;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001319 n = PyParser_SimpleParseStringFlagsFilename(str, filename,
1320 start, 0);
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001321 if (n == NULL)
1322 return NULL;
1323 st = PyNode_CompileSymtable(n, filename);
1324 PyNode_Free(n);
1325 return st;
1326}
1327
Guido van Rossuma110aa61994-08-29 12:50:44 +00001328/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001329
Guido van Rossuma110aa61994-08-29 12:50:44 +00001330node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001331PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001332{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001333 node *n;
1334 perrdetail err;
Tim Petersfe2127d2001-07-16 05:37:24 +00001335 n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar, start,
1336 (char *)0, (char *)0, &err, flags);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001337 if (n == NULL)
1338 err_input(&err);
1339 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001340}
1341
Tim Petersfe2127d2001-07-16 05:37:24 +00001342node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001343PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
Tim Petersfe2127d2001-07-16 05:37:24 +00001344{
1345 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
1346}
1347
Guido van Rossuma110aa61994-08-29 12:50:44 +00001348/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001349
Guido van Rossuma110aa61994-08-29 12:50:44 +00001350node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001351PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001352{
1353 node *n;
1354 perrdetail err;
1355 n = PyParser_ParseStringFlags(str, &_PyParser_Grammar, start, &err,
1356 flags);
1357 if (n == NULL)
1358 err_input(&err);
1359 return n;
1360}
1361
1362node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001363PyParser_SimpleParseString(const char *str, int start)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001364{
Tim Petersfe2127d2001-07-16 05:37:24 +00001365 return PyParser_SimpleParseStringFlags(str, start, 0);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001366}
1367
Thomas Heller6b17abf2002-07-09 09:23:27 +00001368node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001369PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Thomas Heller6b17abf2002-07-09 09:23:27 +00001370 int start, int flags)
1371{
1372 node *n;
1373 perrdetail err;
1374
Tim Petersd08e3822003-04-17 15:24:21 +00001375 n = PyParser_ParseStringFlagsFilename(str, filename,
Thomas Heller6b17abf2002-07-09 09:23:27 +00001376 &_PyParser_Grammar,
1377 start, &err, flags);
1378 if (n == NULL)
1379 err_input(&err);
1380 return n;
1381}
1382
1383node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001384PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001385{
1386 return PyParser_SimpleParseStringFlagsFilename(str, filename,
1387 start, 0);
1388}
1389
Guido van Rossum66ebd912003-04-17 16:02:26 +00001390/* May want to move a more generalized form of this to parsetok.c or
1391 even parser modules. */
1392
1393void
1394PyParser_SetError(perrdetail *err)
1395{
1396 err_input(err);
1397}
1398
Guido van Rossuma110aa61994-08-29 12:50:44 +00001399/* Set the error appropriate to the given input error code (see errcode.h) */
1400
1401static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001402err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001403{
Fred Drake85f36392000-07-11 17:53:00 +00001404 PyObject *v, *w, *errtype;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001405 PyObject* u = NULL;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001406 char *msg = NULL;
Fred Drake85f36392000-07-11 17:53:00 +00001407 errtype = PyExc_SyntaxError;
Guido van Rossum82598051997-03-05 00:20:32 +00001408 v = Py_BuildValue("(ziiz)", err->filename,
Guido van Rossuma110aa61994-08-29 12:50:44 +00001409 err->lineno, err->offset, err->text);
1410 if (err->text != NULL) {
Guido van Rossumb18618d2000-05-03 23:44:39 +00001411 PyMem_DEL(err->text);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001412 err->text = NULL;
1413 }
1414 switch (err->error) {
1415 case E_SYNTAX:
Fred Drake85f36392000-07-11 17:53:00 +00001416 errtype = PyExc_IndentationError;
1417 if (err->expected == INDENT)
1418 msg = "expected an indented block";
1419 else if (err->token == INDENT)
1420 msg = "unexpected indent";
1421 else if (err->token == DEDENT)
1422 msg = "unexpected unindent";
1423 else {
1424 errtype = PyExc_SyntaxError;
1425 msg = "invalid syntax";
1426 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001427 break;
1428 case E_TOKEN:
1429 msg = "invalid token";
Guido van Rossuma110aa61994-08-29 12:50:44 +00001430 break;
Skip Montanaro118ec702002-08-15 01:20:16 +00001431 case E_EOFS:
1432 msg = "EOF while scanning triple-quoted string";
1433 break;
1434 case E_EOLS:
1435 msg = "EOL while scanning single-quoted string";
1436 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001437 case E_INTR:
Guido van Rossum82598051997-03-05 00:20:32 +00001438 PyErr_SetNone(PyExc_KeyboardInterrupt);
Barry Warsawc80baa31999-01-27 16:39:40 +00001439 Py_XDECREF(v);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001440 return;
1441 case E_NOMEM:
Guido van Rossum82598051997-03-05 00:20:32 +00001442 PyErr_NoMemory();
Barry Warsawc80baa31999-01-27 16:39:40 +00001443 Py_XDECREF(v);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001444 return;
1445 case E_EOF:
1446 msg = "unexpected EOF while parsing";
1447 break;
Fred Drake85f36392000-07-11 17:53:00 +00001448 case E_TABSPACE:
1449 errtype = PyExc_TabError;
Guido van Rossum560e8ad1998-04-10 19:43:42 +00001450 msg = "inconsistent use of tabs and spaces in indentation";
1451 break;
Jeremy Hylton94988062000-06-20 19:10:44 +00001452 case E_OVERFLOW:
1453 msg = "expression too long";
1454 break;
Fred Drake85f36392000-07-11 17:53:00 +00001455 case E_DEDENT:
1456 errtype = PyExc_IndentationError;
1457 msg = "unindent does not match any outer indentation level";
1458 break;
1459 case E_TOODEEP:
1460 errtype = PyExc_IndentationError;
1461 msg = "too many levels of indentation";
1462 break;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001463 case E_DECODE: { /* XXX */
1464 PyThreadState* tstate = PyThreadState_Get();
1465 PyObject* value = tstate->curexc_value;
1466 if (value != NULL) {
1467 u = PyObject_Repr(value);
1468 if (u != NULL) {
1469 msg = PyString_AsString(u);
1470 break;
1471 }
1472 }
1473 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001474 default:
1475 fprintf(stderr, "error=%d\n", err->error);
1476 msg = "unknown parsing error";
1477 break;
1478 }
Guido van Rossum82598051997-03-05 00:20:32 +00001479 w = Py_BuildValue("(sO)", msg, v);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001480 Py_XDECREF(u);
Guido van Rossum41318302001-03-23 04:01:07 +00001481 Py_XDECREF(v);
Fred Drake85f36392000-07-11 17:53:00 +00001482 PyErr_SetObject(errtype, w);
Guido van Rossum82598051997-03-05 00:20:32 +00001483 Py_XDECREF(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001484}
1485
1486/* Print fatal error message and abort */
1487
1488void
Tim Peters7c321a82002-07-09 02:57:01 +00001489Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001490{
Guido van Rossum83dd6c31994-09-29 09:38:33 +00001491 fprintf(stderr, "Fatal Python error: %s\n", msg);
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001492#ifdef MS_WINDOWS
Guido van Rossum23c94461997-05-22 20:21:30 +00001493 OutputDebugString("Fatal Python error: ");
Guido van Rossuma44823b1995-03-14 15:01:17 +00001494 OutputDebugString(msg);
1495 OutputDebugString("\n");
Guido van Rossum0ba35361998-08-13 13:33:16 +00001496#ifdef _DEBUG
1497 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00001498#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001499#endif /* MS_WINDOWS */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001500 abort();
1501}
1502
1503/* Clean up and exit */
1504
Guido van Rossuma110aa61994-08-29 12:50:44 +00001505#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00001506#include "pythread.h"
Guido van Rossum82598051997-03-05 00:20:32 +00001507int _PyThread_Started = 0; /* Set by threadmodule.c and maybe others */
Guido van Rossumf9f2e821992-08-17 08:59:08 +00001508#endif
1509
Guido van Rossum2dcfc961998-10-01 16:01:57 +00001510#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001511static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00001512static int nexitfuncs = 0;
1513
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001514int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00001515{
1516 if (nexitfuncs >= NEXITFUNCS)
1517 return -1;
1518 exitfuncs[nexitfuncs++] = func;
1519 return 0;
1520}
1521
Guido van Rossumcc283f51997-08-05 02:22:03 +00001522static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001523call_sys_exitfunc(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001524{
Guido van Rossum82598051997-03-05 00:20:32 +00001525 PyObject *exitfunc = PySys_GetObject("exitfunc");
Guido van Rossum59bff391992-09-03 20:28:00 +00001526
1527 if (exitfunc) {
Fred Drake6a12d8d2001-03-23 17:34:02 +00001528 PyObject *res;
Guido van Rossum82598051997-03-05 00:20:32 +00001529 Py_INCREF(exitfunc);
1530 PySys_SetObject("exitfunc", (PyObject *)NULL);
1531 res = PyEval_CallObject(exitfunc, (PyObject *)NULL);
Guido van Rossum59bff391992-09-03 20:28:00 +00001532 if (res == NULL) {
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001533 if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
1534 PySys_WriteStderr("Error in sys.exitfunc:\n");
1535 }
Guido van Rossum82598051997-03-05 00:20:32 +00001536 PyErr_Print();
Guido van Rossum59bff391992-09-03 20:28:00 +00001537 }
Guido van Rossum82598051997-03-05 00:20:32 +00001538 Py_DECREF(exitfunc);
Guido van Rossum59bff391992-09-03 20:28:00 +00001539 }
1540
Guido van Rossum0829c751998-02-28 04:31:39 +00001541 if (Py_FlushLine())
1542 PyErr_Clear();
Guido van Rossumcc283f51997-08-05 02:22:03 +00001543}
Guido van Rossum1662dd51994-09-07 14:38:28 +00001544
Guido van Rossumcc283f51997-08-05 02:22:03 +00001545static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001546call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00001547{
Guido van Rossum1662dd51994-09-07 14:38:28 +00001548 while (nexitfuncs > 0)
1549 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00001550
1551 fflush(stdout);
1552 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001553}
1554
1555void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001556Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001557{
Guido van Rossumcc283f51997-08-05 02:22:03 +00001558 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001559
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001560 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001561}
1562
Guido van Rossumf1dc5661993-07-05 10:31:29 +00001563static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001564initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001565{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001566#ifdef SIGPIPE
1567 signal(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001568#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00001569#ifdef SIGXFZ
1570 signal(SIGXFZ, SIG_IGN);
1571#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00001572#ifdef SIGXFSZ
1573 signal(SIGXFSZ, SIG_IGN);
1574#endif
Guido van Rossum82598051997-03-05 00:20:32 +00001575 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001576}
1577
Guido van Rossum7433b121997-02-14 19:45:36 +00001578
1579/*
1580 * The file descriptor fd is considered ``interactive'' if either
1581 * a) isatty(fd) is TRUE, or
1582 * b) the -i flag was given, and the filename associated with
1583 * the descriptor is NULL or "<stdin>" or "???".
1584 */
1585int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001586Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00001587{
1588 if (isatty((int)fileno(fp)))
1589 return 1;
1590 if (!Py_InteractiveFlag)
1591 return 0;
1592 return (filename == NULL) ||
1593 (strcmp(filename, "<stdin>") == 0) ||
1594 (strcmp(filename, "???") == 0);
1595}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001596
1597
Tim Petersd08e3822003-04-17 15:24:21 +00001598#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001599#if defined(WIN32) && defined(_MSC_VER)
1600
1601/* Stack checking for Microsoft C */
1602
1603#include <malloc.h>
1604#include <excpt.h>
1605
Fred Drakee8de31c2000-08-31 05:38:39 +00001606/*
1607 * Return non-zero when we run out of memory on the stack; zero otherwise.
1608 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001609int
Fred Drake399739f2000-08-31 05:52:44 +00001610PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001611{
1612 __try {
Tim Peters92e4dd82002-10-05 01:47:34 +00001613 /* alloca throws a stack overflow exception if there's
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001614 not enough space left on the stack */
Tim Peters92e4dd82002-10-05 01:47:34 +00001615 alloca(PYOS_STACK_MARGIN * sizeof(void*));
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001616 return 0;
1617 } __except (EXCEPTION_EXECUTE_HANDLER) {
1618 /* just ignore all errors */
1619 }
1620 return 1;
1621}
1622
1623#endif /* WIN32 && _MSC_VER */
1624
1625/* Alternate implementations can be added here... */
1626
1627#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00001628
1629
1630/* Wrappers around sigaction() or signal(). */
1631
1632PyOS_sighandler_t
1633PyOS_getsig(int sig)
1634{
1635#ifdef HAVE_SIGACTION
1636 struct sigaction context;
Barry Warsawafeb2a42001-11-13 23:08:26 +00001637 /* Initialize context.sa_handler to SIG_ERR which makes about as
1638 * much sense as anything else. It should get overwritten if
1639 * sigaction actually succeeds and otherwise we avoid an
1640 * uninitialized memory read.
1641 */
1642 context.sa_handler = SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00001643 sigaction(sig, NULL, &context);
1644 return context.sa_handler;
1645#else
1646 PyOS_sighandler_t handler;
1647 handler = signal(sig, SIG_IGN);
1648 signal(sig, handler);
1649 return handler;
1650#endif
1651}
1652
1653PyOS_sighandler_t
1654PyOS_setsig(int sig, PyOS_sighandler_t handler)
1655{
1656#ifdef HAVE_SIGACTION
1657 struct sigaction context;
1658 PyOS_sighandler_t oldhandler;
Barry Warsawafeb2a42001-11-13 23:08:26 +00001659 /* Initialize context.sa_handler to SIG_ERR which makes about as
1660 * much sense as anything else. It should get overwritten if
1661 * sigaction actually succeeds and otherwise we avoid an
1662 * uninitialized memory read.
1663 */
1664 context.sa_handler = SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00001665 sigaction(sig, NULL, &context);
1666 oldhandler = context.sa_handler;
1667 context.sa_handler = handler;
1668 sigaction(sig, &context, NULL);
1669 return oldhandler;
1670#else
1671 return signal(sig, handler);
1672#endif
1673}