blob: 3dbe754d26341d36c5b3ee48cc2a5407e56357be [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) {
Benjamin Petersonc8850d02010-10-29 04:02:30 +00001302 if (offset > 0 && offset == strlen(text) && text[offset - 1] == '\n')
1303 offset--;
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001304 for (;;) {
1305 nl = strchr(text, '\n');
1306 if (nl == NULL || nl-text >= offset)
1307 break;
1308 offset -= (int)(nl+1-text);
1309 text = nl+1;
1310 }
1311 while (*text == ' ' || *text == '\t') {
1312 text++;
1313 offset--;
1314 }
1315 }
1316 PyFile_WriteString(" ", f);
1317 PyFile_WriteString(text, f);
1318 if (*text == '\0' || text[strlen(text)-1] != '\n')
1319 PyFile_WriteString("\n", f);
1320 if (offset == -1)
1321 return;
1322 PyFile_WriteString(" ", f);
Benjamin Petersonc8850d02010-10-29 04:02:30 +00001323 while (--offset > 0)
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001324 PyFile_WriteString(" ", f);
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001325 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001326}
1327
Guido van Rossum66e8e862001-03-23 17:54:43 +00001328static void
1329handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001330{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001331 PyObject *exception, *value, *tb;
1332 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001333
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001334 if (Py_InspectFlag)
1335 /* Don't exit if -i flag was given. This flag is set to 0
1336 * when entering interactive mode for inspecting. */
1337 return;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001338
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001339 PyErr_Fetch(&exception, &value, &tb);
1340 fflush(stdout);
1341 if (value == NULL || value == Py_None)
1342 goto done;
1343 if (PyExceptionInstance_Check(value)) {
1344 /* The error code should be in the `code' attribute. */
1345 PyObject *code = PyObject_GetAttrString(value, "code");
1346 if (code) {
1347 Py_DECREF(value);
1348 value = code;
1349 if (value == Py_None)
1350 goto done;
1351 }
1352 /* If we failed to dig out the 'code' attribute,
1353 just let the else clause below print the error. */
1354 }
1355 if (PyLong_Check(value))
1356 exitcode = (int)PyLong_AsLong(value);
1357 else {
Victor Stinner2e71d012010-05-17 09:35:44 +00001358 PyObject *sys_stderr = PySys_GetObject("stderr");
1359 if (sys_stderr != NULL)
1360 PyObject_CallMethod(sys_stderr, "flush", NULL);
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001361 PyObject_Print(value, stderr, Py_PRINT_RAW);
Victor Stinner2e71d012010-05-17 09:35:44 +00001362 fflush(stderr);
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001363 PySys_WriteStderr("\n");
1364 exitcode = 1;
1365 }
Tim Peterscf615b52003-04-19 18:47:02 +00001366 done:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001367 /* Restore and clear the exception info, in order to properly decref
1368 * the exception, value, and traceback. If we just exit instead,
1369 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1370 * some finalizers from running.
1371 */
1372 PyErr_Restore(exception, value, tb);
1373 PyErr_Clear();
1374 Py_Exit(exitcode);
1375 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001376}
1377
1378void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001379PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001380{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001381 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001382
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001383 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1384 handle_system_exit();
1385 }
1386 PyErr_Fetch(&exception, &v, &tb);
1387 if (exception == NULL)
1388 return;
1389 PyErr_NormalizeException(&exception, &v, &tb);
1390 if (tb == NULL) {
1391 tb = Py_None;
1392 Py_INCREF(tb);
1393 }
1394 PyException_SetTraceback(v, tb);
1395 if (exception == NULL)
1396 return;
1397 /* Now we know v != NULL too */
1398 if (set_sys_last_vars) {
1399 PySys_SetObject("last_type", exception);
1400 PySys_SetObject("last_value", v);
1401 PySys_SetObject("last_traceback", tb);
1402 }
1403 hook = PySys_GetObject("excepthook");
1404 if (hook) {
1405 PyObject *args = PyTuple_Pack(3, exception, v, tb);
1406 PyObject *result = PyEval_CallObject(hook, args);
1407 if (result == NULL) {
1408 PyObject *exception2, *v2, *tb2;
1409 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1410 handle_system_exit();
1411 }
1412 PyErr_Fetch(&exception2, &v2, &tb2);
1413 PyErr_NormalizeException(&exception2, &v2, &tb2);
1414 /* It should not be possible for exception2 or v2
1415 to be NULL. However PyErr_Display() can't
1416 tolerate NULLs, so just be safe. */
1417 if (exception2 == NULL) {
1418 exception2 = Py_None;
1419 Py_INCREF(exception2);
1420 }
1421 if (v2 == NULL) {
1422 v2 = Py_None;
1423 Py_INCREF(v2);
1424 }
1425 fflush(stdout);
1426 PySys_WriteStderr("Error in sys.excepthook:\n");
1427 PyErr_Display(exception2, v2, tb2);
1428 PySys_WriteStderr("\nOriginal exception was:\n");
1429 PyErr_Display(exception, v, tb);
1430 Py_DECREF(exception2);
1431 Py_DECREF(v2);
1432 Py_XDECREF(tb2);
1433 }
1434 Py_XDECREF(result);
1435 Py_XDECREF(args);
1436 } else {
1437 PySys_WriteStderr("sys.excepthook is missing\n");
1438 PyErr_Display(exception, v, tb);
1439 }
1440 Py_XDECREF(exception);
1441 Py_XDECREF(v);
1442 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001443}
1444
Benjamin Petersone6528212008-07-15 15:32:09 +00001445static void
1446print_exception(PyObject *f, PyObject *value)
1447{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001448 int err = 0;
1449 PyObject *type, *tb;
Benjamin Petersone6528212008-07-15 15:32:09 +00001450
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001451 if (!PyExceptionInstance_Check(value)) {
1452 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1453 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1454 PyFile_WriteString(" found\n", f);
1455 return;
1456 }
Benjamin Peterson26582602008-08-23 20:08:07 +00001457
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001458 Py_INCREF(value);
1459 fflush(stdout);
1460 type = (PyObject *) Py_TYPE(value);
1461 tb = PyException_GetTraceback(value);
1462 if (tb && tb != Py_None)
1463 err = PyTraceBack_Print(tb, f);
1464 if (err == 0 &&
1465 PyObject_HasAttrString(value, "print_file_and_line"))
1466 {
1467 PyObject *message;
1468 const char *filename, *text;
1469 int lineno, offset;
1470 if (!parse_syntax_error(value, &message, &filename,
1471 &lineno, &offset, &text))
1472 PyErr_Clear();
1473 else {
1474 char buf[10];
1475 PyFile_WriteString(" File \"", f);
1476 if (filename == NULL)
1477 PyFile_WriteString("<string>", f);
1478 else
1479 PyFile_WriteString(filename, f);
1480 PyFile_WriteString("\", line ", f);
1481 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1482 PyFile_WriteString(buf, f);
1483 PyFile_WriteString("\n", f);
1484 if (text != NULL)
1485 print_error_text(f, offset, text);
1486 Py_DECREF(value);
1487 value = message;
1488 /* Can't be bothered to check all those
1489 PyFile_WriteString() calls */
1490 if (PyErr_Occurred())
1491 err = -1;
1492 }
1493 }
1494 if (err) {
1495 /* Don't do anything else */
1496 }
1497 else {
1498 PyObject* moduleName;
1499 char* className;
1500 assert(PyExceptionClass_Check(type));
1501 className = PyExceptionClass_Name(type);
1502 if (className != NULL) {
1503 char *dot = strrchr(className, '.');
1504 if (dot != NULL)
1505 className = dot+1;
1506 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001507
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001508 moduleName = PyObject_GetAttrString(type, "__module__");
1509 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1510 {
1511 Py_DECREF(moduleName);
1512 err = PyFile_WriteString("<unknown>", f);
1513 }
1514 else {
1515 char* modstr = _PyUnicode_AsString(moduleName);
1516 if (modstr && strcmp(modstr, "builtins"))
1517 {
1518 err = PyFile_WriteString(modstr, f);
1519 err += PyFile_WriteString(".", f);
1520 }
1521 Py_DECREF(moduleName);
1522 }
1523 if (err == 0) {
1524 if (className == NULL)
1525 err = PyFile_WriteString("<unknown>", f);
1526 else
1527 err = PyFile_WriteString(className, f);
1528 }
1529 }
1530 if (err == 0 && (value != Py_None)) {
1531 PyObject *s = PyObject_Str(value);
1532 /* only print colon if the str() of the
1533 object is not the empty string
1534 */
1535 if (s == NULL)
1536 err = -1;
1537 else if (!PyUnicode_Check(s) ||
1538 PyUnicode_GetSize(s) != 0)
1539 err = PyFile_WriteString(": ", f);
1540 if (err == 0)
1541 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1542 Py_XDECREF(s);
1543 }
1544 /* try to write a newline in any case */
1545 err += PyFile_WriteString("\n", f);
1546 Py_XDECREF(tb);
1547 Py_DECREF(value);
1548 /* If an error happened here, don't show it.
1549 XXX This is wrong, but too many callers rely on this behavior. */
1550 if (err != 0)
1551 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001552}
1553
1554static const char *cause_message =
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001555 "\nThe above exception was the direct cause "
1556 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001557
1558static const char *context_message =
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001559 "\nDuring handling of the above exception, "
1560 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001561
1562static void
1563print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1564{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001565 int err = 0, res;
1566 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00001567
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001568 if (seen != NULL) {
1569 /* Exception chaining */
1570 if (PySet_Add(seen, value) == -1)
1571 PyErr_Clear();
1572 else if (PyExceptionInstance_Check(value)) {
1573 cause = PyException_GetCause(value);
1574 context = PyException_GetContext(value);
1575 if (cause) {
1576 res = PySet_Contains(seen, cause);
1577 if (res == -1)
1578 PyErr_Clear();
1579 if (res == 0) {
1580 print_exception_recursive(
1581 f, cause, seen);
1582 err |= PyFile_WriteString(
1583 cause_message, f);
1584 }
1585 }
1586 else if (context) {
1587 res = PySet_Contains(seen, context);
1588 if (res == -1)
1589 PyErr_Clear();
1590 if (res == 0) {
1591 print_exception_recursive(
1592 f, context, seen);
1593 err |= PyFile_WriteString(
1594 context_message, f);
1595 }
1596 }
1597 Py_XDECREF(context);
1598 Py_XDECREF(cause);
1599 }
1600 }
1601 print_exception(f, value);
1602 if (err != 0)
1603 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001604}
1605
Thomas Wouters477c8d52006-05-27 19:21:47 +00001606void
1607PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001608{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001609 PyObject *seen;
1610 PyObject *f = PySys_GetObject("stderr");
1611 if (f == Py_None) {
1612 /* pass */
1613 }
1614 else if (f == NULL) {
1615 _PyObject_Dump(value);
1616 fprintf(stderr, "lost sys.stderr\n");
1617 }
1618 else {
1619 /* We choose to ignore seen being possibly NULL, and report
1620 at least the main exception (it could be a MemoryError).
1621 */
1622 seen = PySet_New(NULL);
1623 if (seen == NULL)
1624 PyErr_Clear();
1625 print_exception_recursive(f, value, seen);
1626 Py_XDECREF(seen);
1627 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001628}
1629
Guido van Rossum82598051997-03-05 00:20:32 +00001630PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001631PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001632 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001633{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001634 PyObject *ret = NULL;
1635 mod_ty mod;
1636 PyArena *arena = PyArena_New();
1637 if (arena == NULL)
1638 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001639
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001640 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
1641 if (mod != NULL)
1642 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
1643 PyArena_Free(arena);
1644 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001645}
1646
1647PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001648PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001649 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001650{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001651 PyObject *ret;
1652 mod_ty mod;
1653 PyArena *arena = PyArena_New();
1654 if (arena == NULL)
1655 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001656
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001657 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
1658 flags, NULL, arena);
1659 if (closeit)
1660 fclose(fp);
1661 if (mod == NULL) {
1662 PyArena_Free(arena);
1663 return NULL;
1664 }
1665 ret = run_mod(mod, filename, globals, locals, flags, arena);
1666 PyArena_Free(arena);
1667 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001668}
1669
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001670static void
1671flush_io(void)
1672{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001673 PyObject *f, *r;
1674 PyObject *type, *value, *traceback;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001675
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001676 /* Save the current exception */
1677 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001678
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001679 f = PySys_GetObject("stderr");
1680 if (f != NULL) {
1681 r = PyObject_CallMethod(f, "flush", "");
1682 if (r)
1683 Py_DECREF(r);
1684 else
1685 PyErr_Clear();
1686 }
1687 f = PySys_GetObject("stdout");
1688 if (f != NULL) {
1689 r = PyObject_CallMethod(f, "flush", "");
1690 if (r)
1691 Py_DECREF(r);
1692 else
1693 PyErr_Clear();
1694 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001695
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001696 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001697}
1698
Guido van Rossum82598051997-03-05 00:20:32 +00001699static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001700run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001701 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001702{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001703 PyCodeObject *co;
1704 PyObject *v;
1705 co = PyAST_Compile(mod, filename, flags, arena);
1706 if (co == NULL)
1707 return NULL;
1708 v = PyEval_EvalCode(co, globals, locals);
1709 Py_DECREF(co);
1710 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001711}
1712
Guido van Rossum82598051997-03-05 00:20:32 +00001713static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001714run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001715 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001716{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001717 PyCodeObject *co;
1718 PyObject *v;
1719 long magic;
1720 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001721
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001722 magic = PyMarshal_ReadLongFromFile(fp);
1723 if (magic != PyImport_GetMagicNumber()) {
1724 PyErr_SetString(PyExc_RuntimeError,
1725 "Bad magic number in .pyc file");
1726 return NULL;
1727 }
1728 (void) PyMarshal_ReadLongFromFile(fp);
1729 v = PyMarshal_ReadLastObjectFromFile(fp);
1730 fclose(fp);
1731 if (v == NULL || !PyCode_Check(v)) {
1732 Py_XDECREF(v);
1733 PyErr_SetString(PyExc_RuntimeError,
1734 "Bad code object in .pyc file");
1735 return NULL;
1736 }
1737 co = (PyCodeObject *)v;
1738 v = PyEval_EvalCode(co, globals, locals);
1739 if (v && flags)
1740 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1741 Py_DECREF(co);
1742 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001743}
1744
Guido van Rossum82598051997-03-05 00:20:32 +00001745PyObject *
Tim Petersd08e3822003-04-17 15:24:21 +00001746Py_CompileStringFlags(const char *str, const char *filename, int start,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001747 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001748{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001749 PyCodeObject *co;
1750 mod_ty mod;
1751 PyArena *arena = PyArena_New();
1752 if (arena == NULL)
1753 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001754
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001755 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
1756 if (mod == NULL) {
1757 PyArena_Free(arena);
1758 return NULL;
1759 }
1760 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
1761 PyObject *result = PyAST_mod2obj(mod);
1762 PyArena_Free(arena);
1763 return result;
1764 }
1765 co = PyAST_Compile(mod, filename, flags, arena);
1766 PyArena_Free(arena);
1767 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001768}
1769
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001770struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001771Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001772{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001773 struct symtable *st;
1774 mod_ty mod;
1775 PyCompilerFlags flags;
1776 PyArena *arena = PyArena_New();
1777 if (arena == NULL)
1778 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001779
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001780 flags.cf_flags = 0;
1781 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
1782 if (mod == NULL) {
1783 PyArena_Free(arena);
1784 return NULL;
1785 }
1786 st = PySymtable_Build(mod, filename, 0);
1787 PyArena_Free(arena);
1788 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001789}
1790
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001791/* Preferred access to parser is through AST. */
1792mod_ty
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001793PyParser_ASTFromString(const char *s, const char *filename, int start,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001794 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001795{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001796 mod_ty mod;
1797 PyCompilerFlags localflags;
1798 perrdetail err;
1799 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001800
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001801 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
1802 &_PyParser_Grammar, start, &err,
1803 &iflags);
1804 if (flags == NULL) {
1805 localflags.cf_flags = 0;
1806 flags = &localflags;
1807 }
1808 if (n) {
1809 flags->cf_flags |= iflags & PyCF_MASK;
1810 mod = PyAST_FromNode(n, flags, filename, arena);
1811 PyNode_Free(n);
1812 return mod;
1813 }
1814 else {
1815 err_input(&err);
1816 return NULL;
1817 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001818}
1819
1820mod_ty
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001821PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001822 int start, char *ps1,
1823 char *ps2, PyCompilerFlags *flags, int *errcode,
1824 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001825{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001826 mod_ty mod;
1827 PyCompilerFlags localflags;
1828 perrdetail err;
1829 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001830
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001831 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc,
1832 &_PyParser_Grammar,
1833 start, ps1, ps2, &err, &iflags);
1834 if (flags == NULL) {
1835 localflags.cf_flags = 0;
1836 flags = &localflags;
1837 }
1838 if (n) {
1839 flags->cf_flags |= iflags & PyCF_MASK;
1840 mod = PyAST_FromNode(n, flags, filename, arena);
1841 PyNode_Free(n);
1842 return mod;
1843 }
1844 else {
1845 err_input(&err);
1846 if (errcode)
1847 *errcode = err.error;
1848 return NULL;
1849 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001850}
1851
Guido van Rossuma110aa61994-08-29 12:50:44 +00001852/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001853
Guido van Rossuma110aa61994-08-29 12:50:44 +00001854node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001855PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001856{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001857 perrdetail err;
1858 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
1859 &_PyParser_Grammar,
1860 start, NULL, NULL, &err, flags);
1861 if (n == NULL)
1862 err_input(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001863
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001864 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001865}
1866
Guido van Rossuma110aa61994-08-29 12:50:44 +00001867/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001868
Guido van Rossuma110aa61994-08-29 12:50:44 +00001869node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001870PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001871{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001872 perrdetail err;
1873 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1874 start, &err, flags);
1875 if (n == NULL)
1876 err_input(&err);
1877 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00001878}
1879
1880node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001881PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001882 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001883{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001884 perrdetail err;
1885 node *n = PyParser_ParseStringFlagsFilename(str, filename,
1886 &_PyParser_Grammar, start, &err, flags);
1887 if (n == NULL)
1888 err_input(&err);
1889 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001890}
1891
1892node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001893PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001894{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001895 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001896}
1897
Guido van Rossum66ebd912003-04-17 16:02:26 +00001898/* May want to move a more generalized form of this to parsetok.c or
1899 even parser modules. */
1900
1901void
1902PyParser_SetError(perrdetail *err)
1903{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001904 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00001905}
1906
Guido van Rossuma110aa61994-08-29 12:50:44 +00001907/* Set the error appropriate to the given input error code (see errcode.h) */
1908
1909static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001910err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001911{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001912 PyObject *v, *w, *errtype, *errtext;
1913 PyObject* u = NULL;
Victor Stinner15244f72010-10-19 01:22:07 +00001914 PyObject *filename;
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001915 char *msg = NULL;
Victor Stinner15244f72010-10-19 01:22:07 +00001916
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001917 errtype = PyExc_SyntaxError;
1918 switch (err->error) {
1919 case E_ERROR:
1920 return;
1921 case E_SYNTAX:
1922 errtype = PyExc_IndentationError;
1923 if (err->expected == INDENT)
1924 msg = "expected an indented block";
1925 else if (err->token == INDENT)
1926 msg = "unexpected indent";
1927 else if (err->token == DEDENT)
1928 msg = "unexpected unindent";
1929 else {
1930 errtype = PyExc_SyntaxError;
1931 msg = "invalid syntax";
1932 }
1933 break;
1934 case E_TOKEN:
1935 msg = "invalid token";
1936 break;
1937 case E_EOFS:
1938 msg = "EOF while scanning triple-quoted string literal";
1939 break;
1940 case E_EOLS:
1941 msg = "EOL while scanning string literal";
1942 break;
1943 case E_INTR:
1944 if (!PyErr_Occurred())
1945 PyErr_SetNone(PyExc_KeyboardInterrupt);
1946 goto cleanup;
1947 case E_NOMEM:
1948 PyErr_NoMemory();
1949 goto cleanup;
1950 case E_EOF:
1951 msg = "unexpected EOF while parsing";
1952 break;
1953 case E_TABSPACE:
1954 errtype = PyExc_TabError;
1955 msg = "inconsistent use of tabs and spaces in indentation";
1956 break;
1957 case E_OVERFLOW:
1958 msg = "expression too long";
1959 break;
1960 case E_DEDENT:
1961 errtype = PyExc_IndentationError;
1962 msg = "unindent does not match any outer indentation level";
1963 break;
1964 case E_TOODEEP:
1965 errtype = PyExc_IndentationError;
1966 msg = "too many levels of indentation";
1967 break;
1968 case E_DECODE: {
1969 PyObject *type, *value, *tb;
1970 PyErr_Fetch(&type, &value, &tb);
1971 if (value != NULL) {
1972 u = PyObject_Str(value);
1973 if (u != NULL) {
1974 msg = _PyUnicode_AsString(u);
1975 }
1976 }
1977 if (msg == NULL)
1978 msg = "unknown decode error";
1979 Py_XDECREF(type);
1980 Py_XDECREF(value);
1981 Py_XDECREF(tb);
1982 break;
1983 }
1984 case E_LINECONT:
1985 msg = "unexpected character after line continuation character";
1986 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00001987
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001988 case E_IDENTIFIER:
1989 msg = "invalid character in identifier";
1990 break;
1991 default:
1992 fprintf(stderr, "error=%d\n", err->error);
1993 msg = "unknown parsing error";
1994 break;
1995 }
1996 /* err->text may not be UTF-8 in case of decoding errors.
1997 Explicitly convert to an object. */
1998 if (!err->text) {
1999 errtext = Py_None;
2000 Py_INCREF(Py_None);
2001 } else {
2002 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
2003 "replace");
2004 }
Victor Stinner15244f72010-10-19 01:22:07 +00002005 if (err->filename != NULL)
2006 filename = PyUnicode_DecodeFSDefault(err->filename);
2007 else {
2008 Py_INCREF(Py_None);
2009 filename = Py_None;
2010 }
2011 if (filename != NULL)
2012 v = Py_BuildValue("(NiiN)", filename,
2013 err->lineno, err->offset, errtext);
2014 else
2015 v = NULL;
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002016 w = NULL;
2017 if (v != NULL)
2018 w = Py_BuildValue("(sO)", msg, v);
2019 Py_XDECREF(u);
2020 Py_XDECREF(v);
2021 PyErr_SetObject(errtype, w);
2022 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00002023cleanup:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002024 if (err->text != NULL) {
2025 PyObject_FREE(err->text);
2026 err->text = NULL;
2027 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002028}
2029
2030/* Print fatal error message and abort */
2031
2032void
Tim Peters7c321a82002-07-09 02:57:01 +00002033Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002034{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002035 fprintf(stderr, "Fatal Python error: %s\n", msg);
2036 fflush(stderr); /* it helps in Windows debug build */
2037 if (PyErr_Occurred()) {
Victor Stinner93362d42010-06-08 21:05:20 +00002038 PyErr_PrintEx(0);
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002039 }
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002040#ifdef MS_WINDOWS
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002041 {
2042 size_t len = strlen(msg);
2043 WCHAR* buffer;
2044 size_t i;
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002045
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002046 /* Convert the message to wchar_t. This uses a simple one-to-one
2047 conversion, assuming that the this error message actually uses ASCII
2048 only. If this ceases to be true, we will have to convert. */
2049 buffer = alloca( (len+1) * (sizeof *buffer));
2050 for( i=0; i<=len; ++i)
2051 buffer[i] = msg[i];
2052 OutputDebugStringW(L"Fatal Python error: ");
2053 OutputDebugStringW(buffer);
2054 OutputDebugStringW(L"\n");
2055 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002056#ifdef _DEBUG
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002057 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002058#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002059#endif /* MS_WINDOWS */
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002060 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002061}
2062
2063/* Clean up and exit */
2064
Guido van Rossuma110aa61994-08-29 12:50:44 +00002065#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002066#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002067#endif
2068
Collin Winter670e6922007-03-21 02:57:17 +00002069static void (*pyexitfunc)(void) = NULL;
2070/* For the atexit module. */
2071void _Py_PyAtExit(void (*func)(void))
2072{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002073 pyexitfunc = func;
Collin Winter670e6922007-03-21 02:57:17 +00002074}
2075
2076static void
2077call_py_exitfuncs(void)
2078{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002079 if (pyexitfunc == NULL)
2080 return;
Collin Winter670e6922007-03-21 02:57:17 +00002081
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002082 (*pyexitfunc)();
2083 PyErr_Clear();
Collin Winter670e6922007-03-21 02:57:17 +00002084}
2085
Antoine Pitroucefb3162009-10-20 22:08:36 +00002086/* Wait until threading._shutdown completes, provided
2087 the threading module was imported in the first place.
2088 The shutdown routine will wait until all non-daemon
2089 "threading" threads have completed. */
2090static void
2091wait_for_thread_shutdown(void)
2092{
2093#ifdef WITH_THREAD
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002094 PyObject *result;
2095 PyThreadState *tstate = PyThreadState_GET();
2096 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2097 "threading");
2098 if (threading == NULL) {
2099 /* threading not imported */
2100 PyErr_Clear();
2101 return;
2102 }
2103 result = PyObject_CallMethod(threading, "_shutdown", "");
2104 if (result == NULL) {
2105 PyErr_WriteUnraisable(threading);
2106 }
2107 else {
2108 Py_DECREF(result);
2109 }
2110 Py_DECREF(threading);
Antoine Pitroucefb3162009-10-20 22:08:36 +00002111#endif
2112}
2113
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002114#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002115static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002116static int nexitfuncs = 0;
2117
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002118int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002119{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002120 if (nexitfuncs >= NEXITFUNCS)
2121 return -1;
2122 exitfuncs[nexitfuncs++] = func;
2123 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00002124}
2125
Guido van Rossumcc283f51997-08-05 02:22:03 +00002126static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002127call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002128{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002129 while (nexitfuncs > 0)
2130 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002131
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002132 fflush(stdout);
2133 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002134}
2135
2136void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002137Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002138{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002139 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002140
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002141 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002142}
2143
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002144static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002145initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002146{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002147#ifdef SIGPIPE
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002148 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002149#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002150#ifdef SIGXFZ
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002151 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002152#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002153#ifdef SIGXFSZ
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002154 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002155#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002156 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002157}
2158
Guido van Rossum7433b121997-02-14 19:45:36 +00002159
2160/*
2161 * The file descriptor fd is considered ``interactive'' if either
2162 * a) isatty(fd) is TRUE, or
2163 * b) the -i flag was given, and the filename associated with
2164 * the descriptor is NULL or "<stdin>" or "???".
2165 */
2166int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002167Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002168{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002169 if (isatty((int)fileno(fp)))
2170 return 1;
2171 if (!Py_InteractiveFlag)
2172 return 0;
2173 return (filename == NULL) ||
2174 (strcmp(filename, "<stdin>") == 0) ||
2175 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00002176}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002177
2178
Tim Petersd08e3822003-04-17 15:24:21 +00002179#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002180#if defined(WIN32) && defined(_MSC_VER)
2181
2182/* Stack checking for Microsoft C */
2183
2184#include <malloc.h>
2185#include <excpt.h>
2186
Fred Drakee8de31c2000-08-31 05:38:39 +00002187/*
2188 * Return non-zero when we run out of memory on the stack; zero otherwise.
2189 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002190int
Fred Drake399739f2000-08-31 05:52:44 +00002191PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002192{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002193 __try {
2194 /* alloca throws a stack overflow exception if there's
2195 not enough space left on the stack */
2196 alloca(PYOS_STACK_MARGIN * sizeof(void*));
2197 return 0;
2198 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2199 EXCEPTION_EXECUTE_HANDLER :
2200 EXCEPTION_CONTINUE_SEARCH) {
2201 int errcode = _resetstkoflw();
2202 if (errcode == 0)
2203 {
2204 Py_FatalError("Could not reset the stack!");
2205 }
2206 }
2207 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002208}
2209
2210#endif /* WIN32 && _MSC_VER */
2211
2212/* Alternate implementations can be added here... */
2213
2214#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002215
2216
2217/* Wrappers around sigaction() or signal(). */
2218
2219PyOS_sighandler_t
2220PyOS_getsig(int sig)
2221{
2222#ifdef HAVE_SIGACTION
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002223 struct sigaction context;
2224 if (sigaction(sig, NULL, &context) == -1)
2225 return SIG_ERR;
2226 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002227#else
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002228 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002229/* Special signal handling for the secure CRT in Visual Studio 2005 */
2230#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002231 switch (sig) {
2232 /* Only these signals are valid */
2233 case SIGINT:
2234 case SIGILL:
2235 case SIGFPE:
2236 case SIGSEGV:
2237 case SIGTERM:
2238 case SIGBREAK:
2239 case SIGABRT:
2240 break;
2241 /* Don't call signal() with other values or it will assert */
2242 default:
2243 return SIG_ERR;
2244 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002245#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002246 handler = signal(sig, SIG_IGN);
2247 if (handler != SIG_ERR)
2248 signal(sig, handler);
2249 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002250#endif
2251}
2252
2253PyOS_sighandler_t
2254PyOS_setsig(int sig, PyOS_sighandler_t handler)
2255{
2256#ifdef HAVE_SIGACTION
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002257 /* Some code in Modules/signalmodule.c depends on sigaction() being
2258 * used here if HAVE_SIGACTION is defined. Fix that if this code
2259 * changes to invalidate that assumption.
2260 */
2261 struct sigaction context, ocontext;
2262 context.sa_handler = handler;
2263 sigemptyset(&context.sa_mask);
2264 context.sa_flags = 0;
2265 if (sigaction(sig, &context, &ocontext) == -1)
2266 return SIG_ERR;
2267 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002268#else
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002269 PyOS_sighandler_t oldhandler;
2270 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002271#ifdef HAVE_SIGINTERRUPT
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002272 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002273#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002274 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002275#endif
2276}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002277
2278/* Deprecated C API functions still provided for binary compatiblity */
2279
2280#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002281PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002282PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2283{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002284 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002285}
2286
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002287#undef PyParser_SimpleParseString
2288PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002289PyParser_SimpleParseString(const char *str, int start)
2290{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002291 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002292}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002293
2294#undef PyRun_AnyFile
2295PyAPI_FUNC(int)
2296PyRun_AnyFile(FILE *fp, const char *name)
2297{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002298 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002299}
2300
2301#undef PyRun_AnyFileEx
2302PyAPI_FUNC(int)
2303PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2304{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002305 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002306}
2307
2308#undef PyRun_AnyFileFlags
2309PyAPI_FUNC(int)
2310PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2311{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002312 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002313}
2314
2315#undef PyRun_File
2316PyAPI_FUNC(PyObject *)
2317PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2318{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002319 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002320}
2321
2322#undef PyRun_FileEx
2323PyAPI_FUNC(PyObject *)
2324PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2325{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002326 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002327}
2328
2329#undef PyRun_FileFlags
2330PyAPI_FUNC(PyObject *)
2331PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002332 PyCompilerFlags *flags)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002333{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002334 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002335}
2336
2337#undef PyRun_SimpleFile
2338PyAPI_FUNC(int)
2339PyRun_SimpleFile(FILE *f, const char *p)
2340{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002341 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002342}
2343
2344#undef PyRun_SimpleFileEx
2345PyAPI_FUNC(int)
2346PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2347{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002348 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002349}
2350
2351
2352#undef PyRun_String
2353PyAPI_FUNC(PyObject *)
2354PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2355{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002356 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002357}
2358
2359#undef PyRun_SimpleString
2360PyAPI_FUNC(int)
2361PyRun_SimpleString(const char *s)
2362{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002363 return PyRun_SimpleStringFlags(s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002364}
2365
2366#undef Py_CompileString
2367PyAPI_FUNC(PyObject *)
2368Py_CompileString(const char *str, const char *p, int s)
2369{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002370 return Py_CompileStringFlags(str, p, s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002371}
2372
2373#undef PyRun_InteractiveOne
2374PyAPI_FUNC(int)
2375PyRun_InteractiveOne(FILE *f, const char *p)
2376{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002377 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002378}
2379
2380#undef PyRun_InteractiveLoop
2381PyAPI_FUNC(int)
2382PyRun_InteractiveLoop(FILE *f, const char *p)
2383{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002384 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002385}
2386
2387#ifdef __cplusplus
2388}
2389#endif