blob: 018400cb9208d3e8f437e3a326e911f1ed372768 [file] [log] [blame]
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001
2/* Python interpreter top-level routines, including init/exit */
3
Guido van Rossum82598051997-03-05 00:20:32 +00004#include "Python.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +00005
6#include "grammar.h"
7#include "node.h"
Fred Drake85f36392000-07-11 17:53:00 +00008#include "token.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +00009#include "parsetok.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000010#include "errcode.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000011#include "compile.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000012#include "symtable.h"
Guido van Rossumff4949e1992-08-05 19:58:53 +000013#include "eval.h"
Guido van Rossumfdef2711994-09-14 13:31:04 +000014#include "marshal.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000015
Guido van Rossuma110aa61994-08-29 12:50:44 +000016#ifdef HAVE_SIGNAL_H
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000017#include <signal.h>
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000018#endif
19
Martin v. Löwis73d538b2003-03-05 15:13:47 +000020#ifdef HAVE_LANGINFO_H
21#include <locale.h>
22#include <langinfo.h>
23#endif
24
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000025#ifdef MS_WINDOWS
Guido van Rossuma44823b1995-03-14 15:01:17 +000026#undef BYTE
27#include "windows.h"
28#endif
29
Jack Jansencbf630f2000-07-11 21:59:16 +000030#ifdef macintosh
31#include "macglue.h"
32#endif
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000033extern char *Py_GetPath(void);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000034
Guido van Rossum82598051997-03-05 00:20:32 +000035extern grammar _PyParser_Grammar; /* From graminit.c */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000036
Guido van Rossumb73cc041993-11-01 16:28:59 +000037/* Forward */
Tim Petersdbd9ba62000-07-09 03:09:57 +000038static void initmain(void);
39static void initsite(void);
Martin v. Löwis95292d62002-12-11 14:04:59 +000040static PyObject *run_err_node(node *, const char *, PyObject *, PyObject *,
Jeremy Hylton9f324e92001-03-01 22:59:14 +000041 PyCompilerFlags *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000042static PyObject *run_node(node *, const char *, PyObject *, PyObject *,
Jeremy Hylton9f324e92001-03-01 22:59:14 +000043 PyCompilerFlags *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000044static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
Jeremy Hyltonbc320242001-03-22 02:47:58 +000045 PyCompilerFlags *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000046static void err_input(perrdetail *);
47static void initsigs(void);
48static void call_sys_exitfunc(void);
49static void call_ll_exitfuncs(void);
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000050extern void _PyUnicode_Init(void);
51extern void _PyUnicode_Fini(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +000052
Mark Hammond8d98d2c2003-04-19 15:41:53 +000053#ifdef WITH_THREAD
54extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
55extern void _PyGILState_Fini(void);
56#endif /* WITH_THREAD */
57
Guido van Rossum82598051997-03-05 00:20:32 +000058int Py_DebugFlag; /* Needed by parser.c */
59int Py_VerboseFlag; /* Needed by import.c */
Guido van Rossum7433b121997-02-14 19:45:36 +000060int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Guido van Rossumdcc0c131997-08-29 22:32:42 +000061int Py_NoSiteFlag; /* Suppress 'import site' */
Barry Warsaw3ce09642000-05-02 19:18:59 +000062int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +000063int Py_FrozenFlag; /* Needed by getpath.c */
Guido van Rossumb16d1972000-05-01 17:55:15 +000064int Py_UnicodeFlag = 0; /* Needed by compile.c */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +000065int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Tim Peters3caca232001-12-06 06:23:26 +000066/* _XXX Py_QnewFlag should go away in 2.3. It's true iff -Qnew is passed,
67 on the command line, and is used in 2.2 by ceval.c to make all "/" divisions
68 true divisions (which they will be in 2.3). */
69int _Py_QnewFlag = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +000070
Mark Hammonda43fd0c2003-02-19 00:33:33 +000071/* Reference to 'warnings' module, to avoid importing it
Mark Hammondedd07732003-07-15 23:03:55 +000072 on the fly when the import lock may be held. See 683658/771097
Mark Hammonda43fd0c2003-02-19 00:33:33 +000073*/
Mark Hammondedd07732003-07-15 23:03:55 +000074static PyObject *warnings_module = NULL;
75
76/* Returns a borrowed reference to the 'warnings' module, or NULL.
77 If the module is returned, it is guaranteed to have been obtained
78 without acquiring the import lock
79*/
Martin v. Löwisa2c17c52003-08-09 09:47:11 +000080PyObject *PyModule_GetWarningsModule(void)
Mark Hammondedd07732003-07-15 23:03:55 +000081{
82 PyObject *typ, *val, *tb;
83 PyObject *all_modules;
84 /* If we managed to get the module at init time, just use it */
85 if (warnings_module)
86 return warnings_module;
87 /* If it wasn't available at init time, it may be available
88 now in sys.modules (common scenario is frozen apps: import
89 at init time fails, but the frozen init code sets up sys.path
90 correctly, then does an implicit import of warnings for us
91 */
92 /* Save and restore any exceptions */
93 PyErr_Fetch(&typ, &val, &tb);
94
Mark Hammond5f4e8ca2003-07-16 01:54:38 +000095 all_modules = PySys_GetObject("modules");
Mark Hammondedd07732003-07-15 23:03:55 +000096 if (all_modules) {
97 warnings_module = PyDict_GetItemString(all_modules, "warnings");
98 /* We keep a ref in the global */
99 Py_XINCREF(warnings_module);
100 }
101 PyErr_Restore(typ, val, tb);
102 return warnings_module;
103}
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000104
Guido van Rossum25ce5661997-08-02 03:10:38 +0000105static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000106
Thomas Wouters7e474022000-07-16 12:04:32 +0000107/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000108
109int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000110Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000111{
112 return initialized;
113}
114
Guido van Rossum25ce5661997-08-02 03:10:38 +0000115/* Global initializations. Can be undone by Py_Finalize(). Don't
116 call this twice without an intervening Py_Finalize() call. When
117 initializations fail, a fatal error is issued and the function does
118 not return. On return, the first thread and interpreter state have
119 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000120
Guido van Rossum25ce5661997-08-02 03:10:38 +0000121 Locking: you must hold the interpreter lock while calling this.
122 (If the lock has not yet been initialized, that's equivalent to
123 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000124
Guido van Rossum25ce5661997-08-02 03:10:38 +0000125*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000126
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000127static int
128add_flag(int flag, const char *envs)
129{
130 int env = atoi(envs);
131 if (flag < env)
132 flag = env;
133 if (flag < 1)
134 flag = 1;
135 return flag;
136}
137
Guido van Rossuma027efa1997-05-05 20:56:21 +0000138void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000139Py_Initialize(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000140{
Guido van Rossuma027efa1997-05-05 20:56:21 +0000141 PyInterpreterState *interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000142 PyThreadState *tstate;
143 PyObject *bimod, *sysmod;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000144 char *p;
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000145#if defined(Py_USING_UNICODE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
146 char *codeset;
147 char *saved_locale;
148 PyObject *sys_stream, *sys_isatty;
149#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +0000150 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000151
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000152 if (initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +0000153 return;
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000154 initialized = 1;
Tim Petersd08e3822003-04-17 15:24:21 +0000155
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000156 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000157 Py_DebugFlag = add_flag(Py_DebugFlag, p);
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000158 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000159 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000160 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000161 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000162
Guido van Rossuma027efa1997-05-05 20:56:21 +0000163 interp = PyInterpreterState_New();
164 if (interp == NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000165 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000166
Guido van Rossuma027efa1997-05-05 20:56:21 +0000167 tstate = PyThreadState_New(interp);
168 if (tstate == NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000169 Py_FatalError("Py_Initialize: can't make first thread");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000170 (void) PyThreadState_Swap(tstate);
171
Guido van Rossum70d893a2001-08-16 08:21:42 +0000172 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000173
Neal Norwitzb2501f42002-12-31 03:42:13 +0000174 if (!_PyFrame_Init())
Neal Norwitzc91ed402002-12-30 22:29:22 +0000175 Py_FatalError("Py_Initialize: can't init frames");
176
Neal Norwitzb2501f42002-12-31 03:42:13 +0000177 if (!_PyInt_Init())
Neal Norwitzc91ed402002-12-30 22:29:22 +0000178 Py_FatalError("Py_Initialize: can't init ints");
179
Guido van Rossum25ce5661997-08-02 03:10:38 +0000180 interp->modules = PyDict_New();
181 if (interp->modules == NULL)
182 Py_FatalError("Py_Initialize: can't make modules dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000183
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000184#ifdef Py_USING_UNICODE
Guido van Rossumc94044c2000-03-10 23:03:54 +0000185 /* Init Unicode implementation; relies on the codec registry */
186 _PyUnicode_Init();
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000187#endif
Guido van Rossumc94044c2000-03-10 23:03:54 +0000188
Barry Warsawf242aa02000-05-25 23:09:49 +0000189 bimod = _PyBuiltin_Init();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000190 if (bimod == NULL)
191 Py_FatalError("Py_Initialize: can't initialize __builtin__");
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000192 interp->builtins = PyModule_GetDict(bimod);
193 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000194
195 sysmod = _PySys_Init();
196 if (sysmod == NULL)
197 Py_FatalError("Py_Initialize: can't initialize sys");
198 interp->sysdict = PyModule_GetDict(sysmod);
199 Py_INCREF(interp->sysdict);
200 _PyImport_FixupExtension("sys", "sys");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000201 PySys_SetPath(Py_GetPath());
Guido van Rossum25ce5661997-08-02 03:10:38 +0000202 PyDict_SetItemString(interp->sysdict, "modules",
203 interp->modules);
204
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000205 _PyImport_Init();
206
Barry Warsawf242aa02000-05-25 23:09:49 +0000207 /* initialize builtin exceptions */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000208 _PyExc_Init();
Barry Warsaw5821bc52001-08-13 23:04:56 +0000209 _PyImport_FixupExtension("exceptions", "exceptions");
Barry Warsawf242aa02000-05-25 23:09:49 +0000210
Barry Warsaw035574d1997-08-29 22:07:17 +0000211 /* phase 2 of builtins */
Barry Warsaw963b8711997-09-18 16:42:02 +0000212 _PyImport_FixupExtension("__builtin__", "__builtin__");
Barry Warsaw035574d1997-08-29 22:07:17 +0000213
Just van Rossum52e14d62002-12-30 22:08:05 +0000214 _PyImportHooks_Init();
215
Guido van Rossum25ce5661997-08-02 03:10:38 +0000216 initsigs(); /* Signal handling stuff, including initintr() */
217
218 initmain(); /* Module __main__ */
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000219 if (!Py_NoSiteFlag)
220 initsite(); /* Module site */
Just van Rossum5bfba3a2003-02-25 20:25:12 +0000221
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000222 /* auto-thread-state API, if available */
223#ifdef WITH_THREAD
224 _PyGILState_Init(interp, tstate);
225#endif /* WITH_THREAD */
226
Mark Hammondedd07732003-07-15 23:03:55 +0000227 warnings_module = PyImport_ImportModule("warnings");
228 if (!warnings_module)
229 PyErr_Clear();
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000230
231#if defined(Py_USING_UNICODE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
232 /* On Unix, set the file system encoding according to the
233 user's preference, if the CODESET names a well-known
234 Python codec, and Py_FileSystemDefaultEncoding isn't
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000235 initialized by other means. Also set the encoding of
236 stdin and stdout if these are terminals. */
237
238 saved_locale = setlocale(LC_CTYPE, NULL);
239 setlocale(LC_CTYPE, "");
240 codeset = nl_langinfo(CODESET);
241 if (codeset && *codeset) {
242 PyObject *enc = PyCodec_Encoder(codeset);
243 if (enc) {
244 codeset = strdup(codeset);
245 Py_DECREF(enc);
246 } else {
247 codeset = NULL;
248 PyErr_Clear();
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000249 }
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000250 } else
251 codeset = NULL;
252 setlocale(LC_CTYPE, saved_locale);
253
254 if (codeset) {
Michael W. Hudson68debc92003-08-11 12:20:24 +0000255 sys_stream = PySys_GetObject("stdin");
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000256 sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
257 if (!sys_isatty)
258 PyErr_Clear();
259 if(sys_isatty && PyObject_IsTrue(sys_isatty)) {
260 if (!PyFile_SetEncoding(sys_stream, codeset))
261 Py_FatalError("Cannot set codeset of stdin");
262 }
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000263 Py_XDECREF(sys_isatty);
264
265 sys_stream = PySys_GetObject("stdout");
266 sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
267 if (!sys_isatty)
268 PyErr_Clear();
269 if(sys_isatty && PyObject_IsTrue(sys_isatty)) {
270 if (!PyFile_SetEncoding(sys_stream, codeset))
271 Py_FatalError("Cannot set codeset of stdout");
272 }
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000273 Py_XDECREF(sys_isatty);
274
275 if (!Py_FileSystemDefaultEncoding)
276 Py_FileSystemDefaultEncoding = codeset;
277 else
278 free(codeset);
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000279 }
280#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000281}
282
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000283#ifdef COUNT_ALLOCS
Tim Petersdbd9ba62000-07-09 03:09:57 +0000284extern void dump_counts(void);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000285#endif
286
Guido van Rossum25ce5661997-08-02 03:10:38 +0000287/* Undo the effect of Py_Initialize().
288
289 Beware: if multiple interpreter and/or thread states exist, these
290 are not wiped out; only the current thread and interpreter state
291 are deleted. But since everything else is deleted, those other
292 interpreter and thread states should no longer be used.
293
294 (XXX We should do better, e.g. wipe out all interpreters and
295 threads.)
296
297 Locking: as above.
298
299*/
300
301void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000302Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000303{
304 PyInterpreterState *interp;
305 PyThreadState *tstate;
306
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000307 if (!initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +0000308 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000309
Tim Peters384fd102001-01-21 03:40:37 +0000310 /* The interpreter is still entirely intact at this point, and the
311 * exit funcs may be relying on that. In particular, if some thread
312 * or exit func is still waiting to do an import, the import machinery
313 * expects Py_IsInitialized() to return true. So don't say the
314 * interpreter is uninitialized until after the exit funcs have run.
315 * Note that Threading.py uses an exit func to do a join on all the
316 * threads created thru it, so this also protects pending imports in
317 * the threads created via Threading.
318 */
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000319 call_sys_exitfunc();
Tim Peters384fd102001-01-21 03:40:37 +0000320 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000321
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000322 /* Get current thread state and interpreter pointer */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000323 tstate = PyThreadState_Get();
324 interp = tstate->interp;
325
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000326 /* Disable signal handling */
327 PyOS_FiniInterrupts();
328
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000329 /* drop module references we saved */
Mark Hammondedd07732003-07-15 23:03:55 +0000330 Py_XDECREF(warnings_module);
331 warnings_module = NULL;
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000332
Guido van Rossume13ddc92003-04-17 17:29:22 +0000333 /* Collect garbage. This may call finalizers; it's nice to call these
334 before all modules are destroyed. */
335 PyGC_Collect();
336
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000337 /* Destroy all modules */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000338 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000339
Guido van Rossume13ddc92003-04-17 17:29:22 +0000340 /* Collect final garbage. This disposes of cycles created by
341 new-style class definitions, for example. */
342 PyGC_Collect();
343
Guido van Rossum1707aad1997-12-08 23:43:45 +0000344 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
345 _PyImport_Fini();
346
347 /* Debugging stuff */
348#ifdef COUNT_ALLOCS
349 dump_counts();
350#endif
351
352#ifdef Py_REF_DEBUG
353 fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
354#endif
355
Tim Peters9cf25ce2003-04-17 15:21:01 +0000356#ifdef Py_TRACE_REFS
357 /* Display all objects still alive -- this can invoke arbitrary
358 * __repr__ overrides, so requires a mostly-intact interpreter.
359 * Alas, a lot of stuff may still be alive now that will be cleaned
360 * up later.
361 */
Tim Peters269b2a62003-04-17 19:52:29 +0000362 if (Py_GETENV("PYTHONDUMPREFS"))
Tim Peters9cf25ce2003-04-17 15:21:01 +0000363 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000364#endif /* Py_TRACE_REFS */
365
Barry Warsaw035574d1997-08-29 22:07:17 +0000366 /* Now we decref the exception classes. After this point nothing
367 can raise an exception. That's okay, because each Fini() method
368 below has been checked to make sure no exceptions are ever
369 raised.
370 */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000371 _PyExc_Fini();
Barry Warsawf242aa02000-05-25 23:09:49 +0000372
Mark Hammond6cb90292003-04-22 11:18:00 +0000373 /* Cleanup auto-thread-state */
374#ifdef WITH_THREAD
375 _PyGILState_Fini();
376#endif /* WITH_THREAD */
377
Guido van Rossumd922fa42003-04-15 14:10:09 +0000378 /* Clear interpreter state */
Barry Warsawf242aa02000-05-25 23:09:49 +0000379 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000380
Guido van Rossumd922fa42003-04-15 14:10:09 +0000381 /* Delete current thread */
Barry Warsawf242aa02000-05-25 23:09:49 +0000382 PyThreadState_Swap(NULL);
383 PyInterpreterState_Delete(interp);
384
Guido van Rossumd922fa42003-04-15 14:10:09 +0000385 /* Sundry finalizers */
Guido van Rossumcc283f51997-08-05 02:22:03 +0000386 PyMethod_Fini();
387 PyFrame_Fini();
388 PyCFunction_Fini();
389 PyTuple_Fini();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000390 PyString_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000391 PyInt_Fini();
392 PyFloat_Fini();
393
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000394#ifdef Py_USING_UNICODE
395 /* Cleanup Unicode implementation */
396 _PyUnicode_Fini();
397#endif
398
Guido van Rossumcc283f51997-08-05 02:22:03 +0000399 /* XXX Still allocated:
400 - various static ad-hoc pointers to interned strings
401 - int and float free list blocks
402 - whatever various modules and libraries allocate
403 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000404
405 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000406
Tim Peters269b2a62003-04-17 19:52:29 +0000407#ifdef Py_TRACE_REFS
408 /* Display addresses (& refcnts) of all objects still alive.
409 * An address can be used to find the repr of the object, printed
410 * above by _Py_PrintReferences.
411 */
412 if (Py_GETENV("PYTHONDUMPREFS"))
413 _Py_PrintReferenceAddresses(stderr);
414#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000415#ifdef PYMALLOC_DEBUG
416 if (Py_GETENV("PYTHONMALLOCSTATS"))
417 _PyObject_DebugMallocStats();
418#endif
419
Guido van Rossumcc283f51997-08-05 02:22:03 +0000420 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000421}
422
423/* Create and initialize a new interpreter and thread, and return the
424 new thread. This requires that Py_Initialize() has been called
425 first.
426
427 Unsuccessful initialization yields a NULL pointer. Note that *no*
428 exception information is available even in this case -- the
429 exception information is held in the thread, and there is no
430 thread.
431
432 Locking: as above.
433
434*/
435
436PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000437Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000438{
439 PyInterpreterState *interp;
440 PyThreadState *tstate, *save_tstate;
441 PyObject *bimod, *sysmod;
442
443 if (!initialized)
444 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
445
446 interp = PyInterpreterState_New();
447 if (interp == NULL)
448 return NULL;
449
450 tstate = PyThreadState_New(interp);
451 if (tstate == NULL) {
452 PyInterpreterState_Delete(interp);
453 return NULL;
454 }
455
456 save_tstate = PyThreadState_Swap(tstate);
457
458 /* XXX The following is lax in error checking */
459
460 interp->modules = PyDict_New();
461
462 bimod = _PyImport_FindExtension("__builtin__", "__builtin__");
463 if (bimod != NULL) {
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000464 interp->builtins = PyModule_GetDict(bimod);
465 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000466 }
467 sysmod = _PyImport_FindExtension("sys", "sys");
468 if (bimod != NULL && sysmod != NULL) {
469 interp->sysdict = PyModule_GetDict(sysmod);
470 Py_INCREF(interp->sysdict);
471 PySys_SetPath(Py_GetPath());
472 PyDict_SetItemString(interp->sysdict, "modules",
473 interp->modules);
Martin v. Löwisd7ceb222003-01-22 09:00:38 +0000474 _PyImportHooks_Init();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000475 initmain();
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000476 if (!Py_NoSiteFlag)
477 initsite();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000478 }
479
480 if (!PyErr_Occurred())
481 return tstate;
482
483 /* Oops, it didn't work. Undo it all. */
484
485 PyErr_Print();
486 PyThreadState_Clear(tstate);
487 PyThreadState_Swap(save_tstate);
488 PyThreadState_Delete(tstate);
489 PyInterpreterState_Delete(interp);
490
491 return NULL;
492}
493
494/* Delete an interpreter and its last thread. This requires that the
495 given thread state is current, that the thread has no remaining
496 frames, and that it is its interpreter's only remaining thread.
497 It is a fatal error to violate these constraints.
498
499 (Py_Finalize() doesn't have these constraints -- it zaps
500 everything, regardless.)
501
502 Locking: as above.
503
504*/
505
506void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000507Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000508{
509 PyInterpreterState *interp = tstate->interp;
510
511 if (tstate != PyThreadState_Get())
512 Py_FatalError("Py_EndInterpreter: thread is not current");
513 if (tstate->frame != NULL)
514 Py_FatalError("Py_EndInterpreter: thread still has a frame");
515 if (tstate != interp->tstate_head || tstate->next != NULL)
516 Py_FatalError("Py_EndInterpreter: not the last thread");
517
518 PyImport_Cleanup();
519 PyInterpreterState_Clear(interp);
520 PyThreadState_Swap(NULL);
521 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000522}
523
524static char *progname = "python";
525
526void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000527Py_SetProgramName(char *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000528{
529 if (pn && *pn)
530 progname = pn;
531}
532
533char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000534Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000535{
536 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000537}
538
Guido van Rossuma61691e1998-02-06 22:27:24 +0000539static char *default_home = NULL;
540
541void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000542Py_SetPythonHome(char *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000543{
544 default_home = home;
545}
546
547char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000548Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000549{
550 char *home = default_home;
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000551 if (home == NULL && !Py_IgnoreEnvironmentFlag)
552 home = Py_GETENV("PYTHONHOME");
Guido van Rossuma61691e1998-02-06 22:27:24 +0000553 return home;
554}
555
Guido van Rossum6135a871995-01-09 17:53:26 +0000556/* Create __main__ module */
557
558static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000559initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000560{
Guido van Rossum82598051997-03-05 00:20:32 +0000561 PyObject *m, *d;
562 m = PyImport_AddModule("__main__");
Guido van Rossum6135a871995-01-09 17:53:26 +0000563 if (m == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +0000564 Py_FatalError("can't create __main__ module");
565 d = PyModule_GetDict(m);
566 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
Guido van Rossum858cb731997-11-19 16:15:37 +0000567 PyObject *bimod = PyImport_ImportModule("__builtin__");
568 if (bimod == NULL ||
569 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
Guido van Rossum82598051997-03-05 00:20:32 +0000570 Py_FatalError("can't add __builtins__ to __main__");
Barry Warsaw3d05b1a1999-01-29 21:30:22 +0000571 Py_DECREF(bimod);
Guido van Rossum6135a871995-01-09 17:53:26 +0000572 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000573}
574
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000575/* Import the site module (not into __main__ though) */
576
577static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000578initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000579{
580 PyObject *m, *f;
581 m = PyImport_ImportModule("site");
582 if (m == NULL) {
583 f = PySys_GetObject("stderr");
584 if (Py_VerboseFlag) {
585 PyFile_WriteString(
586 "'import site' failed; traceback:\n", f);
587 PyErr_Print();
588 }
589 else {
590 PyFile_WriteString(
591 "'import site' failed; use -v for traceback\n", f);
592 PyErr_Clear();
593 }
594 }
595 else {
596 Py_DECREF(m);
597 }
598}
599
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000600/* Parse input from a file and execute it */
601
602int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000603PyRun_AnyFile(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000604{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000605 return PyRun_AnyFileExFlags(fp, filename, 0, NULL);
606}
607
608int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000609PyRun_AnyFileFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000610{
611 return PyRun_AnyFileExFlags(fp, filename, 0, flags);
Guido van Rossum0df002c2000-08-27 19:21:52 +0000612}
613
614int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000615PyRun_AnyFileEx(FILE *fp, const char *filename, int closeit)
Guido van Rossum0df002c2000-08-27 19:21:52 +0000616{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000617 return PyRun_AnyFileExFlags(fp, filename, closeit, NULL);
618}
619
620int
Tim Petersd08e3822003-04-17 15:24:21 +0000621PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000622 PyCompilerFlags *flags)
623{
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000624 if (filename == NULL)
625 filename = "???";
Guido van Rossum0df002c2000-08-27 19:21:52 +0000626 if (Py_FdIsInteractive(fp, filename)) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000627 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
Guido van Rossum0df002c2000-08-27 19:21:52 +0000628 if (closeit)
629 fclose(fp);
630 return err;
631 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000632 else
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000633 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000634}
635
636int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000637PyRun_InteractiveLoop(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000638{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000639 return PyRun_InteractiveLoopFlags(fp, filename, NULL);
640}
641
642int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000643PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000644{
Guido van Rossum82598051997-03-05 00:20:32 +0000645 PyObject *v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000646 int ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000647 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000648
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000649 if (flags == NULL) {
650 flags = &local_flags;
Tim Peters5ba58662001-07-16 02:29:45 +0000651 local_flags.cf_flags = 0;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000652 }
Guido van Rossum82598051997-03-05 00:20:32 +0000653 v = PySys_GetObject("ps1");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000654 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000655 PySys_SetObject("ps1", v = PyString_FromString(">>> "));
656 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000657 }
Guido van Rossum82598051997-03-05 00:20:32 +0000658 v = PySys_GetObject("ps2");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000659 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000660 PySys_SetObject("ps2", v = PyString_FromString("... "));
661 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000662 }
663 for (;;) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000664 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
Guido van Rossumaae0d321996-05-22 16:35:33 +0000665#ifdef Py_REF_DEBUG
Guido van Rossum6f9e4331995-03-29 16:57:48 +0000666 fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000667#endif
668 if (ret == E_EOF)
669 return 0;
670 /*
671 if (ret == E_NOMEM)
672 return -1;
673 */
674 }
675}
676
677int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000678PyRun_InteractiveOne(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000679{
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000680 return PyRun_InteractiveOneFlags(fp, filename, NULL);
681}
682
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000683/* compute parser flags based on compiler flags */
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000684#define PARSER_FLAGS(flags) \
Guido van Rossum4b499dd32003-02-13 22:07:59 +0000685 (((flags) && (flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
686 PyPARSE_DONT_IMPLY_DEDENT : 0)
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000687
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000688int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000689PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000690{
Guido van Rossum82598051997-03-05 00:20:32 +0000691 PyObject *m, *d, *v, *w;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000692 node *n;
Guido van Rossuma110aa61994-08-29 12:50:44 +0000693 perrdetail err;
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000694 char *ps1 = "", *ps2 = "";
Tim Petersfe2127d2001-07-16 05:37:24 +0000695
Guido van Rossum82598051997-03-05 00:20:32 +0000696 v = PySys_GetObject("ps1");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000697 if (v != NULL) {
698 v = PyObject_Str(v);
699 if (v == NULL)
700 PyErr_Clear();
701 else if (PyString_Check(v))
702 ps1 = PyString_AsString(v);
703 }
Guido van Rossum82598051997-03-05 00:20:32 +0000704 w = PySys_GetObject("ps2");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000705 if (w != NULL) {
706 w = PyObject_Str(w);
707 if (w == NULL)
708 PyErr_Clear();
709 else if (PyString_Check(w))
710 ps2 = PyString_AsString(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000711 }
Tim Petersfe2127d2001-07-16 05:37:24 +0000712 n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar,
713 Py_single_input, ps1, ps2, &err,
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000714 PARSER_FLAGS(flags));
Guido van Rossum82598051997-03-05 00:20:32 +0000715 Py_XDECREF(v);
716 Py_XDECREF(w);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000717 if (n == NULL) {
718 if (err.error == E_EOF) {
719 if (err.text)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000720 PyMem_DEL(err.text);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000721 return E_EOF;
722 }
723 err_input(&err);
Guido van Rossum82598051997-03-05 00:20:32 +0000724 PyErr_Print();
Guido van Rossuma110aa61994-08-29 12:50:44 +0000725 return err.error;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000726 }
Guido van Rossum82598051997-03-05 00:20:32 +0000727 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000728 if (m == NULL)
729 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000730 d = PyModule_GetDict(m);
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000731 v = run_node(n, filename, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000732 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000733 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000734 return -1;
735 }
Guido van Rossum82598051997-03-05 00:20:32 +0000736 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000737 if (Py_FlushLine())
738 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000739 return 0;
740}
741
742int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000743PyRun_SimpleFile(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000744{
Guido van Rossum0df002c2000-08-27 19:21:52 +0000745 return PyRun_SimpleFileEx(fp, filename, 0);
746}
747
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000748/* Check whether a file maybe a pyc file: Look at the extension,
749 the file type, and, if we may close it, at the first few bytes. */
750
751static int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000752maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000753{
754 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
755 return 1;
756
757#ifdef macintosh
758 /* On a mac, we also assume a pyc file for types 'PYC ' and 'APPL' */
Jack Jansen72f3b7a2002-12-13 15:23:10 +0000759 if (PyMac_getfiletype((char *)filename) == 'PYC '
760 || PyMac_getfiletype((char *)filename) == 'APPL')
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000761 return 1;
762#endif /* macintosh */
763
764 /* Only look into the file if we are allowed to close it, since
765 it then should also be seekable. */
766 if (closeit) {
767 /* Read only two bytes of the magic. If the file was opened in
768 text mode, the bytes 3 and 4 of the magic (\r\n) might not
769 be read as they are on disk. */
770 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
771 unsigned char buf[2];
Tim Peters3e876562001-02-11 04:35:39 +0000772 /* Mess: In case of -x, the stream is NOT at its start now,
773 and ungetc() was used to push back the first newline,
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000774 which makes the current stream position formally undefined,
775 and a x-platform nightmare.
776 Unfortunately, we have no direct way to know whether -x
777 was specified. So we use a terrible hack: if the current
778 stream position is not 0, we assume -x was specified, and
779 give up. Bug 132850 on SourceForge spells out the
780 hopelessness of trying anything else (fseek and ftell
781 don't work predictably x-platform for text-mode files).
Tim Peters3e876562001-02-11 04:35:39 +0000782 */
Tim Peters3e876562001-02-11 04:35:39 +0000783 int ispyc = 0;
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000784 if (ftell(fp) == 0) {
785 if (fread(buf, 1, 2, fp) == 2 &&
Tim Petersd08e3822003-04-17 15:24:21 +0000786 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000787 ispyc = 1;
788 rewind(fp);
789 }
Tim Peters3e876562001-02-11 04:35:39 +0000790 return ispyc;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000791 }
792 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +0000793}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000794
Guido van Rossum0df002c2000-08-27 19:21:52 +0000795int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000796PyRun_SimpleFileEx(FILE *fp, const char *filename, int closeit)
Guido van Rossum0df002c2000-08-27 19:21:52 +0000797{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000798 return PyRun_SimpleFileExFlags(fp, filename, closeit, NULL);
799}
800
801int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000802PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000803 PyCompilerFlags *flags)
804{
Guido van Rossum82598051997-03-05 00:20:32 +0000805 PyObject *m, *d, *v;
Martin v. Löwis95292d62002-12-11 14:04:59 +0000806 const char *ext;
Guido van Rossumfdef2711994-09-14 13:31:04 +0000807
Guido van Rossum82598051997-03-05 00:20:32 +0000808 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000809 if (m == NULL)
810 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000811 d = PyModule_GetDict(m);
Fred Drake8ed02042002-10-17 21:24:58 +0000812 if (PyDict_GetItemString(d, "__file__") == NULL) {
813 PyObject *f = PyString_FromString(filename);
814 if (f == NULL)
815 return -1;
816 if (PyDict_SetItemString(d, "__file__", f) < 0) {
817 Py_DECREF(f);
818 return -1;
819 }
820 Py_DECREF(f);
821 }
Guido van Rossumfdef2711994-09-14 13:31:04 +0000822 ext = filename + strlen(filename) - 4;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000823 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Guido van Rossumfdef2711994-09-14 13:31:04 +0000824 /* Try to run a pyc file. First, re-open in binary */
Guido van Rossum0df002c2000-08-27 19:21:52 +0000825 if (closeit)
826 fclose(fp);
Fred Drake8ed02042002-10-17 21:24:58 +0000827 if ((fp = fopen(filename, "rb")) == NULL) {
Guido van Rossumfdef2711994-09-14 13:31:04 +0000828 fprintf(stderr, "python: Can't reopen .pyc file\n");
829 return -1;
830 }
Guido van Rossum2a7f58d1997-04-02 05:28:38 +0000831 /* Turn on optimization if a .pyo file is given */
832 if (strcmp(ext, ".pyo") == 0)
833 Py_OptimizeFlag = 1;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000834 v = run_pyc_file(fp, filename, d, d, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000835 } else {
Tim Petersd08e3822003-04-17 15:24:21 +0000836 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000837 closeit, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000838 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000839 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000840 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000841 return -1;
842 }
Guido van Rossum82598051997-03-05 00:20:32 +0000843 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000844 if (Py_FlushLine())
845 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000846 return 0;
847}
848
849int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000850PyRun_SimpleString(const char *command)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000851{
Guido van Rossum393661d2001-08-31 17:40:15 +0000852 return PyRun_SimpleStringFlags(command, NULL);
853}
854
855int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000856PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +0000857{
Guido van Rossum82598051997-03-05 00:20:32 +0000858 PyObject *m, *d, *v;
859 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000860 if (m == NULL)
861 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000862 d = PyModule_GetDict(m);
Guido van Rossum393661d2001-08-31 17:40:15 +0000863 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000864 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000865 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000866 return -1;
867 }
Guido van Rossum82598051997-03-05 00:20:32 +0000868 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000869 if (Py_FlushLine())
870 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000871 return 0;
872}
873
Barry Warsaw035574d1997-08-29 22:07:17 +0000874static int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000875parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
876 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +0000877{
878 long hold;
879 PyObject *v;
880
881 /* old style errors */
882 if (PyTuple_Check(err))
Neal Norwitz78293352002-04-01 01:41:20 +0000883 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
884 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +0000885
886 /* new style errors. `err' is an instance */
887
888 if (! (v = PyObject_GetAttrString(err, "msg")))
889 goto finally;
890 *message = v;
891
892 if (!(v = PyObject_GetAttrString(err, "filename")))
893 goto finally;
894 if (v == Py_None)
895 *filename = NULL;
896 else if (! (*filename = PyString_AsString(v)))
897 goto finally;
898
899 Py_DECREF(v);
900 if (!(v = PyObject_GetAttrString(err, "lineno")))
901 goto finally;
902 hold = PyInt_AsLong(v);
903 Py_DECREF(v);
904 v = NULL;
905 if (hold < 0 && PyErr_Occurred())
906 goto finally;
907 *lineno = (int)hold;
908
909 if (!(v = PyObject_GetAttrString(err, "offset")))
910 goto finally;
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000911 if (v == Py_None) {
912 *offset = -1;
913 Py_DECREF(v);
914 v = NULL;
915 } else {
916 hold = PyInt_AsLong(v);
917 Py_DECREF(v);
918 v = NULL;
919 if (hold < 0 && PyErr_Occurred())
920 goto finally;
921 *offset = (int)hold;
922 }
Barry Warsaw035574d1997-08-29 22:07:17 +0000923
924 if (!(v = PyObject_GetAttrString(err, "text")))
925 goto finally;
926 if (v == Py_None)
927 *text = NULL;
928 else if (! (*text = PyString_AsString(v)))
929 goto finally;
930 Py_DECREF(v);
931 return 1;
932
933finally:
934 Py_XDECREF(v);
935 return 0;
936}
937
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000938void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000939PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000940{
Guido van Rossuma61691e1998-02-06 22:27:24 +0000941 PyErr_PrintEx(1);
942}
943
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000944static void
Martin v. Löwis95292d62002-12-11 14:04:59 +0000945print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000946{
947 char *nl;
948 if (offset >= 0) {
949 if (offset > 0 && offset == (int)strlen(text))
950 offset--;
951 for (;;) {
952 nl = strchr(text, '\n');
953 if (nl == NULL || nl-text >= offset)
954 break;
955 offset -= (nl+1-text);
956 text = nl+1;
957 }
958 while (*text == ' ' || *text == '\t') {
959 text++;
960 offset--;
961 }
962 }
963 PyFile_WriteString(" ", f);
964 PyFile_WriteString(text, f);
965 if (*text == '\0' || text[strlen(text)-1] != '\n')
966 PyFile_WriteString("\n", f);
967 if (offset == -1)
968 return;
969 PyFile_WriteString(" ", f);
970 offset--;
971 while (offset > 0) {
972 PyFile_WriteString(" ", f);
973 offset--;
974 }
975 PyFile_WriteString("^\n", f);
976}
977
Guido van Rossum66e8e862001-03-23 17:54:43 +0000978static void
979handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000980{
Guido van Rossum66e8e862001-03-23 17:54:43 +0000981 PyObject *exception, *value, *tb;
Tim Peterscf615b52003-04-19 18:47:02 +0000982 int exitcode = 0;
983
Guido van Rossum66e8e862001-03-23 17:54:43 +0000984 PyErr_Fetch(&exception, &value, &tb);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000985 if (Py_FlushLine())
986 PyErr_Clear();
987 fflush(stdout);
988 if (value == NULL || value == Py_None)
Tim Peterscf615b52003-04-19 18:47:02 +0000989 goto done;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000990 if (PyInstance_Check(value)) {
991 /* The error code should be in the `code' attribute. */
992 PyObject *code = PyObject_GetAttrString(value, "code");
993 if (code) {
994 Py_DECREF(value);
995 value = code;
996 if (value == Py_None)
Tim Peterscf615b52003-04-19 18:47:02 +0000997 goto done;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000998 }
999 /* If we failed to dig out the 'code' attribute,
1000 just let the else clause below print the error. */
1001 }
1002 if (PyInt_Check(value))
Tim Peterscf615b52003-04-19 18:47:02 +00001003 exitcode = (int)PyInt_AsLong(value);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001004 else {
1005 PyObject_Print(value, stderr, Py_PRINT_RAW);
1006 PySys_WriteStderr("\n");
Tim Peterscf615b52003-04-19 18:47:02 +00001007 exitcode = 1;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001008 }
Tim Peterscf615b52003-04-19 18:47:02 +00001009 done:
1010 /* Restore and clear the exception info, in order to properly decref
1011 * the exception, value, and traceback. If we just exit instead,
1012 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1013 * some finalizers from running.
1014 */
1015 PyErr_Restore(exception, value, tb);
1016 PyErr_Clear();
1017 Py_Exit(exitcode);
1018 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001019}
1020
1021void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001022PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001023{
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001024 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001025
1026 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1027 handle_system_exit();
1028 }
Guido van Rossum82598051997-03-05 00:20:32 +00001029 PyErr_Fetch(&exception, &v, &tb);
Barry Warsaw035574d1997-08-29 22:07:17 +00001030 PyErr_NormalizeException(&exception, &v, &tb);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001031 if (exception == NULL)
Guido van Rossum296b4751997-05-23 00:19:20 +00001032 return;
Guido van Rossuma61691e1998-02-06 22:27:24 +00001033 if (set_sys_last_vars) {
1034 PySys_SetObject("last_type", exception);
1035 PySys_SetObject("last_value", v);
1036 PySys_SetObject("last_traceback", tb);
1037 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001038 hook = PySys_GetObject("excepthook");
1039 if (hook) {
1040 PyObject *args = Py_BuildValue("(OOO)",
1041 exception, v ? v : Py_None, tb ? tb : Py_None);
1042 PyObject *result = PyEval_CallObject(hook, args);
1043 if (result == NULL) {
1044 PyObject *exception2, *v2, *tb2;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001045 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1046 handle_system_exit();
1047 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001048 PyErr_Fetch(&exception2, &v2, &tb2);
1049 PyErr_NormalizeException(&exception2, &v2, &tb2);
1050 if (Py_FlushLine())
1051 PyErr_Clear();
1052 fflush(stdout);
1053 PySys_WriteStderr("Error in sys.excepthook:\n");
1054 PyErr_Display(exception2, v2, tb2);
1055 PySys_WriteStderr("\nOriginal exception was:\n");
1056 PyErr_Display(exception, v, tb);
Jeremy Hylton07028582001-12-07 15:35:35 +00001057 Py_XDECREF(exception2);
1058 Py_XDECREF(v2);
1059 Py_XDECREF(tb2);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001060 }
1061 Py_XDECREF(result);
1062 Py_XDECREF(args);
1063 } else {
1064 PySys_WriteStderr("sys.excepthook is missing\n");
1065 PyErr_Display(exception, v, tb);
1066 }
1067 Py_XDECREF(exception);
1068 Py_XDECREF(v);
1069 Py_XDECREF(tb);
1070}
1071
1072void PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
1073{
1074 int err = 0;
1075 PyObject *v = value;
1076 PyObject *f = PySys_GetObject("stderr");
Guido van Rossum3165fe61992-09-25 21:59:05 +00001077 if (f == NULL)
1078 fprintf(stderr, "lost sys.stderr\n");
1079 else {
Guido van Rossum0829c751998-02-28 04:31:39 +00001080 if (Py_FlushLine())
1081 PyErr_Clear();
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001082 fflush(stdout);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001083 if (tb && tb != Py_None)
1084 err = PyTraceBack_Print(tb, f);
Barry Warsaw36b8f941997-08-26 18:09:48 +00001085 if (err == 0 &&
Martin v. Löwiscfeb3b62002-03-03 21:30:27 +00001086 PyObject_HasAttrString(v, "print_file_and_line"))
Barry Warsaw36b8f941997-08-26 18:09:48 +00001087 {
Guido van Rossum82598051997-03-05 00:20:32 +00001088 PyObject *message;
Martin v. Löwis95292d62002-12-11 14:04:59 +00001089 const char *filename, *text;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001090 int lineno, offset;
Barry Warsaw035574d1997-08-29 22:07:17 +00001091 if (!parse_syntax_error(v, &message, &filename,
1092 &lineno, &offset, &text))
Guido van Rossum82598051997-03-05 00:20:32 +00001093 PyErr_Clear();
Guido van Rossuma110aa61994-08-29 12:50:44 +00001094 else {
1095 char buf[10];
Guido van Rossum82598051997-03-05 00:20:32 +00001096 PyFile_WriteString(" File \"", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001097 if (filename == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +00001098 PyFile_WriteString("<string>", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001099 else
Guido van Rossum82598051997-03-05 00:20:32 +00001100 PyFile_WriteString(filename, f);
1101 PyFile_WriteString("\", line ", f);
Jeremy Hylton518ab1c2001-11-28 20:42:20 +00001102 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
Guido van Rossum82598051997-03-05 00:20:32 +00001103 PyFile_WriteString(buf, f);
1104 PyFile_WriteString("\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001105 if (text != NULL)
1106 print_error_text(f, offset, text);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001107 v = message;
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001108 /* Can't be bothered to check all those
1109 PyFile_WriteString() calls */
1110 if (PyErr_Occurred())
1111 err = -1;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001112 }
1113 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001114 if (err) {
1115 /* Don't do anything else */
1116 }
1117 else if (PyClass_Check(exception)) {
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001118 PyClassObject* exc = (PyClassObject*)exception;
1119 PyObject* className = exc->cl_name;
1120 PyObject* moduleName =
1121 PyDict_GetItemString(exc->cl_dict, "__module__");
1122
1123 if (moduleName == NULL)
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001124 err = PyFile_WriteString("<unknown>", f);
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001125 else {
1126 char* modstr = PyString_AsString(moduleName);
Tim Petersd08e3822003-04-17 15:24:21 +00001127 if (modstr && strcmp(modstr, "exceptions"))
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001128 {
1129 err = PyFile_WriteString(modstr, f);
1130 err += PyFile_WriteString(".", f);
1131 }
1132 }
1133 if (err == 0) {
1134 if (className == NULL)
1135 err = PyFile_WriteString("<unknown>", f);
1136 else
1137 err = PyFile_WriteObject(className, f,
1138 Py_PRINT_RAW);
1139 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001140 }
1141 else
1142 err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
1143 if (err == 0) {
1144 if (v != NULL && v != Py_None) {
Barry Warsaw035574d1997-08-29 22:07:17 +00001145 PyObject *s = PyObject_Str(v);
1146 /* only print colon if the str() of the
1147 object is not the empty string
1148 */
Guido van Rossumd6bf45b1997-09-05 19:11:53 +00001149 if (s == NULL)
1150 err = -1;
1151 else if (!PyString_Check(s) ||
1152 PyString_GET_SIZE(s) != 0)
Barry Warsaw035574d1997-08-29 22:07:17 +00001153 err = PyFile_WriteString(": ", f);
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001154 if (err == 0)
Guido van Rossumd6bf45b1997-09-05 19:11:53 +00001155 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1156 Py_XDECREF(s);
Guido van Rossum262e1241995-02-07 15:30:45 +00001157 }
Guido van Rossum262e1241995-02-07 15:30:45 +00001158 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001159 if (err == 0)
1160 err = PyFile_WriteString("\n", f);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001161 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001162 /* If an error happened here, don't show it.
1163 XXX This is wrong, but too many callers rely on this behavior. */
1164 if (err != 0)
1165 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001166}
1167
Guido van Rossum82598051997-03-05 00:20:32 +00001168PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001169PyRun_String(const char *str, int start, PyObject *globals, PyObject *locals)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001170{
Guido van Rossum82598051997-03-05 00:20:32 +00001171 return run_err_node(PyParser_SimpleParseString(str, start),
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001172 "<string>", globals, locals, NULL);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001173}
1174
Guido van Rossum82598051997-03-05 00:20:32 +00001175PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001176PyRun_File(FILE *fp, const char *filename, int start, PyObject *globals,
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001177 PyObject *locals)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001178{
Tim Peterse8682112000-08-27 20:18:17 +00001179 return PyRun_FileEx(fp, filename, start, globals, locals, 0);
Guido van Rossum0df002c2000-08-27 19:21:52 +00001180}
1181
1182PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001183PyRun_FileEx(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001184 PyObject *locals, int closeit)
Guido van Rossum0df002c2000-08-27 19:21:52 +00001185{
1186 node *n = PyParser_SimpleParseFile(fp, filename, start);
1187 if (closeit)
1188 fclose(fp);
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001189 return run_err_node(n, filename, globals, locals, NULL);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001190}
1191
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001192PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001193PyRun_StringFlags(const char *str, int start, PyObject *globals, PyObject *locals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001194 PyCompilerFlags *flags)
1195{
Guido van Rossuma1b3a472001-07-16 16:51:33 +00001196 return run_err_node(PyParser_SimpleParseStringFlags(
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001197 str, start, PARSER_FLAGS(flags)),
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001198 "<string>", globals, locals, flags);
1199}
1200
1201PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001202PyRun_FileFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001203 PyObject *locals, PyCompilerFlags *flags)
1204{
1205 return PyRun_FileExFlags(fp, filename, start, globals, locals, 0,
Tim Petersd08e3822003-04-17 15:24:21 +00001206 flags);
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001207}
1208
1209PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001210PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001211 PyObject *locals, int closeit, PyCompilerFlags *flags)
1212{
Tim Petersfe2127d2001-07-16 05:37:24 +00001213 node *n = PyParser_SimpleParseFileFlags(fp, filename, start,
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001214 PARSER_FLAGS(flags));
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001215 if (closeit)
1216 fclose(fp);
1217 return run_err_node(n, filename, globals, locals, flags);
1218}
1219
Guido van Rossum82598051997-03-05 00:20:32 +00001220static PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001221run_err_node(node *n, const char *filename, PyObject *globals, PyObject *locals,
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001222 PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001223{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001224 if (n == NULL)
1225 return NULL;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001226 return run_node(n, filename, globals, locals, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001227}
1228
Guido van Rossum82598051997-03-05 00:20:32 +00001229static PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001230run_node(node *n, const char *filename, PyObject *globals, PyObject *locals,
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001231 PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001232{
Guido van Rossum82598051997-03-05 00:20:32 +00001233 PyCodeObject *co;
1234 PyObject *v;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001235 co = PyNode_CompileFlags(n, filename, flags);
Guido van Rossum82598051997-03-05 00:20:32 +00001236 PyNode_Free(n);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001237 if (co == NULL)
1238 return NULL;
Guido van Rossum82598051997-03-05 00:20:32 +00001239 v = PyEval_EvalCode(co, globals, locals);
1240 Py_DECREF(co);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001241 return v;
1242}
1243
Guido van Rossum82598051997-03-05 00:20:32 +00001244static PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001245run_pyc_file(FILE *fp, const char *filename, PyObject *globals, PyObject *locals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001246 PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001247{
Guido van Rossum82598051997-03-05 00:20:32 +00001248 PyCodeObject *co;
1249 PyObject *v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001250 long magic;
Fred Drakee8de31c2000-08-31 05:38:39 +00001251 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001252
Guido van Rossum82598051997-03-05 00:20:32 +00001253 magic = PyMarshal_ReadLongFromFile(fp);
1254 if (magic != PyImport_GetMagicNumber()) {
1255 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001256 "Bad magic number in .pyc file");
1257 return NULL;
1258 }
Guido van Rossum82598051997-03-05 00:20:32 +00001259 (void) PyMarshal_ReadLongFromFile(fp);
Tim Petersd9b9ac82001-01-28 00:27:39 +00001260 v = PyMarshal_ReadLastObjectFromFile(fp);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001261 fclose(fp);
Guido van Rossum82598051997-03-05 00:20:32 +00001262 if (v == NULL || !PyCode_Check(v)) {
1263 Py_XDECREF(v);
1264 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001265 "Bad code object in .pyc file");
1266 return NULL;
1267 }
Guido van Rossum82598051997-03-05 00:20:32 +00001268 co = (PyCodeObject *)v;
1269 v = PyEval_EvalCode(co, globals, locals);
Jeremy Hyltonb857ba22001-08-10 21:41:33 +00001270 if (v && flags)
1271 flags->cf_flags |= (co->co_flags & PyCF_MASK);
Guido van Rossum82598051997-03-05 00:20:32 +00001272 Py_DECREF(co);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001273 return v;
1274}
1275
Guido van Rossum82598051997-03-05 00:20:32 +00001276PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001277Py_CompileString(const char *str, const char *filename, int start)
Guido van Rossum5b722181993-03-30 17:46:03 +00001278{
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001279 return Py_CompileStringFlags(str, filename, start, NULL);
1280}
1281
1282PyObject *
Tim Petersd08e3822003-04-17 15:24:21 +00001283Py_CompileStringFlags(const char *str, const char *filename, int start,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001284 PyCompilerFlags *flags)
1285{
Guido van Rossum5b722181993-03-30 17:46:03 +00001286 node *n;
Guido van Rossum82598051997-03-05 00:20:32 +00001287 PyCodeObject *co;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001288
1289 n = PyParser_SimpleParseStringFlagsFilename(str, filename, start,
1290 PARSER_FLAGS(flags));
Guido van Rossuma110aa61994-08-29 12:50:44 +00001291 if (n == NULL)
Guido van Rossum5b722181993-03-30 17:46:03 +00001292 return NULL;
Jeremy Hylton673a4fd2001-03-26 19:53:38 +00001293 co = PyNode_CompileFlags(n, filename, flags);
Guido van Rossum82598051997-03-05 00:20:32 +00001294 PyNode_Free(n);
1295 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001296}
1297
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001298struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001299Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001300{
1301 node *n;
1302 struct symtable *st;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001303 n = PyParser_SimpleParseStringFlagsFilename(str, filename,
1304 start, 0);
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001305 if (n == NULL)
1306 return NULL;
1307 st = PyNode_CompileSymtable(n, filename);
1308 PyNode_Free(n);
1309 return st;
1310}
1311
Guido van Rossuma110aa61994-08-29 12:50:44 +00001312/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001313
Guido van Rossuma110aa61994-08-29 12:50:44 +00001314node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001315PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001316{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001317 node *n;
1318 perrdetail err;
Tim Petersfe2127d2001-07-16 05:37:24 +00001319 n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar, start,
1320 (char *)0, (char *)0, &err, flags);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001321 if (n == NULL)
1322 err_input(&err);
1323 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001324}
1325
Tim Petersfe2127d2001-07-16 05:37:24 +00001326node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001327PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
Tim Petersfe2127d2001-07-16 05:37:24 +00001328{
1329 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
1330}
1331
Guido van Rossuma110aa61994-08-29 12:50:44 +00001332/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001333
Guido van Rossuma110aa61994-08-29 12:50:44 +00001334node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001335PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001336{
1337 node *n;
1338 perrdetail err;
1339 n = PyParser_ParseStringFlags(str, &_PyParser_Grammar, start, &err,
1340 flags);
1341 if (n == NULL)
1342 err_input(&err);
1343 return n;
1344}
1345
1346node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001347PyParser_SimpleParseString(const char *str, int start)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001348{
Tim Petersfe2127d2001-07-16 05:37:24 +00001349 return PyParser_SimpleParseStringFlags(str, start, 0);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001350}
1351
Thomas Heller6b17abf2002-07-09 09:23:27 +00001352node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001353PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Thomas Heller6b17abf2002-07-09 09:23:27 +00001354 int start, int flags)
1355{
1356 node *n;
1357 perrdetail err;
1358
Tim Petersd08e3822003-04-17 15:24:21 +00001359 n = PyParser_ParseStringFlagsFilename(str, filename,
Thomas Heller6b17abf2002-07-09 09:23:27 +00001360 &_PyParser_Grammar,
1361 start, &err, flags);
1362 if (n == NULL)
1363 err_input(&err);
1364 return n;
1365}
1366
1367node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001368PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001369{
1370 return PyParser_SimpleParseStringFlagsFilename(str, filename,
1371 start, 0);
1372}
1373
Guido van Rossum66ebd912003-04-17 16:02:26 +00001374/* May want to move a more generalized form of this to parsetok.c or
1375 even parser modules. */
1376
1377void
1378PyParser_SetError(perrdetail *err)
1379{
1380 err_input(err);
1381}
1382
Guido van Rossuma110aa61994-08-29 12:50:44 +00001383/* Set the error appropriate to the given input error code (see errcode.h) */
1384
1385static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001386err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001387{
Fred Drake85f36392000-07-11 17:53:00 +00001388 PyObject *v, *w, *errtype;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001389 PyObject* u = NULL;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001390 char *msg = NULL;
Fred Drake85f36392000-07-11 17:53:00 +00001391 errtype = PyExc_SyntaxError;
Guido van Rossum82598051997-03-05 00:20:32 +00001392 v = Py_BuildValue("(ziiz)", err->filename,
Guido van Rossuma110aa61994-08-29 12:50:44 +00001393 err->lineno, err->offset, err->text);
1394 if (err->text != NULL) {
Guido van Rossumb18618d2000-05-03 23:44:39 +00001395 PyMem_DEL(err->text);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001396 err->text = NULL;
1397 }
1398 switch (err->error) {
1399 case E_SYNTAX:
Fred Drake85f36392000-07-11 17:53:00 +00001400 errtype = PyExc_IndentationError;
1401 if (err->expected == INDENT)
1402 msg = "expected an indented block";
1403 else if (err->token == INDENT)
1404 msg = "unexpected indent";
1405 else if (err->token == DEDENT)
1406 msg = "unexpected unindent";
1407 else {
1408 errtype = PyExc_SyntaxError;
1409 msg = "invalid syntax";
1410 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001411 break;
1412 case E_TOKEN:
1413 msg = "invalid token";
Guido van Rossuma110aa61994-08-29 12:50:44 +00001414 break;
Skip Montanaro118ec702002-08-15 01:20:16 +00001415 case E_EOFS:
1416 msg = "EOF while scanning triple-quoted string";
1417 break;
1418 case E_EOLS:
1419 msg = "EOL while scanning single-quoted string";
1420 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001421 case E_INTR:
Guido van Rossum82598051997-03-05 00:20:32 +00001422 PyErr_SetNone(PyExc_KeyboardInterrupt);
Barry Warsawc80baa31999-01-27 16:39:40 +00001423 Py_XDECREF(v);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001424 return;
1425 case E_NOMEM:
Guido van Rossum82598051997-03-05 00:20:32 +00001426 PyErr_NoMemory();
Barry Warsawc80baa31999-01-27 16:39:40 +00001427 Py_XDECREF(v);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001428 return;
1429 case E_EOF:
1430 msg = "unexpected EOF while parsing";
1431 break;
Fred Drake85f36392000-07-11 17:53:00 +00001432 case E_TABSPACE:
1433 errtype = PyExc_TabError;
Guido van Rossum560e8ad1998-04-10 19:43:42 +00001434 msg = "inconsistent use of tabs and spaces in indentation";
1435 break;
Jeremy Hylton94988062000-06-20 19:10:44 +00001436 case E_OVERFLOW:
1437 msg = "expression too long";
1438 break;
Fred Drake85f36392000-07-11 17:53:00 +00001439 case E_DEDENT:
1440 errtype = PyExc_IndentationError;
1441 msg = "unindent does not match any outer indentation level";
1442 break;
1443 case E_TOODEEP:
1444 errtype = PyExc_IndentationError;
1445 msg = "too many levels of indentation";
1446 break;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001447 case E_DECODE: { /* XXX */
1448 PyThreadState* tstate = PyThreadState_Get();
1449 PyObject* value = tstate->curexc_value;
1450 if (value != NULL) {
1451 u = PyObject_Repr(value);
1452 if (u != NULL) {
1453 msg = PyString_AsString(u);
1454 break;
1455 }
1456 }
1457 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001458 default:
1459 fprintf(stderr, "error=%d\n", err->error);
1460 msg = "unknown parsing error";
1461 break;
1462 }
Guido van Rossum82598051997-03-05 00:20:32 +00001463 w = Py_BuildValue("(sO)", msg, v);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001464 Py_XDECREF(u);
Guido van Rossum41318302001-03-23 04:01:07 +00001465 Py_XDECREF(v);
Fred Drake85f36392000-07-11 17:53:00 +00001466 PyErr_SetObject(errtype, w);
Guido van Rossum82598051997-03-05 00:20:32 +00001467 Py_XDECREF(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001468}
1469
1470/* Print fatal error message and abort */
1471
1472void
Tim Peters7c321a82002-07-09 02:57:01 +00001473Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001474{
Guido van Rossum83dd6c31994-09-29 09:38:33 +00001475 fprintf(stderr, "Fatal Python error: %s\n", msg);
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001476#ifdef MS_WINDOWS
Guido van Rossum23c94461997-05-22 20:21:30 +00001477 OutputDebugString("Fatal Python error: ");
Guido van Rossuma44823b1995-03-14 15:01:17 +00001478 OutputDebugString(msg);
1479 OutputDebugString("\n");
Guido van Rossum0ba35361998-08-13 13:33:16 +00001480#ifdef _DEBUG
1481 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00001482#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001483#endif /* MS_WINDOWS */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001484 abort();
1485}
1486
1487/* Clean up and exit */
1488
Guido van Rossuma110aa61994-08-29 12:50:44 +00001489#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00001490#include "pythread.h"
Guido van Rossum82598051997-03-05 00:20:32 +00001491int _PyThread_Started = 0; /* Set by threadmodule.c and maybe others */
Guido van Rossumf9f2e821992-08-17 08:59:08 +00001492#endif
1493
Guido van Rossum2dcfc961998-10-01 16:01:57 +00001494#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001495static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00001496static int nexitfuncs = 0;
1497
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001498int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00001499{
1500 if (nexitfuncs >= NEXITFUNCS)
1501 return -1;
1502 exitfuncs[nexitfuncs++] = func;
1503 return 0;
1504}
1505
Guido van Rossumcc283f51997-08-05 02:22:03 +00001506static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001507call_sys_exitfunc(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001508{
Guido van Rossum82598051997-03-05 00:20:32 +00001509 PyObject *exitfunc = PySys_GetObject("exitfunc");
Guido van Rossum59bff391992-09-03 20:28:00 +00001510
1511 if (exitfunc) {
Fred Drake6a12d8d2001-03-23 17:34:02 +00001512 PyObject *res;
Guido van Rossum82598051997-03-05 00:20:32 +00001513 Py_INCREF(exitfunc);
1514 PySys_SetObject("exitfunc", (PyObject *)NULL);
1515 res = PyEval_CallObject(exitfunc, (PyObject *)NULL);
Guido van Rossum59bff391992-09-03 20:28:00 +00001516 if (res == NULL) {
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001517 if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
1518 PySys_WriteStderr("Error in sys.exitfunc:\n");
1519 }
Guido van Rossum82598051997-03-05 00:20:32 +00001520 PyErr_Print();
Guido van Rossum59bff391992-09-03 20:28:00 +00001521 }
Guido van Rossum82598051997-03-05 00:20:32 +00001522 Py_DECREF(exitfunc);
Guido van Rossum59bff391992-09-03 20:28:00 +00001523 }
1524
Guido van Rossum0829c751998-02-28 04:31:39 +00001525 if (Py_FlushLine())
1526 PyErr_Clear();
Guido van Rossumcc283f51997-08-05 02:22:03 +00001527}
Guido van Rossum1662dd51994-09-07 14:38:28 +00001528
Guido van Rossumcc283f51997-08-05 02:22:03 +00001529static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001530call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00001531{
Guido van Rossum1662dd51994-09-07 14:38:28 +00001532 while (nexitfuncs > 0)
1533 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00001534
1535 fflush(stdout);
1536 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001537}
1538
1539void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001540Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001541{
Guido van Rossumcc283f51997-08-05 02:22:03 +00001542 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001543
Jack Jansen66a89771995-10-27 13:22:14 +00001544#ifdef macintosh
1545 PyMac_Exit(sts);
1546#else
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001547 exit(sts);
Jack Jansen66a89771995-10-27 13:22:14 +00001548#endif
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001549}
1550
Guido van Rossumf1dc5661993-07-05 10:31:29 +00001551static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001552initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001553{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001554#ifdef HAVE_SIGNAL_H
1555#ifdef SIGPIPE
1556 signal(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001557#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00001558#ifdef SIGXFZ
1559 signal(SIGXFZ, SIG_IGN);
1560#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00001561#ifdef SIGXFSZ
1562 signal(SIGXFSZ, SIG_IGN);
1563#endif
Guido van Rossuma110aa61994-08-29 12:50:44 +00001564#endif /* HAVE_SIGNAL_H */
Guido van Rossum82598051997-03-05 00:20:32 +00001565 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001566}
1567
Guido van Rossuma110aa61994-08-29 12:50:44 +00001568#ifdef MPW
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001569
1570/* Check for file descriptor connected to interactive device.
1571 Pretend that stdin is always interactive, other files never. */
1572
1573int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001574isatty(int fd)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001575{
1576 return fd == fileno(stdin);
1577}
1578
1579#endif
Guido van Rossum7433b121997-02-14 19:45:36 +00001580
1581/*
1582 * The file descriptor fd is considered ``interactive'' if either
1583 * a) isatty(fd) is TRUE, or
1584 * b) the -i flag was given, and the filename associated with
1585 * the descriptor is NULL or "<stdin>" or "???".
1586 */
1587int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001588Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00001589{
1590 if (isatty((int)fileno(fp)))
1591 return 1;
1592 if (!Py_InteractiveFlag)
1593 return 0;
1594 return (filename == NULL) ||
1595 (strcmp(filename, "<stdin>") == 0) ||
1596 (strcmp(filename, "???") == 0);
1597}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001598
1599
Tim Petersd08e3822003-04-17 15:24:21 +00001600#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001601#if defined(WIN32) && defined(_MSC_VER)
1602
1603/* Stack checking for Microsoft C */
1604
1605#include <malloc.h>
1606#include <excpt.h>
1607
Fred Drakee8de31c2000-08-31 05:38:39 +00001608/*
1609 * Return non-zero when we run out of memory on the stack; zero otherwise.
1610 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001611int
Fred Drake399739f2000-08-31 05:52:44 +00001612PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001613{
1614 __try {
Tim Peters92e4dd82002-10-05 01:47:34 +00001615 /* alloca throws a stack overflow exception if there's
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001616 not enough space left on the stack */
Tim Peters92e4dd82002-10-05 01:47:34 +00001617 alloca(PYOS_STACK_MARGIN * sizeof(void*));
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001618 return 0;
1619 } __except (EXCEPTION_EXECUTE_HANDLER) {
1620 /* just ignore all errors */
1621 }
1622 return 1;
1623}
1624
1625#endif /* WIN32 && _MSC_VER */
1626
1627/* Alternate implementations can be added here... */
1628
1629#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00001630
1631
1632/* Wrappers around sigaction() or signal(). */
1633
1634PyOS_sighandler_t
1635PyOS_getsig(int sig)
1636{
1637#ifdef HAVE_SIGACTION
1638 struct sigaction context;
Barry Warsawafeb2a42001-11-13 23:08:26 +00001639 /* Initialize context.sa_handler to SIG_ERR which makes about as
1640 * much sense as anything else. It should get overwritten if
1641 * sigaction actually succeeds and otherwise we avoid an
1642 * uninitialized memory read.
1643 */
1644 context.sa_handler = SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00001645 sigaction(sig, NULL, &context);
1646 return context.sa_handler;
1647#else
1648 PyOS_sighandler_t handler;
1649 handler = signal(sig, SIG_IGN);
1650 signal(sig, handler);
1651 return handler;
1652#endif
1653}
1654
1655PyOS_sighandler_t
1656PyOS_setsig(int sig, PyOS_sighandler_t handler)
1657{
1658#ifdef HAVE_SIGACTION
1659 struct sigaction context;
1660 PyOS_sighandler_t oldhandler;
Barry Warsawafeb2a42001-11-13 23:08:26 +00001661 /* Initialize context.sa_handler to SIG_ERR which makes about as
1662 * much sense as anything else. It should get overwritten if
1663 * sigaction actually succeeds and otherwise we avoid an
1664 * uninitialized memory read.
1665 */
1666 context.sa_handler = SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00001667 sigaction(sig, NULL, &context);
1668 oldhandler = context.sa_handler;
1669 context.sa_handler = handler;
1670 sigaction(sig, &context, NULL);
1671 return oldhandler;
1672#else
1673 return signal(sig, handler);
1674#endif
1675}