blob: f82de0adbe24bbc2f13ff3f35830bfe8cba4d00d [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) {
255 sys_stream = PySys_GetObject("stdout");
256 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 }
263 Py_XDECREF(sys_stream);
264 Py_XDECREF(sys_isatty);
265
266 sys_stream = PySys_GetObject("stdout");
267 sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
268 if (!sys_isatty)
269 PyErr_Clear();
270 if(sys_isatty && PyObject_IsTrue(sys_isatty)) {
271 if (!PyFile_SetEncoding(sys_stream, codeset))
272 Py_FatalError("Cannot set codeset of stdout");
273 }
274 Py_XDECREF(sys_stream);
275 Py_XDECREF(sys_isatty);
276
277 if (!Py_FileSystemDefaultEncoding)
278 Py_FileSystemDefaultEncoding = codeset;
279 else
280 free(codeset);
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000281 }
282#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000283}
284
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000285#ifdef COUNT_ALLOCS
Tim Petersdbd9ba62000-07-09 03:09:57 +0000286extern void dump_counts(void);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000287#endif
288
Guido van Rossum25ce5661997-08-02 03:10:38 +0000289/* Undo the effect of Py_Initialize().
290
291 Beware: if multiple interpreter and/or thread states exist, these
292 are not wiped out; only the current thread and interpreter state
293 are deleted. But since everything else is deleted, those other
294 interpreter and thread states should no longer be used.
295
296 (XXX We should do better, e.g. wipe out all interpreters and
297 threads.)
298
299 Locking: as above.
300
301*/
302
303void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000304Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000305{
306 PyInterpreterState *interp;
307 PyThreadState *tstate;
308
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000309 if (!initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +0000310 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000311
Tim Peters384fd102001-01-21 03:40:37 +0000312 /* The interpreter is still entirely intact at this point, and the
313 * exit funcs may be relying on that. In particular, if some thread
314 * or exit func is still waiting to do an import, the import machinery
315 * expects Py_IsInitialized() to return true. So don't say the
316 * interpreter is uninitialized until after the exit funcs have run.
317 * Note that Threading.py uses an exit func to do a join on all the
318 * threads created thru it, so this also protects pending imports in
319 * the threads created via Threading.
320 */
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000321 call_sys_exitfunc();
Tim Peters384fd102001-01-21 03:40:37 +0000322 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000323
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000324 /* Get current thread state and interpreter pointer */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000325 tstate = PyThreadState_Get();
326 interp = tstate->interp;
327
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000328 /* Disable signal handling */
329 PyOS_FiniInterrupts();
330
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000331 /* drop module references we saved */
Mark Hammondedd07732003-07-15 23:03:55 +0000332 Py_XDECREF(warnings_module);
333 warnings_module = NULL;
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000334
Guido van Rossume13ddc92003-04-17 17:29:22 +0000335 /* Collect garbage. This may call finalizers; it's nice to call these
336 before all modules are destroyed. */
337 PyGC_Collect();
338
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000339 /* Destroy all modules */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000340 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000341
Guido van Rossume13ddc92003-04-17 17:29:22 +0000342 /* Collect final garbage. This disposes of cycles created by
343 new-style class definitions, for example. */
344 PyGC_Collect();
345
Guido van Rossum1707aad1997-12-08 23:43:45 +0000346 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
347 _PyImport_Fini();
348
349 /* Debugging stuff */
350#ifdef COUNT_ALLOCS
351 dump_counts();
352#endif
353
354#ifdef Py_REF_DEBUG
355 fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
356#endif
357
Tim Peters9cf25ce2003-04-17 15:21:01 +0000358#ifdef Py_TRACE_REFS
359 /* Display all objects still alive -- this can invoke arbitrary
360 * __repr__ overrides, so requires a mostly-intact interpreter.
361 * Alas, a lot of stuff may still be alive now that will be cleaned
362 * up later.
363 */
Tim Peters269b2a62003-04-17 19:52:29 +0000364 if (Py_GETENV("PYTHONDUMPREFS"))
Tim Peters9cf25ce2003-04-17 15:21:01 +0000365 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000366#endif /* Py_TRACE_REFS */
367
Barry Warsaw035574d1997-08-29 22:07:17 +0000368 /* Now we decref the exception classes. After this point nothing
369 can raise an exception. That's okay, because each Fini() method
370 below has been checked to make sure no exceptions are ever
371 raised.
372 */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000373 _PyExc_Fini();
Barry Warsawf242aa02000-05-25 23:09:49 +0000374
Mark Hammond6cb90292003-04-22 11:18:00 +0000375 /* Cleanup auto-thread-state */
376#ifdef WITH_THREAD
377 _PyGILState_Fini();
378#endif /* WITH_THREAD */
379
Guido van Rossumd922fa42003-04-15 14:10:09 +0000380 /* Clear interpreter state */
Barry Warsawf242aa02000-05-25 23:09:49 +0000381 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000382
Guido van Rossumd922fa42003-04-15 14:10:09 +0000383 /* Delete current thread */
Barry Warsawf242aa02000-05-25 23:09:49 +0000384 PyThreadState_Swap(NULL);
385 PyInterpreterState_Delete(interp);
386
Guido van Rossumd922fa42003-04-15 14:10:09 +0000387 /* Sundry finalizers */
Guido van Rossumcc283f51997-08-05 02:22:03 +0000388 PyMethod_Fini();
389 PyFrame_Fini();
390 PyCFunction_Fini();
391 PyTuple_Fini();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000392 PyString_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000393 PyInt_Fini();
394 PyFloat_Fini();
395
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000396#ifdef Py_USING_UNICODE
397 /* Cleanup Unicode implementation */
398 _PyUnicode_Fini();
399#endif
400
Guido van Rossumcc283f51997-08-05 02:22:03 +0000401 /* XXX Still allocated:
402 - various static ad-hoc pointers to interned strings
403 - int and float free list blocks
404 - whatever various modules and libraries allocate
405 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000406
407 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000408
Tim Peters269b2a62003-04-17 19:52:29 +0000409#ifdef Py_TRACE_REFS
410 /* Display addresses (& refcnts) of all objects still alive.
411 * An address can be used to find the repr of the object, printed
412 * above by _Py_PrintReferences.
413 */
414 if (Py_GETENV("PYTHONDUMPREFS"))
415 _Py_PrintReferenceAddresses(stderr);
416#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000417#ifdef PYMALLOC_DEBUG
418 if (Py_GETENV("PYTHONMALLOCSTATS"))
419 _PyObject_DebugMallocStats();
420#endif
421
Guido van Rossumcc283f51997-08-05 02:22:03 +0000422 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000423}
424
425/* Create and initialize a new interpreter and thread, and return the
426 new thread. This requires that Py_Initialize() has been called
427 first.
428
429 Unsuccessful initialization yields a NULL pointer. Note that *no*
430 exception information is available even in this case -- the
431 exception information is held in the thread, and there is no
432 thread.
433
434 Locking: as above.
435
436*/
437
438PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000439Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000440{
441 PyInterpreterState *interp;
442 PyThreadState *tstate, *save_tstate;
443 PyObject *bimod, *sysmod;
444
445 if (!initialized)
446 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
447
448 interp = PyInterpreterState_New();
449 if (interp == NULL)
450 return NULL;
451
452 tstate = PyThreadState_New(interp);
453 if (tstate == NULL) {
454 PyInterpreterState_Delete(interp);
455 return NULL;
456 }
457
458 save_tstate = PyThreadState_Swap(tstate);
459
460 /* XXX The following is lax in error checking */
461
462 interp->modules = PyDict_New();
463
464 bimod = _PyImport_FindExtension("__builtin__", "__builtin__");
465 if (bimod != NULL) {
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000466 interp->builtins = PyModule_GetDict(bimod);
467 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000468 }
469 sysmod = _PyImport_FindExtension("sys", "sys");
470 if (bimod != NULL && sysmod != NULL) {
471 interp->sysdict = PyModule_GetDict(sysmod);
472 Py_INCREF(interp->sysdict);
473 PySys_SetPath(Py_GetPath());
474 PyDict_SetItemString(interp->sysdict, "modules",
475 interp->modules);
Martin v. Löwisd7ceb222003-01-22 09:00:38 +0000476 _PyImportHooks_Init();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000477 initmain();
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000478 if (!Py_NoSiteFlag)
479 initsite();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000480 }
481
482 if (!PyErr_Occurred())
483 return tstate;
484
485 /* Oops, it didn't work. Undo it all. */
486
487 PyErr_Print();
488 PyThreadState_Clear(tstate);
489 PyThreadState_Swap(save_tstate);
490 PyThreadState_Delete(tstate);
491 PyInterpreterState_Delete(interp);
492
493 return NULL;
494}
495
496/* Delete an interpreter and its last thread. This requires that the
497 given thread state is current, that the thread has no remaining
498 frames, and that it is its interpreter's only remaining thread.
499 It is a fatal error to violate these constraints.
500
501 (Py_Finalize() doesn't have these constraints -- it zaps
502 everything, regardless.)
503
504 Locking: as above.
505
506*/
507
508void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000509Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000510{
511 PyInterpreterState *interp = tstate->interp;
512
513 if (tstate != PyThreadState_Get())
514 Py_FatalError("Py_EndInterpreter: thread is not current");
515 if (tstate->frame != NULL)
516 Py_FatalError("Py_EndInterpreter: thread still has a frame");
517 if (tstate != interp->tstate_head || tstate->next != NULL)
518 Py_FatalError("Py_EndInterpreter: not the last thread");
519
520 PyImport_Cleanup();
521 PyInterpreterState_Clear(interp);
522 PyThreadState_Swap(NULL);
523 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000524}
525
526static char *progname = "python";
527
528void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000529Py_SetProgramName(char *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000530{
531 if (pn && *pn)
532 progname = pn;
533}
534
535char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000536Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000537{
538 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000539}
540
Guido van Rossuma61691e1998-02-06 22:27:24 +0000541static char *default_home = NULL;
542
543void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000544Py_SetPythonHome(char *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000545{
546 default_home = home;
547}
548
549char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000550Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000551{
552 char *home = default_home;
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000553 if (home == NULL && !Py_IgnoreEnvironmentFlag)
554 home = Py_GETENV("PYTHONHOME");
Guido van Rossuma61691e1998-02-06 22:27:24 +0000555 return home;
556}
557
Guido van Rossum6135a871995-01-09 17:53:26 +0000558/* Create __main__ module */
559
560static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000561initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000562{
Guido van Rossum82598051997-03-05 00:20:32 +0000563 PyObject *m, *d;
564 m = PyImport_AddModule("__main__");
Guido van Rossum6135a871995-01-09 17:53:26 +0000565 if (m == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +0000566 Py_FatalError("can't create __main__ module");
567 d = PyModule_GetDict(m);
568 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
Guido van Rossum858cb731997-11-19 16:15:37 +0000569 PyObject *bimod = PyImport_ImportModule("__builtin__");
570 if (bimod == NULL ||
571 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
Guido van Rossum82598051997-03-05 00:20:32 +0000572 Py_FatalError("can't add __builtins__ to __main__");
Barry Warsaw3d05b1a1999-01-29 21:30:22 +0000573 Py_DECREF(bimod);
Guido van Rossum6135a871995-01-09 17:53:26 +0000574 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000575}
576
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000577/* Import the site module (not into __main__ though) */
578
579static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000580initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000581{
582 PyObject *m, *f;
583 m = PyImport_ImportModule("site");
584 if (m == NULL) {
585 f = PySys_GetObject("stderr");
586 if (Py_VerboseFlag) {
587 PyFile_WriteString(
588 "'import site' failed; traceback:\n", f);
589 PyErr_Print();
590 }
591 else {
592 PyFile_WriteString(
593 "'import site' failed; use -v for traceback\n", f);
594 PyErr_Clear();
595 }
596 }
597 else {
598 Py_DECREF(m);
599 }
600}
601
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000602/* Parse input from a file and execute it */
603
604int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000605PyRun_AnyFile(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000606{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000607 return PyRun_AnyFileExFlags(fp, filename, 0, NULL);
608}
609
610int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000611PyRun_AnyFileFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000612{
613 return PyRun_AnyFileExFlags(fp, filename, 0, flags);
Guido van Rossum0df002c2000-08-27 19:21:52 +0000614}
615
616int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000617PyRun_AnyFileEx(FILE *fp, const char *filename, int closeit)
Guido van Rossum0df002c2000-08-27 19:21:52 +0000618{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000619 return PyRun_AnyFileExFlags(fp, filename, closeit, NULL);
620}
621
622int
Tim Petersd08e3822003-04-17 15:24:21 +0000623PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000624 PyCompilerFlags *flags)
625{
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000626 if (filename == NULL)
627 filename = "???";
Guido van Rossum0df002c2000-08-27 19:21:52 +0000628 if (Py_FdIsInteractive(fp, filename)) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000629 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
Guido van Rossum0df002c2000-08-27 19:21:52 +0000630 if (closeit)
631 fclose(fp);
632 return err;
633 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000634 else
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000635 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000636}
637
638int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000639PyRun_InteractiveLoop(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000640{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000641 return PyRun_InteractiveLoopFlags(fp, filename, NULL);
642}
643
644int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000645PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000646{
Guido van Rossum82598051997-03-05 00:20:32 +0000647 PyObject *v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000648 int ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000649 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000650
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000651 if (flags == NULL) {
652 flags = &local_flags;
Tim Peters5ba58662001-07-16 02:29:45 +0000653 local_flags.cf_flags = 0;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000654 }
Guido van Rossum82598051997-03-05 00:20:32 +0000655 v = PySys_GetObject("ps1");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000656 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000657 PySys_SetObject("ps1", v = PyString_FromString(">>> "));
658 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000659 }
Guido van Rossum82598051997-03-05 00:20:32 +0000660 v = PySys_GetObject("ps2");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000661 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000662 PySys_SetObject("ps2", v = PyString_FromString("... "));
663 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000664 }
665 for (;;) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000666 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
Guido van Rossumaae0d321996-05-22 16:35:33 +0000667#ifdef Py_REF_DEBUG
Guido van Rossum6f9e4331995-03-29 16:57:48 +0000668 fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000669#endif
670 if (ret == E_EOF)
671 return 0;
672 /*
673 if (ret == E_NOMEM)
674 return -1;
675 */
676 }
677}
678
679int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000680PyRun_InteractiveOne(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000681{
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000682 return PyRun_InteractiveOneFlags(fp, filename, NULL);
683}
684
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000685/* compute parser flags based on compiler flags */
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000686#define PARSER_FLAGS(flags) \
Guido van Rossum4b499dd32003-02-13 22:07:59 +0000687 (((flags) && (flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
688 PyPARSE_DONT_IMPLY_DEDENT : 0)
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000689
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000690int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000691PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000692{
Guido van Rossum82598051997-03-05 00:20:32 +0000693 PyObject *m, *d, *v, *w;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000694 node *n;
Guido van Rossuma110aa61994-08-29 12:50:44 +0000695 perrdetail err;
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000696 char *ps1 = "", *ps2 = "";
Tim Petersfe2127d2001-07-16 05:37:24 +0000697
Guido van Rossum82598051997-03-05 00:20:32 +0000698 v = PySys_GetObject("ps1");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000699 if (v != NULL) {
700 v = PyObject_Str(v);
701 if (v == NULL)
702 PyErr_Clear();
703 else if (PyString_Check(v))
704 ps1 = PyString_AsString(v);
705 }
Guido van Rossum82598051997-03-05 00:20:32 +0000706 w = PySys_GetObject("ps2");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000707 if (w != NULL) {
708 w = PyObject_Str(w);
709 if (w == NULL)
710 PyErr_Clear();
711 else if (PyString_Check(w))
712 ps2 = PyString_AsString(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000713 }
Tim Petersfe2127d2001-07-16 05:37:24 +0000714 n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar,
715 Py_single_input, ps1, ps2, &err,
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000716 PARSER_FLAGS(flags));
Guido van Rossum82598051997-03-05 00:20:32 +0000717 Py_XDECREF(v);
718 Py_XDECREF(w);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000719 if (n == NULL) {
720 if (err.error == E_EOF) {
721 if (err.text)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000722 PyMem_DEL(err.text);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000723 return E_EOF;
724 }
725 err_input(&err);
Guido van Rossum82598051997-03-05 00:20:32 +0000726 PyErr_Print();
Guido van Rossuma110aa61994-08-29 12:50:44 +0000727 return err.error;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000728 }
Guido van Rossum82598051997-03-05 00:20:32 +0000729 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000730 if (m == NULL)
731 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000732 d = PyModule_GetDict(m);
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000733 v = run_node(n, filename, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000734 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000735 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000736 return -1;
737 }
Guido van Rossum82598051997-03-05 00:20:32 +0000738 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000739 if (Py_FlushLine())
740 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000741 return 0;
742}
743
744int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000745PyRun_SimpleFile(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000746{
Guido van Rossum0df002c2000-08-27 19:21:52 +0000747 return PyRun_SimpleFileEx(fp, filename, 0);
748}
749
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000750/* Check whether a file maybe a pyc file: Look at the extension,
751 the file type, and, if we may close it, at the first few bytes. */
752
753static int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000754maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000755{
756 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
757 return 1;
758
759#ifdef macintosh
760 /* On a mac, we also assume a pyc file for types 'PYC ' and 'APPL' */
Jack Jansen72f3b7a2002-12-13 15:23:10 +0000761 if (PyMac_getfiletype((char *)filename) == 'PYC '
762 || PyMac_getfiletype((char *)filename) == 'APPL')
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000763 return 1;
764#endif /* macintosh */
765
766 /* Only look into the file if we are allowed to close it, since
767 it then should also be seekable. */
768 if (closeit) {
769 /* Read only two bytes of the magic. If the file was opened in
770 text mode, the bytes 3 and 4 of the magic (\r\n) might not
771 be read as they are on disk. */
772 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
773 unsigned char buf[2];
Tim Peters3e876562001-02-11 04:35:39 +0000774 /* Mess: In case of -x, the stream is NOT at its start now,
775 and ungetc() was used to push back the first newline,
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000776 which makes the current stream position formally undefined,
777 and a x-platform nightmare.
778 Unfortunately, we have no direct way to know whether -x
779 was specified. So we use a terrible hack: if the current
780 stream position is not 0, we assume -x was specified, and
781 give up. Bug 132850 on SourceForge spells out the
782 hopelessness of trying anything else (fseek and ftell
783 don't work predictably x-platform for text-mode files).
Tim Peters3e876562001-02-11 04:35:39 +0000784 */
Tim Peters3e876562001-02-11 04:35:39 +0000785 int ispyc = 0;
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000786 if (ftell(fp) == 0) {
787 if (fread(buf, 1, 2, fp) == 2 &&
Tim Petersd08e3822003-04-17 15:24:21 +0000788 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000789 ispyc = 1;
790 rewind(fp);
791 }
Tim Peters3e876562001-02-11 04:35:39 +0000792 return ispyc;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000793 }
794 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +0000795}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000796
Guido van Rossum0df002c2000-08-27 19:21:52 +0000797int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000798PyRun_SimpleFileEx(FILE *fp, const char *filename, int closeit)
Guido van Rossum0df002c2000-08-27 19:21:52 +0000799{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000800 return PyRun_SimpleFileExFlags(fp, filename, closeit, NULL);
801}
802
803int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000804PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000805 PyCompilerFlags *flags)
806{
Guido van Rossum82598051997-03-05 00:20:32 +0000807 PyObject *m, *d, *v;
Martin v. Löwis95292d62002-12-11 14:04:59 +0000808 const char *ext;
Guido van Rossumfdef2711994-09-14 13:31:04 +0000809
Guido van Rossum82598051997-03-05 00:20:32 +0000810 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000811 if (m == NULL)
812 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000813 d = PyModule_GetDict(m);
Fred Drake8ed02042002-10-17 21:24:58 +0000814 if (PyDict_GetItemString(d, "__file__") == NULL) {
815 PyObject *f = PyString_FromString(filename);
816 if (f == NULL)
817 return -1;
818 if (PyDict_SetItemString(d, "__file__", f) < 0) {
819 Py_DECREF(f);
820 return -1;
821 }
822 Py_DECREF(f);
823 }
Guido van Rossumfdef2711994-09-14 13:31:04 +0000824 ext = filename + strlen(filename) - 4;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000825 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Guido van Rossumfdef2711994-09-14 13:31:04 +0000826 /* Try to run a pyc file. First, re-open in binary */
Guido van Rossum0df002c2000-08-27 19:21:52 +0000827 if (closeit)
828 fclose(fp);
Fred Drake8ed02042002-10-17 21:24:58 +0000829 if ((fp = fopen(filename, "rb")) == NULL) {
Guido van Rossumfdef2711994-09-14 13:31:04 +0000830 fprintf(stderr, "python: Can't reopen .pyc file\n");
831 return -1;
832 }
Guido van Rossum2a7f58d1997-04-02 05:28:38 +0000833 /* Turn on optimization if a .pyo file is given */
834 if (strcmp(ext, ".pyo") == 0)
835 Py_OptimizeFlag = 1;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000836 v = run_pyc_file(fp, filename, d, d, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000837 } else {
Tim Petersd08e3822003-04-17 15:24:21 +0000838 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000839 closeit, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000840 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000841 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000842 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000843 return -1;
844 }
Guido van Rossum82598051997-03-05 00:20:32 +0000845 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000846 if (Py_FlushLine())
847 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000848 return 0;
849}
850
851int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000852PyRun_SimpleString(const char *command)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000853{
Guido van Rossum393661d2001-08-31 17:40:15 +0000854 return PyRun_SimpleStringFlags(command, NULL);
855}
856
857int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000858PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +0000859{
Guido van Rossum82598051997-03-05 00:20:32 +0000860 PyObject *m, *d, *v;
861 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000862 if (m == NULL)
863 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000864 d = PyModule_GetDict(m);
Guido van Rossum393661d2001-08-31 17:40:15 +0000865 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000866 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000867 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000868 return -1;
869 }
Guido van Rossum82598051997-03-05 00:20:32 +0000870 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000871 if (Py_FlushLine())
872 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000873 return 0;
874}
875
Barry Warsaw035574d1997-08-29 22:07:17 +0000876static int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000877parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
878 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +0000879{
880 long hold;
881 PyObject *v;
882
883 /* old style errors */
884 if (PyTuple_Check(err))
Neal Norwitz78293352002-04-01 01:41:20 +0000885 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
886 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +0000887
888 /* new style errors. `err' is an instance */
889
890 if (! (v = PyObject_GetAttrString(err, "msg")))
891 goto finally;
892 *message = v;
893
894 if (!(v = PyObject_GetAttrString(err, "filename")))
895 goto finally;
896 if (v == Py_None)
897 *filename = NULL;
898 else if (! (*filename = PyString_AsString(v)))
899 goto finally;
900
901 Py_DECREF(v);
902 if (!(v = PyObject_GetAttrString(err, "lineno")))
903 goto finally;
904 hold = PyInt_AsLong(v);
905 Py_DECREF(v);
906 v = NULL;
907 if (hold < 0 && PyErr_Occurred())
908 goto finally;
909 *lineno = (int)hold;
910
911 if (!(v = PyObject_GetAttrString(err, "offset")))
912 goto finally;
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000913 if (v == Py_None) {
914 *offset = -1;
915 Py_DECREF(v);
916 v = NULL;
917 } else {
918 hold = PyInt_AsLong(v);
919 Py_DECREF(v);
920 v = NULL;
921 if (hold < 0 && PyErr_Occurred())
922 goto finally;
923 *offset = (int)hold;
924 }
Barry Warsaw035574d1997-08-29 22:07:17 +0000925
926 if (!(v = PyObject_GetAttrString(err, "text")))
927 goto finally;
928 if (v == Py_None)
929 *text = NULL;
930 else if (! (*text = PyString_AsString(v)))
931 goto finally;
932 Py_DECREF(v);
933 return 1;
934
935finally:
936 Py_XDECREF(v);
937 return 0;
938}
939
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000940void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000941PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000942{
Guido van Rossuma61691e1998-02-06 22:27:24 +0000943 PyErr_PrintEx(1);
944}
945
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000946static void
Martin v. Löwis95292d62002-12-11 14:04:59 +0000947print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000948{
949 char *nl;
950 if (offset >= 0) {
951 if (offset > 0 && offset == (int)strlen(text))
952 offset--;
953 for (;;) {
954 nl = strchr(text, '\n');
955 if (nl == NULL || nl-text >= offset)
956 break;
957 offset -= (nl+1-text);
958 text = nl+1;
959 }
960 while (*text == ' ' || *text == '\t') {
961 text++;
962 offset--;
963 }
964 }
965 PyFile_WriteString(" ", f);
966 PyFile_WriteString(text, f);
967 if (*text == '\0' || text[strlen(text)-1] != '\n')
968 PyFile_WriteString("\n", f);
969 if (offset == -1)
970 return;
971 PyFile_WriteString(" ", f);
972 offset--;
973 while (offset > 0) {
974 PyFile_WriteString(" ", f);
975 offset--;
976 }
977 PyFile_WriteString("^\n", f);
978}
979
Guido van Rossum66e8e862001-03-23 17:54:43 +0000980static void
981handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000982{
Guido van Rossum66e8e862001-03-23 17:54:43 +0000983 PyObject *exception, *value, *tb;
Tim Peterscf615b52003-04-19 18:47:02 +0000984 int exitcode = 0;
985
Guido van Rossum66e8e862001-03-23 17:54:43 +0000986 PyErr_Fetch(&exception, &value, &tb);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000987 if (Py_FlushLine())
988 PyErr_Clear();
989 fflush(stdout);
990 if (value == NULL || value == Py_None)
Tim Peterscf615b52003-04-19 18:47:02 +0000991 goto done;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000992 if (PyInstance_Check(value)) {
993 /* The error code should be in the `code' attribute. */
994 PyObject *code = PyObject_GetAttrString(value, "code");
995 if (code) {
996 Py_DECREF(value);
997 value = code;
998 if (value == Py_None)
Tim Peterscf615b52003-04-19 18:47:02 +0000999 goto done;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001000 }
1001 /* If we failed to dig out the 'code' attribute,
1002 just let the else clause below print the error. */
1003 }
1004 if (PyInt_Check(value))
Tim Peterscf615b52003-04-19 18:47:02 +00001005 exitcode = (int)PyInt_AsLong(value);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001006 else {
1007 PyObject_Print(value, stderr, Py_PRINT_RAW);
1008 PySys_WriteStderr("\n");
Tim Peterscf615b52003-04-19 18:47:02 +00001009 exitcode = 1;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001010 }
Tim Peterscf615b52003-04-19 18:47:02 +00001011 done:
1012 /* Restore and clear the exception info, in order to properly decref
1013 * the exception, value, and traceback. If we just exit instead,
1014 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1015 * some finalizers from running.
1016 */
1017 PyErr_Restore(exception, value, tb);
1018 PyErr_Clear();
1019 Py_Exit(exitcode);
1020 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001021}
1022
1023void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001024PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001025{
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001026 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001027
1028 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1029 handle_system_exit();
1030 }
Guido van Rossum82598051997-03-05 00:20:32 +00001031 PyErr_Fetch(&exception, &v, &tb);
Barry Warsaw035574d1997-08-29 22:07:17 +00001032 PyErr_NormalizeException(&exception, &v, &tb);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001033 if (exception == NULL)
Guido van Rossum296b4751997-05-23 00:19:20 +00001034 return;
Guido van Rossuma61691e1998-02-06 22:27:24 +00001035 if (set_sys_last_vars) {
1036 PySys_SetObject("last_type", exception);
1037 PySys_SetObject("last_value", v);
1038 PySys_SetObject("last_traceback", tb);
1039 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001040 hook = PySys_GetObject("excepthook");
1041 if (hook) {
1042 PyObject *args = Py_BuildValue("(OOO)",
1043 exception, v ? v : Py_None, tb ? tb : Py_None);
1044 PyObject *result = PyEval_CallObject(hook, args);
1045 if (result == NULL) {
1046 PyObject *exception2, *v2, *tb2;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001047 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1048 handle_system_exit();
1049 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001050 PyErr_Fetch(&exception2, &v2, &tb2);
1051 PyErr_NormalizeException(&exception2, &v2, &tb2);
1052 if (Py_FlushLine())
1053 PyErr_Clear();
1054 fflush(stdout);
1055 PySys_WriteStderr("Error in sys.excepthook:\n");
1056 PyErr_Display(exception2, v2, tb2);
1057 PySys_WriteStderr("\nOriginal exception was:\n");
1058 PyErr_Display(exception, v, tb);
Jeremy Hylton07028582001-12-07 15:35:35 +00001059 Py_XDECREF(exception2);
1060 Py_XDECREF(v2);
1061 Py_XDECREF(tb2);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001062 }
1063 Py_XDECREF(result);
1064 Py_XDECREF(args);
1065 } else {
1066 PySys_WriteStderr("sys.excepthook is missing\n");
1067 PyErr_Display(exception, v, tb);
1068 }
1069 Py_XDECREF(exception);
1070 Py_XDECREF(v);
1071 Py_XDECREF(tb);
1072}
1073
1074void PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
1075{
1076 int err = 0;
1077 PyObject *v = value;
1078 PyObject *f = PySys_GetObject("stderr");
Guido van Rossum3165fe61992-09-25 21:59:05 +00001079 if (f == NULL)
1080 fprintf(stderr, "lost sys.stderr\n");
1081 else {
Guido van Rossum0829c751998-02-28 04:31:39 +00001082 if (Py_FlushLine())
1083 PyErr_Clear();
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001084 fflush(stdout);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001085 if (tb && tb != Py_None)
1086 err = PyTraceBack_Print(tb, f);
Barry Warsaw36b8f941997-08-26 18:09:48 +00001087 if (err == 0 &&
Martin v. Löwiscfeb3b62002-03-03 21:30:27 +00001088 PyObject_HasAttrString(v, "print_file_and_line"))
Barry Warsaw36b8f941997-08-26 18:09:48 +00001089 {
Guido van Rossum82598051997-03-05 00:20:32 +00001090 PyObject *message;
Martin v. Löwis95292d62002-12-11 14:04:59 +00001091 const char *filename, *text;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001092 int lineno, offset;
Barry Warsaw035574d1997-08-29 22:07:17 +00001093 if (!parse_syntax_error(v, &message, &filename,
1094 &lineno, &offset, &text))
Guido van Rossum82598051997-03-05 00:20:32 +00001095 PyErr_Clear();
Guido van Rossuma110aa61994-08-29 12:50:44 +00001096 else {
1097 char buf[10];
Guido van Rossum82598051997-03-05 00:20:32 +00001098 PyFile_WriteString(" File \"", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001099 if (filename == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +00001100 PyFile_WriteString("<string>", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001101 else
Guido van Rossum82598051997-03-05 00:20:32 +00001102 PyFile_WriteString(filename, f);
1103 PyFile_WriteString("\", line ", f);
Jeremy Hylton518ab1c2001-11-28 20:42:20 +00001104 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
Guido van Rossum82598051997-03-05 00:20:32 +00001105 PyFile_WriteString(buf, f);
1106 PyFile_WriteString("\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001107 if (text != NULL)
1108 print_error_text(f, offset, text);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001109 v = message;
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001110 /* Can't be bothered to check all those
1111 PyFile_WriteString() calls */
1112 if (PyErr_Occurred())
1113 err = -1;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001114 }
1115 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001116 if (err) {
1117 /* Don't do anything else */
1118 }
1119 else if (PyClass_Check(exception)) {
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001120 PyClassObject* exc = (PyClassObject*)exception;
1121 PyObject* className = exc->cl_name;
1122 PyObject* moduleName =
1123 PyDict_GetItemString(exc->cl_dict, "__module__");
1124
1125 if (moduleName == NULL)
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001126 err = PyFile_WriteString("<unknown>", f);
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001127 else {
1128 char* modstr = PyString_AsString(moduleName);
Tim Petersd08e3822003-04-17 15:24:21 +00001129 if (modstr && strcmp(modstr, "exceptions"))
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001130 {
1131 err = PyFile_WriteString(modstr, f);
1132 err += PyFile_WriteString(".", f);
1133 }
1134 }
1135 if (err == 0) {
1136 if (className == NULL)
1137 err = PyFile_WriteString("<unknown>", f);
1138 else
1139 err = PyFile_WriteObject(className, f,
1140 Py_PRINT_RAW);
1141 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001142 }
1143 else
1144 err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
1145 if (err == 0) {
1146 if (v != NULL && v != Py_None) {
Barry Warsaw035574d1997-08-29 22:07:17 +00001147 PyObject *s = PyObject_Str(v);
1148 /* only print colon if the str() of the
1149 object is not the empty string
1150 */
Guido van Rossumd6bf45b1997-09-05 19:11:53 +00001151 if (s == NULL)
1152 err = -1;
1153 else if (!PyString_Check(s) ||
1154 PyString_GET_SIZE(s) != 0)
Barry Warsaw035574d1997-08-29 22:07:17 +00001155 err = PyFile_WriteString(": ", f);
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001156 if (err == 0)
Guido van Rossumd6bf45b1997-09-05 19:11:53 +00001157 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1158 Py_XDECREF(s);
Guido van Rossum262e1241995-02-07 15:30:45 +00001159 }
Guido van Rossum262e1241995-02-07 15:30:45 +00001160 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001161 if (err == 0)
1162 err = PyFile_WriteString("\n", f);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001163 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001164 /* If an error happened here, don't show it.
1165 XXX This is wrong, but too many callers rely on this behavior. */
1166 if (err != 0)
1167 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001168}
1169
Guido van Rossum82598051997-03-05 00:20:32 +00001170PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001171PyRun_String(const char *str, int start, PyObject *globals, PyObject *locals)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001172{
Guido van Rossum82598051997-03-05 00:20:32 +00001173 return run_err_node(PyParser_SimpleParseString(str, start),
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001174 "<string>", globals, locals, NULL);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001175}
1176
Guido van Rossum82598051997-03-05 00:20:32 +00001177PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001178PyRun_File(FILE *fp, const char *filename, int start, PyObject *globals,
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001179 PyObject *locals)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001180{
Tim Peterse8682112000-08-27 20:18:17 +00001181 return PyRun_FileEx(fp, filename, start, globals, locals, 0);
Guido van Rossum0df002c2000-08-27 19:21:52 +00001182}
1183
1184PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001185PyRun_FileEx(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001186 PyObject *locals, int closeit)
Guido van Rossum0df002c2000-08-27 19:21:52 +00001187{
1188 node *n = PyParser_SimpleParseFile(fp, filename, start);
1189 if (closeit)
1190 fclose(fp);
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001191 return run_err_node(n, filename, globals, locals, NULL);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001192}
1193
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001194PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001195PyRun_StringFlags(const char *str, int start, PyObject *globals, PyObject *locals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001196 PyCompilerFlags *flags)
1197{
Guido van Rossuma1b3a472001-07-16 16:51:33 +00001198 return run_err_node(PyParser_SimpleParseStringFlags(
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001199 str, start, PARSER_FLAGS(flags)),
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001200 "<string>", globals, locals, flags);
1201}
1202
1203PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001204PyRun_FileFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001205 PyObject *locals, PyCompilerFlags *flags)
1206{
1207 return PyRun_FileExFlags(fp, filename, start, globals, locals, 0,
Tim Petersd08e3822003-04-17 15:24:21 +00001208 flags);
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001209}
1210
1211PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001212PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001213 PyObject *locals, int closeit, PyCompilerFlags *flags)
1214{
Tim Petersfe2127d2001-07-16 05:37:24 +00001215 node *n = PyParser_SimpleParseFileFlags(fp, filename, start,
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001216 PARSER_FLAGS(flags));
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001217 if (closeit)
1218 fclose(fp);
1219 return run_err_node(n, filename, globals, locals, flags);
1220}
1221
Guido van Rossum82598051997-03-05 00:20:32 +00001222static PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001223run_err_node(node *n, const char *filename, PyObject *globals, PyObject *locals,
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001224 PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001225{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001226 if (n == NULL)
1227 return NULL;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001228 return run_node(n, filename, globals, locals, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001229}
1230
Guido van Rossum82598051997-03-05 00:20:32 +00001231static PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001232run_node(node *n, const char *filename, PyObject *globals, PyObject *locals,
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001233 PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001234{
Guido van Rossum82598051997-03-05 00:20:32 +00001235 PyCodeObject *co;
1236 PyObject *v;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001237 co = PyNode_CompileFlags(n, filename, flags);
Guido van Rossum82598051997-03-05 00:20:32 +00001238 PyNode_Free(n);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001239 if (co == NULL)
1240 return NULL;
Guido van Rossum82598051997-03-05 00:20:32 +00001241 v = PyEval_EvalCode(co, globals, locals);
1242 Py_DECREF(co);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001243 return v;
1244}
1245
Guido van Rossum82598051997-03-05 00:20:32 +00001246static PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001247run_pyc_file(FILE *fp, const char *filename, PyObject *globals, PyObject *locals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001248 PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001249{
Guido van Rossum82598051997-03-05 00:20:32 +00001250 PyCodeObject *co;
1251 PyObject *v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001252 long magic;
Fred Drakee8de31c2000-08-31 05:38:39 +00001253 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001254
Guido van Rossum82598051997-03-05 00:20:32 +00001255 magic = PyMarshal_ReadLongFromFile(fp);
1256 if (magic != PyImport_GetMagicNumber()) {
1257 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001258 "Bad magic number in .pyc file");
1259 return NULL;
1260 }
Guido van Rossum82598051997-03-05 00:20:32 +00001261 (void) PyMarshal_ReadLongFromFile(fp);
Tim Petersd9b9ac82001-01-28 00:27:39 +00001262 v = PyMarshal_ReadLastObjectFromFile(fp);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001263 fclose(fp);
Guido van Rossum82598051997-03-05 00:20:32 +00001264 if (v == NULL || !PyCode_Check(v)) {
1265 Py_XDECREF(v);
1266 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001267 "Bad code object in .pyc file");
1268 return NULL;
1269 }
Guido van Rossum82598051997-03-05 00:20:32 +00001270 co = (PyCodeObject *)v;
1271 v = PyEval_EvalCode(co, globals, locals);
Jeremy Hyltonb857ba22001-08-10 21:41:33 +00001272 if (v && flags)
1273 flags->cf_flags |= (co->co_flags & PyCF_MASK);
Guido van Rossum82598051997-03-05 00:20:32 +00001274 Py_DECREF(co);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001275 return v;
1276}
1277
Guido van Rossum82598051997-03-05 00:20:32 +00001278PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001279Py_CompileString(const char *str, const char *filename, int start)
Guido van Rossum5b722181993-03-30 17:46:03 +00001280{
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001281 return Py_CompileStringFlags(str, filename, start, NULL);
1282}
1283
1284PyObject *
Tim Petersd08e3822003-04-17 15:24:21 +00001285Py_CompileStringFlags(const char *str, const char *filename, int start,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001286 PyCompilerFlags *flags)
1287{
Guido van Rossum5b722181993-03-30 17:46:03 +00001288 node *n;
Guido van Rossum82598051997-03-05 00:20:32 +00001289 PyCodeObject *co;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001290
1291 n = PyParser_SimpleParseStringFlagsFilename(str, filename, start,
1292 PARSER_FLAGS(flags));
Guido van Rossuma110aa61994-08-29 12:50:44 +00001293 if (n == NULL)
Guido van Rossum5b722181993-03-30 17:46:03 +00001294 return NULL;
Jeremy Hylton673a4fd2001-03-26 19:53:38 +00001295 co = PyNode_CompileFlags(n, filename, flags);
Guido van Rossum82598051997-03-05 00:20:32 +00001296 PyNode_Free(n);
1297 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001298}
1299
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001300struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001301Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001302{
1303 node *n;
1304 struct symtable *st;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001305 n = PyParser_SimpleParseStringFlagsFilename(str, filename,
1306 start, 0);
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001307 if (n == NULL)
1308 return NULL;
1309 st = PyNode_CompileSymtable(n, filename);
1310 PyNode_Free(n);
1311 return st;
1312}
1313
Guido van Rossuma110aa61994-08-29 12:50:44 +00001314/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001315
Guido van Rossuma110aa61994-08-29 12:50:44 +00001316node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001317PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001318{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001319 node *n;
1320 perrdetail err;
Tim Petersfe2127d2001-07-16 05:37:24 +00001321 n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar, start,
1322 (char *)0, (char *)0, &err, flags);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001323 if (n == NULL)
1324 err_input(&err);
1325 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001326}
1327
Tim Petersfe2127d2001-07-16 05:37:24 +00001328node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001329PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
Tim Petersfe2127d2001-07-16 05:37:24 +00001330{
1331 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
1332}
1333
Guido van Rossuma110aa61994-08-29 12:50:44 +00001334/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001335
Guido van Rossuma110aa61994-08-29 12:50:44 +00001336node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001337PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001338{
1339 node *n;
1340 perrdetail err;
1341 n = PyParser_ParseStringFlags(str, &_PyParser_Grammar, start, &err,
1342 flags);
1343 if (n == NULL)
1344 err_input(&err);
1345 return n;
1346}
1347
1348node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001349PyParser_SimpleParseString(const char *str, int start)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001350{
Tim Petersfe2127d2001-07-16 05:37:24 +00001351 return PyParser_SimpleParseStringFlags(str, start, 0);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001352}
1353
Thomas Heller6b17abf2002-07-09 09:23:27 +00001354node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001355PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Thomas Heller6b17abf2002-07-09 09:23:27 +00001356 int start, int flags)
1357{
1358 node *n;
1359 perrdetail err;
1360
Tim Petersd08e3822003-04-17 15:24:21 +00001361 n = PyParser_ParseStringFlagsFilename(str, filename,
Thomas Heller6b17abf2002-07-09 09:23:27 +00001362 &_PyParser_Grammar,
1363 start, &err, flags);
1364 if (n == NULL)
1365 err_input(&err);
1366 return n;
1367}
1368
1369node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001370PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001371{
1372 return PyParser_SimpleParseStringFlagsFilename(str, filename,
1373 start, 0);
1374}
1375
Guido van Rossum66ebd912003-04-17 16:02:26 +00001376/* May want to move a more generalized form of this to parsetok.c or
1377 even parser modules. */
1378
1379void
1380PyParser_SetError(perrdetail *err)
1381{
1382 err_input(err);
1383}
1384
Guido van Rossuma110aa61994-08-29 12:50:44 +00001385/* Set the error appropriate to the given input error code (see errcode.h) */
1386
1387static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001388err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001389{
Fred Drake85f36392000-07-11 17:53:00 +00001390 PyObject *v, *w, *errtype;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001391 PyObject* u = NULL;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001392 char *msg = NULL;
Fred Drake85f36392000-07-11 17:53:00 +00001393 errtype = PyExc_SyntaxError;
Guido van Rossum82598051997-03-05 00:20:32 +00001394 v = Py_BuildValue("(ziiz)", err->filename,
Guido van Rossuma110aa61994-08-29 12:50:44 +00001395 err->lineno, err->offset, err->text);
1396 if (err->text != NULL) {
Guido van Rossumb18618d2000-05-03 23:44:39 +00001397 PyMem_DEL(err->text);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001398 err->text = NULL;
1399 }
1400 switch (err->error) {
1401 case E_SYNTAX:
Fred Drake85f36392000-07-11 17:53:00 +00001402 errtype = PyExc_IndentationError;
1403 if (err->expected == INDENT)
1404 msg = "expected an indented block";
1405 else if (err->token == INDENT)
1406 msg = "unexpected indent";
1407 else if (err->token == DEDENT)
1408 msg = "unexpected unindent";
1409 else {
1410 errtype = PyExc_SyntaxError;
1411 msg = "invalid syntax";
1412 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001413 break;
1414 case E_TOKEN:
1415 msg = "invalid token";
Guido van Rossuma110aa61994-08-29 12:50:44 +00001416 break;
Skip Montanaro118ec702002-08-15 01:20:16 +00001417 case E_EOFS:
1418 msg = "EOF while scanning triple-quoted string";
1419 break;
1420 case E_EOLS:
1421 msg = "EOL while scanning single-quoted string";
1422 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001423 case E_INTR:
Guido van Rossum82598051997-03-05 00:20:32 +00001424 PyErr_SetNone(PyExc_KeyboardInterrupt);
Barry Warsawc80baa31999-01-27 16:39:40 +00001425 Py_XDECREF(v);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001426 return;
1427 case E_NOMEM:
Guido van Rossum82598051997-03-05 00:20:32 +00001428 PyErr_NoMemory();
Barry Warsawc80baa31999-01-27 16:39:40 +00001429 Py_XDECREF(v);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001430 return;
1431 case E_EOF:
1432 msg = "unexpected EOF while parsing";
1433 break;
Fred Drake85f36392000-07-11 17:53:00 +00001434 case E_TABSPACE:
1435 errtype = PyExc_TabError;
Guido van Rossum560e8ad1998-04-10 19:43:42 +00001436 msg = "inconsistent use of tabs and spaces in indentation";
1437 break;
Jeremy Hylton94988062000-06-20 19:10:44 +00001438 case E_OVERFLOW:
1439 msg = "expression too long";
1440 break;
Fred Drake85f36392000-07-11 17:53:00 +00001441 case E_DEDENT:
1442 errtype = PyExc_IndentationError;
1443 msg = "unindent does not match any outer indentation level";
1444 break;
1445 case E_TOODEEP:
1446 errtype = PyExc_IndentationError;
1447 msg = "too many levels of indentation";
1448 break;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001449 case E_DECODE: { /* XXX */
1450 PyThreadState* tstate = PyThreadState_Get();
1451 PyObject* value = tstate->curexc_value;
1452 if (value != NULL) {
1453 u = PyObject_Repr(value);
1454 if (u != NULL) {
1455 msg = PyString_AsString(u);
1456 break;
1457 }
1458 }
1459 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001460 default:
1461 fprintf(stderr, "error=%d\n", err->error);
1462 msg = "unknown parsing error";
1463 break;
1464 }
Guido van Rossum82598051997-03-05 00:20:32 +00001465 w = Py_BuildValue("(sO)", msg, v);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001466 Py_XDECREF(u);
Guido van Rossum41318302001-03-23 04:01:07 +00001467 Py_XDECREF(v);
Fred Drake85f36392000-07-11 17:53:00 +00001468 PyErr_SetObject(errtype, w);
Guido van Rossum82598051997-03-05 00:20:32 +00001469 Py_XDECREF(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001470}
1471
1472/* Print fatal error message and abort */
1473
1474void
Tim Peters7c321a82002-07-09 02:57:01 +00001475Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001476{
Guido van Rossum83dd6c31994-09-29 09:38:33 +00001477 fprintf(stderr, "Fatal Python error: %s\n", msg);
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001478#ifdef MS_WINDOWS
Guido van Rossum23c94461997-05-22 20:21:30 +00001479 OutputDebugString("Fatal Python error: ");
Guido van Rossuma44823b1995-03-14 15:01:17 +00001480 OutputDebugString(msg);
1481 OutputDebugString("\n");
Guido van Rossum0ba35361998-08-13 13:33:16 +00001482#ifdef _DEBUG
1483 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00001484#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001485#endif /* MS_WINDOWS */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001486 abort();
1487}
1488
1489/* Clean up and exit */
1490
Guido van Rossuma110aa61994-08-29 12:50:44 +00001491#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00001492#include "pythread.h"
Guido van Rossum82598051997-03-05 00:20:32 +00001493int _PyThread_Started = 0; /* Set by threadmodule.c and maybe others */
Guido van Rossumf9f2e821992-08-17 08:59:08 +00001494#endif
1495
Guido van Rossum2dcfc961998-10-01 16:01:57 +00001496#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001497static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00001498static int nexitfuncs = 0;
1499
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001500int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00001501{
1502 if (nexitfuncs >= NEXITFUNCS)
1503 return -1;
1504 exitfuncs[nexitfuncs++] = func;
1505 return 0;
1506}
1507
Guido van Rossumcc283f51997-08-05 02:22:03 +00001508static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001509call_sys_exitfunc(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001510{
Guido van Rossum82598051997-03-05 00:20:32 +00001511 PyObject *exitfunc = PySys_GetObject("exitfunc");
Guido van Rossum59bff391992-09-03 20:28:00 +00001512
1513 if (exitfunc) {
Fred Drake6a12d8d2001-03-23 17:34:02 +00001514 PyObject *res;
Guido van Rossum82598051997-03-05 00:20:32 +00001515 Py_INCREF(exitfunc);
1516 PySys_SetObject("exitfunc", (PyObject *)NULL);
1517 res = PyEval_CallObject(exitfunc, (PyObject *)NULL);
Guido van Rossum59bff391992-09-03 20:28:00 +00001518 if (res == NULL) {
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001519 if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
1520 PySys_WriteStderr("Error in sys.exitfunc:\n");
1521 }
Guido van Rossum82598051997-03-05 00:20:32 +00001522 PyErr_Print();
Guido van Rossum59bff391992-09-03 20:28:00 +00001523 }
Guido van Rossum82598051997-03-05 00:20:32 +00001524 Py_DECREF(exitfunc);
Guido van Rossum59bff391992-09-03 20:28:00 +00001525 }
1526
Guido van Rossum0829c751998-02-28 04:31:39 +00001527 if (Py_FlushLine())
1528 PyErr_Clear();
Guido van Rossumcc283f51997-08-05 02:22:03 +00001529}
Guido van Rossum1662dd51994-09-07 14:38:28 +00001530
Guido van Rossumcc283f51997-08-05 02:22:03 +00001531static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001532call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00001533{
Guido van Rossum1662dd51994-09-07 14:38:28 +00001534 while (nexitfuncs > 0)
1535 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00001536
1537 fflush(stdout);
1538 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001539}
1540
1541void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001542Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001543{
Guido van Rossumcc283f51997-08-05 02:22:03 +00001544 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001545
Jack Jansen66a89771995-10-27 13:22:14 +00001546#ifdef macintosh
1547 PyMac_Exit(sts);
1548#else
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001549 exit(sts);
Jack Jansen66a89771995-10-27 13:22:14 +00001550#endif
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001551}
1552
Guido van Rossumf1dc5661993-07-05 10:31:29 +00001553static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001554initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001555{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001556#ifdef HAVE_SIGNAL_H
1557#ifdef SIGPIPE
1558 signal(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001559#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00001560#ifdef SIGXFZ
1561 signal(SIGXFZ, SIG_IGN);
1562#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00001563#ifdef SIGXFSZ
1564 signal(SIGXFSZ, SIG_IGN);
1565#endif
Guido van Rossuma110aa61994-08-29 12:50:44 +00001566#endif /* HAVE_SIGNAL_H */
Guido van Rossum82598051997-03-05 00:20:32 +00001567 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001568}
1569
Guido van Rossuma110aa61994-08-29 12:50:44 +00001570#ifdef MPW
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001571
1572/* Check for file descriptor connected to interactive device.
1573 Pretend that stdin is always interactive, other files never. */
1574
1575int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001576isatty(int fd)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001577{
1578 return fd == fileno(stdin);
1579}
1580
1581#endif
Guido van Rossum7433b121997-02-14 19:45:36 +00001582
1583/*
1584 * The file descriptor fd is considered ``interactive'' if either
1585 * a) isatty(fd) is TRUE, or
1586 * b) the -i flag was given, and the filename associated with
1587 * the descriptor is NULL or "<stdin>" or "???".
1588 */
1589int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001590Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00001591{
1592 if (isatty((int)fileno(fp)))
1593 return 1;
1594 if (!Py_InteractiveFlag)
1595 return 0;
1596 return (filename == NULL) ||
1597 (strcmp(filename, "<stdin>") == 0) ||
1598 (strcmp(filename, "???") == 0);
1599}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001600
1601
Tim Petersd08e3822003-04-17 15:24:21 +00001602#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001603#if defined(WIN32) && defined(_MSC_VER)
1604
1605/* Stack checking for Microsoft C */
1606
1607#include <malloc.h>
1608#include <excpt.h>
1609
Fred Drakee8de31c2000-08-31 05:38:39 +00001610/*
1611 * Return non-zero when we run out of memory on the stack; zero otherwise.
1612 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001613int
Fred Drake399739f2000-08-31 05:52:44 +00001614PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001615{
1616 __try {
Tim Peters92e4dd82002-10-05 01:47:34 +00001617 /* alloca throws a stack overflow exception if there's
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001618 not enough space left on the stack */
Tim Peters92e4dd82002-10-05 01:47:34 +00001619 alloca(PYOS_STACK_MARGIN * sizeof(void*));
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001620 return 0;
1621 } __except (EXCEPTION_EXECUTE_HANDLER) {
1622 /* just ignore all errors */
1623 }
1624 return 1;
1625}
1626
1627#endif /* WIN32 && _MSC_VER */
1628
1629/* Alternate implementations can be added here... */
1630
1631#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00001632
1633
1634/* Wrappers around sigaction() or signal(). */
1635
1636PyOS_sighandler_t
1637PyOS_getsig(int sig)
1638{
1639#ifdef HAVE_SIGACTION
1640 struct sigaction context;
Barry Warsawafeb2a42001-11-13 23:08:26 +00001641 /* Initialize context.sa_handler to SIG_ERR which makes about as
1642 * much sense as anything else. It should get overwritten if
1643 * sigaction actually succeeds and otherwise we avoid an
1644 * uninitialized memory read.
1645 */
1646 context.sa_handler = SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00001647 sigaction(sig, NULL, &context);
1648 return context.sa_handler;
1649#else
1650 PyOS_sighandler_t handler;
1651 handler = signal(sig, SIG_IGN);
1652 signal(sig, handler);
1653 return handler;
1654#endif
1655}
1656
1657PyOS_sighandler_t
1658PyOS_setsig(int sig, PyOS_sighandler_t handler)
1659{
1660#ifdef HAVE_SIGACTION
1661 struct sigaction context;
1662 PyOS_sighandler_t oldhandler;
Barry Warsawafeb2a42001-11-13 23:08:26 +00001663 /* Initialize context.sa_handler to SIG_ERR which makes about as
1664 * much sense as anything else. It should get overwritten if
1665 * sigaction actually succeeds and otherwise we avoid an
1666 * uninitialized memory read.
1667 */
1668 context.sa_handler = SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00001669 sigaction(sig, NULL, &context);
1670 oldhandler = context.sa_handler;
1671 context.sa_handler = handler;
1672 sigaction(sig, &context, NULL);
1673 return oldhandler;
1674#else
1675 return signal(sig, handler);
1676#endif
1677}