blob: 8ccf70dea979666f28b9a1fdcea5d86aa409f3dc [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"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000014#include "symtable.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000015#include "ast.h"
Guido van Rossumfdef2711994-09-14 13:31:04 +000016#include "marshal.h"
Martin v. Löwis790465f2008-04-05 20:41:37 +000017#include "osdefs.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000018
Thomas Wouters0e3f5912006-08-11 14:57:12 +000019#ifdef HAVE_SIGNAL_H
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000020#include <signal.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000021#endif
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000022
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000023#ifdef MS_WINDOWS
Martin v. Löwis5c88d812009-01-02 20:47:48 +000024#include "malloc.h" /* for alloca */
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000025#endif
Martin v. Löwis5c88d812009-01-02 20:47:48 +000026
Martin v. Löwis73d538b2003-03-05 15:13:47 +000027#ifdef HAVE_LANGINFO_H
28#include <locale.h>
29#include <langinfo.h>
30#endif
31
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000032#ifdef MS_WINDOWS
Guido van Rossuma44823b1995-03-14 15:01:17 +000033#undef BYTE
34#include "windows.h"
Martin v. Löwis790465f2008-04-05 20:41:37 +000035#define PATH_MAX MAXPATHLEN
Guido van Rossuma44823b1995-03-14 15:01:17 +000036#endif
37
Victor Stinnerbd303c12013-11-07 23:07:29 +010038_Py_IDENTIFIER(builtins);
Victor Stinner09054372013-11-06 22:41:44 +010039_Py_IDENTIFIER(excepthook);
Victor Stinner3f36a572013-11-12 21:39:02 +010040_Py_IDENTIFIER(flush);
Victor Stinnerbd303c12013-11-07 23:07:29 +010041_Py_IDENTIFIER(last_traceback);
Victor Stinner09054372013-11-06 22:41:44 +010042_Py_IDENTIFIER(last_type);
43_Py_IDENTIFIER(last_value);
Victor Stinner3f36a572013-11-12 21:39:02 +010044_Py_IDENTIFIER(name);
Victor Stinnerbd303c12013-11-07 23:07:29 +010045_Py_IDENTIFIER(ps1);
46_Py_IDENTIFIER(ps2);
47_Py_IDENTIFIER(stdin);
48_Py_IDENTIFIER(stdout);
49_Py_IDENTIFIER(stderr);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +010050_Py_static_string(PyId_string, "<string>");
Victor Stinner09054372013-11-06 22:41:44 +010051
Ezio Melotti1f8898a2013-03-26 01:59:56 +020052#ifdef Py_REF_DEBUG
Antoine Pitrou208ac5c2013-04-24 20:17:53 +020053static
54void _print_total_refs(void) {
Victor Stinner4ee41c52013-11-06 18:28:21 +010055 PyObject *xoptions, *value;
56 _Py_IDENTIFIER(showrefcount);
57
Ezio Melotti1f8898a2013-03-26 01:59:56 +020058 xoptions = PySys_GetXOptions();
59 if (xoptions == NULL)
60 return;
Victor Stinner4ee41c52013-11-06 18:28:21 +010061 value = _PyDict_GetItemId(xoptions, &PyId_showrefcount);
Ezio Melotti1f8898a2013-03-26 01:59:56 +020062 if (value == Py_True)
63 fprintf(stderr,
64 "[%" PY_FORMAT_SIZE_T "d refs, "
65 "%" PY_FORMAT_SIZE_T "d blocks]\n",
66 _Py_GetRefTotal(), _Py_GetAllocatedBlocks());
67}
68#endif
69
Neal Norwitz4281cef2006-03-04 19:58:13 +000070#ifndef Py_REF_DEBUG
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000071#define PRINT_TOTAL_REFS()
Neal Norwitz4281cef2006-03-04 19:58:13 +000072#else /* Py_REF_DEBUG */
Ezio Melotti1f8898a2013-03-26 01:59:56 +020073#define PRINT_TOTAL_REFS() _print_total_refs()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000074#endif
75
76#ifdef __cplusplus
77extern "C" {
Neal Norwitz4281cef2006-03-04 19:58:13 +000078#endif
79
Martin v. Löwis790465f2008-04-05 20:41:37 +000080extern wchar_t *Py_GetPath(void);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000081
Guido van Rossum82598051997-03-05 00:20:32 +000082extern grammar _PyParser_Grammar; /* From graminit.c */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000083
Guido van Rossumb73cc041993-11-01 16:28:59 +000084/* Forward */
Nick Coghlan85e729e2012-07-15 18:09:52 +100085static void initmain(PyInterpreterState *interp);
Victor Stinner793b5312011-04-27 00:24:21 +020086static int initfsencoding(PyInterpreterState *interp);
Tim Petersdbd9ba62000-07-09 03:09:57 +000087static void initsite(void);
Guido van Rossumce3a72a2007-10-19 23:16:50 +000088static int initstdio(void);
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +000089static void flush_io(void);
Victor Stinner95701bd2013-11-06 18:41:07 +010090static PyObject *run_mod(mod_ty, PyObject *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000091 PyCompilerFlags *, PyArena *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000092static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000093 PyCompilerFlags *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000094static void err_input(perrdetail *);
Victor Stinner7f2fee32011-04-05 00:39:01 +020095static void err_free(perrdetail *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000096static void initsigs(void);
Collin Winter670e6922007-03-21 02:57:17 +000097static void call_py_exitfuncs(void);
Antoine Pitrou011bd622009-10-20 21:52:47 +000098static void wait_for_thread_shutdown(void);
Tim Petersdbd9ba62000-07-09 03:09:57 +000099static void call_ll_exitfuncs(void);
Victor Stinner3a50e702011-10-18 21:21:00 +0200100extern int _PyUnicode_Init(void);
Victor Stinner26f91992013-07-17 01:22:45 +0200101extern int _PyStructSequence_Init(void);
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000102extern void _PyUnicode_Fini(void);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000103extern int _PyLong_Init(void);
104extern void PyLong_Fini(void);
Victor Stinner024e37a2011-03-31 01:31:06 +0200105extern int _PyFaulthandler_Init(void);
106extern void _PyFaulthandler_Fini(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +0000107
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000108#ifdef WITH_THREAD
109extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
110extern void _PyGILState_Fini(void);
111#endif /* WITH_THREAD */
112
Guido van Rossum82598051997-03-05 00:20:32 +0000113int Py_DebugFlag; /* Needed by parser.c */
114int Py_VerboseFlag; /* Needed by import.c */
Georg Brandl8aa7e992010-12-28 18:30:18 +0000115int Py_QuietFlag; /* Needed by sysmodule.c */
Guido van Rossum7433b121997-02-14 19:45:36 +0000116int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Georg Brandl0b2489e2011-05-15 08:49:12 +0200117int Py_InspectFlag; /* Needed to determine whether to exit at SystemExit */
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000118int Py_NoSiteFlag; /* Suppress 'import site' */
Guido van Rossum98297ee2007-11-06 21:34:58 +0000119int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
Christian Heimes790c8232008-01-07 21:14:23 +0000120int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.py[co]) */
Barry Warsaw3ce09642000-05-02 19:18:59 +0000121int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +0000122int Py_FrozenFlag; /* Needed by getpath.c */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000123int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Christian Heimes8dc226f2008-05-06 23:45:46 +0000124int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
Antoine Pitrou05608432009-01-09 18:53:14 +0000125int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100126int Py_HashRandomizationFlag = 0; /* for -R and PYTHONHASHSEED */
Christian Heimesad73a9c2013-08-10 16:36:18 +0200127int Py_IsolatedFlag = 0; /* for -I, isolate from user's env */
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000128
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200129PyThreadState *_Py_Finalizing = NULL;
130
Christian Heimes49e61802013-10-22 10:22:29 +0200131/* Hack to force loading of object files */
132int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
133 PyOS_mystrnicmp; /* Python/pystrcmp.o */
134
Christian Heimes33fe8092008-04-13 13:53:33 +0000135/* PyModule_GetWarningsModule is no longer necessary as of 2.6
136since _warnings is builtin. This API should not be used. */
137PyObject *
138PyModule_GetWarningsModule(void)
Mark Hammondedd07732003-07-15 23:03:55 +0000139{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000140 return PyImport_ImportModule("warnings");
Mark Hammondedd07732003-07-15 23:03:55 +0000141}
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000142
Guido van Rossum25ce5661997-08-02 03:10:38 +0000143static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000144
Thomas Wouters7e474022000-07-16 12:04:32 +0000145/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000146
147int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000148Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000149{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000150 return initialized;
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000151}
152
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000153/* Helper to allow an embedding application to override the normal
154 * mechanism that attempts to figure out an appropriate IO encoding
155 */
156
157static char *_Py_StandardStreamEncoding = NULL;
158static char *_Py_StandardStreamErrors = NULL;
159
160int
161Py_SetStandardStreamEncoding(const char *encoding, const char *errors)
162{
163 if (Py_IsInitialized()) {
164 /* This is too late to have any effect */
165 return -1;
166 }
Nick Coghlan1805a622013-10-18 23:11:47 +1000167 /* Can't call PyErr_NoMemory() on errors, as Python hasn't been
168 * initialised yet.
169 *
170 * However, the raw memory allocators are initialised appropriately
171 * as C static variables, so _PyMem_RawStrdup is OK even though
172 * Py_Initialize hasn't been called yet.
173 */
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000174 if (encoding) {
175 _Py_StandardStreamEncoding = _PyMem_RawStrdup(encoding);
176 if (!_Py_StandardStreamEncoding) {
Nick Coghlan1805a622013-10-18 23:11:47 +1000177 return -2;
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000178 }
179 }
180 if (errors) {
181 _Py_StandardStreamErrors = _PyMem_RawStrdup(errors);
182 if (!_Py_StandardStreamErrors) {
183 if (_Py_StandardStreamEncoding) {
184 PyMem_RawFree(_Py_StandardStreamEncoding);
185 }
Nick Coghlan1805a622013-10-18 23:11:47 +1000186 return -3;
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000187 }
188 }
189 return 0;
190}
191
Guido van Rossum25ce5661997-08-02 03:10:38 +0000192/* Global initializations. Can be undone by Py_Finalize(). Don't
193 call this twice without an intervening Py_Finalize() call. When
194 initializations fail, a fatal error is issued and the function does
195 not return. On return, the first thread and interpreter state have
196 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000197
Guido van Rossum25ce5661997-08-02 03:10:38 +0000198 Locking: you must hold the interpreter lock while calling this.
199 (If the lock has not yet been initialized, that's equivalent to
200 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000201
Guido van Rossum25ce5661997-08-02 03:10:38 +0000202*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000203
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000204static int
205add_flag(int flag, const char *envs)
206{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000207 int env = atoi(envs);
208 if (flag < env)
209 flag = env;
210 if (flag < 1)
211 flag = 1;
212 return flag;
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000213}
214
Christian Heimes5833a2f2008-10-30 21:40:04 +0000215static char*
Victor Stinner94908bb2010-08-18 21:23:25 +0000216get_codec_name(const char *encoding)
Christian Heimes5833a2f2008-10-30 21:40:04 +0000217{
Victor Stinner94908bb2010-08-18 21:23:25 +0000218 char *name_utf8, *name_str;
Victor Stinner386fe712010-05-19 00:34:15 +0000219 PyObject *codec, *name = NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000220
Victor Stinner94908bb2010-08-18 21:23:25 +0000221 codec = _PyCodec_Lookup(encoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000222 if (!codec)
223 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000224
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200225 name = _PyObject_GetAttrId(codec, &PyId_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000226 Py_CLEAR(codec);
227 if (!name)
228 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000229
Victor Stinner94908bb2010-08-18 21:23:25 +0000230 name_utf8 = _PyUnicode_AsString(name);
Victor Stinner4ca28092011-03-20 23:09:03 +0100231 if (name_utf8 == NULL)
Victor Stinner386fe712010-05-19 00:34:15 +0000232 goto error;
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200233 name_str = _PyMem_RawStrdup(name_utf8);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 Py_DECREF(name);
Victor Stinner94908bb2010-08-18 21:23:25 +0000235 if (name_str == NULL) {
236 PyErr_NoMemory();
237 return NULL;
238 }
239 return name_str;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000240
241error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000242 Py_XDECREF(codec);
Victor Stinner386fe712010-05-19 00:34:15 +0000243 Py_XDECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000244 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000245}
Victor Stinner94908bb2010-08-18 21:23:25 +0000246
Victor Stinner94908bb2010-08-18 21:23:25 +0000247static char*
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200248get_locale_encoding(void)
Victor Stinner94908bb2010-08-18 21:23:25 +0000249{
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200250#ifdef MS_WINDOWS
251 char codepage[100];
252 PyOS_snprintf(codepage, sizeof(codepage), "cp%d", GetACP());
253 return get_codec_name(codepage);
254#elif defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94908bb2010-08-18 21:23:25 +0000255 char* codeset = nl_langinfo(CODESET);
256 if (!codeset || codeset[0] == '\0') {
257 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
258 return NULL;
259 }
260 return get_codec_name(codeset);
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200261#else
262 PyErr_SetNone(PyExc_NotImplementedError);
263 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000264#endif
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200265}
Christian Heimes5833a2f2008-10-30 21:40:04 +0000266
Brett Cannonfd074152012-04-14 14:10:13 -0400267static void
268import_init(PyInterpreterState *interp, PyObject *sysmod)
269{
270 PyObject *importlib;
271 PyObject *impmod;
272 PyObject *sys_modules;
273 PyObject *value;
274
275 /* Import _importlib through its frozen version, _frozen_importlib. */
Brett Cannonfd074152012-04-14 14:10:13 -0400276 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
277 Py_FatalError("Py_Initialize: can't import _frozen_importlib");
278 }
279 else if (Py_VerboseFlag) {
280 PySys_FormatStderr("import _frozen_importlib # frozen\n");
281 }
282 importlib = PyImport_AddModule("_frozen_importlib");
283 if (importlib == NULL) {
284 Py_FatalError("Py_Initialize: couldn't get _frozen_importlib from "
285 "sys.modules");
286 }
287 interp->importlib = importlib;
288 Py_INCREF(interp->importlib);
289
290 /* Install _importlib as __import__ */
291 impmod = PyInit_imp();
292 if (impmod == NULL) {
293 Py_FatalError("Py_Initialize: can't import imp");
294 }
295 else if (Py_VerboseFlag) {
296 PySys_FormatStderr("import imp # builtin\n");
297 }
298 sys_modules = PyImport_GetModuleDict();
299 if (Py_VerboseFlag) {
300 PySys_FormatStderr("import sys # builtin\n");
301 }
Brett Cannon6f44d662012-04-15 16:08:47 -0400302 if (PyDict_SetItemString(sys_modules, "_imp", impmod) < 0) {
303 Py_FatalError("Py_Initialize: can't save _imp to sys.modules");
Brett Cannonfd074152012-04-14 14:10:13 -0400304 }
305
Brett Cannone0d88a12012-04-25 20:54:04 -0400306 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
Brett Cannonfd074152012-04-14 14:10:13 -0400307 if (value == NULL) {
308 PyErr_Print();
309 Py_FatalError("Py_Initialize: importlib install failed");
310 }
311 Py_DECREF(value);
Brett Cannonfc9ca272012-04-15 01:35:05 -0400312 Py_DECREF(impmod);
Brett Cannonfd074152012-04-14 14:10:13 -0400313
314 _PyImportZip_Init();
315}
316
317
Guido van Rossuma027efa1997-05-05 20:56:21 +0000318void
Antoine Pitroue67f48c2012-06-19 22:29:35 +0200319_Py_InitializeEx_Private(int install_sigs, int install_importlib)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000320{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 PyInterpreterState *interp;
322 PyThreadState *tstate;
323 PyObject *bimod, *sysmod, *pstderr;
324 char *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000325 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000327 if (initialized)
328 return;
329 initialized = 1;
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200330 _Py_Finalizing = NULL;
Tim Petersd08e3822003-04-17 15:24:21 +0000331
Andrew M. Kuchlingb2ceb3a2010-02-22 23:26:10 +0000332#if defined(HAVE_LANGINFO_H) && defined(HAVE_SETLOCALE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 /* Set up the LC_CTYPE locale, so we can obtain
334 the locale's charset without having to switch
335 locales. */
336 setlocale(LC_CTYPE, "");
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +0000337#endif
338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
340 Py_DebugFlag = add_flag(Py_DebugFlag, p);
341 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
342 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
343 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
344 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
345 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
346 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100347 /* The variable is only tested for existence here; _PyRandom_Init will
348 check its value further. */
349 if ((p = Py_GETENV("PYTHONHASHSEED")) && *p != '\0')
350 Py_HashRandomizationFlag = add_flag(Py_HashRandomizationFlag, p);
351
352 _PyRandom_Init();
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000354 interp = PyInterpreterState_New();
355 if (interp == NULL)
356 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000358 tstate = PyThreadState_New(interp);
359 if (tstate == NULL)
360 Py_FatalError("Py_Initialize: can't make first thread");
361 (void) PyThreadState_Swap(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000362
Victor Stinner6961bd62010-08-17 22:26:51 +0000363#ifdef WITH_THREAD
Antoine Pitroub0b384b2010-09-20 20:13:48 +0000364 /* We can't call _PyEval_FiniThreads() in Py_Finalize because
365 destroying the GIL might fail when it is being referenced from
366 another running thread (see issue #9901).
367 Instead we destroy the previously created GIL here, which ensures
368 that we can call Py_Initialize / Py_Finalize multiple times. */
369 _PyEval_FiniThreads();
370
371 /* Auto-thread-state API */
Victor Stinner6961bd62010-08-17 22:26:51 +0000372 _PyGILState_Init(interp, tstate);
373#endif /* WITH_THREAD */
374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377 if (!_PyFrame_Init())
378 Py_FatalError("Py_Initialize: can't init frames");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 if (!_PyLong_Init())
381 Py_FatalError("Py_Initialize: can't init longs");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 if (!PyByteArray_Init())
384 Py_FatalError("Py_Initialize: can't init bytearray");
Neal Norwitz6968b052007-02-27 19:02:19 +0000385
Victor Stinner1c8f0592013-07-22 22:24:54 +0200386 if (!_PyFloat_Init())
387 Py_FatalError("Py_Initialize: can't init float");
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389 interp->modules = PyDict_New();
390 if (interp->modules == NULL)
391 Py_FatalError("Py_Initialize: can't make modules dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 /* Init Unicode implementation; relies on the codec registry */
Victor Stinner3a50e702011-10-18 21:21:00 +0200394 if (_PyUnicode_Init() < 0)
395 Py_FatalError("Py_Initialize: can't initialize unicode");
Victor Stinner26f91992013-07-17 01:22:45 +0200396 if (_PyStructSequence_Init() < 0)
397 Py_FatalError("Py_Initialize: can't initialize structseq");
Guido van Rossumc94044c2000-03-10 23:03:54 +0000398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399 bimod = _PyBuiltin_Init();
400 if (bimod == NULL)
401 Py_FatalError("Py_Initialize: can't initialize builtins modules");
Victor Stinner49d3f252010-10-17 01:24:53 +0000402 _PyImport_FixupBuiltin(bimod, "builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 interp->builtins = PyModule_GetDict(bimod);
404 if (interp->builtins == NULL)
405 Py_FatalError("Py_Initialize: can't initialize builtins dict");
406 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 /* initialize builtin exceptions */
Brett Cannonfd074152012-04-14 14:10:13 -0400409 _PyExc_Init(bimod);
Christian Heimes9a68f8c2007-11-14 00:16:07 +0000410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 sysmod = _PySys_Init();
412 if (sysmod == NULL)
413 Py_FatalError("Py_Initialize: can't initialize sys");
414 interp->sysdict = PyModule_GetDict(sysmod);
415 if (interp->sysdict == NULL)
416 Py_FatalError("Py_Initialize: can't initialize sys dict");
417 Py_INCREF(interp->sysdict);
Victor Stinner49d3f252010-10-17 01:24:53 +0000418 _PyImport_FixupBuiltin(sysmod, "sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 PySys_SetPath(Py_GetPath());
420 PyDict_SetItemString(interp->sysdict, "modules",
421 interp->modules);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 /* Set up a preliminary stderr printer until we have enough
424 infrastructure for the io module in place. */
425 pstderr = PyFile_NewStdPrinter(fileno(stderr));
426 if (pstderr == NULL)
427 Py_FatalError("Py_Initialize: can't set preliminary stderr");
Victor Stinnerbd303c12013-11-07 23:07:29 +0100428 _PySys_SetObjectId(&PyId_stderr, pstderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000430 Py_DECREF(pstderr);
Guido van Rossum826d8972007-10-30 18:34:07 +0000431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000432 _PyImport_Init();
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 _PyImportHooks_Init();
Just van Rossum52e14d62002-12-30 22:08:05 +0000435
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000436 /* Initialize _warnings. */
437 _PyWarnings_Init();
438
Antoine Pitroue67f48c2012-06-19 22:29:35 +0200439 if (!install_importlib)
440 return;
441
Brett Cannonfd074152012-04-14 14:10:13 -0400442 import_init(interp, sysmod);
443
Victor Stinnerd5698cb2012-07-31 02:55:49 +0200444 /* initialize the faulthandler module */
445 if (_PyFaulthandler_Init())
446 Py_FatalError("Py_Initialize: can't initialize faulthandler");
447
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +0000448 _PyTime_Init();
449
Victor Stinner793b5312011-04-27 00:24:21 +0200450 if (initfsencoding(interp) < 0)
451 Py_FatalError("Py_Initialize: unable to load the file system codec");
Martin v. Löwis011e8422009-05-05 04:43:17 +0000452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 if (install_sigs)
454 initsigs(); /* Signal handling stuff, including initintr() */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000455
Nick Coghlan85e729e2012-07-15 18:09:52 +1000456 initmain(interp); /* Module __main__ */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 if (initstdio() < 0)
458 Py_FatalError(
459 "Py_Initialize: can't initialize sys standard streams");
460
Antoine Pitroucf9f9802010-11-10 13:55:25 +0000461 /* Initialize warnings. */
462 if (PySys_HasWarnOptions()) {
463 PyObject *warnings_module = PyImport_ImportModule("warnings");
464 if (warnings_module == NULL) {
465 fprintf(stderr, "'import warnings' failed; traceback:\n");
466 PyErr_Print();
467 }
468 Py_XDECREF(warnings_module);
469 }
470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 if (!Py_NoSiteFlag)
472 initsite(); /* Module site */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000473}
474
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000475void
Antoine Pitroue67f48c2012-06-19 22:29:35 +0200476Py_InitializeEx(int install_sigs)
477{
478 _Py_InitializeEx_Private(install_sigs, 1);
479}
480
481void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000482Py_Initialize(void)
483{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 Py_InitializeEx(1);
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000485}
486
487
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000488#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000489extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000490#endif
491
Guido van Rossume8432ac2007-07-09 15:04:50 +0000492/* Flush stdout and stderr */
493
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100494static int
495file_is_closed(PyObject *fobj)
496{
497 int r;
498 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
499 if (tmp == NULL) {
500 PyErr_Clear();
501 return 0;
502 }
503 r = PyObject_IsTrue(tmp);
504 Py_DECREF(tmp);
505 if (r < 0)
506 PyErr_Clear();
507 return r > 0;
508}
509
Neal Norwitz2bad9702007-08-27 06:19:22 +0000510static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000511flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000512{
Victor Stinnerbd303c12013-11-07 23:07:29 +0100513 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
514 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 PyObject *tmp;
Guido van Rossume8432ac2007-07-09 15:04:50 +0000516
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100517 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200518 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 if (tmp == NULL)
Antoine Pitroubddc9fe2010-08-08 20:46:42 +0000520 PyErr_WriteUnraisable(fout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 else
522 Py_DECREF(tmp);
523 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000524
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100525 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200526 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000527 if (tmp == NULL)
528 PyErr_Clear();
529 else
530 Py_DECREF(tmp);
531 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000532}
533
Guido van Rossum25ce5661997-08-02 03:10:38 +0000534/* Undo the effect of Py_Initialize().
535
536 Beware: if multiple interpreter and/or thread states exist, these
537 are not wiped out; only the current thread and interpreter state
538 are deleted. But since everything else is deleted, those other
539 interpreter and thread states should no longer be used.
540
541 (XXX We should do better, e.g. wipe out all interpreters and
542 threads.)
543
544 Locking: as above.
545
546*/
547
548void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000549Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000550{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 PyInterpreterState *interp;
552 PyThreadState *tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 if (!initialized)
555 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 wait_for_thread_shutdown();
Antoine Pitrou011bd622009-10-20 21:52:47 +0000558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 /* The interpreter is still entirely intact at this point, and the
560 * exit funcs may be relying on that. In particular, if some thread
561 * or exit func is still waiting to do an import, the import machinery
562 * expects Py_IsInitialized() to return true. So don't say the
563 * interpreter is uninitialized until after the exit funcs have run.
564 * Note that Threading.py uses an exit func to do a join on all the
565 * threads created thru it, so this also protects pending imports in
566 * the threads created via Threading.
567 */
568 call_py_exitfuncs();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 /* Get current thread state and interpreter pointer */
571 tstate = PyThreadState_GET();
572 interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000573
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200574 /* Remaining threads (e.g. daemon threads) will automatically exit
575 after taking the GIL (in PyEval_RestoreThread()). */
576 _Py_Finalizing = tstate;
577 initialized = 0;
578
Victor Stinner45956b92013-11-12 16:37:55 +0100579 /* Destroy the state of all threads except of the current thread: in
580 practice, only daemon threads should still be alive. Clear frames of
581 other threads to call objects destructor. Destructors will be called in
582 the current Python thread. Since _Py_Finalizing has been set, no other
583 Python threads can lock the GIL at this point (if they try, they will
Victor Stinnerdcf17f82013-11-12 17:18:51 +0100584 exit immediately). */
Victor Stinner45956b92013-11-12 16:37:55 +0100585 _PyThreadState_DeleteExcept(tstate);
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000587 /* Collect garbage. This may call finalizers; it's nice to call these
588 * before all modules are destroyed.
589 * XXX If a __del__ or weakref callback is triggered here, and tries to
590 * XXX import a module, bad things can happen, because Python no
591 * XXX longer believes it's initialized.
592 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
593 * XXX is easy to provoke that way. I've also seen, e.g.,
594 * XXX Exception exceptions.ImportError: 'No module named sha'
595 * XXX in <function callback at 0x008F5718> ignored
596 * XXX but I'm unclear on exactly how that one happens. In any case,
597 * XXX I haven't seen a real-life report of either of these.
598 */
599 PyGC_Collect();
Victor Stinner45956b92013-11-12 16:37:55 +0100600
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000601#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 /* With COUNT_ALLOCS, it helps to run GC multiple times:
603 each collection might release some types from the type
604 list, so they become garbage. */
605 while (PyGC_Collect() > 0)
606 /* nothing */;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000607#endif
Victor Stinner45956b92013-11-12 16:37:55 +0100608
609 /* Flush stdout+stderr */
610 flush_std_files();
611
612 /* Disable signal handling */
613 PyOS_FiniInterrupts();
614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 /* Destroy all modules */
616 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 /* Flush stdout+stderr (again, in case more was printed) */
619 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 /* Collect final garbage. This disposes of cycles created by
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100622 * class definitions, for example.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000623 * XXX This is disabled because it caused too many problems. If
624 * XXX a __del__ or weakref callback triggers here, Python code has
625 * XXX a hard time running, because even the sys module has been
626 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
627 * XXX One symptom is a sequence of information-free messages
628 * XXX coming from threads (if a __del__ or callback is invoked,
629 * XXX other threads can execute too, and any exception they encounter
630 * XXX triggers a comedy of errors as subsystem after subsystem
631 * XXX fails to find what it *expects* to find in sys to help report
632 * XXX the exception and consequent unexpected failures). I've also
633 * XXX seen segfaults then, after adding print statements to the
634 * XXX Python code getting called.
635 */
Tim Peters1d7323e2003-12-01 21:35:27 +0000636#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000637 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000638#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
641 _PyImport_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000642
Antoine Pitroufd417cc2013-05-05 08:12:42 +0200643 /* Cleanup typeobject.c's internal caches. */
644 _PyType_Fini();
645
Victor Stinner024e37a2011-03-31 01:31:06 +0200646 /* unload faulthandler module */
647 _PyFaulthandler_Fini();
648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 /* Debugging stuff */
Guido van Rossum1707aad1997-12-08 23:43:45 +0000650#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000652#endif
653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000655
Tim Peters9cf25ce2003-04-17 15:21:01 +0000656#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 /* Display all objects still alive -- this can invoke arbitrary
658 * __repr__ overrides, so requires a mostly-intact interpreter.
659 * Alas, a lot of stuff may still be alive now that will be cleaned
660 * up later.
661 */
662 if (Py_GETENV("PYTHONDUMPREFS"))
663 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000664#endif /* Py_TRACE_REFS */
665
Antoine Pitroufd417cc2013-05-05 08:12:42 +0200666 /* Clear interpreter state and all thread states. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000667 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000669 /* Now we decref the exception classes. After this point nothing
670 can raise an exception. That's okay, because each Fini() method
671 below has been checked to make sure no exceptions are ever
672 raised.
673 */
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 _PyExc_Fini();
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000676
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 /* Sundry finalizers */
678 PyMethod_Fini();
679 PyFrame_Fini();
680 PyCFunction_Fini();
681 PyTuple_Fini();
682 PyList_Fini();
683 PySet_Fini();
684 PyBytes_Fini();
685 PyByteArray_Fini();
686 PyLong_Fini();
687 PyFloat_Fini();
688 PyDict_Fini();
Antoine Pitrouf34a0cd2011-11-18 20:14:34 +0100689 PySlice_Fini();
Antoine Pitrou5f454a02013-05-06 21:15:57 +0200690 _PyGC_Fini();
Antoine Pitrou4879a962013-08-31 00:26:02 +0200691 _PyRandom_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 /* Cleanup Unicode implementation */
694 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000696 /* reset file system default encoding */
Victor Stinnerb744ba12010-05-15 12:27:16 +0000697 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200698 PyMem_RawFree((char*)Py_FileSystemDefaultEncoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 Py_FileSystemDefaultEncoding = NULL;
700 }
Christian Heimesc8967002007-11-30 10:18:26 +0000701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 /* XXX Still allocated:
703 - various static ad-hoc pointers to interned strings
704 - int and float free list blocks
705 - whatever various modules and libraries allocate
706 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000709
Victor Stinner51fa4582013-07-07 15:50:49 +0200710 /* Cleanup auto-thread-state */
711#ifdef WITH_THREAD
712 _PyGILState_Fini();
713#endif /* WITH_THREAD */
714
715 /* Delete current thread. After this, many C API calls become crashy. */
716 PyThreadState_Swap(NULL);
717 PyInterpreterState_Delete(interp);
718
Tim Peters269b2a62003-04-17 19:52:29 +0000719#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 /* Display addresses (& refcnts) of all objects still alive.
721 * An address can be used to find the repr of the object, printed
722 * above by _Py_PrintReferences.
723 */
724 if (Py_GETENV("PYTHONDUMPREFS"))
725 _Py_PrintReferenceAddresses(stderr);
Tim Peters269b2a62003-04-17 19:52:29 +0000726#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000727#ifdef PYMALLOC_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000728 if (Py_GETENV("PYTHONMALLOCSTATS"))
David Malcolm49526f42012-06-22 14:55:41 -0400729 _PyObject_DebugMallocStats(stderr);
Tim Peters0e871182002-04-13 08:29:14 +0000730#endif
731
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000733}
734
735/* Create and initialize a new interpreter and thread, and return the
736 new thread. This requires that Py_Initialize() has been called
737 first.
738
739 Unsuccessful initialization yields a NULL pointer. Note that *no*
740 exception information is available even in this case -- the
741 exception information is held in the thread, and there is no
742 thread.
743
744 Locking: as above.
745
746*/
747
748PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000749Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000750{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 PyInterpreterState *interp;
752 PyThreadState *tstate, *save_tstate;
753 PyObject *bimod, *sysmod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000755 if (!initialized)
756 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 interp = PyInterpreterState_New();
759 if (interp == NULL)
760 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000761
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 tstate = PyThreadState_New(interp);
763 if (tstate == NULL) {
764 PyInterpreterState_Delete(interp);
765 return NULL;
766 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 save_tstate = PyThreadState_Swap(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000770 /* XXX The following is lax in error checking */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 interp->modules = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000773
Victor Stinner49d3f252010-10-17 01:24:53 +0000774 bimod = _PyImport_FindBuiltin("builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 if (bimod != NULL) {
776 interp->builtins = PyModule_GetDict(bimod);
777 if (interp->builtins == NULL)
778 goto handle_error;
779 Py_INCREF(interp->builtins);
780 }
Christian Heimes6a27efa2008-10-30 21:48:26 +0000781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 /* initialize builtin exceptions */
Brett Cannonfd074152012-04-14 14:10:13 -0400783 _PyExc_Init(bimod);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000784
Victor Stinner49d3f252010-10-17 01:24:53 +0000785 sysmod = _PyImport_FindBuiltin("sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 if (bimod != NULL && sysmod != NULL) {
787 PyObject *pstderr;
Brett Cannonfd074152012-04-14 14:10:13 -0400788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 interp->sysdict = PyModule_GetDict(sysmod);
790 if (interp->sysdict == NULL)
791 goto handle_error;
792 Py_INCREF(interp->sysdict);
793 PySys_SetPath(Py_GetPath());
794 PyDict_SetItemString(interp->sysdict, "modules",
795 interp->modules);
796 /* Set up a preliminary stderr printer until we have enough
797 infrastructure for the io module in place. */
798 pstderr = PyFile_NewStdPrinter(fileno(stderr));
799 if (pstderr == NULL)
800 Py_FatalError("Py_Initialize: can't set preliminary stderr");
Victor Stinnerbd303c12013-11-07 23:07:29 +0100801 _PySys_SetObjectId(&PyId_stderr, pstderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000803 Py_DECREF(pstderr);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000804
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000805 _PyImportHooks_Init();
Victor Stinner793b5312011-04-27 00:24:21 +0200806
Brett Cannonfd074152012-04-14 14:10:13 -0400807 import_init(interp, sysmod);
808
Victor Stinner793b5312011-04-27 00:24:21 +0200809 if (initfsencoding(interp) < 0)
810 goto handle_error;
811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 if (initstdio() < 0)
813 Py_FatalError(
814 "Py_Initialize: can't initialize sys standard streams");
Nick Coghlan85e729e2012-07-15 18:09:52 +1000815 initmain(interp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 if (!Py_NoSiteFlag)
817 initsite();
818 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 if (!PyErr_Occurred())
821 return tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000822
Thomas Wouters89f507f2006-12-13 04:49:30 +0000823handle_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000824 /* Oops, it didn't work. Undo it all. */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000825
Victor Stinnerc40a3502011-04-27 00:20:27 +0200826 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000827 PyThreadState_Clear(tstate);
828 PyThreadState_Swap(save_tstate);
829 PyThreadState_Delete(tstate);
830 PyInterpreterState_Delete(interp);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000832 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000833}
834
835/* Delete an interpreter and its last thread. This requires that the
836 given thread state is current, that the thread has no remaining
837 frames, and that it is its interpreter's only remaining thread.
838 It is a fatal error to violate these constraints.
839
840 (Py_Finalize() doesn't have these constraints -- it zaps
841 everything, regardless.)
842
843 Locking: as above.
844
845*/
846
847void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000848Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000849{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 PyInterpreterState *interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000852 if (tstate != PyThreadState_GET())
853 Py_FatalError("Py_EndInterpreter: thread is not current");
854 if (tstate->frame != NULL)
855 Py_FatalError("Py_EndInterpreter: thread still has a frame");
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200856
857 wait_for_thread_shutdown();
858
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 if (tstate != interp->tstate_head || tstate->next != NULL)
860 Py_FatalError("Py_EndInterpreter: not the last thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 PyImport_Cleanup();
863 PyInterpreterState_Clear(interp);
864 PyThreadState_Swap(NULL);
865 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000866}
867
Antoine Pitrou01cca5e2012-07-05 20:56:30 +0200868#ifdef MS_WINDOWS
Martin v. Löwis790465f2008-04-05 20:41:37 +0000869static wchar_t *progname = L"python";
Antoine Pitrou01cca5e2012-07-05 20:56:30 +0200870#else
871static wchar_t *progname = L"python3";
872#endif
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000873
874void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000875Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000876{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 if (pn && *pn)
878 progname = pn;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000879}
880
Martin v. Löwis790465f2008-04-05 20:41:37 +0000881wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000882Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000883{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000885}
886
Martin v. Löwis790465f2008-04-05 20:41:37 +0000887static wchar_t *default_home = NULL;
Victor Stinner55a12202013-08-28 01:47:46 +0200888static wchar_t env_home[MAXPATHLEN+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000889
890void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000891Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000892{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 default_home = home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000894}
895
Martin v. Löwis790465f2008-04-05 20:41:37 +0000896wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000897Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000898{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 wchar_t *home = default_home;
900 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
901 char* chome = Py_GETENV("PYTHONHOME");
902 if (chome) {
903 size_t r = mbstowcs(env_home, chome, PATH_MAX+1);
904 if (r != (size_t)-1 && r <= PATH_MAX)
905 home = env_home;
906 }
Martin v. Löwis790465f2008-04-05 20:41:37 +0000907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 }
909 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000910}
911
Guido van Rossum6135a871995-01-09 17:53:26 +0000912/* Create __main__ module */
913
914static void
Nick Coghlan85e729e2012-07-15 18:09:52 +1000915initmain(PyInterpreterState *interp)
Guido van Rossum6135a871995-01-09 17:53:26 +0000916{
Brett Cannon13853a62013-05-04 17:37:09 -0400917 PyObject *m, *d, *loader;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 m = PyImport_AddModule("__main__");
919 if (m == NULL)
920 Py_FatalError("can't create __main__ module");
921 d = PyModule_GetDict(m);
922 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
923 PyObject *bimod = PyImport_ImportModule("builtins");
Nick Coghlan85e729e2012-07-15 18:09:52 +1000924 if (bimod == NULL) {
925 Py_FatalError("Failed to retrieve builtins module");
926 }
927 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
928 Py_FatalError("Failed to initialize __main__.__builtins__");
929 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000930 Py_DECREF(bimod);
931 }
Nick Coghlan85e729e2012-07-15 18:09:52 +1000932 /* Main is a little special - imp.is_builtin("__main__") will return
933 * False, but BuiltinImporter is still the most appropriate initial
934 * setting for its __loader__ attribute. A more suitable value will
935 * be set if __main__ gets further initialized later in the startup
936 * process.
937 */
Brett Cannon13853a62013-05-04 17:37:09 -0400938 loader = PyDict_GetItemString(d, "__loader__");
Brett Cannon4c14b5d2013-05-04 13:56:58 -0400939 if (loader == NULL || loader == Py_None) {
Nick Coghlan85e729e2012-07-15 18:09:52 +1000940 PyObject *loader = PyObject_GetAttrString(interp->importlib,
941 "BuiltinImporter");
942 if (loader == NULL) {
943 Py_FatalError("Failed to retrieve BuiltinImporter");
944 }
945 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
946 Py_FatalError("Failed to initialize __main__.__loader__");
947 }
948 Py_DECREF(loader);
949 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000950}
951
Victor Stinner793b5312011-04-27 00:24:21 +0200952static int
953initfsencoding(PyInterpreterState *interp)
Victor Stinnerb744ba12010-05-15 12:27:16 +0000954{
955 PyObject *codec;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000956
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200957 if (Py_FileSystemDefaultEncoding == NULL)
958 {
959 Py_FileSystemDefaultEncoding = get_locale_encoding();
960 if (Py_FileSystemDefaultEncoding == NULL)
Victor Stinnere4743092010-10-19 00:05:51 +0000961 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
Victor Stinnerb744ba12010-05-15 12:27:16 +0000962
Victor Stinnere4743092010-10-19 00:05:51 +0000963 Py_HasFileSystemDefaultEncoding = 0;
Victor Stinner793b5312011-04-27 00:24:21 +0200964 interp->fscodec_initialized = 1;
965 return 0;
Victor Stinner7f84ab52010-06-11 00:36:33 +0000966 }
Victor Stinnerb744ba12010-05-15 12:27:16 +0000967
968 /* the encoding is mbcs, utf-8 or ascii */
969 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
970 if (!codec) {
971 /* Such error can only occurs in critical situations: no more
972 * memory, import a module of the standard library failed,
973 * etc. */
Victor Stinner793b5312011-04-27 00:24:21 +0200974 return -1;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000975 }
Victor Stinner793b5312011-04-27 00:24:21 +0200976 Py_DECREF(codec);
977 interp->fscodec_initialized = 1;
978 return 0;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000979}
980
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000981/* Import the site module (not into __main__ though) */
982
983static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000984initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000985{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 PyObject *m;
987 m = PyImport_ImportModule("site");
988 if (m == NULL) {
Victor Stinner62ce62a2013-07-22 22:53:28 +0200989 fprintf(stderr, "Failed to import the site module\n");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 PyErr_Print();
991 Py_Finalize();
992 exit(1);
993 }
994 else {
995 Py_DECREF(m);
996 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000997}
998
Antoine Pitrou05608432009-01-09 18:53:14 +0000999static PyObject*
1000create_stdio(PyObject* io,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 int fd, int write_mode, char* name,
1002 char* encoding, char* errors)
Antoine Pitrou05608432009-01-09 18:53:14 +00001003{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1005 const char* mode;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001006 const char* newline;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 PyObject *line_buffering;
1008 int buffering, isatty;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001009 _Py_IDENTIFIER(open);
1010 _Py_IDENTIFIER(isatty);
1011 _Py_IDENTIFIER(TextIOWrapper);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001012 _Py_IDENTIFIER(mode);
Antoine Pitrou05608432009-01-09 18:53:14 +00001013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 /* stdin is always opened in buffered mode, first because it shouldn't
1015 make a difference in common use cases, second because TextIOWrapper
1016 depends on the presence of a read1() method which only exists on
1017 buffered streams.
1018 */
1019 if (Py_UnbufferedStdioFlag && write_mode)
1020 buffering = 0;
1021 else
1022 buffering = -1;
1023 if (write_mode)
1024 mode = "wb";
1025 else
1026 mode = "rb";
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001027 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1028 fd, mode, buffering,
1029 Py_None, Py_None, Py_None, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 if (buf == NULL)
1031 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +00001032
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001033 if (buffering) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001034 _Py_IDENTIFIER(raw);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001035 raw = _PyObject_GetAttrId(buf, &PyId_raw);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 if (raw == NULL)
1037 goto error;
1038 }
1039 else {
1040 raw = buf;
1041 Py_INCREF(raw);
1042 }
Antoine Pitrou05608432009-01-09 18:53:14 +00001043
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 text = PyUnicode_FromString(name);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001045 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 goto error;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001047 res = _PyObject_CallMethodId(raw, &PyId_isatty, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 if (res == NULL)
1049 goto error;
1050 isatty = PyObject_IsTrue(res);
1051 Py_DECREF(res);
1052 if (isatty == -1)
1053 goto error;
1054 if (isatty || Py_UnbufferedStdioFlag)
1055 line_buffering = Py_True;
1056 else
1057 line_buffering = Py_False;
Antoine Pitrou91696412009-01-09 22:12:30 +00001058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 Py_CLEAR(raw);
1060 Py_CLEAR(text);
Antoine Pitrou91696412009-01-09 22:12:30 +00001061
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001062#ifdef MS_WINDOWS
Victor Stinner7b3f0fa2012-08-04 01:28:00 +02001063 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1064 newlines to "\n".
1065 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1066 newline = NULL;
1067#else
1068 /* sys.stdin: split lines at "\n".
1069 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1070 newline = "\n";
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001071#endif
1072
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001073 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssO",
1074 buf, encoding, errors,
1075 newline, line_buffering);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 Py_CLEAR(buf);
1077 if (stream == NULL)
1078 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +00001079
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 if (write_mode)
1081 mode = "w";
1082 else
1083 mode = "r";
1084 text = PyUnicode_FromString(mode);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001085 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 goto error;
1087 Py_CLEAR(text);
1088 return stream;
Antoine Pitrou05608432009-01-09 18:53:14 +00001089
1090error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 Py_XDECREF(buf);
1092 Py_XDECREF(stream);
1093 Py_XDECREF(text);
1094 Py_XDECREF(raw);
1095 return NULL;
Antoine Pitrou05608432009-01-09 18:53:14 +00001096}
1097
Antoine Pitrou11942a52011-11-28 19:08:36 +01001098static int
1099is_valid_fd(int fd)
1100{
1101 int dummy_fd;
1102 if (fd < 0 || !_PyVerify_fd(fd))
1103 return 0;
1104 dummy_fd = dup(fd);
1105 if (dummy_fd < 0)
1106 return 0;
1107 close(dummy_fd);
1108 return 1;
1109}
1110
Georg Brandl1a3284e2007-12-02 09:40:06 +00001111/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001112static int
1113initstdio(void)
1114{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 PyObject *iomod = NULL, *wrapper;
1116 PyObject *bimod = NULL;
1117 PyObject *m;
1118 PyObject *std = NULL;
1119 int status = 0, fd;
1120 PyObject * encoding_attr;
Serhiy Storchakabf28d2d2013-09-13 11:46:24 +03001121 char *pythonioencoding = NULL, *encoding, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 /* Hack to avoid a nasty recursion issue when Python is invoked
1124 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1125 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1126 goto error;
1127 }
1128 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1131 goto error;
1132 }
1133 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001135 if (!(bimod = PyImport_ImportModule("builtins"))) {
1136 goto error;
1137 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001139 if (!(iomod = PyImport_ImportModule("io"))) {
1140 goto error;
1141 }
1142 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1143 goto error;
1144 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 /* Set builtins.open */
1147 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
Antoine Pitrou5a96b522010-11-20 19:50:57 +00001148 Py_DECREF(wrapper);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 goto error;
1150 }
Antoine Pitrou5a96b522010-11-20 19:50:57 +00001151 Py_DECREF(wrapper);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001152
Nick Coghlan7d270ee2013-10-17 22:35:35 +10001153 encoding = _Py_StandardStreamEncoding;
1154 errors = _Py_StandardStreamErrors;
1155 if (!encoding || !errors) {
1156 pythonioencoding = Py_GETENV("PYTHONIOENCODING");
1157 if (pythonioencoding) {
1158 char *err;
1159 pythonioencoding = _PyMem_Strdup(pythonioencoding);
1160 if (pythonioencoding == NULL) {
1161 PyErr_NoMemory();
1162 goto error;
1163 }
1164 err = strchr(pythonioencoding, ':');
1165 if (err) {
1166 *err = '\0';
1167 err++;
1168 if (*err && !errors) {
1169 errors = err;
1170 }
1171 }
1172 if (*pythonioencoding && !encoding) {
1173 encoding = pythonioencoding;
1174 }
Victor Stinner49fc8ec2013-07-07 23:30:24 +02001175 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001176 }
Martin v. Löwis0f599892008-06-02 11:13:03 +00001177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 /* Set sys.stdin */
1179 fd = fileno(stdin);
1180 /* Under some conditions stdin, stdout and stderr may not be connected
1181 * and fileno() may point to an invalid file descriptor. For example
1182 * GUI apps don't have valid standard streams by default.
1183 */
Antoine Pitrou11942a52011-11-28 19:08:36 +01001184 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001185 std = Py_None;
1186 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 }
1188 else {
1189 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1190 if (std == NULL)
1191 goto error;
1192 } /* if (fd < 0) */
1193 PySys_SetObject("__stdin__", std);
Victor Stinnerbd303c12013-11-07 23:07:29 +01001194 _PySys_SetObjectId(&PyId_stdin, std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 /* Set sys.stdout */
1198 fd = fileno(stdout);
Antoine Pitrou11942a52011-11-28 19:08:36 +01001199 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001200 std = Py_None;
1201 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 }
1203 else {
1204 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1205 if (std == NULL)
1206 goto error;
1207 } /* if (fd < 0) */
1208 PySys_SetObject("__stdout__", std);
Victor Stinnerbd303c12013-11-07 23:07:29 +01001209 _PySys_SetObjectId(&PyId_stdout, std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001211
Guido van Rossum98297ee2007-11-06 21:34:58 +00001212#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 /* Set sys.stderr, replaces the preliminary stderr */
1214 fd = fileno(stderr);
Antoine Pitrou11942a52011-11-28 19:08:36 +01001215 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216 std = Py_None;
1217 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001218 }
1219 else {
1220 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1221 if (std == NULL)
1222 goto error;
1223 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +00001224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 /* Same as hack above, pre-import stderr's codec to avoid recursion
1226 when import.c tries to write to stderr in verbose mode. */
1227 encoding_attr = PyObject_GetAttrString(std, "encoding");
1228 if (encoding_attr != NULL) {
Victor Stinner49fc8ec2013-07-07 23:30:24 +02001229 const char * std_encoding;
1230 std_encoding = _PyUnicode_AsString(encoding_attr);
1231 if (std_encoding != NULL) {
1232 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
Antoine Pitrou2fabfac2012-01-18 15:14:46 +01001233 Py_XDECREF(codec_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 }
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +00001235 Py_DECREF(encoding_attr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001236 }
1237 PyErr_Clear(); /* Not a fatal error if codec isn't available */
Trent Nelson39e307e2008-03-19 06:45:48 +00001238
Victor Stinnerba308832013-07-22 23:55:19 +02001239 if (PySys_SetObject("__stderr__", std) < 0) {
1240 Py_DECREF(std);
1241 goto error;
1242 }
Victor Stinnerbd303c12013-11-07 23:07:29 +01001243 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
Victor Stinnerba308832013-07-22 23:55:19 +02001244 Py_DECREF(std);
1245 goto error;
1246 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001248#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001250 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001251 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001252 status = -1;
1253 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001254
Nick Coghlan7d270ee2013-10-17 22:35:35 +10001255 /* We won't need them anymore. */
1256 if (_Py_StandardStreamEncoding) {
1257 PyMem_RawFree(_Py_StandardStreamEncoding);
1258 _Py_StandardStreamEncoding = NULL;
1259 }
1260 if (_Py_StandardStreamErrors) {
1261 PyMem_RawFree(_Py_StandardStreamErrors);
1262 _Py_StandardStreamErrors = NULL;
1263 }
Serhiy Storchakabf28d2d2013-09-13 11:46:24 +03001264 PyMem_Free(pythonioencoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 Py_XDECREF(bimod);
1266 Py_XDECREF(iomod);
1267 return status;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001268}
1269
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001270/* Parse input from a file and execute it */
1271
1272int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001273PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001274 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001275{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001276 if (filename == NULL)
1277 filename = "???";
1278 if (Py_FdIsInteractive(fp, filename)) {
1279 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
1280 if (closeit)
1281 fclose(fp);
1282 return err;
1283 }
1284 else
1285 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001286}
1287
1288int
Victor Stinner95701bd2013-11-06 18:41:07 +01001289PyRun_InteractiveLoopFlags(FILE *fp, const char *filename_str, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001290{
Victor Stinner95701bd2013-11-06 18:41:07 +01001291 PyObject *filename, *v;
1292 int ret, err;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001294
Victor Stinner95701bd2013-11-06 18:41:07 +01001295 filename = PyUnicode_DecodeFSDefault(filename_str);
1296 if (filename == NULL) {
1297 PyErr_Print();
1298 return -1;
1299 }
1300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001301 if (flags == NULL) {
1302 flags = &local_flags;
1303 local_flags.cf_flags = 0;
1304 }
Victor Stinner09054372013-11-06 22:41:44 +01001305 v = _PySys_GetObjectId(&PyId_ps1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001306 if (v == NULL) {
Victor Stinner09054372013-11-06 22:41:44 +01001307 _PySys_SetObjectId(&PyId_ps1, v = PyUnicode_FromString(">>> "));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001308 Py_XDECREF(v);
1309 }
Victor Stinner09054372013-11-06 22:41:44 +01001310 v = _PySys_GetObjectId(&PyId_ps2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001311 if (v == NULL) {
Victor Stinner09054372013-11-06 22:41:44 +01001312 _PySys_SetObjectId(&PyId_ps2, v = PyUnicode_FromString("... "));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 Py_XDECREF(v);
1314 }
Victor Stinner95701bd2013-11-06 18:41:07 +01001315 err = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001316 for (;;) {
Victor Stinner95701bd2013-11-06 18:41:07 +01001317 ret = PyRun_InteractiveOneObject(fp, filename, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001318 PRINT_TOTAL_REFS();
Victor Stinner95701bd2013-11-06 18:41:07 +01001319 if (ret == E_EOF) {
1320 err = 0;
1321 break;
1322 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001323 /*
1324 if (ret == E_NOMEM)
Victor Stinner95701bd2013-11-06 18:41:07 +01001325 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001326 */
1327 }
Victor Stinner95701bd2013-11-06 18:41:07 +01001328 Py_DECREF(filename);
1329 return err;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001330}
1331
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001332/* compute parser flags based on compiler flags */
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001333static int PARSER_FLAGS(PyCompilerFlags *flags)
1334{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 int parser_flags = 0;
1336 if (!flags)
1337 return 0;
1338 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
1339 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1340 if (flags->cf_flags & PyCF_IGNORE_COOKIE)
1341 parser_flags |= PyPARSE_IGNORE_COOKIE;
1342 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
1343 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1344 return parser_flags;
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001345}
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001346
Thomas Wouters89f507f2006-12-13 04:49:30 +00001347#if 0
1348/* Keep an example of flags with future keyword support. */
1349#define PARSER_FLAGS(flags) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001350 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1351 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1352 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1353 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001354#endif
1355
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001356int
Victor Stinner95701bd2013-11-06 18:41:07 +01001357PyRun_InteractiveOneObject(FILE *fp, PyObject *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001358{
Victor Stinner95701bd2013-11-06 18:41:07 +01001359 PyObject *m, *d, *v, *w, *oenc = NULL, *mod_name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 mod_ty mod;
1361 PyArena *arena;
1362 char *ps1 = "", *ps2 = "", *enc = NULL;
1363 int errcode = 0;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001364 _Py_IDENTIFIER(encoding);
Victor Stinner95701bd2013-11-06 18:41:07 +01001365 _Py_IDENTIFIER(__main__);
1366
1367 mod_name = _PyUnicode_FromId(&PyId___main__); /* borrowed */
1368 if (mod_name == NULL) {
1369 PyErr_Print();
1370 return -1;
1371 }
Tim Petersfe2127d2001-07-16 05:37:24 +00001372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001373 if (fp == stdin) {
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -04001374 /* Fetch encoding from sys.stdin if possible. */
Victor Stinnerbd303c12013-11-07 23:07:29 +01001375 v = _PySys_GetObjectId(&PyId_stdin);
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -04001376 if (v && v != Py_None) {
1377 oenc = _PyObject_GetAttrId(v, &PyId_encoding);
1378 if (oenc)
1379 enc = _PyUnicode_AsString(oenc);
1380 if (!enc)
1381 PyErr_Clear();
1382 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001383 }
Victor Stinner09054372013-11-06 22:41:44 +01001384 v = _PySys_GetObjectId(&PyId_ps1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001385 if (v != NULL) {
1386 v = PyObject_Str(v);
1387 if (v == NULL)
1388 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001389 else if (PyUnicode_Check(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001390 ps1 = _PyUnicode_AsString(v);
Victor Stinner386fe712010-05-19 00:34:15 +00001391 if (ps1 == NULL) {
1392 PyErr_Clear();
1393 ps1 = "";
1394 }
1395 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001396 }
Victor Stinner09054372013-11-06 22:41:44 +01001397 w = _PySys_GetObjectId(&PyId_ps2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398 if (w != NULL) {
1399 w = PyObject_Str(w);
1400 if (w == NULL)
1401 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001402 else if (PyUnicode_Check(w)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 ps2 = _PyUnicode_AsString(w);
Victor Stinner386fe712010-05-19 00:34:15 +00001404 if (ps2 == NULL) {
1405 PyErr_Clear();
1406 ps2 = "";
1407 }
1408 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001409 }
1410 arena = PyArena_New();
1411 if (arena == NULL) {
1412 Py_XDECREF(v);
1413 Py_XDECREF(w);
1414 Py_XDECREF(oenc);
1415 return -1;
1416 }
Victor Stinner95701bd2013-11-06 18:41:07 +01001417 mod = PyParser_ASTFromFileObject(fp, filename, enc,
1418 Py_single_input, ps1, ps2,
1419 flags, &errcode, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001420 Py_XDECREF(v);
1421 Py_XDECREF(w);
1422 Py_XDECREF(oenc);
1423 if (mod == NULL) {
1424 PyArena_Free(arena);
1425 if (errcode == E_EOF) {
1426 PyErr_Clear();
1427 return E_EOF;
1428 }
1429 PyErr_Print();
1430 return -1;
1431 }
Victor Stinner95701bd2013-11-06 18:41:07 +01001432 m = PyImport_AddModuleObject(mod_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001433 if (m == NULL) {
1434 PyArena_Free(arena);
1435 return -1;
1436 }
1437 d = PyModule_GetDict(m);
1438 v = run_mod(mod, filename, d, d, flags, arena);
1439 PyArena_Free(arena);
1440 flush_io();
1441 if (v == NULL) {
1442 PyErr_Print();
1443 return -1;
1444 }
1445 Py_DECREF(v);
1446 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001447}
1448
Victor Stinner95701bd2013-11-06 18:41:07 +01001449int
1450PyRun_InteractiveOneFlags(FILE *fp, const char *filename_str, PyCompilerFlags *flags)
1451{
1452 PyObject *filename;
1453 int res;
1454
1455 filename = PyUnicode_DecodeFSDefault(filename_str);
1456 if (filename == NULL) {
1457 PyErr_Print();
1458 return -1;
1459 }
1460 res = PyRun_InteractiveOneObject(fp, filename, flags);
1461 Py_DECREF(filename);
1462 return res;
1463}
1464
1465
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001466/* Check whether a file maybe a pyc file: Look at the extension,
1467 the file type, and, if we may close it, at the first few bytes. */
1468
1469static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001470maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001471{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1473 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001475 /* Only look into the file if we are allowed to close it, since
1476 it then should also be seekable. */
1477 if (closeit) {
1478 /* Read only two bytes of the magic. If the file was opened in
1479 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1480 be read as they are on disk. */
1481 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1482 unsigned char buf[2];
1483 /* Mess: In case of -x, the stream is NOT at its start now,
1484 and ungetc() was used to push back the first newline,
1485 which makes the current stream position formally undefined,
1486 and a x-platform nightmare.
1487 Unfortunately, we have no direct way to know whether -x
1488 was specified. So we use a terrible hack: if the current
1489 stream position is not 0, we assume -x was specified, and
1490 give up. Bug 132850 on SourceForge spells out the
1491 hopelessness of trying anything else (fseek and ftell
1492 don't work predictably x-platform for text-mode files).
1493 */
1494 int ispyc = 0;
1495 if (ftell(fp) == 0) {
1496 if (fread(buf, 1, 2, fp) == 2 &&
1497 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
1498 ispyc = 1;
1499 rewind(fp);
1500 }
1501 return ispyc;
1502 }
1503 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001504}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001505
Antoine Pitrou32d483c2013-07-30 21:01:23 +02001506static int
1507set_main_loader(PyObject *d, const char *filename, const char *loader_name)
Nick Coghlan85e729e2012-07-15 18:09:52 +10001508{
1509 PyInterpreterState *interp;
1510 PyThreadState *tstate;
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001511 PyObject *filename_obj, *loader_type, *loader;
Nick Coghlanb7a58942012-07-15 23:21:08 +10001512 int result = 0;
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001513
1514 filename_obj = PyUnicode_DecodeFSDefault(filename);
1515 if (filename_obj == NULL)
1516 return -1;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001517 /* Get current thread state and interpreter pointer */
1518 tstate = PyThreadState_GET();
1519 interp = tstate->interp;
Nick Coghlan3f94cbf2012-07-15 19:10:39 +10001520 loader_type = PyObject_GetAttrString(interp->importlib, loader_name);
1521 if (loader_type == NULL) {
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001522 Py_DECREF(filename_obj);
Nick Coghlan3f94cbf2012-07-15 19:10:39 +10001523 return -1;
1524 }
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001525 loader = PyObject_CallFunction(loader_type, "sN", "__main__", filename_obj);
Nick Coghlanb7a58942012-07-15 23:21:08 +10001526 Py_DECREF(loader_type);
1527 if (loader == NULL) {
Nick Coghlan85e729e2012-07-15 18:09:52 +10001528 return -1;
1529 }
Nick Coghlanb7a58942012-07-15 23:21:08 +10001530 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
1531 result = -1;
1532 }
Nick Coghlan85e729e2012-07-15 18:09:52 +10001533 Py_DECREF(loader);
Nick Coghlanb7a58942012-07-15 23:21:08 +10001534 return result;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001535}
1536
1537int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001538PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001539 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001540{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001541 PyObject *m, *d, *v;
1542 const char *ext;
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001543 int set_file_name = 0, ret = -1;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00001544 size_t len;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001546 m = PyImport_AddModule("__main__");
1547 if (m == NULL)
1548 return -1;
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001549 Py_INCREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001550 d = PyModule_GetDict(m);
1551 if (PyDict_GetItemString(d, "__file__") == NULL) {
1552 PyObject *f;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00001553 f = PyUnicode_DecodeFSDefault(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001554 if (f == NULL)
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001555 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001556 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1557 Py_DECREF(f);
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001558 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 }
Barry Warsaw916048d2011-09-20 14:45:44 -04001560 if (PyDict_SetItemString(d, "__cached__", Py_None) < 0) {
1561 Py_DECREF(f);
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001562 goto done;
Barry Warsaw916048d2011-09-20 14:45:44 -04001563 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001564 set_file_name = 1;
1565 Py_DECREF(f);
1566 }
1567 len = strlen(filename);
1568 ext = filename + len - (len > 4 ? 4 : 0);
1569 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Christian Heimes04ac4c12012-09-11 15:47:28 +02001570 FILE *pyc_fp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001571 /* Try to run a pyc file. First, re-open in binary */
1572 if (closeit)
1573 fclose(fp);
Victor Stinnerdaf45552013-08-28 00:53:59 +02001574 if ((pyc_fp = _Py_fopen(filename, "rb")) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001575 fprintf(stderr, "python: Can't reopen .pyc file\n");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 goto done;
1577 }
1578 /* Turn on optimization if a .pyo file is given */
1579 if (strcmp(ext, ".pyo") == 0)
1580 Py_OptimizeFlag = 1;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001581
1582 if (set_main_loader(d, filename, "SourcelessFileLoader") < 0) {
1583 fprintf(stderr, "python: failed to set __main__.__loader__\n");
1584 ret = -1;
Christian Heimes04ac4c12012-09-11 15:47:28 +02001585 fclose(pyc_fp);
Nick Coghlan85e729e2012-07-15 18:09:52 +10001586 goto done;
1587 }
Christian Heimes04ac4c12012-09-11 15:47:28 +02001588 v = run_pyc_file(pyc_fp, filename, d, d, flags);
1589 fclose(pyc_fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001590 } else {
Nick Coghlan85e729e2012-07-15 18:09:52 +10001591 /* When running from stdin, leave __main__.__loader__ alone */
1592 if (strcmp(filename, "<stdin>") != 0 &&
1593 set_main_loader(d, filename, "SourceFileLoader") < 0) {
1594 fprintf(stderr, "python: failed to set __main__.__loader__\n");
1595 ret = -1;
1596 goto done;
1597 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001598 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
1599 closeit, flags);
1600 }
1601 flush_io();
1602 if (v == NULL) {
1603 PyErr_Print();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001604 goto done;
1605 }
1606 Py_DECREF(v);
1607 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001608 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1610 PyErr_Clear();
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001611 Py_DECREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001612 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001613}
1614
1615int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001616PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001617{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 PyObject *m, *d, *v;
1619 m = PyImport_AddModule("__main__");
1620 if (m == NULL)
1621 return -1;
1622 d = PyModule_GetDict(m);
1623 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
1624 if (v == NULL) {
1625 PyErr_Print();
1626 return -1;
1627 }
1628 Py_DECREF(v);
1629 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001630}
1631
Barry Warsaw035574d1997-08-29 22:07:17 +00001632static int
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001633parse_syntax_error(PyObject *err, PyObject **message, PyObject **filename,
1634 int *lineno, int *offset, PyObject **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001635{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001636 long hold;
1637 PyObject *v;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001638 _Py_IDENTIFIER(msg);
1639 _Py_IDENTIFIER(filename);
1640 _Py_IDENTIFIER(lineno);
1641 _Py_IDENTIFIER(offset);
1642 _Py_IDENTIFIER(text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001643
Benjamin Peterson80d50422012-04-03 00:30:38 -04001644 *message = NULL;
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001645 *filename = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001647 /* new style errors. `err' is an instance */
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001648 *message = _PyObject_GetAttrId(err, &PyId_msg);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001649 if (!*message)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001650 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001651
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001652 v = _PyObject_GetAttrId(err, &PyId_filename);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001653 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001655 if (v == Py_None) {
1656 Py_DECREF(v);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001657 *filename = _PyUnicode_FromId(&PyId_string);
1658 if (*filename == NULL)
1659 goto finally;
1660 Py_INCREF(*filename);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001661 }
1662 else {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001663 *filename = v;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001664 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001665
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001666 v = _PyObject_GetAttrId(err, &PyId_lineno);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001667 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001668 goto finally;
1669 hold = PyLong_AsLong(v);
1670 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001671 if (hold < 0 && PyErr_Occurred())
1672 goto finally;
1673 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001674
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001675 v = _PyObject_GetAttrId(err, &PyId_offset);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001676 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001677 goto finally;
1678 if (v == Py_None) {
1679 *offset = -1;
1680 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001681 } else {
1682 hold = PyLong_AsLong(v);
1683 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001684 if (hold < 0 && PyErr_Occurred())
1685 goto finally;
1686 *offset = (int)hold;
1687 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001688
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001689 v = _PyObject_GetAttrId(err, &PyId_text);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001690 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001691 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001692 if (v == Py_None) {
1693 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001694 *text = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001695 }
1696 else {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001697 *text = v;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001698 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001699 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001700
1701finally:
Benjamin Peterson80d50422012-04-03 00:30:38 -04001702 Py_XDECREF(*message);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001703 Py_XDECREF(*filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001704 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001705}
1706
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001707void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001708PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001709{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001710 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001711}
1712
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001713static void
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001714print_error_text(PyObject *f, int offset, PyObject *text_obj)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001715{
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001716 char *text;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001717 char *nl;
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001718
1719 text = _PyUnicode_AsString(text_obj);
1720 if (text == NULL)
1721 return;
1722
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001723 if (offset >= 0) {
Benjamin Petersona95e9772010-10-29 03:28:14 +00001724 if (offset > 0 && offset == strlen(text) && text[offset - 1] == '\n')
1725 offset--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 for (;;) {
1727 nl = strchr(text, '\n');
1728 if (nl == NULL || nl-text >= offset)
1729 break;
1730 offset -= (int)(nl+1-text);
1731 text = nl+1;
1732 }
1733 while (*text == ' ' || *text == '\t') {
1734 text++;
1735 offset--;
1736 }
1737 }
1738 PyFile_WriteString(" ", f);
1739 PyFile_WriteString(text, f);
1740 if (*text == '\0' || text[strlen(text)-1] != '\n')
1741 PyFile_WriteString("\n", f);
1742 if (offset == -1)
1743 return;
1744 PyFile_WriteString(" ", f);
Benjamin Petersona95e9772010-10-29 03:28:14 +00001745 while (--offset > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001746 PyFile_WriteString(" ", f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001747 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001748}
1749
Guido van Rossum66e8e862001-03-23 17:54:43 +00001750static void
1751handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001752{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001753 PyObject *exception, *value, *tb;
1754 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001756 if (Py_InspectFlag)
1757 /* Don't exit if -i flag was given. This flag is set to 0
1758 * when entering interactive mode for inspecting. */
1759 return;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001761 PyErr_Fetch(&exception, &value, &tb);
1762 fflush(stdout);
1763 if (value == NULL || value == Py_None)
1764 goto done;
1765 if (PyExceptionInstance_Check(value)) {
1766 /* The error code should be in the `code' attribute. */
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001767 _Py_IDENTIFIER(code);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001768 PyObject *code = _PyObject_GetAttrId(value, &PyId_code);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001769 if (code) {
1770 Py_DECREF(value);
1771 value = code;
1772 if (value == Py_None)
1773 goto done;
1774 }
1775 /* If we failed to dig out the 'code' attribute,
1776 just let the else clause below print the error. */
1777 }
1778 if (PyLong_Check(value))
1779 exitcode = (int)PyLong_AsLong(value);
1780 else {
Victor Stinnerbd303c12013-11-07 23:07:29 +01001781 PyObject *sys_stderr = _PySys_GetObjectId(&PyId_stderr);
Victor Stinner7126dbc2010-05-21 23:45:42 +00001782 if (sys_stderr != NULL && sys_stderr != Py_None) {
1783 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
1784 } else {
1785 PyObject_Print(value, stderr, Py_PRINT_RAW);
1786 fflush(stderr);
1787 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001788 PySys_WriteStderr("\n");
1789 exitcode = 1;
1790 }
Tim Peterscf615b52003-04-19 18:47:02 +00001791 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 /* Restore and clear the exception info, in order to properly decref
1793 * the exception, value, and traceback. If we just exit instead,
1794 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1795 * some finalizers from running.
1796 */
1797 PyErr_Restore(exception, value, tb);
1798 PyErr_Clear();
1799 Py_Exit(exitcode);
1800 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001801}
1802
1803void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001804PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001805{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001806 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001808 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1809 handle_system_exit();
1810 }
1811 PyErr_Fetch(&exception, &v, &tb);
1812 if (exception == NULL)
1813 return;
1814 PyErr_NormalizeException(&exception, &v, &tb);
1815 if (tb == NULL) {
1816 tb = Py_None;
1817 Py_INCREF(tb);
1818 }
1819 PyException_SetTraceback(v, tb);
1820 if (exception == NULL)
1821 return;
1822 /* Now we know v != NULL too */
1823 if (set_sys_last_vars) {
Victor Stinner09054372013-11-06 22:41:44 +01001824 _PySys_SetObjectId(&PyId_last_type, exception);
1825 _PySys_SetObjectId(&PyId_last_value, v);
1826 _PySys_SetObjectId(&PyId_last_traceback, tb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001827 }
Victor Stinner09054372013-11-06 22:41:44 +01001828 hook = _PySys_GetObjectId(&PyId_excepthook);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001829 if (hook) {
1830 PyObject *args = PyTuple_Pack(3, exception, v, tb);
1831 PyObject *result = PyEval_CallObject(hook, args);
1832 if (result == NULL) {
1833 PyObject *exception2, *v2, *tb2;
1834 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1835 handle_system_exit();
1836 }
1837 PyErr_Fetch(&exception2, &v2, &tb2);
1838 PyErr_NormalizeException(&exception2, &v2, &tb2);
1839 /* It should not be possible for exception2 or v2
1840 to be NULL. However PyErr_Display() can't
1841 tolerate NULLs, so just be safe. */
1842 if (exception2 == NULL) {
1843 exception2 = Py_None;
1844 Py_INCREF(exception2);
1845 }
1846 if (v2 == NULL) {
1847 v2 = Py_None;
1848 Py_INCREF(v2);
1849 }
1850 fflush(stdout);
1851 PySys_WriteStderr("Error in sys.excepthook:\n");
1852 PyErr_Display(exception2, v2, tb2);
1853 PySys_WriteStderr("\nOriginal exception was:\n");
1854 PyErr_Display(exception, v, tb);
1855 Py_DECREF(exception2);
1856 Py_DECREF(v2);
1857 Py_XDECREF(tb2);
1858 }
1859 Py_XDECREF(result);
1860 Py_XDECREF(args);
1861 } else {
1862 PySys_WriteStderr("sys.excepthook is missing\n");
1863 PyErr_Display(exception, v, tb);
1864 }
1865 Py_XDECREF(exception);
1866 Py_XDECREF(v);
1867 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001868}
1869
Benjamin Petersone6528212008-07-15 15:32:09 +00001870static void
1871print_exception(PyObject *f, PyObject *value)
1872{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001873 int err = 0;
1874 PyObject *type, *tb;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001875 _Py_IDENTIFIER(print_file_and_line);
Benjamin Petersone6528212008-07-15 15:32:09 +00001876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001877 if (!PyExceptionInstance_Check(value)) {
1878 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1879 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1880 PyFile_WriteString(" found\n", f);
1881 return;
1882 }
Benjamin Peterson26582602008-08-23 20:08:07 +00001883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001884 Py_INCREF(value);
1885 fflush(stdout);
1886 type = (PyObject *) Py_TYPE(value);
1887 tb = PyException_GetTraceback(value);
1888 if (tb && tb != Py_None)
1889 err = PyTraceBack_Print(tb, f);
1890 if (err == 0 &&
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001891 _PyObject_HasAttrId(value, &PyId_print_file_and_line))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001892 {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001893 PyObject *message, *filename, *text;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001894 int lineno, offset;
1895 if (!parse_syntax_error(value, &message, &filename,
1896 &lineno, &offset, &text))
1897 PyErr_Clear();
1898 else {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001899 PyObject *line;
1900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001901 Py_DECREF(value);
1902 value = message;
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001903
1904 line = PyUnicode_FromFormat(" File \"%U\", line %d\n",
1905 filename, lineno);
1906 Py_DECREF(filename);
1907 if (line != NULL) {
1908 PyFile_WriteObject(line, f, Py_PRINT_RAW);
1909 Py_DECREF(line);
1910 }
1911
1912 if (text != NULL) {
1913 print_error_text(f, offset, text);
1914 Py_DECREF(text);
1915 }
1916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001917 /* Can't be bothered to check all those
1918 PyFile_WriteString() calls */
1919 if (PyErr_Occurred())
1920 err = -1;
1921 }
1922 }
1923 if (err) {
1924 /* Don't do anything else */
1925 }
1926 else {
1927 PyObject* moduleName;
1928 char* className;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001929 _Py_IDENTIFIER(__module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001930 assert(PyExceptionClass_Check(type));
1931 className = PyExceptionClass_Name(type);
1932 if (className != NULL) {
1933 char *dot = strrchr(className, '.');
1934 if (dot != NULL)
1935 className = dot+1;
1936 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001937
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001938 moduleName = _PyObject_GetAttrId(type, &PyId___module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001939 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1940 {
Victor Stinner13b21bd2011-05-26 14:25:13 +02001941 Py_XDECREF(moduleName);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001942 err = PyFile_WriteString("<unknown>", f);
1943 }
1944 else {
Victor Stinnerbd303c12013-11-07 23:07:29 +01001945 if (_PyUnicode_CompareWithId(moduleName, &PyId_builtins) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001946 {
Victor Stinner937114f2013-11-07 00:12:30 +01001947 err = PyFile_WriteObject(moduleName, f, Py_PRINT_RAW);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001948 err += PyFile_WriteString(".", f);
1949 }
1950 Py_DECREF(moduleName);
1951 }
1952 if (err == 0) {
1953 if (className == NULL)
1954 err = PyFile_WriteString("<unknown>", f);
1955 else
1956 err = PyFile_WriteString(className, f);
1957 }
1958 }
1959 if (err == 0 && (value != Py_None)) {
1960 PyObject *s = PyObject_Str(value);
1961 /* only print colon if the str() of the
1962 object is not the empty string
1963 */
1964 if (s == NULL)
1965 err = -1;
1966 else if (!PyUnicode_Check(s) ||
Victor Stinnere251d6d2011-11-20 19:20:00 +01001967 PyUnicode_GetLength(s) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001968 err = PyFile_WriteString(": ", f);
1969 if (err == 0)
1970 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1971 Py_XDECREF(s);
1972 }
1973 /* try to write a newline in any case */
1974 err += PyFile_WriteString("\n", f);
1975 Py_XDECREF(tb);
1976 Py_DECREF(value);
1977 /* If an error happened here, don't show it.
1978 XXX This is wrong, but too many callers rely on this behavior. */
1979 if (err != 0)
1980 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001981}
1982
1983static const char *cause_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001984 "\nThe above exception was the direct cause "
1985 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001986
1987static const char *context_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001988 "\nDuring handling of the above exception, "
1989 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001990
1991static void
1992print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1993{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 int err = 0, res;
1995 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00001996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001997 if (seen != NULL) {
1998 /* Exception chaining */
1999 if (PySet_Add(seen, value) == -1)
2000 PyErr_Clear();
2001 else if (PyExceptionInstance_Check(value)) {
2002 cause = PyException_GetCause(value);
2003 context = PyException_GetContext(value);
Benjamin Petersond5a1c442012-05-14 22:09:31 -07002004 if (cause) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002005 res = PySet_Contains(seen, cause);
2006 if (res == -1)
2007 PyErr_Clear();
2008 if (res == 0) {
2009 print_exception_recursive(
2010 f, cause, seen);
2011 err |= PyFile_WriteString(
2012 cause_message, f);
2013 }
2014 }
Benjamin Petersond5a1c442012-05-14 22:09:31 -07002015 else if (context &&
2016 !((PyBaseExceptionObject *)value)->suppress_context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002017 res = PySet_Contains(seen, context);
2018 if (res == -1)
2019 PyErr_Clear();
2020 if (res == 0) {
2021 print_exception_recursive(
2022 f, context, seen);
2023 err |= PyFile_WriteString(
2024 context_message, f);
2025 }
2026 }
2027 Py_XDECREF(context);
2028 Py_XDECREF(cause);
2029 }
2030 }
2031 print_exception(f, value);
2032 if (err != 0)
2033 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00002034}
2035
Thomas Wouters477c8d52006-05-27 19:21:47 +00002036void
2037PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002038{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002039 PyObject *seen;
Victor Stinnerbd303c12013-11-07 23:07:29 +01002040 PyObject *f = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrou24201d42013-10-13 21:53:13 +02002041 if (PyExceptionInstance_Check(value)
2042 && tb != NULL && PyTraceBack_Check(tb)) {
2043 /* Put the traceback on the exception, otherwise it won't get
2044 displayed. See issue #18776. */
2045 PyObject *cur_tb = PyException_GetTraceback(value);
2046 if (cur_tb == NULL)
2047 PyException_SetTraceback(value, tb);
2048 else
2049 Py_DECREF(cur_tb);
2050 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002051 if (f == Py_None) {
2052 /* pass */
2053 }
2054 else if (f == NULL) {
2055 _PyObject_Dump(value);
2056 fprintf(stderr, "lost sys.stderr\n");
2057 }
2058 else {
2059 /* We choose to ignore seen being possibly NULL, and report
2060 at least the main exception (it could be a MemoryError).
2061 */
2062 seen = PySet_New(NULL);
2063 if (seen == NULL)
2064 PyErr_Clear();
2065 print_exception_recursive(f, value, seen);
2066 Py_XDECREF(seen);
2067 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002068}
2069
Guido van Rossum82598051997-03-05 00:20:32 +00002070PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002071PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002072 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002073{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002074 PyObject *ret = NULL;
2075 mod_ty mod;
Victor Stinner95701bd2013-11-06 18:41:07 +01002076 PyArena *arena;
Victor Stinner95701bd2013-11-06 18:41:07 +01002077 PyObject *filename;
2078
2079 filename = _PyUnicode_FromId(&PyId_string); /* borrowed */
2080 if (filename == NULL)
2081 return NULL;
2082
2083 arena = PyArena_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002084 if (arena == NULL)
2085 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00002086
Victor Stinner95701bd2013-11-06 18:41:07 +01002087 mod = PyParser_ASTFromStringObject(str, filename, start, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002088 if (mod != NULL)
Victor Stinner95701bd2013-11-06 18:41:07 +01002089 ret = run_mod(mod, filename, globals, locals, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002090 PyArena_Free(arena);
2091 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002092}
2093
2094PyObject *
Victor Stinner95701bd2013-11-06 18:41:07 +01002095PyRun_FileExFlags(FILE *fp, const char *filename_str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002096 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002097{
Victor Stinner95701bd2013-11-06 18:41:07 +01002098 PyObject *ret = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002099 mod_ty mod;
Victor Stinner95701bd2013-11-06 18:41:07 +01002100 PyArena *arena = NULL;
2101 PyObject *filename;
Guido van Rossum98297ee2007-11-06 21:34:58 +00002102
Victor Stinner95701bd2013-11-06 18:41:07 +01002103 filename = PyUnicode_DecodeFSDefault(filename_str);
2104 if (filename == NULL)
2105 goto exit;
2106
2107 arena = PyArena_New();
2108 if (arena == NULL)
2109 goto exit;
2110
2111 mod = PyParser_ASTFromFileObject(fp, filename, NULL, start, 0, 0,
2112 flags, NULL, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002113 if (closeit)
2114 fclose(fp);
2115 if (mod == NULL) {
Victor Stinner95701bd2013-11-06 18:41:07 +01002116 goto exit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002117 }
2118 ret = run_mod(mod, filename, globals, locals, flags, arena);
Victor Stinner95701bd2013-11-06 18:41:07 +01002119
2120exit:
2121 Py_XDECREF(filename);
2122 if (arena != NULL)
2123 PyArena_Free(arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002125}
2126
Guido van Rossum6c193fa2007-12-05 05:14:58 +00002127static void
2128flush_io(void)
2129{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 PyObject *f, *r;
2131 PyObject *type, *value, *traceback;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00002132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002133 /* Save the current exception */
2134 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00002135
Victor Stinnerbd303c12013-11-07 23:07:29 +01002136 f = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 if (f != NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002138 r = _PyObject_CallMethodId(f, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002139 if (r)
2140 Py_DECREF(r);
2141 else
2142 PyErr_Clear();
2143 }
Victor Stinnerbd303c12013-11-07 23:07:29 +01002144 f = _PySys_GetObjectId(&PyId_stdout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002145 if (f != NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002146 r = _PyObject_CallMethodId(f, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147 if (r)
2148 Py_DECREF(r);
2149 else
2150 PyErr_Clear();
2151 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00002152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002153 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00002154}
2155
Guido van Rossum82598051997-03-05 00:20:32 +00002156static PyObject *
Victor Stinner95701bd2013-11-06 18:41:07 +01002157run_mod(mod_ty mod, PyObject *filename, PyObject *globals, PyObject *locals,
2158 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002159{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 PyCodeObject *co;
2161 PyObject *v;
Victor Stinner95701bd2013-11-06 18:41:07 +01002162 co = PyAST_CompileObject(mod, filename, flags, -1, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 if (co == NULL)
2164 return NULL;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002165 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002166 Py_DECREF(co);
2167 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002168}
2169
Guido van Rossum82598051997-03-05 00:20:32 +00002170static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002171run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002172 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00002173{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002174 PyCodeObject *co;
2175 PyObject *v;
2176 long magic;
2177 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00002178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002179 magic = PyMarshal_ReadLongFromFile(fp);
2180 if (magic != PyImport_GetMagicNumber()) {
2181 PyErr_SetString(PyExc_RuntimeError,
2182 "Bad magic number in .pyc file");
2183 return NULL;
2184 }
Antoine Pitrou5136ac02012-01-13 18:52:16 +01002185 /* Skip mtime and size */
2186 (void) PyMarshal_ReadLongFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002187 (void) PyMarshal_ReadLongFromFile(fp);
2188 v = PyMarshal_ReadLastObjectFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002189 if (v == NULL || !PyCode_Check(v)) {
2190 Py_XDECREF(v);
2191 PyErr_SetString(PyExc_RuntimeError,
2192 "Bad code object in .pyc file");
2193 return NULL;
2194 }
2195 co = (PyCodeObject *)v;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002196 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197 if (v && flags)
2198 flags->cf_flags |= (co->co_flags & PyCF_MASK);
2199 Py_DECREF(co);
2200 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00002201}
2202
Guido van Rossum82598051997-03-05 00:20:32 +00002203PyObject *
Victor Stinner14e461d2013-08-26 22:28:21 +02002204Py_CompileStringObject(const char *str, PyObject *filename, int start,
2205 PyCompilerFlags *flags, int optimize)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002206{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002207 PyCodeObject *co;
2208 mod_ty mod;
2209 PyArena *arena = PyArena_New();
2210 if (arena == NULL)
2211 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002212
Victor Stinner14e461d2013-08-26 22:28:21 +02002213 mod = PyParser_ASTFromStringObject(str, filename, start, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002214 if (mod == NULL) {
2215 PyArena_Free(arena);
2216 return NULL;
2217 }
2218 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
2219 PyObject *result = PyAST_mod2obj(mod);
2220 PyArena_Free(arena);
2221 return result;
2222 }
Victor Stinner14e461d2013-08-26 22:28:21 +02002223 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002224 PyArena_Free(arena);
2225 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00002226}
2227
Victor Stinner14e461d2013-08-26 22:28:21 +02002228PyObject *
2229Py_CompileStringExFlags(const char *str, const char *filename_str, int start,
2230 PyCompilerFlags *flags, int optimize)
2231{
2232 PyObject *filename, *co;
2233 filename = PyUnicode_DecodeFSDefault(filename_str);
2234 if (filename == NULL)
2235 return NULL;
2236 co = Py_CompileStringObject(str, filename, start, flags, optimize);
2237 Py_DECREF(filename);
2238 return co;
2239}
2240
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002241/* For use in Py_LIMITED_API */
2242#undef Py_CompileString
2243PyObject *
2244PyCompileString(const char *str, const char *filename, int start)
2245{
2246 return Py_CompileStringFlags(str, filename, start, NULL);
2247}
2248
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002249struct symtable *
Victor Stinner14e461d2013-08-26 22:28:21 +02002250Py_SymtableStringObject(const char *str, PyObject *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002251{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002252 struct symtable *st;
2253 mod_ty mod;
2254 PyCompilerFlags flags;
Victor Stinner14e461d2013-08-26 22:28:21 +02002255 PyArena *arena;
2256
2257 arena = PyArena_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002258 if (arena == NULL)
2259 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002261 flags.cf_flags = 0;
Victor Stinner14e461d2013-08-26 22:28:21 +02002262 mod = PyParser_ASTFromStringObject(str, filename, start, &flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002263 if (mod == NULL) {
2264 PyArena_Free(arena);
2265 return NULL;
2266 }
Victor Stinner14e461d2013-08-26 22:28:21 +02002267 st = PySymtable_BuildObject(mod, filename, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002268 PyArena_Free(arena);
2269 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002270}
2271
Victor Stinner14e461d2013-08-26 22:28:21 +02002272struct symtable *
2273Py_SymtableString(const char *str, const char *filename_str, int start)
2274{
2275 PyObject *filename;
2276 struct symtable *st;
2277
2278 filename = PyUnicode_DecodeFSDefault(filename_str);
2279 if (filename == NULL)
2280 return NULL;
2281 st = Py_SymtableStringObject(str, filename, start);
2282 Py_DECREF(filename);
2283 return st;
2284}
2285
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002286/* Preferred access to parser is through AST. */
2287mod_ty
Victor Stinner14e461d2013-08-26 22:28:21 +02002288PyParser_ASTFromStringObject(const char *s, PyObject *filename, int start,
2289 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002290{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002291 mod_ty mod;
2292 PyCompilerFlags localflags;
2293 perrdetail err;
2294 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00002295
Victor Stinner14e461d2013-08-26 22:28:21 +02002296 node *n = PyParser_ParseStringObject(s, filename,
2297 &_PyParser_Grammar, start, &err,
2298 &iflags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002299 if (flags == NULL) {
2300 localflags.cf_flags = 0;
2301 flags = &localflags;
2302 }
2303 if (n) {
2304 flags->cf_flags |= iflags & PyCF_MASK;
Victor Stinner14e461d2013-08-26 22:28:21 +02002305 mod = PyAST_FromNodeObject(n, flags, filename, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002306 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002307 }
2308 else {
2309 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002310 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002311 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002312 err_free(&err);
2313 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002314}
2315
2316mod_ty
Victor Stinner14e461d2013-08-26 22:28:21 +02002317PyParser_ASTFromString(const char *s, const char *filename_str, int start,
2318 PyCompilerFlags *flags, PyArena *arena)
2319{
2320 PyObject *filename;
2321 mod_ty mod;
2322 filename = PyUnicode_DecodeFSDefault(filename_str);
2323 if (filename == NULL)
2324 return NULL;
2325 mod = PyParser_ASTFromStringObject(s, filename, start, flags, arena);
2326 Py_DECREF(filename);
2327 return mod;
2328}
2329
2330mod_ty
2331PyParser_ASTFromFileObject(FILE *fp, PyObject *filename, const char* enc,
2332 int start, char *ps1,
2333 char *ps2, PyCompilerFlags *flags, int *errcode,
2334 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002335{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002336 mod_ty mod;
2337 PyCompilerFlags localflags;
2338 perrdetail err;
2339 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00002340
Victor Stinner14e461d2013-08-26 22:28:21 +02002341 node *n = PyParser_ParseFileObject(fp, filename, enc,
2342 &_PyParser_Grammar,
2343 start, ps1, ps2, &err, &iflags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002344 if (flags == NULL) {
2345 localflags.cf_flags = 0;
2346 flags = &localflags;
2347 }
2348 if (n) {
2349 flags->cf_flags |= iflags & PyCF_MASK;
Victor Stinner14e461d2013-08-26 22:28:21 +02002350 mod = PyAST_FromNodeObject(n, flags, filename, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002351 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002352 }
2353 else {
2354 err_input(&err);
2355 if (errcode)
2356 *errcode = err.error;
Victor Stinner7f2fee32011-04-05 00:39:01 +02002357 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002358 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002359 err_free(&err);
2360 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002361}
2362
Victor Stinner14e461d2013-08-26 22:28:21 +02002363mod_ty
2364PyParser_ASTFromFile(FILE *fp, const char *filename_str, const char* enc,
2365 int start, char *ps1,
2366 char *ps2, PyCompilerFlags *flags, int *errcode,
2367 PyArena *arena)
2368{
2369 mod_ty mod;
2370 PyObject *filename;
2371 filename = PyUnicode_DecodeFSDefault(filename_str);
2372 if (filename == NULL)
2373 return NULL;
2374 mod = PyParser_ASTFromFileObject(fp, filename, enc, start, ps1, ps2,
2375 flags, errcode, arena);
2376 Py_DECREF(filename);
2377 return mod;
2378}
2379
Guido van Rossuma110aa61994-08-29 12:50:44 +00002380/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002381
Guido van Rossuma110aa61994-08-29 12:50:44 +00002382node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002383PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002384{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385 perrdetail err;
2386 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
2387 &_PyParser_Grammar,
2388 start, NULL, NULL, &err, flags);
2389 if (n == NULL)
2390 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002391 err_free(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002393 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002394}
2395
Guido van Rossuma110aa61994-08-29 12:50:44 +00002396/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002397
Guido van Rossuma110aa61994-08-29 12:50:44 +00002398node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002399PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00002400{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002401 perrdetail err;
2402 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
2403 start, &err, flags);
2404 if (n == NULL)
2405 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002406 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002407 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00002408}
2409
2410node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002411PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002412 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00002413{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002414 perrdetail err;
2415 node *n = PyParser_ParseStringFlagsFilename(str, filename,
2416 &_PyParser_Grammar, start, &err, flags);
2417 if (n == NULL)
2418 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002419 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002420 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00002421}
2422
2423node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002424PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00002425{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002426 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00002427}
2428
Guido van Rossum66ebd912003-04-17 16:02:26 +00002429/* May want to move a more generalized form of this to parsetok.c or
2430 even parser modules. */
2431
2432void
Victor Stinner7f2fee32011-04-05 00:39:01 +02002433PyParser_ClearError(perrdetail *err)
2434{
2435 err_free(err);
2436}
2437
2438void
Guido van Rossum66ebd912003-04-17 16:02:26 +00002439PyParser_SetError(perrdetail *err)
2440{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002441 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00002442}
2443
Victor Stinner7f2fee32011-04-05 00:39:01 +02002444static void
2445err_free(perrdetail *err)
2446{
2447 Py_CLEAR(err->filename);
2448}
2449
Guido van Rossuma110aa61994-08-29 12:50:44 +00002450/* Set the error appropriate to the given input error code (see errcode.h) */
2451
2452static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002453err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00002454{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002455 PyObject *v, *w, *errtype, *errtext;
2456 PyObject *msg_obj = NULL;
2457 char *msg = NULL;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00002458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002459 errtype = PyExc_SyntaxError;
2460 switch (err->error) {
2461 case E_ERROR:
2462 return;
2463 case E_SYNTAX:
2464 errtype = PyExc_IndentationError;
2465 if (err->expected == INDENT)
2466 msg = "expected an indented block";
2467 else if (err->token == INDENT)
2468 msg = "unexpected indent";
2469 else if (err->token == DEDENT)
2470 msg = "unexpected unindent";
2471 else {
2472 errtype = PyExc_SyntaxError;
2473 msg = "invalid syntax";
2474 }
2475 break;
2476 case E_TOKEN:
2477 msg = "invalid token";
2478 break;
2479 case E_EOFS:
2480 msg = "EOF while scanning triple-quoted string literal";
2481 break;
2482 case E_EOLS:
2483 msg = "EOL while scanning string literal";
2484 break;
2485 case E_INTR:
2486 if (!PyErr_Occurred())
2487 PyErr_SetNone(PyExc_KeyboardInterrupt);
2488 goto cleanup;
2489 case E_NOMEM:
2490 PyErr_NoMemory();
2491 goto cleanup;
2492 case E_EOF:
2493 msg = "unexpected EOF while parsing";
2494 break;
2495 case E_TABSPACE:
2496 errtype = PyExc_TabError;
2497 msg = "inconsistent use of tabs and spaces in indentation";
2498 break;
2499 case E_OVERFLOW:
2500 msg = "expression too long";
2501 break;
2502 case E_DEDENT:
2503 errtype = PyExc_IndentationError;
2504 msg = "unindent does not match any outer indentation level";
2505 break;
2506 case E_TOODEEP:
2507 errtype = PyExc_IndentationError;
2508 msg = "too many levels of indentation";
2509 break;
2510 case E_DECODE: {
2511 PyObject *type, *value, *tb;
2512 PyErr_Fetch(&type, &value, &tb);
2513 msg = "unknown decode error";
2514 if (value != NULL)
2515 msg_obj = PyObject_Str(value);
2516 Py_XDECREF(type);
2517 Py_XDECREF(value);
2518 Py_XDECREF(tb);
2519 break;
2520 }
2521 case E_LINECONT:
2522 msg = "unexpected character after line continuation character";
2523 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00002524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002525 case E_IDENTIFIER:
2526 msg = "invalid character in identifier";
2527 break;
Meador Ingefa21bf02012-01-19 01:08:41 -06002528 case E_BADSINGLE:
2529 msg = "multiple statements found while compiling a single statement";
2530 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002531 default:
2532 fprintf(stderr, "error=%d\n", err->error);
2533 msg = "unknown parsing error";
2534 break;
2535 }
2536 /* err->text may not be UTF-8 in case of decoding errors.
2537 Explicitly convert to an object. */
2538 if (!err->text) {
2539 errtext = Py_None;
2540 Py_INCREF(Py_None);
2541 } else {
2542 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
2543 "replace");
2544 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002545 v = Py_BuildValue("(OiiN)", err->filename,
2546 err->lineno, err->offset, errtext);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002547 if (v != NULL) {
2548 if (msg_obj)
2549 w = Py_BuildValue("(OO)", msg_obj, v);
2550 else
2551 w = Py_BuildValue("(sO)", msg, v);
2552 } else
2553 w = NULL;
2554 Py_XDECREF(v);
2555 PyErr_SetObject(errtype, w);
2556 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00002557cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002558 Py_XDECREF(msg_obj);
2559 if (err->text != NULL) {
2560 PyObject_FREE(err->text);
2561 err->text = NULL;
2562 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002563}
2564
2565/* Print fatal error message and abort */
2566
2567void
Tim Peters7c321a82002-07-09 02:57:01 +00002568Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002569{
Victor Stinner024e37a2011-03-31 01:31:06 +02002570 const int fd = fileno(stderr);
2571 PyThreadState *tstate;
2572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002573 fprintf(stderr, "Fatal Python error: %s\n", msg);
2574 fflush(stderr); /* it helps in Windows debug build */
2575 if (PyErr_Occurred()) {
Victor Stinner55a5c782010-06-08 21:00:13 +00002576 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002577 }
Victor Stinner024e37a2011-03-31 01:31:06 +02002578 else {
2579 tstate = _Py_atomic_load_relaxed(&_PyThreadState_Current);
2580 if (tstate != NULL) {
2581 fputc('\n', stderr);
2582 fflush(stderr);
Victor Stinner7bba62f2011-05-07 12:43:00 +02002583 _Py_DumpTracebackThreads(fd, tstate->interp, tstate);
Victor Stinner024e37a2011-03-31 01:31:06 +02002584 }
Victor Stinnerd727e232011-04-01 12:13:55 +02002585 _PyFaulthandler_Fini();
Victor Stinner024e37a2011-03-31 01:31:06 +02002586 }
2587
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002588#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002589 {
2590 size_t len = strlen(msg);
2591 WCHAR* buffer;
2592 size_t i;
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002594 /* Convert the message to wchar_t. This uses a simple one-to-one
2595 conversion, assuming that the this error message actually uses ASCII
2596 only. If this ceases to be true, we will have to convert. */
2597 buffer = alloca( (len+1) * (sizeof *buffer));
2598 for( i=0; i<=len; ++i)
2599 buffer[i] = msg[i];
2600 OutputDebugStringW(L"Fatal Python error: ");
2601 OutputDebugStringW(buffer);
2602 OutputDebugStringW(L"\n");
2603 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002604#ifdef _DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002605 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002606#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002607#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002608 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002609}
2610
2611/* Clean up and exit */
2612
Guido van Rossuma110aa61994-08-29 12:50:44 +00002613#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002614#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002615#endif
2616
Collin Winter670e6922007-03-21 02:57:17 +00002617static void (*pyexitfunc)(void) = NULL;
2618/* For the atexit module. */
2619void _Py_PyAtExit(void (*func)(void))
2620{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002621 pyexitfunc = func;
Collin Winter670e6922007-03-21 02:57:17 +00002622}
2623
2624static void
2625call_py_exitfuncs(void)
2626{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002627 if (pyexitfunc == NULL)
2628 return;
Collin Winter670e6922007-03-21 02:57:17 +00002629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002630 (*pyexitfunc)();
2631 PyErr_Clear();
Collin Winter670e6922007-03-21 02:57:17 +00002632}
2633
Antoine Pitrou011bd622009-10-20 21:52:47 +00002634/* Wait until threading._shutdown completes, provided
2635 the threading module was imported in the first place.
2636 The shutdown routine will wait until all non-daemon
2637 "threading" threads have completed. */
2638static void
2639wait_for_thread_shutdown(void)
2640{
2641#ifdef WITH_THREAD
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002642 _Py_IDENTIFIER(_shutdown);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002643 PyObject *result;
2644 PyThreadState *tstate = PyThreadState_GET();
2645 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2646 "threading");
2647 if (threading == NULL) {
2648 /* threading not imported */
2649 PyErr_Clear();
2650 return;
2651 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002652 result = _PyObject_CallMethodId(threading, &PyId__shutdown, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002653 if (result == NULL) {
2654 PyErr_WriteUnraisable(threading);
2655 }
2656 else {
2657 Py_DECREF(result);
2658 }
2659 Py_DECREF(threading);
Antoine Pitrou011bd622009-10-20 21:52:47 +00002660#endif
2661}
2662
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002663#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002664static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002665static int nexitfuncs = 0;
2666
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002667int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002668{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002669 if (nexitfuncs >= NEXITFUNCS)
2670 return -1;
2671 exitfuncs[nexitfuncs++] = func;
2672 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00002673}
2674
Guido van Rossumcc283f51997-08-05 02:22:03 +00002675static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002676call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002677{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002678 while (nexitfuncs > 0)
2679 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002681 fflush(stdout);
2682 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002683}
2684
2685void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002686Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002687{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002688 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002689
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002690 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002691}
2692
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002693static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002694initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002695{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002696#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002697 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002698#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002699#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002700 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002701#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002702#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002703 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002704#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002705 PyOS_InitInterrupts(); /* May imply initsignal() */
Victor Stinnerd786ad52013-07-21 13:25:51 +02002706 if (PyErr_Occurred()) {
2707 Py_FatalError("Py_Initialize: can't import signal");
2708 }
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002709}
2710
Guido van Rossum7433b121997-02-14 19:45:36 +00002711
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002712/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2713 *
2714 * All of the code in this function must only use async-signal-safe functions,
2715 * listed at `man 7 signal` or
2716 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2717 */
2718void
2719_Py_RestoreSignals(void)
2720{
2721#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002722 PyOS_setsig(SIGPIPE, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002723#endif
2724#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002725 PyOS_setsig(SIGXFZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002726#endif
2727#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002728 PyOS_setsig(SIGXFSZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002729#endif
2730}
2731
2732
Guido van Rossum7433b121997-02-14 19:45:36 +00002733/*
2734 * The file descriptor fd is considered ``interactive'' if either
2735 * a) isatty(fd) is TRUE, or
2736 * b) the -i flag was given, and the filename associated with
2737 * the descriptor is NULL or "<stdin>" or "???".
2738 */
2739int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002740Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002741{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002742 if (isatty((int)fileno(fp)))
2743 return 1;
2744 if (!Py_InteractiveFlag)
2745 return 0;
2746 return (filename == NULL) ||
2747 (strcmp(filename, "<stdin>") == 0) ||
2748 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00002749}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002750
2751
Tim Petersd08e3822003-04-17 15:24:21 +00002752#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002753#if defined(WIN32) && defined(_MSC_VER)
2754
2755/* Stack checking for Microsoft C */
2756
2757#include <malloc.h>
2758#include <excpt.h>
2759
Fred Drakee8de31c2000-08-31 05:38:39 +00002760/*
2761 * Return non-zero when we run out of memory on the stack; zero otherwise.
2762 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002763int
Fred Drake399739f2000-08-31 05:52:44 +00002764PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002765{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002766 __try {
2767 /* alloca throws a stack overflow exception if there's
2768 not enough space left on the stack */
2769 alloca(PYOS_STACK_MARGIN * sizeof(void*));
2770 return 0;
2771 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2772 EXCEPTION_EXECUTE_HANDLER :
2773 EXCEPTION_CONTINUE_SEARCH) {
2774 int errcode = _resetstkoflw();
2775 if (errcode == 0)
2776 {
2777 Py_FatalError("Could not reset the stack!");
2778 }
2779 }
2780 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002781}
2782
2783#endif /* WIN32 && _MSC_VER */
2784
2785/* Alternate implementations can be added here... */
2786
2787#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002788
2789
2790/* Wrappers around sigaction() or signal(). */
2791
2792PyOS_sighandler_t
2793PyOS_getsig(int sig)
2794{
2795#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002796 struct sigaction context;
2797 if (sigaction(sig, NULL, &context) == -1)
2798 return SIG_ERR;
2799 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002800#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002801 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002802/* Special signal handling for the secure CRT in Visual Studio 2005 */
2803#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002804 switch (sig) {
2805 /* Only these signals are valid */
2806 case SIGINT:
2807 case SIGILL:
2808 case SIGFPE:
2809 case SIGSEGV:
2810 case SIGTERM:
2811 case SIGBREAK:
2812 case SIGABRT:
2813 break;
2814 /* Don't call signal() with other values or it will assert */
2815 default:
2816 return SIG_ERR;
2817 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002818#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002819 handler = signal(sig, SIG_IGN);
2820 if (handler != SIG_ERR)
2821 signal(sig, handler);
2822 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002823#endif
2824}
2825
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002826/*
2827 * All of the code in this function must only use async-signal-safe functions,
2828 * listed at `man 7 signal` or
2829 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2830 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002831PyOS_sighandler_t
2832PyOS_setsig(int sig, PyOS_sighandler_t handler)
2833{
2834#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002835 /* Some code in Modules/signalmodule.c depends on sigaction() being
2836 * used here if HAVE_SIGACTION is defined. Fix that if this code
2837 * changes to invalidate that assumption.
2838 */
2839 struct sigaction context, ocontext;
2840 context.sa_handler = handler;
2841 sigemptyset(&context.sa_mask);
2842 context.sa_flags = 0;
2843 if (sigaction(sig, &context, &ocontext) == -1)
2844 return SIG_ERR;
2845 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002846#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002847 PyOS_sighandler_t oldhandler;
2848 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002849#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002850 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002851#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002852 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002853#endif
2854}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002855
2856/* Deprecated C API functions still provided for binary compatiblity */
2857
2858#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002859PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002860PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2861{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002862 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002863}
2864
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002865#undef PyParser_SimpleParseString
2866PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002867PyParser_SimpleParseString(const char *str, int start)
2868{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002869 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002870}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002871
2872#undef PyRun_AnyFile
2873PyAPI_FUNC(int)
2874PyRun_AnyFile(FILE *fp, const char *name)
2875{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002876 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002877}
2878
2879#undef PyRun_AnyFileEx
2880PyAPI_FUNC(int)
2881PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2882{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002883 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002884}
2885
2886#undef PyRun_AnyFileFlags
2887PyAPI_FUNC(int)
2888PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2889{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002890 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002891}
2892
2893#undef PyRun_File
2894PyAPI_FUNC(PyObject *)
2895PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2896{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002897 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002898}
2899
2900#undef PyRun_FileEx
2901PyAPI_FUNC(PyObject *)
2902PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2903{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002904 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002905}
2906
2907#undef PyRun_FileFlags
2908PyAPI_FUNC(PyObject *)
2909PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002910 PyCompilerFlags *flags)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002911{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002912 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002913}
2914
2915#undef PyRun_SimpleFile
2916PyAPI_FUNC(int)
2917PyRun_SimpleFile(FILE *f, const char *p)
2918{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002919 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002920}
2921
2922#undef PyRun_SimpleFileEx
2923PyAPI_FUNC(int)
2924PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2925{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002926 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002927}
2928
2929
2930#undef PyRun_String
2931PyAPI_FUNC(PyObject *)
2932PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2933{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002934 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002935}
2936
2937#undef PyRun_SimpleString
2938PyAPI_FUNC(int)
2939PyRun_SimpleString(const char *s)
2940{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002941 return PyRun_SimpleStringFlags(s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002942}
2943
2944#undef Py_CompileString
2945PyAPI_FUNC(PyObject *)
2946Py_CompileString(const char *str, const char *p, int s)
2947{
Georg Brandl8334fd92010-12-04 10:26:46 +00002948 return Py_CompileStringExFlags(str, p, s, NULL, -1);
2949}
2950
2951#undef Py_CompileStringFlags
2952PyAPI_FUNC(PyObject *)
2953Py_CompileStringFlags(const char *str, const char *p, int s,
2954 PyCompilerFlags *flags)
2955{
2956 return Py_CompileStringExFlags(str, p, s, flags, -1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002957}
2958
2959#undef PyRun_InteractiveOne
2960PyAPI_FUNC(int)
2961PyRun_InteractiveOne(FILE *f, const char *p)
2962{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002963 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002964}
2965
2966#undef PyRun_InteractiveLoop
2967PyAPI_FUNC(int)
2968PyRun_InteractiveLoop(FILE *f, const char *p)
2969{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002970 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002971}
2972
2973#ifdef __cplusplus
2974}
2975#endif