blob: 10a1d504a0807317d0299d394e7bcaf15cf4753a [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
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006#include "Python-ast.h"
Guido van Rossumd8faa362007-04-27 19:54:29 +00007#undef Yield /* undefine macro conflicting with winbase.h */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00008#include "grammar.h"
9#include "node.h"
Fred Drake85f36392000-07-11 17:53:00 +000010#include "token.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000011#include "parsetok.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000012#include "errcode.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013#include "code.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000014#include "compile.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000015#include "symtable.h"
Neal Norwitzadb69fc2005-12-17 20:54:49 +000016#include "pyarena.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000017#include "ast.h"
Guido van Rossumff4949e1992-08-05 19:58:53 +000018#include "eval.h"
Guido van Rossumfdef2711994-09-14 13:31:04 +000019#include "marshal.h"
Martin v. Löwis790465f2008-04-05 20:41:37 +000020#include "osdefs.h"
Antoine Pitroucefb3162009-10-20 22:08:36 +000021#include "abstract.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000022
Thomas Wouters0e3f5912006-08-11 14:57:12 +000023#ifdef HAVE_SIGNAL_H
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000024#include <signal.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000025#endif
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000026
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000027#ifdef MS_WINDOWS
Martin v. Löwis5c88d812009-01-02 20:47:48 +000028#include "malloc.h" /* for alloca */
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000029#endif
Martin v. Löwis5c88d812009-01-02 20:47:48 +000030
Martin v. Löwis73d538b2003-03-05 15:13:47 +000031#ifdef HAVE_LANGINFO_H
32#include <locale.h>
33#include <langinfo.h>
34#endif
35
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000036#ifdef MS_WINDOWS
Guido van Rossuma44823b1995-03-14 15:01:17 +000037#undef BYTE
38#include "windows.h"
Martin v. Löwis790465f2008-04-05 20:41:37 +000039#define PATH_MAX MAXPATHLEN
Guido van Rossuma44823b1995-03-14 15:01:17 +000040#endif
41
Neal Norwitz4281cef2006-03-04 19:58:13 +000042#ifndef Py_REF_DEBUG
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000043#define PRINT_TOTAL_REFS()
Neal Norwitz4281cef2006-03-04 19:58:13 +000044#else /* Py_REF_DEBUG */
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000045#define PRINT_TOTAL_REFS() fprintf(stderr, \
46 "[%" PY_FORMAT_SIZE_T "d refs]\n", \
47 _Py_GetRefTotal())
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000048#endif
49
50#ifdef __cplusplus
51extern "C" {
Neal Norwitz4281cef2006-03-04 19:58:13 +000052#endif
53
Martin v. Löwis790465f2008-04-05 20:41:37 +000054extern wchar_t *Py_GetPath(void);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000055
Guido van Rossum82598051997-03-05 00:20:32 +000056extern grammar _PyParser_Grammar; /* From graminit.c */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000057
Guido van Rossumb73cc041993-11-01 16:28:59 +000058/* Forward */
Tim Petersdbd9ba62000-07-09 03:09:57 +000059static void initmain(void);
60static void initsite(void);
Guido van Rossumce3a72a2007-10-19 23:16:50 +000061static int initstdio(void);
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +000062static void flush_io(void);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000063static PyObject *run_mod(mod_ty, const char *, PyObject *, PyObject *,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000064 PyCompilerFlags *, PyArena *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000065static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000066 PyCompilerFlags *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000067static void err_input(perrdetail *);
68static void initsigs(void);
Collin Winter670e6922007-03-21 02:57:17 +000069static void call_py_exitfuncs(void);
Antoine Pitroucefb3162009-10-20 22:08:36 +000070static void wait_for_thread_shutdown(void);
Tim Petersdbd9ba62000-07-09 03:09:57 +000071static void call_ll_exitfuncs(void);
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000072extern void _PyUnicode_Init(void);
73extern void _PyUnicode_Fini(void);
Guido van Rossumddefaf32007-01-14 03:31:43 +000074extern int _PyLong_Init(void);
75extern void PyLong_Fini(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +000076
Mark Hammond8d98d2c2003-04-19 15:41:53 +000077#ifdef WITH_THREAD
78extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
79extern void _PyGILState_Fini(void);
80#endif /* WITH_THREAD */
81
Guido van Rossum82598051997-03-05 00:20:32 +000082int Py_DebugFlag; /* Needed by parser.c */
83int Py_VerboseFlag; /* Needed by import.c */
Guido van Rossum7433b121997-02-14 19:45:36 +000084int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Guido van Rossumd8faa362007-04-27 19:54:29 +000085int Py_InspectFlag; /* Needed to determine whether to exit at SystemError */
Guido van Rossumdcc0c131997-08-29 22:32:42 +000086int Py_NoSiteFlag; /* Suppress 'import site' */
Guido van Rossum98297ee2007-11-06 21:34:58 +000087int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
Christian Heimes790c8232008-01-07 21:14:23 +000088int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.py[co]) */
Barry Warsaw3ce09642000-05-02 19:18:59 +000089int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +000090int Py_FrozenFlag; /* Needed by getpath.c */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +000091int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Christian Heimes8dc226f2008-05-06 23:45:46 +000092int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
Antoine Pitrou05608432009-01-09 18:53:14 +000093int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000094
Christian Heimes33fe8092008-04-13 13:53:33 +000095/* PyModule_GetWarningsModule is no longer necessary as of 2.6
96since _warnings is builtin. This API should not be used. */
97PyObject *
98PyModule_GetWarningsModule(void)
Mark Hammondedd07732003-07-15 23:03:55 +000099{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000100 return PyImport_ImportModule("warnings");
Mark Hammondedd07732003-07-15 23:03:55 +0000101}
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000102
Guido van Rossum25ce5661997-08-02 03:10:38 +0000103static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000104
Thomas Wouters7e474022000-07-16 12:04:32 +0000105/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000106
107int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000108Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000109{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000110 return initialized;
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000111}
112
Guido van Rossum25ce5661997-08-02 03:10:38 +0000113/* Global initializations. Can be undone by Py_Finalize(). Don't
114 call this twice without an intervening Py_Finalize() call. When
115 initializations fail, a fatal error is issued and the function does
116 not return. On return, the first thread and interpreter state have
117 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000118
Guido van Rossum25ce5661997-08-02 03:10:38 +0000119 Locking: you must hold the interpreter lock while calling this.
120 (If the lock has not yet been initialized, that's equivalent to
121 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000122
Guido van Rossum25ce5661997-08-02 03:10:38 +0000123*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000124
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000125static int
126add_flag(int flag, const char *envs)
127{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000128 int env = atoi(envs);
129 if (flag < env)
130 flag = env;
131 if (flag < 1)
132 flag = 1;
133 return flag;
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000134}
135
Christian Heimes5833a2f2008-10-30 21:40:04 +0000136#if defined(HAVE_LANGINFO_H) && defined(CODESET)
137static char*
138get_codeset(void)
139{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000140 char* codeset;
141 PyObject *codec, *name;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000142
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000143 codeset = nl_langinfo(CODESET);
144 if (!codeset || codeset[0] == '\0')
145 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000146
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000147 codec = _PyCodec_Lookup(codeset);
148 if (!codec)
149 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000150
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000151 name = PyObject_GetAttrString(codec, "name");
152 Py_CLEAR(codec);
153 if (!name)
154 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000155
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000156 codeset = strdup(_PyUnicode_AsString(name));
157 Py_DECREF(name);
158 return codeset;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000159
160error:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000161 Py_XDECREF(codec);
162 PyErr_Clear();
163 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000164}
165#endif
166
Guido van Rossuma027efa1997-05-05 20:56:21 +0000167void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000168Py_InitializeEx(int install_sigs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000169{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000170 PyInterpreterState *interp;
171 PyThreadState *tstate;
172 PyObject *bimod, *sysmod, *pstderr;
173 char *p;
Guido van Rossum8d30cc02007-05-03 17:49:24 +0000174#if defined(HAVE_LANGINFO_H) && defined(CODESET)
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000175 char *codeset;
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000176#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000177 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000178
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000179 if (initialized)
180 return;
181 initialized = 1;
Tim Petersd08e3822003-04-17 15:24:21 +0000182
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +0000183#ifdef HAVE_SETLOCALE
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000184 /* Set up the LC_CTYPE locale, so we can obtain
185 the locale's charset without having to switch
186 locales. */
187 setlocale(LC_CTYPE, "");
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +0000188#endif
189
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000190 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
191 Py_DebugFlag = add_flag(Py_DebugFlag, p);
192 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
193 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
194 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
195 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
196 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
197 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000198
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000199 interp = PyInterpreterState_New();
200 if (interp == NULL)
201 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000202
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000203 tstate = PyThreadState_New(interp);
204 if (tstate == NULL)
205 Py_FatalError("Py_Initialize: can't make first thread");
206 (void) PyThreadState_Swap(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000207
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000208 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000209
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000210 if (!_PyFrame_Init())
211 Py_FatalError("Py_Initialize: can't init frames");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000212
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000213 if (!_PyLong_Init())
214 Py_FatalError("Py_Initialize: can't init longs");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000215
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000216 if (!PyByteArray_Init())
217 Py_FatalError("Py_Initialize: can't init bytearray");
Neal Norwitz6968b052007-02-27 19:02:19 +0000218
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000219 _PyFloat_Init();
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000220
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000221 interp->modules = PyDict_New();
222 if (interp->modules == NULL)
223 Py_FatalError("Py_Initialize: can't make modules dictionary");
224 interp->modules_reloading = PyDict_New();
225 if (interp->modules_reloading == NULL)
226 Py_FatalError("Py_Initialize: can't make modules_reloading dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000227
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000228 /* Init Unicode implementation; relies on the codec registry */
229 _PyUnicode_Init();
Guido van Rossumc94044c2000-03-10 23:03:54 +0000230
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000231 bimod = _PyBuiltin_Init();
232 if (bimod == NULL)
233 Py_FatalError("Py_Initialize: can't initialize builtins modules");
234 _PyImport_FixupExtension(bimod, "builtins", "builtins");
235 interp->builtins = PyModule_GetDict(bimod);
236 if (interp->builtins == NULL)
237 Py_FatalError("Py_Initialize: can't initialize builtins dict");
238 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000239
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000240 /* initialize builtin exceptions */
241 _PyExc_Init();
Christian Heimes9a68f8c2007-11-14 00:16:07 +0000242
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000243 sysmod = _PySys_Init();
244 if (sysmod == NULL)
245 Py_FatalError("Py_Initialize: can't initialize sys");
246 interp->sysdict = PyModule_GetDict(sysmod);
247 if (interp->sysdict == NULL)
248 Py_FatalError("Py_Initialize: can't initialize sys dict");
249 Py_INCREF(interp->sysdict);
250 _PyImport_FixupExtension(sysmod, "sys", "sys");
251 PySys_SetPath(Py_GetPath());
252 PyDict_SetItemString(interp->sysdict, "modules",
253 interp->modules);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000254
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000255 /* Set up a preliminary stderr printer until we have enough
256 infrastructure for the io module in place. */
257 pstderr = PyFile_NewStdPrinter(fileno(stderr));
258 if (pstderr == NULL)
259 Py_FatalError("Py_Initialize: can't set preliminary stderr");
260 PySys_SetObject("stderr", pstderr);
261 PySys_SetObject("__stderr__", pstderr);
Guido van Rossum826d8972007-10-30 18:34:07 +0000262
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000263 _PyImport_Init();
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000264
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000265 _PyImportHooks_Init();
Just van Rossum52e14d62002-12-30 22:08:05 +0000266
Victor Stinner148051a2010-05-20 21:00:34 +0000267 /* Initialize _warnings. */
268 _PyWarnings_Init();
269
Martin v. Löwis011e8422009-05-05 04:43:17 +0000270#if defined(HAVE_LANGINFO_H) && defined(CODESET)
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000271 /* On Unix, set the file system encoding according to the
272 user's preference, if the CODESET names a well-known
273 Python codec, and Py_FileSystemDefaultEncoding isn't
274 initialized by other means. Also set the encoding of
275 stdin and stdout if these are terminals. */
Martin v. Löwis011e8422009-05-05 04:43:17 +0000276
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000277 codeset = get_codeset();
278 if (codeset) {
279 if (!Py_FileSystemDefaultEncoding)
280 Py_FileSystemDefaultEncoding = codeset;
281 else
282 free(codeset);
283 }
Martin v. Löwis011e8422009-05-05 04:43:17 +0000284#endif
285
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000286 if (install_sigs)
287 initsigs(); /* Signal handling stuff, including initintr() */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000288
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000289 /* Initialize warnings. */
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000290 if (PySys_HasWarnOptions()) {
291 PyObject *warnings_module = PyImport_ImportModule("warnings");
292 if (!warnings_module)
293 PyErr_Clear();
294 Py_XDECREF(warnings_module);
295 }
Just van Rossum5bfba3a2003-02-25 20:25:12 +0000296
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000297 initmain(); /* Module __main__ */
298 if (initstdio() < 0)
299 Py_FatalError(
300 "Py_Initialize: can't initialize sys standard streams");
301
302 /* auto-thread-state API, if available */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000303#ifdef WITH_THREAD
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000304 _PyGILState_Init(interp, tstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000305#endif /* WITH_THREAD */
Victor Stinnerffbc2f62010-03-21 21:48:45 +0000306
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000307 if (!Py_NoSiteFlag)
308 initsite(); /* Module site */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000309}
310
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000311void
312Py_Initialize(void)
313{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000314 Py_InitializeEx(1);
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000315}
316
317
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000318#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000319extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000320#endif
321
Guido van Rossume8432ac2007-07-09 15:04:50 +0000322/* Flush stdout and stderr */
323
Neal Norwitz2bad9702007-08-27 06:19:22 +0000324static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000325flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000326{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000327 PyObject *fout = PySys_GetObject("stdout");
328 PyObject *ferr = PySys_GetObject("stderr");
329 PyObject *tmp;
Guido van Rossume8432ac2007-07-09 15:04:50 +0000330
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000331 if (fout != NULL && fout != Py_None) {
332 tmp = PyObject_CallMethod(fout, "flush", "");
333 if (tmp == NULL)
Antoine Pitroub61d5c92010-08-08 20:49:19 +0000334 PyErr_WriteUnraisable(fout);
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000335 else
336 Py_DECREF(tmp);
337 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000338
Victor Stinnerebb5a882010-05-14 01:03:14 +0000339 if (ferr != NULL && ferr != Py_None) {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000340 tmp = PyObject_CallMethod(ferr, "flush", "");
341 if (tmp == NULL)
342 PyErr_Clear();
343 else
344 Py_DECREF(tmp);
345 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000346}
347
Guido van Rossum25ce5661997-08-02 03:10:38 +0000348/* Undo the effect of Py_Initialize().
349
350 Beware: if multiple interpreter and/or thread states exist, these
351 are not wiped out; only the current thread and interpreter state
352 are deleted. But since everything else is deleted, those other
353 interpreter and thread states should no longer be used.
354
355 (XXX We should do better, e.g. wipe out all interpreters and
356 threads.)
357
358 Locking: as above.
359
360*/
361
362void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000363Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000364{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000365 PyInterpreterState *interp;
366 PyThreadState *tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000367
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000368 if (!initialized)
369 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000370
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000371 wait_for_thread_shutdown();
Antoine Pitroucefb3162009-10-20 22:08:36 +0000372
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000373 /* The interpreter is still entirely intact at this point, and the
374 * exit funcs may be relying on that. In particular, if some thread
375 * or exit func is still waiting to do an import, the import machinery
376 * expects Py_IsInitialized() to return true. So don't say the
377 * interpreter is uninitialized until after the exit funcs have run.
378 * Note that Threading.py uses an exit func to do a join on all the
379 * threads created thru it, so this also protects pending imports in
380 * the threads created via Threading.
381 */
382 call_py_exitfuncs();
383 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000384
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000385 /* Flush stdout+stderr */
386 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000387
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000388 /* Get current thread state and interpreter pointer */
389 tstate = PyThreadState_GET();
390 interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000391
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000392 /* Disable signal handling */
393 PyOS_FiniInterrupts();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000394
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000395 /* Clear type lookup cache */
396 PyType_ClearCache();
Christian Heimes26855632008-01-27 23:50:43 +0000397
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000398 /* Collect garbage. This may call finalizers; it's nice to call these
399 * before all modules are destroyed.
400 * XXX If a __del__ or weakref callback is triggered here, and tries to
401 * XXX import a module, bad things can happen, because Python no
402 * XXX longer believes it's initialized.
403 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
404 * XXX is easy to provoke that way. I've also seen, e.g.,
405 * XXX Exception exceptions.ImportError: 'No module named sha'
406 * XXX in <function callback at 0x008F5718> ignored
407 * XXX but I'm unclear on exactly how that one happens. In any case,
408 * XXX I haven't seen a real-life report of either of these.
409 */
410 PyGC_Collect();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000411#ifdef COUNT_ALLOCS
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000412 /* With COUNT_ALLOCS, it helps to run GC multiple times:
413 each collection might release some types from the type
414 list, so they become garbage. */
415 while (PyGC_Collect() > 0)
416 /* nothing */;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000417#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000418
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000419 /* Destroy all modules */
420 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000421
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000422 /* Flush stdout+stderr (again, in case more was printed) */
423 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000424
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000425 /* Collect final garbage. This disposes of cycles created by
426 * new-style class definitions, for example.
427 * XXX This is disabled because it caused too many problems. If
428 * XXX a __del__ or weakref callback triggers here, Python code has
429 * XXX a hard time running, because even the sys module has been
430 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
431 * XXX One symptom is a sequence of information-free messages
432 * XXX coming from threads (if a __del__ or callback is invoked,
433 * XXX other threads can execute too, and any exception they encounter
434 * XXX triggers a comedy of errors as subsystem after subsystem
435 * XXX fails to find what it *expects* to find in sys to help report
436 * XXX the exception and consequent unexpected failures). I've also
437 * XXX seen segfaults then, after adding print statements to the
438 * XXX Python code getting called.
439 */
Tim Peters1d7323e2003-12-01 21:35:27 +0000440#if 0
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000441 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000442#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000443
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000444 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
445 _PyImport_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000446
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000447 /* Debugging stuff */
Guido van Rossum1707aad1997-12-08 23:43:45 +0000448#ifdef COUNT_ALLOCS
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000449 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000450#endif
451
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000452 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000453
Tim Peters9cf25ce2003-04-17 15:21:01 +0000454#ifdef Py_TRACE_REFS
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000455 /* Display all objects still alive -- this can invoke arbitrary
456 * __repr__ overrides, so requires a mostly-intact interpreter.
457 * Alas, a lot of stuff may still be alive now that will be cleaned
458 * up later.
459 */
460 if (Py_GETENV("PYTHONDUMPREFS"))
461 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000462#endif /* Py_TRACE_REFS */
463
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000464 /* Clear interpreter state */
465 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000466
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000467 /* Now we decref the exception classes. After this point nothing
468 can raise an exception. That's okay, because each Fini() method
469 below has been checked to make sure no exceptions are ever
470 raised.
471 */
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000472
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000473 _PyExc_Fini();
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000474
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000475 /* Cleanup auto-thread-state */
Christian Heimes7d2ff882007-11-30 14:35:04 +0000476#ifdef WITH_THREAD
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000477 _PyGILState_Fini();
Christian Heimes7d2ff882007-11-30 14:35:04 +0000478#endif /* WITH_THREAD */
479
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000480 /* Delete current thread */
481 PyThreadState_Swap(NULL);
482 PyInterpreterState_Delete(interp);
Barry Warsawf242aa02000-05-25 23:09:49 +0000483
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000484 /* Sundry finalizers */
485 PyMethod_Fini();
486 PyFrame_Fini();
487 PyCFunction_Fini();
488 PyTuple_Fini();
489 PyList_Fini();
490 PySet_Fini();
491 PyBytes_Fini();
492 PyByteArray_Fini();
493 PyLong_Fini();
494 PyFloat_Fini();
495 PyDict_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000496
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000497 /* Cleanup Unicode implementation */
498 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000499
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000500 /* reset file system default encoding */
501 if (!Py_HasFileSystemDefaultEncoding) {
502 free((char*)Py_FileSystemDefaultEncoding);
503 Py_FileSystemDefaultEncoding = NULL;
504 }
Christian Heimesc8967002007-11-30 10:18:26 +0000505
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000506 /* XXX Still allocated:
507 - various static ad-hoc pointers to interned strings
508 - int and float free list blocks
509 - whatever various modules and libraries allocate
510 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000511
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000512 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000513
Tim Peters269b2a62003-04-17 19:52:29 +0000514#ifdef Py_TRACE_REFS
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000515 /* Display addresses (& refcnts) of all objects still alive.
516 * An address can be used to find the repr of the object, printed
517 * above by _Py_PrintReferences.
518 */
519 if (Py_GETENV("PYTHONDUMPREFS"))
520 _Py_PrintReferenceAddresses(stderr);
Tim Peters269b2a62003-04-17 19:52:29 +0000521#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000522#ifdef PYMALLOC_DEBUG
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000523 if (Py_GETENV("PYTHONMALLOCSTATS"))
524 _PyObject_DebugMallocStats();
Tim Peters0e871182002-04-13 08:29:14 +0000525#endif
526
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000527 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000528}
529
530/* Create and initialize a new interpreter and thread, and return the
531 new thread. This requires that Py_Initialize() has been called
532 first.
533
534 Unsuccessful initialization yields a NULL pointer. Note that *no*
535 exception information is available even in this case -- the
536 exception information is held in the thread, and there is no
537 thread.
538
539 Locking: as above.
540
541*/
542
543PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000544Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000545{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000546 PyInterpreterState *interp;
547 PyThreadState *tstate, *save_tstate;
548 PyObject *bimod, *sysmod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000549
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000550 if (!initialized)
551 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000552
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000553 interp = PyInterpreterState_New();
554 if (interp == NULL)
555 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000556
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000557 tstate = PyThreadState_New(interp);
558 if (tstate == NULL) {
559 PyInterpreterState_Delete(interp);
560 return NULL;
561 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000562
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000563 save_tstate = PyThreadState_Swap(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000564
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000565 /* XXX The following is lax in error checking */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000566
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000567 interp->modules = PyDict_New();
568 interp->modules_reloading = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000569
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000570 bimod = _PyImport_FindExtension("builtins", "builtins");
571 if (bimod != NULL) {
572 interp->builtins = PyModule_GetDict(bimod);
573 if (interp->builtins == NULL)
574 goto handle_error;
575 Py_INCREF(interp->builtins);
576 }
Christian Heimes6a27efa2008-10-30 21:48:26 +0000577
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000578 /* initialize builtin exceptions */
579 _PyExc_Init();
Christian Heimes6a27efa2008-10-30 21:48:26 +0000580
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000581 sysmod = _PyImport_FindExtension("sys", "sys");
582 if (bimod != NULL && sysmod != NULL) {
583 PyObject *pstderr;
584 interp->sysdict = PyModule_GetDict(sysmod);
585 if (interp->sysdict == NULL)
586 goto handle_error;
587 Py_INCREF(interp->sysdict);
588 PySys_SetPath(Py_GetPath());
589 PyDict_SetItemString(interp->sysdict, "modules",
590 interp->modules);
591 /* Set up a preliminary stderr printer until we have enough
592 infrastructure for the io module in place. */
593 pstderr = PyFile_NewStdPrinter(fileno(stderr));
594 if (pstderr == NULL)
595 Py_FatalError("Py_Initialize: can't set preliminary stderr");
596 PySys_SetObject("stderr", pstderr);
597 PySys_SetObject("__stderr__", pstderr);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000598
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000599 _PyImportHooks_Init();
600 if (initstdio() < 0)
601 Py_FatalError(
602 "Py_Initialize: can't initialize sys standard streams");
603 initmain();
604 if (!Py_NoSiteFlag)
605 initsite();
606 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000607
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000608 if (!PyErr_Occurred())
609 return tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000610
Thomas Wouters89f507f2006-12-13 04:49:30 +0000611handle_error:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000612 /* Oops, it didn't work. Undo it all. */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000613
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000614 PyErr_Print();
615 PyThreadState_Clear(tstate);
616 PyThreadState_Swap(save_tstate);
617 PyThreadState_Delete(tstate);
618 PyInterpreterState_Delete(interp);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000619
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000620 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000621}
622
623/* Delete an interpreter and its last thread. This requires that the
624 given thread state is current, that the thread has no remaining
625 frames, and that it is its interpreter's only remaining thread.
626 It is a fatal error to violate these constraints.
627
628 (Py_Finalize() doesn't have these constraints -- it zaps
629 everything, regardless.)
630
631 Locking: as above.
632
633*/
634
635void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000636Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000637{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000638 PyInterpreterState *interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000639
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000640 if (tstate != PyThreadState_GET())
641 Py_FatalError("Py_EndInterpreter: thread is not current");
642 if (tstate->frame != NULL)
643 Py_FatalError("Py_EndInterpreter: thread still has a frame");
644 if (tstate != interp->tstate_head || tstate->next != NULL)
645 Py_FatalError("Py_EndInterpreter: not the last thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000646
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000647 PyImport_Cleanup();
648 PyInterpreterState_Clear(interp);
649 PyThreadState_Swap(NULL);
650 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000651}
652
Martin v. Löwis790465f2008-04-05 20:41:37 +0000653static wchar_t *progname = L"python";
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000654
655void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000656Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000657{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000658 if (pn && *pn)
659 progname = pn;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000660}
661
Martin v. Löwis790465f2008-04-05 20:41:37 +0000662wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000663Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000664{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000665 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000666}
667
Martin v. Löwis790465f2008-04-05 20:41:37 +0000668static wchar_t *default_home = NULL;
669static wchar_t env_home[PATH_MAX+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000670
671void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000672Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000673{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000674 default_home = home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000675}
676
Martin v. Löwis790465f2008-04-05 20:41:37 +0000677wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000678Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000679{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000680 wchar_t *home = default_home;
681 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
682 char* chome = Py_GETENV("PYTHONHOME");
683 if (chome) {
684 size_t r = mbstowcs(env_home, chome, PATH_MAX+1);
685 if (r != (size_t)-1 && r <= PATH_MAX)
686 home = env_home;
687 }
Martin v. Löwis790465f2008-04-05 20:41:37 +0000688
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000689 }
690 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000691}
692
Guido van Rossum6135a871995-01-09 17:53:26 +0000693/* Create __main__ module */
694
695static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000696initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000697{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000698 PyObject *m, *d;
699 m = PyImport_AddModule("__main__");
700 if (m == NULL)
701 Py_FatalError("can't create __main__ module");
702 d = PyModule_GetDict(m);
703 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
704 PyObject *bimod = PyImport_ImportModule("builtins");
705 if (bimod == NULL ||
706 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
707 Py_FatalError("can't add __builtins__ to __main__");
708 Py_DECREF(bimod);
709 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000710}
711
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000712/* Import the site module (not into __main__ though) */
713
714static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000715initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000716{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000717 PyObject *m, *f;
718 m = PyImport_ImportModule("site");
719 if (m == NULL) {
720 f = PySys_GetObject("stderr");
721 if (f == NULL || f == Py_None)
722 return;
723 if (Py_VerboseFlag) {
Victor Stinner3aa6cea2010-10-23 08:50:36 +0000724 PyObject *type, *value, *traceback;
725 PyErr_Fetch(&type, &value, &traceback);
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000726 PyFile_WriteString(
727 "'import site' failed; traceback:\n", f);
Victor Stinner3aa6cea2010-10-23 08:50:36 +0000728 PyErr_Restore(type, value, traceback);
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000729 PyErr_Print();
730 }
731 else {
Victor Stinner3aa6cea2010-10-23 08:50:36 +0000732 PyErr_Clear();
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000733 PyFile_WriteString(
734 "'import site' failed; use -v for traceback\n", f);
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000735 }
736 }
737 else {
738 Py_DECREF(m);
739 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000740}
741
Antoine Pitrou05608432009-01-09 18:53:14 +0000742static PyObject*
743create_stdio(PyObject* io,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000744 int fd, int write_mode, char* name,
745 char* encoding, char* errors)
Antoine Pitrou05608432009-01-09 18:53:14 +0000746{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000747 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
748 const char* mode;
749 PyObject *line_buffering;
750 int buffering, isatty;
Antoine Pitrou05608432009-01-09 18:53:14 +0000751
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000752 /* stdin is always opened in buffered mode, first because it shouldn't
753 make a difference in common use cases, second because TextIOWrapper
754 depends on the presence of a read1() method which only exists on
755 buffered streams.
756 */
757 if (Py_UnbufferedStdioFlag && write_mode)
758 buffering = 0;
759 else
760 buffering = -1;
761 if (write_mode)
762 mode = "wb";
763 else
764 mode = "rb";
765 buf = PyObject_CallMethod(io, "open", "isiOOOi",
766 fd, mode, buffering,
767 Py_None, Py_None, Py_None, 0);
768 if (buf == NULL)
769 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000770
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000771 if (buffering) {
772 raw = PyObject_GetAttrString(buf, "raw");
773 if (raw == NULL)
774 goto error;
775 }
776 else {
777 raw = buf;
778 Py_INCREF(raw);
779 }
Antoine Pitrou05608432009-01-09 18:53:14 +0000780
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000781 text = PyUnicode_FromString(name);
782 if (text == NULL || PyObject_SetAttrString(raw, "name", text) < 0)
783 goto error;
784 res = PyObject_CallMethod(raw, "isatty", "");
785 if (res == NULL)
786 goto error;
787 isatty = PyObject_IsTrue(res);
788 Py_DECREF(res);
789 if (isatty == -1)
790 goto error;
791 if (isatty || Py_UnbufferedStdioFlag)
792 line_buffering = Py_True;
793 else
794 line_buffering = Py_False;
Antoine Pitrou91696412009-01-09 22:12:30 +0000795
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000796 Py_CLEAR(raw);
797 Py_CLEAR(text);
Antoine Pitrou91696412009-01-09 22:12:30 +0000798
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000799 stream = PyObject_CallMethod(io, "TextIOWrapper", "OsssO",
800 buf, encoding, errors,
801 "\n", line_buffering);
802 Py_CLEAR(buf);
803 if (stream == NULL)
804 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000805
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000806 if (write_mode)
807 mode = "w";
808 else
809 mode = "r";
810 text = PyUnicode_FromString(mode);
811 if (!text || PyObject_SetAttrString(stream, "mode", text) < 0)
812 goto error;
813 Py_CLEAR(text);
814 return stream;
Antoine Pitrou05608432009-01-09 18:53:14 +0000815
816error:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000817 Py_XDECREF(buf);
818 Py_XDECREF(stream);
819 Py_XDECREF(text);
820 Py_XDECREF(raw);
821 return NULL;
Antoine Pitrou05608432009-01-09 18:53:14 +0000822}
823
Georg Brandl1a3284e2007-12-02 09:40:06 +0000824/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000825static int
826initstdio(void)
827{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000828 PyObject *iomod = NULL, *wrapper;
829 PyObject *bimod = NULL;
830 PyObject *m;
831 PyObject *std = NULL;
832 int status = 0, fd;
833 PyObject * encoding_attr;
834 char *encoding = NULL, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000835
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000836 /* Hack to avoid a nasty recursion issue when Python is invoked
837 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
838 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
839 goto error;
840 }
841 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000842
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000843 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
844 goto error;
845 }
846 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000847
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000848 if (!(bimod = PyImport_ImportModule("builtins"))) {
849 goto error;
850 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000851
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000852 if (!(iomod = PyImport_ImportModule("io"))) {
853 goto error;
854 }
855 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
856 goto error;
857 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000858
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000859 /* Set builtins.open */
860 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
861 goto error;
862 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000863
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000864 encoding = Py_GETENV("PYTHONIOENCODING");
865 errors = NULL;
866 if (encoding) {
867 encoding = strdup(encoding);
868 errors = strchr(encoding, ':');
869 if (errors) {
870 *errors = '\0';
871 errors++;
872 }
873 }
Martin v. Löwis0f599892008-06-02 11:13:03 +0000874
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000875 /* Set sys.stdin */
876 fd = fileno(stdin);
877 /* Under some conditions stdin, stdout and stderr may not be connected
878 * and fileno() may point to an invalid file descriptor. For example
879 * GUI apps don't have valid standard streams by default.
880 */
881 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000882#ifdef MS_WINDOWS
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000883 std = Py_None;
884 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000885#else
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000886 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000887#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000888 }
889 else {
890 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
891 if (std == NULL)
892 goto error;
893 } /* if (fd < 0) */
894 PySys_SetObject("__stdin__", std);
895 PySys_SetObject("stdin", std);
896 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000897
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000898 /* Set sys.stdout */
899 fd = fileno(stdout);
900 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000901#ifdef MS_WINDOWS
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000902 std = Py_None;
903 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000904#else
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000905 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000906#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000907 }
908 else {
909 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
910 if (std == NULL)
911 goto error;
912 } /* if (fd < 0) */
913 PySys_SetObject("__stdout__", std);
914 PySys_SetObject("stdout", std);
915 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000916
Guido van Rossum98297ee2007-11-06 21:34:58 +0000917#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000918 /* Set sys.stderr, replaces the preliminary stderr */
919 fd = fileno(stderr);
920 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000921#ifdef MS_WINDOWS
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000922 std = Py_None;
923 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000924#else
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000925 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000926#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000927 }
928 else {
929 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
930 if (std == NULL)
931 goto error;
932 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +0000933
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000934 /* Same as hack above, pre-import stderr's codec to avoid recursion
935 when import.c tries to write to stderr in verbose mode. */
936 encoding_attr = PyObject_GetAttrString(std, "encoding");
937 if (encoding_attr != NULL) {
938 const char * encoding;
939 encoding = _PyUnicode_AsString(encoding_attr);
940 if (encoding != NULL) {
941 _PyCodec_Lookup(encoding);
942 }
943 }
944 PyErr_Clear(); /* Not a fatal error if codec isn't available */
Trent Nelson39e307e2008-03-19 06:45:48 +0000945
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000946 PySys_SetObject("__stderr__", std);
947 PySys_SetObject("stderr", std);
948 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +0000949#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000950
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000951 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000952 error:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000953 status = -1;
954 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000955
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000956 if (encoding)
957 free(encoding);
958 Py_XDECREF(bimod);
959 Py_XDECREF(iomod);
960 return status;
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000961}
962
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000963/* Parse input from a file and execute it */
964
965int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000966PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000967 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000968{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000969 if (filename == NULL)
970 filename = "???";
971 if (Py_FdIsInteractive(fp, filename)) {
972 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
973 if (closeit)
974 fclose(fp);
975 return err;
976 }
977 else
978 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000979}
980
981int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000982PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000983{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000984 PyObject *v;
985 int ret;
986 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000987
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000988 if (flags == NULL) {
989 flags = &local_flags;
990 local_flags.cf_flags = 0;
991 }
992 v = PySys_GetObject("ps1");
993 if (v == NULL) {
994 PySys_SetObject("ps1", v = PyUnicode_FromString(">>> "));
995 Py_XDECREF(v);
996 }
997 v = PySys_GetObject("ps2");
998 if (v == NULL) {
999 PySys_SetObject("ps2", v = PyUnicode_FromString("... "));
1000 Py_XDECREF(v);
1001 }
1002 for (;;) {
1003 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
1004 PRINT_TOTAL_REFS();
1005 if (ret == E_EOF)
1006 return 0;
1007 /*
1008 if (ret == E_NOMEM)
1009 return -1;
1010 */
1011 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001012}
1013
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001014/* compute parser flags based on compiler flags */
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001015static int PARSER_FLAGS(PyCompilerFlags *flags)
1016{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001017 int parser_flags = 0;
1018 if (!flags)
1019 return 0;
1020 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
1021 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1022 if (flags->cf_flags & PyCF_IGNORE_COOKIE)
1023 parser_flags |= PyPARSE_IGNORE_COOKIE;
1024 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
1025 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1026 return parser_flags;
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001027}
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001028
Thomas Wouters89f507f2006-12-13 04:49:30 +00001029#if 0
1030/* Keep an example of flags with future keyword support. */
1031#define PARSER_FLAGS(flags) \
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001032 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1033 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1034 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1035 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001036#endif
1037
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001038int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001039PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001040{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001041 PyObject *m, *d, *v, *w, *oenc = NULL;
1042 mod_ty mod;
1043 PyArena *arena;
1044 char *ps1 = "", *ps2 = "", *enc = NULL;
1045 int errcode = 0;
Tim Petersfe2127d2001-07-16 05:37:24 +00001046
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001047 if (fp == stdin) {
1048 /* Fetch encoding from sys.stdin */
1049 v = PySys_GetObject("stdin");
1050 if (v == NULL || v == Py_None)
1051 return -1;
1052 oenc = PyObject_GetAttrString(v, "encoding");
1053 if (!oenc)
1054 return -1;
1055 enc = _PyUnicode_AsString(oenc);
1056 }
1057 v = PySys_GetObject("ps1");
1058 if (v != NULL) {
1059 v = PyObject_Str(v);
1060 if (v == NULL)
1061 PyErr_Clear();
1062 else if (PyUnicode_Check(v))
1063 ps1 = _PyUnicode_AsString(v);
1064 }
1065 w = PySys_GetObject("ps2");
1066 if (w != NULL) {
1067 w = PyObject_Str(w);
1068 if (w == NULL)
1069 PyErr_Clear();
1070 else if (PyUnicode_Check(w))
1071 ps2 = _PyUnicode_AsString(w);
1072 }
1073 arena = PyArena_New();
1074 if (arena == NULL) {
1075 Py_XDECREF(v);
1076 Py_XDECREF(w);
1077 Py_XDECREF(oenc);
1078 return -1;
1079 }
1080 mod = PyParser_ASTFromFile(fp, filename, enc,
1081 Py_single_input, ps1, ps2,
1082 flags, &errcode, arena);
1083 Py_XDECREF(v);
1084 Py_XDECREF(w);
1085 Py_XDECREF(oenc);
1086 if (mod == NULL) {
1087 PyArena_Free(arena);
1088 if (errcode == E_EOF) {
1089 PyErr_Clear();
1090 return E_EOF;
1091 }
1092 PyErr_Print();
1093 return -1;
1094 }
1095 m = PyImport_AddModule("__main__");
1096 if (m == NULL) {
1097 PyArena_Free(arena);
1098 return -1;
1099 }
1100 d = PyModule_GetDict(m);
1101 v = run_mod(mod, filename, d, d, flags, arena);
1102 PyArena_Free(arena);
1103 flush_io();
1104 if (v == NULL) {
1105 PyErr_Print();
1106 return -1;
1107 }
1108 Py_DECREF(v);
1109 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001110}
1111
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001112/* Check whether a file maybe a pyc file: Look at the extension,
1113 the file type, and, if we may close it, at the first few bytes. */
1114
1115static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001116maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001117{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001118 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1119 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001120
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001121 /* Only look into the file if we are allowed to close it, since
1122 it then should also be seekable. */
1123 if (closeit) {
1124 /* Read only two bytes of the magic. If the file was opened in
1125 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1126 be read as they are on disk. */
1127 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1128 unsigned char buf[2];
1129 /* Mess: In case of -x, the stream is NOT at its start now,
1130 and ungetc() was used to push back the first newline,
1131 which makes the current stream position formally undefined,
1132 and a x-platform nightmare.
1133 Unfortunately, we have no direct way to know whether -x
1134 was specified. So we use a terrible hack: if the current
1135 stream position is not 0, we assume -x was specified, and
1136 give up. Bug 132850 on SourceForge spells out the
1137 hopelessness of trying anything else (fseek and ftell
1138 don't work predictably x-platform for text-mode files).
1139 */
1140 int ispyc = 0;
1141 if (ftell(fp) == 0) {
1142 if (fread(buf, 1, 2, fp) == 2 &&
1143 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
1144 ispyc = 1;
1145 rewind(fp);
1146 }
1147 return ispyc;
1148 }
1149 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001150}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001151
Guido van Rossum0df002c2000-08-27 19:21:52 +00001152int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001153PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001154 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001155{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001156 PyObject *m, *d, *v;
1157 const char *ext;
1158 int set_file_name = 0, ret, len;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001159
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001160 m = PyImport_AddModule("__main__");
1161 if (m == NULL)
1162 return -1;
1163 d = PyModule_GetDict(m);
1164 if (PyDict_GetItemString(d, "__file__") == NULL) {
1165 PyObject *f;
Victor Stinner15244f72010-10-19 01:22:07 +00001166 f = PyUnicode_DecodeFSDefault(filename);
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001167 if (f == NULL)
1168 return -1;
1169 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1170 Py_DECREF(f);
1171 return -1;
1172 }
1173 set_file_name = 1;
1174 Py_DECREF(f);
1175 }
1176 len = strlen(filename);
1177 ext = filename + len - (len > 4 ? 4 : 0);
1178 if (maybe_pyc_file(fp, filename, ext, closeit)) {
1179 /* Try to run a pyc file. First, re-open in binary */
1180 if (closeit)
1181 fclose(fp);
1182 if ((fp = fopen(filename, "rb")) == NULL) {
1183 fprintf(stderr, "python: Can't reopen .pyc file\n");
1184 ret = -1;
1185 goto done;
1186 }
1187 /* Turn on optimization if a .pyo file is given */
1188 if (strcmp(ext, ".pyo") == 0)
1189 Py_OptimizeFlag = 1;
1190 v = run_pyc_file(fp, filename, d, d, flags);
1191 } else {
1192 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
1193 closeit, flags);
1194 }
1195 flush_io();
1196 if (v == NULL) {
1197 PyErr_Print();
1198 ret = -1;
1199 goto done;
1200 }
1201 Py_DECREF(v);
1202 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001203 done:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001204 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1205 PyErr_Clear();
1206 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001207}
1208
1209int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001210PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001211{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001212 PyObject *m, *d, *v;
1213 m = PyImport_AddModule("__main__");
1214 if (m == NULL)
1215 return -1;
1216 d = PyModule_GetDict(m);
1217 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
1218 if (v == NULL) {
1219 PyErr_Print();
1220 return -1;
1221 }
1222 Py_DECREF(v);
1223 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001224}
1225
Barry Warsaw035574d1997-08-29 22:07:17 +00001226static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001227parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001228 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001229{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001230 long hold;
1231 PyObject *v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001232
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001233 /* old style errors */
1234 if (PyTuple_Check(err))
1235 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
1236 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001237
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001238 /* new style errors. `err' is an instance */
Barry Warsaw035574d1997-08-29 22:07:17 +00001239
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001240 if (! (v = PyObject_GetAttrString(err, "msg")))
1241 goto finally;
1242 *message = v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001243
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001244 if (!(v = PyObject_GetAttrString(err, "filename")))
1245 goto finally;
1246 if (v == Py_None)
1247 *filename = NULL;
1248 else if (! (*filename = _PyUnicode_AsString(v)))
1249 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001250
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001251 Py_DECREF(v);
1252 if (!(v = PyObject_GetAttrString(err, "lineno")))
1253 goto finally;
1254 hold = PyLong_AsLong(v);
1255 Py_DECREF(v);
1256 v = NULL;
1257 if (hold < 0 && PyErr_Occurred())
1258 goto finally;
1259 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001260
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001261 if (!(v = PyObject_GetAttrString(err, "offset")))
1262 goto finally;
1263 if (v == Py_None) {
1264 *offset = -1;
1265 Py_DECREF(v);
1266 v = NULL;
1267 } else {
1268 hold = PyLong_AsLong(v);
1269 Py_DECREF(v);
1270 v = NULL;
1271 if (hold < 0 && PyErr_Occurred())
1272 goto finally;
1273 *offset = (int)hold;
1274 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001275
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001276 if (!(v = PyObject_GetAttrString(err, "text")))
1277 goto finally;
1278 if (v == Py_None)
1279 *text = NULL;
1280 else if (!PyUnicode_Check(v) ||
1281 !(*text = _PyUnicode_AsString(v)))
1282 goto finally;
1283 Py_DECREF(v);
1284 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001285
1286finally:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001287 Py_XDECREF(v);
1288 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001289}
1290
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001291void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001292PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001293{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001294 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001295}
1296
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001297static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001298print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001299{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001300 char *nl;
1301 if (offset >= 0) {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001302 for (;;) {
1303 nl = strchr(text, '\n');
1304 if (nl == NULL || nl-text >= offset)
1305 break;
1306 offset -= (int)(nl+1-text);
1307 text = nl+1;
1308 }
1309 while (*text == ' ' || *text == '\t') {
1310 text++;
1311 offset--;
1312 }
1313 }
1314 PyFile_WriteString(" ", f);
1315 PyFile_WriteString(text, f);
1316 if (*text == '\0' || text[strlen(text)-1] != '\n')
1317 PyFile_WriteString("\n", f);
1318 if (offset == -1)
1319 return;
1320 PyFile_WriteString(" ", f);
1321 offset--;
1322 while (offset > 0) {
1323 PyFile_WriteString(" ", f);
1324 offset--;
1325 }
1326 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001327}
1328
Guido van Rossum66e8e862001-03-23 17:54:43 +00001329static void
1330handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001331{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001332 PyObject *exception, *value, *tb;
1333 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001334
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001335 if (Py_InspectFlag)
1336 /* Don't exit if -i flag was given. This flag is set to 0
1337 * when entering interactive mode for inspecting. */
1338 return;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001339
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001340 PyErr_Fetch(&exception, &value, &tb);
1341 fflush(stdout);
1342 if (value == NULL || value == Py_None)
1343 goto done;
1344 if (PyExceptionInstance_Check(value)) {
1345 /* The error code should be in the `code' attribute. */
1346 PyObject *code = PyObject_GetAttrString(value, "code");
1347 if (code) {
1348 Py_DECREF(value);
1349 value = code;
1350 if (value == Py_None)
1351 goto done;
1352 }
1353 /* If we failed to dig out the 'code' attribute,
1354 just let the else clause below print the error. */
1355 }
1356 if (PyLong_Check(value))
1357 exitcode = (int)PyLong_AsLong(value);
1358 else {
Victor Stinner2e71d012010-05-17 09:35:44 +00001359 PyObject *sys_stderr = PySys_GetObject("stderr");
1360 if (sys_stderr != NULL)
1361 PyObject_CallMethod(sys_stderr, "flush", NULL);
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001362 PyObject_Print(value, stderr, Py_PRINT_RAW);
Victor Stinner2e71d012010-05-17 09:35:44 +00001363 fflush(stderr);
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001364 PySys_WriteStderr("\n");
1365 exitcode = 1;
1366 }
Tim Peterscf615b52003-04-19 18:47:02 +00001367 done:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001368 /* Restore and clear the exception info, in order to properly decref
1369 * the exception, value, and traceback. If we just exit instead,
1370 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1371 * some finalizers from running.
1372 */
1373 PyErr_Restore(exception, value, tb);
1374 PyErr_Clear();
1375 Py_Exit(exitcode);
1376 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001377}
1378
1379void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001380PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001381{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001382 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001383
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001384 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1385 handle_system_exit();
1386 }
1387 PyErr_Fetch(&exception, &v, &tb);
1388 if (exception == NULL)
1389 return;
1390 PyErr_NormalizeException(&exception, &v, &tb);
1391 if (tb == NULL) {
1392 tb = Py_None;
1393 Py_INCREF(tb);
1394 }
1395 PyException_SetTraceback(v, tb);
1396 if (exception == NULL)
1397 return;
1398 /* Now we know v != NULL too */
1399 if (set_sys_last_vars) {
1400 PySys_SetObject("last_type", exception);
1401 PySys_SetObject("last_value", v);
1402 PySys_SetObject("last_traceback", tb);
1403 }
1404 hook = PySys_GetObject("excepthook");
1405 if (hook) {
1406 PyObject *args = PyTuple_Pack(3, exception, v, tb);
1407 PyObject *result = PyEval_CallObject(hook, args);
1408 if (result == NULL) {
1409 PyObject *exception2, *v2, *tb2;
1410 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1411 handle_system_exit();
1412 }
1413 PyErr_Fetch(&exception2, &v2, &tb2);
1414 PyErr_NormalizeException(&exception2, &v2, &tb2);
1415 /* It should not be possible for exception2 or v2
1416 to be NULL. However PyErr_Display() can't
1417 tolerate NULLs, so just be safe. */
1418 if (exception2 == NULL) {
1419 exception2 = Py_None;
1420 Py_INCREF(exception2);
1421 }
1422 if (v2 == NULL) {
1423 v2 = Py_None;
1424 Py_INCREF(v2);
1425 }
1426 fflush(stdout);
1427 PySys_WriteStderr("Error in sys.excepthook:\n");
1428 PyErr_Display(exception2, v2, tb2);
1429 PySys_WriteStderr("\nOriginal exception was:\n");
1430 PyErr_Display(exception, v, tb);
1431 Py_DECREF(exception2);
1432 Py_DECREF(v2);
1433 Py_XDECREF(tb2);
1434 }
1435 Py_XDECREF(result);
1436 Py_XDECREF(args);
1437 } else {
1438 PySys_WriteStderr("sys.excepthook is missing\n");
1439 PyErr_Display(exception, v, tb);
1440 }
1441 Py_XDECREF(exception);
1442 Py_XDECREF(v);
1443 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001444}
1445
Benjamin Petersone6528212008-07-15 15:32:09 +00001446static void
1447print_exception(PyObject *f, PyObject *value)
1448{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001449 int err = 0;
1450 PyObject *type, *tb;
Benjamin Petersone6528212008-07-15 15:32:09 +00001451
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001452 if (!PyExceptionInstance_Check(value)) {
1453 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1454 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1455 PyFile_WriteString(" found\n", f);
1456 return;
1457 }
Benjamin Peterson26582602008-08-23 20:08:07 +00001458
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001459 Py_INCREF(value);
1460 fflush(stdout);
1461 type = (PyObject *) Py_TYPE(value);
1462 tb = PyException_GetTraceback(value);
1463 if (tb && tb != Py_None)
1464 err = PyTraceBack_Print(tb, f);
1465 if (err == 0 &&
1466 PyObject_HasAttrString(value, "print_file_and_line"))
1467 {
1468 PyObject *message;
1469 const char *filename, *text;
1470 int lineno, offset;
1471 if (!parse_syntax_error(value, &message, &filename,
1472 &lineno, &offset, &text))
1473 PyErr_Clear();
1474 else {
1475 char buf[10];
1476 PyFile_WriteString(" File \"", f);
1477 if (filename == NULL)
1478 PyFile_WriteString("<string>", f);
1479 else
1480 PyFile_WriteString(filename, f);
1481 PyFile_WriteString("\", line ", f);
1482 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1483 PyFile_WriteString(buf, f);
1484 PyFile_WriteString("\n", f);
1485 if (text != NULL)
1486 print_error_text(f, offset, text);
1487 Py_DECREF(value);
1488 value = message;
1489 /* Can't be bothered to check all those
1490 PyFile_WriteString() calls */
1491 if (PyErr_Occurred())
1492 err = -1;
1493 }
1494 }
1495 if (err) {
1496 /* Don't do anything else */
1497 }
1498 else {
1499 PyObject* moduleName;
1500 char* className;
1501 assert(PyExceptionClass_Check(type));
1502 className = PyExceptionClass_Name(type);
1503 if (className != NULL) {
1504 char *dot = strrchr(className, '.');
1505 if (dot != NULL)
1506 className = dot+1;
1507 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001508
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001509 moduleName = PyObject_GetAttrString(type, "__module__");
1510 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1511 {
1512 Py_DECREF(moduleName);
1513 err = PyFile_WriteString("<unknown>", f);
1514 }
1515 else {
1516 char* modstr = _PyUnicode_AsString(moduleName);
1517 if (modstr && strcmp(modstr, "builtins"))
1518 {
1519 err = PyFile_WriteString(modstr, f);
1520 err += PyFile_WriteString(".", f);
1521 }
1522 Py_DECREF(moduleName);
1523 }
1524 if (err == 0) {
1525 if (className == NULL)
1526 err = PyFile_WriteString("<unknown>", f);
1527 else
1528 err = PyFile_WriteString(className, f);
1529 }
1530 }
1531 if (err == 0 && (value != Py_None)) {
1532 PyObject *s = PyObject_Str(value);
1533 /* only print colon if the str() of the
1534 object is not the empty string
1535 */
1536 if (s == NULL)
1537 err = -1;
1538 else if (!PyUnicode_Check(s) ||
1539 PyUnicode_GetSize(s) != 0)
1540 err = PyFile_WriteString(": ", f);
1541 if (err == 0)
1542 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1543 Py_XDECREF(s);
1544 }
1545 /* try to write a newline in any case */
1546 err += PyFile_WriteString("\n", f);
1547 Py_XDECREF(tb);
1548 Py_DECREF(value);
1549 /* If an error happened here, don't show it.
1550 XXX This is wrong, but too many callers rely on this behavior. */
1551 if (err != 0)
1552 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001553}
1554
1555static const char *cause_message =
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001556 "\nThe above exception was the direct cause "
1557 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001558
1559static const char *context_message =
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001560 "\nDuring handling of the above exception, "
1561 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001562
1563static void
1564print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1565{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001566 int err = 0, res;
1567 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00001568
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001569 if (seen != NULL) {
1570 /* Exception chaining */
1571 if (PySet_Add(seen, value) == -1)
1572 PyErr_Clear();
1573 else if (PyExceptionInstance_Check(value)) {
1574 cause = PyException_GetCause(value);
1575 context = PyException_GetContext(value);
1576 if (cause) {
1577 res = PySet_Contains(seen, cause);
1578 if (res == -1)
1579 PyErr_Clear();
1580 if (res == 0) {
1581 print_exception_recursive(
1582 f, cause, seen);
1583 err |= PyFile_WriteString(
1584 cause_message, f);
1585 }
1586 }
1587 else if (context) {
1588 res = PySet_Contains(seen, context);
1589 if (res == -1)
1590 PyErr_Clear();
1591 if (res == 0) {
1592 print_exception_recursive(
1593 f, context, seen);
1594 err |= PyFile_WriteString(
1595 context_message, f);
1596 }
1597 }
1598 Py_XDECREF(context);
1599 Py_XDECREF(cause);
1600 }
1601 }
1602 print_exception(f, value);
1603 if (err != 0)
1604 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001605}
1606
Thomas Wouters477c8d52006-05-27 19:21:47 +00001607void
1608PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001609{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001610 PyObject *seen;
1611 PyObject *f = PySys_GetObject("stderr");
1612 if (f == Py_None) {
1613 /* pass */
1614 }
1615 else if (f == NULL) {
1616 _PyObject_Dump(value);
1617 fprintf(stderr, "lost sys.stderr\n");
1618 }
1619 else {
1620 /* We choose to ignore seen being possibly NULL, and report
1621 at least the main exception (it could be a MemoryError).
1622 */
1623 seen = PySet_New(NULL);
1624 if (seen == NULL)
1625 PyErr_Clear();
1626 print_exception_recursive(f, value, seen);
1627 Py_XDECREF(seen);
1628 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001629}
1630
Guido van Rossum82598051997-03-05 00:20:32 +00001631PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001632PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001633 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001634{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001635 PyObject *ret = NULL;
1636 mod_ty mod;
1637 PyArena *arena = PyArena_New();
1638 if (arena == NULL)
1639 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001640
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001641 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
1642 if (mod != NULL)
1643 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
1644 PyArena_Free(arena);
1645 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001646}
1647
1648PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001649PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001650 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001651{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001652 PyObject *ret;
1653 mod_ty mod;
1654 PyArena *arena = PyArena_New();
1655 if (arena == NULL)
1656 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001657
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001658 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
1659 flags, NULL, arena);
1660 if (closeit)
1661 fclose(fp);
1662 if (mod == NULL) {
1663 PyArena_Free(arena);
1664 return NULL;
1665 }
1666 ret = run_mod(mod, filename, globals, locals, flags, arena);
1667 PyArena_Free(arena);
1668 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001669}
1670
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001671static void
1672flush_io(void)
1673{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001674 PyObject *f, *r;
1675 PyObject *type, *value, *traceback;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001676
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001677 /* Save the current exception */
1678 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001679
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001680 f = PySys_GetObject("stderr");
1681 if (f != NULL) {
1682 r = PyObject_CallMethod(f, "flush", "");
1683 if (r)
1684 Py_DECREF(r);
1685 else
1686 PyErr_Clear();
1687 }
1688 f = PySys_GetObject("stdout");
1689 if (f != NULL) {
1690 r = PyObject_CallMethod(f, "flush", "");
1691 if (r)
1692 Py_DECREF(r);
1693 else
1694 PyErr_Clear();
1695 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001696
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001697 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001698}
1699
Guido van Rossum82598051997-03-05 00:20:32 +00001700static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001701run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001702 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001703{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001704 PyCodeObject *co;
1705 PyObject *v;
1706 co = PyAST_Compile(mod, filename, flags, arena);
1707 if (co == NULL)
1708 return NULL;
1709 v = PyEval_EvalCode(co, globals, locals);
1710 Py_DECREF(co);
1711 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001712}
1713
Guido van Rossum82598051997-03-05 00:20:32 +00001714static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001715run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001716 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001717{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001718 PyCodeObject *co;
1719 PyObject *v;
1720 long magic;
1721 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001722
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001723 magic = PyMarshal_ReadLongFromFile(fp);
1724 if (magic != PyImport_GetMagicNumber()) {
1725 PyErr_SetString(PyExc_RuntimeError,
1726 "Bad magic number in .pyc file");
1727 return NULL;
1728 }
1729 (void) PyMarshal_ReadLongFromFile(fp);
1730 v = PyMarshal_ReadLastObjectFromFile(fp);
1731 fclose(fp);
1732 if (v == NULL || !PyCode_Check(v)) {
1733 Py_XDECREF(v);
1734 PyErr_SetString(PyExc_RuntimeError,
1735 "Bad code object in .pyc file");
1736 return NULL;
1737 }
1738 co = (PyCodeObject *)v;
1739 v = PyEval_EvalCode(co, globals, locals);
1740 if (v && flags)
1741 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1742 Py_DECREF(co);
1743 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001744}
1745
Guido van Rossum82598051997-03-05 00:20:32 +00001746PyObject *
Tim Petersd08e3822003-04-17 15:24:21 +00001747Py_CompileStringFlags(const char *str, const char *filename, int start,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001748 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001749{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001750 PyCodeObject *co;
1751 mod_ty mod;
1752 PyArena *arena = PyArena_New();
1753 if (arena == NULL)
1754 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001755
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001756 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
1757 if (mod == NULL) {
1758 PyArena_Free(arena);
1759 return NULL;
1760 }
1761 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
1762 PyObject *result = PyAST_mod2obj(mod);
1763 PyArena_Free(arena);
1764 return result;
1765 }
1766 co = PyAST_Compile(mod, filename, flags, arena);
1767 PyArena_Free(arena);
1768 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001769}
1770
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001771struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001772Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001773{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001774 struct symtable *st;
1775 mod_ty mod;
1776 PyCompilerFlags flags;
1777 PyArena *arena = PyArena_New();
1778 if (arena == NULL)
1779 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001780
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001781 flags.cf_flags = 0;
1782 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
1783 if (mod == NULL) {
1784 PyArena_Free(arena);
1785 return NULL;
1786 }
1787 st = PySymtable_Build(mod, filename, 0);
1788 PyArena_Free(arena);
1789 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001790}
1791
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001792/* Preferred access to parser is through AST. */
1793mod_ty
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001794PyParser_ASTFromString(const char *s, const char *filename, int start,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001795 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001796{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001797 mod_ty mod;
1798 PyCompilerFlags localflags;
1799 perrdetail err;
1800 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001801
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001802 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
1803 &_PyParser_Grammar, start, &err,
1804 &iflags);
1805 if (flags == NULL) {
1806 localflags.cf_flags = 0;
1807 flags = &localflags;
1808 }
1809 if (n) {
1810 flags->cf_flags |= iflags & PyCF_MASK;
1811 mod = PyAST_FromNode(n, flags, filename, arena);
1812 PyNode_Free(n);
1813 return mod;
1814 }
1815 else {
1816 err_input(&err);
1817 return NULL;
1818 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001819}
1820
1821mod_ty
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001822PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001823 int start, char *ps1,
1824 char *ps2, PyCompilerFlags *flags, int *errcode,
1825 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001826{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001827 mod_ty mod;
1828 PyCompilerFlags localflags;
1829 perrdetail err;
1830 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001831
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001832 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc,
1833 &_PyParser_Grammar,
1834 start, ps1, ps2, &err, &iflags);
1835 if (flags == NULL) {
1836 localflags.cf_flags = 0;
1837 flags = &localflags;
1838 }
1839 if (n) {
1840 flags->cf_flags |= iflags & PyCF_MASK;
1841 mod = PyAST_FromNode(n, flags, filename, arena);
1842 PyNode_Free(n);
1843 return mod;
1844 }
1845 else {
1846 err_input(&err);
1847 if (errcode)
1848 *errcode = err.error;
1849 return NULL;
1850 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001851}
1852
Guido van Rossuma110aa61994-08-29 12:50:44 +00001853/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001854
Guido van Rossuma110aa61994-08-29 12:50:44 +00001855node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001856PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001857{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001858 perrdetail err;
1859 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
1860 &_PyParser_Grammar,
1861 start, NULL, NULL, &err, flags);
1862 if (n == NULL)
1863 err_input(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001864
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001865 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001866}
1867
Guido van Rossuma110aa61994-08-29 12:50:44 +00001868/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001869
Guido van Rossuma110aa61994-08-29 12:50:44 +00001870node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001871PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001872{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001873 perrdetail err;
1874 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1875 start, &err, flags);
1876 if (n == NULL)
1877 err_input(&err);
1878 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00001879}
1880
1881node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001882PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001883 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001884{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001885 perrdetail err;
1886 node *n = PyParser_ParseStringFlagsFilename(str, filename,
1887 &_PyParser_Grammar, start, &err, flags);
1888 if (n == NULL)
1889 err_input(&err);
1890 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001891}
1892
1893node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001894PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001895{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001896 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001897}
1898
Guido van Rossum66ebd912003-04-17 16:02:26 +00001899/* May want to move a more generalized form of this to parsetok.c or
1900 even parser modules. */
1901
1902void
1903PyParser_SetError(perrdetail *err)
1904{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001905 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00001906}
1907
Guido van Rossuma110aa61994-08-29 12:50:44 +00001908/* Set the error appropriate to the given input error code (see errcode.h) */
1909
1910static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001911err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001912{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001913 PyObject *v, *w, *errtype, *errtext;
1914 PyObject* u = NULL;
Victor Stinner15244f72010-10-19 01:22:07 +00001915 PyObject *filename;
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001916 char *msg = NULL;
Victor Stinner15244f72010-10-19 01:22:07 +00001917
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001918 errtype = PyExc_SyntaxError;
1919 switch (err->error) {
1920 case E_ERROR:
1921 return;
1922 case E_SYNTAX:
1923 errtype = PyExc_IndentationError;
1924 if (err->expected == INDENT)
1925 msg = "expected an indented block";
1926 else if (err->token == INDENT)
1927 msg = "unexpected indent";
1928 else if (err->token == DEDENT)
1929 msg = "unexpected unindent";
1930 else {
1931 errtype = PyExc_SyntaxError;
1932 msg = "invalid syntax";
1933 }
1934 break;
1935 case E_TOKEN:
1936 msg = "invalid token";
1937 break;
1938 case E_EOFS:
1939 msg = "EOF while scanning triple-quoted string literal";
1940 break;
1941 case E_EOLS:
1942 msg = "EOL while scanning string literal";
1943 break;
1944 case E_INTR:
1945 if (!PyErr_Occurred())
1946 PyErr_SetNone(PyExc_KeyboardInterrupt);
1947 goto cleanup;
1948 case E_NOMEM:
1949 PyErr_NoMemory();
1950 goto cleanup;
1951 case E_EOF:
1952 msg = "unexpected EOF while parsing";
1953 break;
1954 case E_TABSPACE:
1955 errtype = PyExc_TabError;
1956 msg = "inconsistent use of tabs and spaces in indentation";
1957 break;
1958 case E_OVERFLOW:
1959 msg = "expression too long";
1960 break;
1961 case E_DEDENT:
1962 errtype = PyExc_IndentationError;
1963 msg = "unindent does not match any outer indentation level";
1964 break;
1965 case E_TOODEEP:
1966 errtype = PyExc_IndentationError;
1967 msg = "too many levels of indentation";
1968 break;
1969 case E_DECODE: {
1970 PyObject *type, *value, *tb;
1971 PyErr_Fetch(&type, &value, &tb);
1972 if (value != NULL) {
1973 u = PyObject_Str(value);
1974 if (u != NULL) {
1975 msg = _PyUnicode_AsString(u);
1976 }
1977 }
1978 if (msg == NULL)
1979 msg = "unknown decode error";
1980 Py_XDECREF(type);
1981 Py_XDECREF(value);
1982 Py_XDECREF(tb);
1983 break;
1984 }
1985 case E_LINECONT:
1986 msg = "unexpected character after line continuation character";
1987 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00001988
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001989 case E_IDENTIFIER:
1990 msg = "invalid character in identifier";
1991 break;
1992 default:
1993 fprintf(stderr, "error=%d\n", err->error);
1994 msg = "unknown parsing error";
1995 break;
1996 }
1997 /* err->text may not be UTF-8 in case of decoding errors.
1998 Explicitly convert to an object. */
1999 if (!err->text) {
2000 errtext = Py_None;
2001 Py_INCREF(Py_None);
2002 } else {
2003 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
2004 "replace");
2005 }
Victor Stinner15244f72010-10-19 01:22:07 +00002006 if (err->filename != NULL)
2007 filename = PyUnicode_DecodeFSDefault(err->filename);
2008 else {
2009 Py_INCREF(Py_None);
2010 filename = Py_None;
2011 }
2012 if (filename != NULL)
2013 v = Py_BuildValue("(NiiN)", filename,
2014 err->lineno, err->offset, errtext);
2015 else
2016 v = NULL;
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002017 w = NULL;
2018 if (v != NULL)
2019 w = Py_BuildValue("(sO)", msg, v);
2020 Py_XDECREF(u);
2021 Py_XDECREF(v);
2022 PyErr_SetObject(errtype, w);
2023 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00002024cleanup:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002025 if (err->text != NULL) {
2026 PyObject_FREE(err->text);
2027 err->text = NULL;
2028 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002029}
2030
2031/* Print fatal error message and abort */
2032
2033void
Tim Peters7c321a82002-07-09 02:57:01 +00002034Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002035{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002036 fprintf(stderr, "Fatal Python error: %s\n", msg);
2037 fflush(stderr); /* it helps in Windows debug build */
2038 if (PyErr_Occurred()) {
Victor Stinner93362d42010-06-08 21:05:20 +00002039 PyErr_PrintEx(0);
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002040 }
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002041#ifdef MS_WINDOWS
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002042 {
2043 size_t len = strlen(msg);
2044 WCHAR* buffer;
2045 size_t i;
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002046
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002047 /* Convert the message to wchar_t. This uses a simple one-to-one
2048 conversion, assuming that the this error message actually uses ASCII
2049 only. If this ceases to be true, we will have to convert. */
2050 buffer = alloca( (len+1) * (sizeof *buffer));
2051 for( i=0; i<=len; ++i)
2052 buffer[i] = msg[i];
2053 OutputDebugStringW(L"Fatal Python error: ");
2054 OutputDebugStringW(buffer);
2055 OutputDebugStringW(L"\n");
2056 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002057#ifdef _DEBUG
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002058 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002059#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002060#endif /* MS_WINDOWS */
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002061 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002062}
2063
2064/* Clean up and exit */
2065
Guido van Rossuma110aa61994-08-29 12:50:44 +00002066#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002067#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002068#endif
2069
Collin Winter670e6922007-03-21 02:57:17 +00002070static void (*pyexitfunc)(void) = NULL;
2071/* For the atexit module. */
2072void _Py_PyAtExit(void (*func)(void))
2073{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002074 pyexitfunc = func;
Collin Winter670e6922007-03-21 02:57:17 +00002075}
2076
2077static void
2078call_py_exitfuncs(void)
2079{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002080 if (pyexitfunc == NULL)
2081 return;
Collin Winter670e6922007-03-21 02:57:17 +00002082
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002083 (*pyexitfunc)();
2084 PyErr_Clear();
Collin Winter670e6922007-03-21 02:57:17 +00002085}
2086
Antoine Pitroucefb3162009-10-20 22:08:36 +00002087/* Wait until threading._shutdown completes, provided
2088 the threading module was imported in the first place.
2089 The shutdown routine will wait until all non-daemon
2090 "threading" threads have completed. */
2091static void
2092wait_for_thread_shutdown(void)
2093{
2094#ifdef WITH_THREAD
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002095 PyObject *result;
2096 PyThreadState *tstate = PyThreadState_GET();
2097 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2098 "threading");
2099 if (threading == NULL) {
2100 /* threading not imported */
2101 PyErr_Clear();
2102 return;
2103 }
2104 result = PyObject_CallMethod(threading, "_shutdown", "");
2105 if (result == NULL) {
2106 PyErr_WriteUnraisable(threading);
2107 }
2108 else {
2109 Py_DECREF(result);
2110 }
2111 Py_DECREF(threading);
Antoine Pitroucefb3162009-10-20 22:08:36 +00002112#endif
2113}
2114
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002115#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002116static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002117static int nexitfuncs = 0;
2118
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002119int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002120{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002121 if (nexitfuncs >= NEXITFUNCS)
2122 return -1;
2123 exitfuncs[nexitfuncs++] = func;
2124 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00002125}
2126
Guido van Rossumcc283f51997-08-05 02:22:03 +00002127static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002128call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002129{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002130 while (nexitfuncs > 0)
2131 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002132
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002133 fflush(stdout);
2134 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002135}
2136
2137void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002138Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002139{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002140 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002141
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002142 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002143}
2144
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002145static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002146initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002147{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002148#ifdef SIGPIPE
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002149 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002150#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002151#ifdef SIGXFZ
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002152 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002153#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002154#ifdef SIGXFSZ
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002155 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002156#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002157 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002158}
2159
Guido van Rossum7433b121997-02-14 19:45:36 +00002160
2161/*
2162 * The file descriptor fd is considered ``interactive'' if either
2163 * a) isatty(fd) is TRUE, or
2164 * b) the -i flag was given, and the filename associated with
2165 * the descriptor is NULL or "<stdin>" or "???".
2166 */
2167int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002168Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002169{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002170 if (isatty((int)fileno(fp)))
2171 return 1;
2172 if (!Py_InteractiveFlag)
2173 return 0;
2174 return (filename == NULL) ||
2175 (strcmp(filename, "<stdin>") == 0) ||
2176 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00002177}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002178
2179
Tim Petersd08e3822003-04-17 15:24:21 +00002180#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002181#if defined(WIN32) && defined(_MSC_VER)
2182
2183/* Stack checking for Microsoft C */
2184
2185#include <malloc.h>
2186#include <excpt.h>
2187
Fred Drakee8de31c2000-08-31 05:38:39 +00002188/*
2189 * Return non-zero when we run out of memory on the stack; zero otherwise.
2190 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002191int
Fred Drake399739f2000-08-31 05:52:44 +00002192PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002193{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002194 __try {
2195 /* alloca throws a stack overflow exception if there's
2196 not enough space left on the stack */
2197 alloca(PYOS_STACK_MARGIN * sizeof(void*));
2198 return 0;
2199 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2200 EXCEPTION_EXECUTE_HANDLER :
2201 EXCEPTION_CONTINUE_SEARCH) {
2202 int errcode = _resetstkoflw();
2203 if (errcode == 0)
2204 {
2205 Py_FatalError("Could not reset the stack!");
2206 }
2207 }
2208 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002209}
2210
2211#endif /* WIN32 && _MSC_VER */
2212
2213/* Alternate implementations can be added here... */
2214
2215#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002216
2217
2218/* Wrappers around sigaction() or signal(). */
2219
2220PyOS_sighandler_t
2221PyOS_getsig(int sig)
2222{
2223#ifdef HAVE_SIGACTION
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002224 struct sigaction context;
2225 if (sigaction(sig, NULL, &context) == -1)
2226 return SIG_ERR;
2227 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002228#else
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002229 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002230/* Special signal handling for the secure CRT in Visual Studio 2005 */
2231#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002232 switch (sig) {
2233 /* Only these signals are valid */
2234 case SIGINT:
2235 case SIGILL:
2236 case SIGFPE:
2237 case SIGSEGV:
2238 case SIGTERM:
2239 case SIGBREAK:
2240 case SIGABRT:
2241 break;
2242 /* Don't call signal() with other values or it will assert */
2243 default:
2244 return SIG_ERR;
2245 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002246#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002247 handler = signal(sig, SIG_IGN);
2248 if (handler != SIG_ERR)
2249 signal(sig, handler);
2250 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002251#endif
2252}
2253
2254PyOS_sighandler_t
2255PyOS_setsig(int sig, PyOS_sighandler_t handler)
2256{
2257#ifdef HAVE_SIGACTION
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002258 /* Some code in Modules/signalmodule.c depends on sigaction() being
2259 * used here if HAVE_SIGACTION is defined. Fix that if this code
2260 * changes to invalidate that assumption.
2261 */
2262 struct sigaction context, ocontext;
2263 context.sa_handler = handler;
2264 sigemptyset(&context.sa_mask);
2265 context.sa_flags = 0;
2266 if (sigaction(sig, &context, &ocontext) == -1)
2267 return SIG_ERR;
2268 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002269#else
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002270 PyOS_sighandler_t oldhandler;
2271 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002272#ifdef HAVE_SIGINTERRUPT
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002273 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002274#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002275 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002276#endif
2277}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002278
2279/* Deprecated C API functions still provided for binary compatiblity */
2280
2281#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002282PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002283PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2284{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002285 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002286}
2287
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002288#undef PyParser_SimpleParseString
2289PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002290PyParser_SimpleParseString(const char *str, int start)
2291{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002292 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002293}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002294
2295#undef PyRun_AnyFile
2296PyAPI_FUNC(int)
2297PyRun_AnyFile(FILE *fp, const char *name)
2298{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002299 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002300}
2301
2302#undef PyRun_AnyFileEx
2303PyAPI_FUNC(int)
2304PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2305{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002306 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002307}
2308
2309#undef PyRun_AnyFileFlags
2310PyAPI_FUNC(int)
2311PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2312{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002313 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002314}
2315
2316#undef PyRun_File
2317PyAPI_FUNC(PyObject *)
2318PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2319{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002320 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002321}
2322
2323#undef PyRun_FileEx
2324PyAPI_FUNC(PyObject *)
2325PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2326{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002327 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002328}
2329
2330#undef PyRun_FileFlags
2331PyAPI_FUNC(PyObject *)
2332PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002333 PyCompilerFlags *flags)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002334{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002335 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002336}
2337
2338#undef PyRun_SimpleFile
2339PyAPI_FUNC(int)
2340PyRun_SimpleFile(FILE *f, const char *p)
2341{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002342 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002343}
2344
2345#undef PyRun_SimpleFileEx
2346PyAPI_FUNC(int)
2347PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2348{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002349 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002350}
2351
2352
2353#undef PyRun_String
2354PyAPI_FUNC(PyObject *)
2355PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2356{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002357 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002358}
2359
2360#undef PyRun_SimpleString
2361PyAPI_FUNC(int)
2362PyRun_SimpleString(const char *s)
2363{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002364 return PyRun_SimpleStringFlags(s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002365}
2366
2367#undef Py_CompileString
2368PyAPI_FUNC(PyObject *)
2369Py_CompileString(const char *str, const char *p, int s)
2370{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002371 return Py_CompileStringFlags(str, p, s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002372}
2373
2374#undef PyRun_InteractiveOne
2375PyAPI_FUNC(int)
2376PyRun_InteractiveOne(FILE *f, const char *p)
2377{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002378 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002379}
2380
2381#undef PyRun_InteractiveLoop
2382PyAPI_FUNC(int)
2383PyRun_InteractiveLoop(FILE *f, const char *p)
2384{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002385 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002386}
2387
2388#ifdef __cplusplus
2389}
2390#endif