blob: b5d57dfcbf95de6663b3b36222e2d93d6b4f0c9a [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);
Christian Heimes985ecdc2013-11-20 11:46:18 +0100107extern void _PyHash_Fini(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +0000108
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000109#ifdef WITH_THREAD
110extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
111extern void _PyGILState_Fini(void);
112#endif /* WITH_THREAD */
113
Guido van Rossum82598051997-03-05 00:20:32 +0000114int Py_DebugFlag; /* Needed by parser.c */
115int Py_VerboseFlag; /* Needed by import.c */
Georg Brandl8aa7e992010-12-28 18:30:18 +0000116int Py_QuietFlag; /* Needed by sysmodule.c */
Guido van Rossum7433b121997-02-14 19:45:36 +0000117int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Georg Brandl0b2489e2011-05-15 08:49:12 +0200118int Py_InspectFlag; /* Needed to determine whether to exit at SystemExit */
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000119int Py_NoSiteFlag; /* Suppress 'import site' */
Guido van Rossum98297ee2007-11-06 21:34:58 +0000120int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
Christian Heimes790c8232008-01-07 21:14:23 +0000121int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.py[co]) */
Barry Warsaw3ce09642000-05-02 19:18:59 +0000122int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +0000123int Py_FrozenFlag; /* Needed by getpath.c */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000124int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Christian Heimes8dc226f2008-05-06 23:45:46 +0000125int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
Antoine Pitrou05608432009-01-09 18:53:14 +0000126int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100127int Py_HashRandomizationFlag = 0; /* for -R and PYTHONHASHSEED */
Christian Heimesad73a9c2013-08-10 16:36:18 +0200128int Py_IsolatedFlag = 0; /* for -I, isolate from user's env */
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000129
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200130PyThreadState *_Py_Finalizing = NULL;
131
Christian Heimes49e61802013-10-22 10:22:29 +0200132/* Hack to force loading of object files */
133int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
134 PyOS_mystrnicmp; /* Python/pystrcmp.o */
135
Christian Heimes33fe8092008-04-13 13:53:33 +0000136/* PyModule_GetWarningsModule is no longer necessary as of 2.6
137since _warnings is builtin. This API should not be used. */
138PyObject *
139PyModule_GetWarningsModule(void)
Mark Hammondedd07732003-07-15 23:03:55 +0000140{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000141 return PyImport_ImportModule("warnings");
Mark Hammondedd07732003-07-15 23:03:55 +0000142}
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000143
Guido van Rossum25ce5661997-08-02 03:10:38 +0000144static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000145
Thomas Wouters7e474022000-07-16 12:04:32 +0000146/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000147
148int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000149Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151 return initialized;
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000152}
153
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000154/* Helper to allow an embedding application to override the normal
155 * mechanism that attempts to figure out an appropriate IO encoding
156 */
157
158static char *_Py_StandardStreamEncoding = NULL;
159static char *_Py_StandardStreamErrors = NULL;
160
161int
162Py_SetStandardStreamEncoding(const char *encoding, const char *errors)
163{
164 if (Py_IsInitialized()) {
165 /* This is too late to have any effect */
166 return -1;
167 }
Nick Coghlan1805a622013-10-18 23:11:47 +1000168 /* Can't call PyErr_NoMemory() on errors, as Python hasn't been
169 * initialised yet.
170 *
171 * However, the raw memory allocators are initialised appropriately
172 * as C static variables, so _PyMem_RawStrdup is OK even though
173 * Py_Initialize hasn't been called yet.
174 */
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000175 if (encoding) {
176 _Py_StandardStreamEncoding = _PyMem_RawStrdup(encoding);
177 if (!_Py_StandardStreamEncoding) {
Nick Coghlan1805a622013-10-18 23:11:47 +1000178 return -2;
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000179 }
180 }
181 if (errors) {
182 _Py_StandardStreamErrors = _PyMem_RawStrdup(errors);
183 if (!_Py_StandardStreamErrors) {
184 if (_Py_StandardStreamEncoding) {
185 PyMem_RawFree(_Py_StandardStreamEncoding);
186 }
Nick Coghlan1805a622013-10-18 23:11:47 +1000187 return -3;
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000188 }
189 }
190 return 0;
191}
192
Guido van Rossum25ce5661997-08-02 03:10:38 +0000193/* Global initializations. Can be undone by Py_Finalize(). Don't
194 call this twice without an intervening Py_Finalize() call. When
195 initializations fail, a fatal error is issued and the function does
196 not return. On return, the first thread and interpreter state have
197 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000198
Guido van Rossum25ce5661997-08-02 03:10:38 +0000199 Locking: you must hold the interpreter lock while calling this.
200 (If the lock has not yet been initialized, that's equivalent to
201 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000202
Guido van Rossum25ce5661997-08-02 03:10:38 +0000203*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000204
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000205static int
206add_flag(int flag, const char *envs)
207{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 int env = atoi(envs);
209 if (flag < env)
210 flag = env;
211 if (flag < 1)
212 flag = 1;
213 return flag;
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000214}
215
Christian Heimes5833a2f2008-10-30 21:40:04 +0000216static char*
Victor Stinner94908bb2010-08-18 21:23:25 +0000217get_codec_name(const char *encoding)
Christian Heimes5833a2f2008-10-30 21:40:04 +0000218{
Victor Stinner94908bb2010-08-18 21:23:25 +0000219 char *name_utf8, *name_str;
Victor Stinner386fe712010-05-19 00:34:15 +0000220 PyObject *codec, *name = NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000221
Victor Stinner94908bb2010-08-18 21:23:25 +0000222 codec = _PyCodec_Lookup(encoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000223 if (!codec)
224 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000225
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200226 name = _PyObject_GetAttrId(codec, &PyId_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 Py_CLEAR(codec);
228 if (!name)
229 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000230
Victor Stinner94908bb2010-08-18 21:23:25 +0000231 name_utf8 = _PyUnicode_AsString(name);
Victor Stinner4ca28092011-03-20 23:09:03 +0100232 if (name_utf8 == NULL)
Victor Stinner386fe712010-05-19 00:34:15 +0000233 goto error;
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200234 name_str = _PyMem_RawStrdup(name_utf8);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 Py_DECREF(name);
Victor Stinner94908bb2010-08-18 21:23:25 +0000236 if (name_str == NULL) {
237 PyErr_NoMemory();
238 return NULL;
239 }
240 return name_str;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000241
242error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000243 Py_XDECREF(codec);
Victor Stinner386fe712010-05-19 00:34:15 +0000244 Py_XDECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000246}
Victor Stinner94908bb2010-08-18 21:23:25 +0000247
Victor Stinner94908bb2010-08-18 21:23:25 +0000248static char*
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200249get_locale_encoding(void)
Victor Stinner94908bb2010-08-18 21:23:25 +0000250{
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200251#ifdef MS_WINDOWS
252 char codepage[100];
253 PyOS_snprintf(codepage, sizeof(codepage), "cp%d", GetACP());
254 return get_codec_name(codepage);
255#elif defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94908bb2010-08-18 21:23:25 +0000256 char* codeset = nl_langinfo(CODESET);
257 if (!codeset || codeset[0] == '\0') {
258 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
259 return NULL;
260 }
261 return get_codec_name(codeset);
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200262#else
263 PyErr_SetNone(PyExc_NotImplementedError);
264 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000265#endif
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200266}
Christian Heimes5833a2f2008-10-30 21:40:04 +0000267
Brett Cannonfd074152012-04-14 14:10:13 -0400268static void
269import_init(PyInterpreterState *interp, PyObject *sysmod)
270{
271 PyObject *importlib;
272 PyObject *impmod;
273 PyObject *sys_modules;
274 PyObject *value;
275
276 /* Import _importlib through its frozen version, _frozen_importlib. */
Brett Cannonfd074152012-04-14 14:10:13 -0400277 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
278 Py_FatalError("Py_Initialize: can't import _frozen_importlib");
279 }
280 else if (Py_VerboseFlag) {
281 PySys_FormatStderr("import _frozen_importlib # frozen\n");
282 }
283 importlib = PyImport_AddModule("_frozen_importlib");
284 if (importlib == NULL) {
285 Py_FatalError("Py_Initialize: couldn't get _frozen_importlib from "
286 "sys.modules");
287 }
288 interp->importlib = importlib;
289 Py_INCREF(interp->importlib);
290
291 /* Install _importlib as __import__ */
292 impmod = PyInit_imp();
293 if (impmod == NULL) {
294 Py_FatalError("Py_Initialize: can't import imp");
295 }
296 else if (Py_VerboseFlag) {
297 PySys_FormatStderr("import imp # builtin\n");
298 }
299 sys_modules = PyImport_GetModuleDict();
300 if (Py_VerboseFlag) {
301 PySys_FormatStderr("import sys # builtin\n");
302 }
Brett Cannon6f44d662012-04-15 16:08:47 -0400303 if (PyDict_SetItemString(sys_modules, "_imp", impmod) < 0) {
304 Py_FatalError("Py_Initialize: can't save _imp to sys.modules");
Brett Cannonfd074152012-04-14 14:10:13 -0400305 }
306
Brett Cannone0d88a12012-04-25 20:54:04 -0400307 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
Brett Cannonfd074152012-04-14 14:10:13 -0400308 if (value == NULL) {
309 PyErr_Print();
310 Py_FatalError("Py_Initialize: importlib install failed");
311 }
312 Py_DECREF(value);
Brett Cannonfc9ca272012-04-15 01:35:05 -0400313 Py_DECREF(impmod);
Brett Cannonfd074152012-04-14 14:10:13 -0400314
315 _PyImportZip_Init();
316}
317
318
Guido van Rossuma027efa1997-05-05 20:56:21 +0000319void
Antoine Pitroue67f48c2012-06-19 22:29:35 +0200320_Py_InitializeEx_Private(int install_sigs, int install_importlib)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000321{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000322 PyInterpreterState *interp;
323 PyThreadState *tstate;
324 PyObject *bimod, *sysmod, *pstderr;
325 char *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000326 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000328 if (initialized)
329 return;
330 initialized = 1;
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200331 _Py_Finalizing = NULL;
Tim Petersd08e3822003-04-17 15:24:21 +0000332
Andrew M. Kuchlingb2ceb3a2010-02-22 23:26:10 +0000333#if defined(HAVE_LANGINFO_H) && defined(HAVE_SETLOCALE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 /* Set up the LC_CTYPE locale, so we can obtain
335 the locale's charset without having to switch
336 locales. */
337 setlocale(LC_CTYPE, "");
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +0000338#endif
339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000340 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
341 Py_DebugFlag = add_flag(Py_DebugFlag, p);
342 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
343 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
344 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
345 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
346 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
347 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100348 /* The variable is only tested for existence here; _PyRandom_Init will
349 check its value further. */
350 if ((p = Py_GETENV("PYTHONHASHSEED")) && *p != '\0')
351 Py_HashRandomizationFlag = add_flag(Py_HashRandomizationFlag, p);
352
353 _PyRandom_Init();
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000355 interp = PyInterpreterState_New();
356 if (interp == NULL)
357 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000359 tstate = PyThreadState_New(interp);
360 if (tstate == NULL)
361 Py_FatalError("Py_Initialize: can't make first thread");
362 (void) PyThreadState_Swap(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000363
Victor Stinner6961bd62010-08-17 22:26:51 +0000364#ifdef WITH_THREAD
Antoine Pitroub0b384b2010-09-20 20:13:48 +0000365 /* We can't call _PyEval_FiniThreads() in Py_Finalize because
366 destroying the GIL might fail when it is being referenced from
367 another running thread (see issue #9901).
368 Instead we destroy the previously created GIL here, which ensures
369 that we can call Py_Initialize / Py_Finalize multiple times. */
370 _PyEval_FiniThreads();
371
372 /* Auto-thread-state API */
Victor Stinner6961bd62010-08-17 22:26:51 +0000373 _PyGILState_Init(interp, tstate);
374#endif /* WITH_THREAD */
375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000378 if (!_PyFrame_Init())
379 Py_FatalError("Py_Initialize: can't init frames");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000381 if (!_PyLong_Init())
382 Py_FatalError("Py_Initialize: can't init longs");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 if (!PyByteArray_Init())
385 Py_FatalError("Py_Initialize: can't init bytearray");
Neal Norwitz6968b052007-02-27 19:02:19 +0000386
Victor Stinner1c8f0592013-07-22 22:24:54 +0200387 if (!_PyFloat_Init())
388 Py_FatalError("Py_Initialize: can't init float");
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000390 interp->modules = PyDict_New();
391 if (interp->modules == NULL)
392 Py_FatalError("Py_Initialize: can't make modules dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 /* Init Unicode implementation; relies on the codec registry */
Victor Stinner3a50e702011-10-18 21:21:00 +0200395 if (_PyUnicode_Init() < 0)
396 Py_FatalError("Py_Initialize: can't initialize unicode");
Victor Stinner26f91992013-07-17 01:22:45 +0200397 if (_PyStructSequence_Init() < 0)
398 Py_FatalError("Py_Initialize: can't initialize structseq");
Guido van Rossumc94044c2000-03-10 23:03:54 +0000399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 bimod = _PyBuiltin_Init();
401 if (bimod == NULL)
402 Py_FatalError("Py_Initialize: can't initialize builtins modules");
Victor Stinner49d3f252010-10-17 01:24:53 +0000403 _PyImport_FixupBuiltin(bimod, "builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404 interp->builtins = PyModule_GetDict(bimod);
405 if (interp->builtins == NULL)
406 Py_FatalError("Py_Initialize: can't initialize builtins dict");
407 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000409 /* initialize builtin exceptions */
Brett Cannonfd074152012-04-14 14:10:13 -0400410 _PyExc_Init(bimod);
Christian Heimes9a68f8c2007-11-14 00:16:07 +0000411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412 sysmod = _PySys_Init();
413 if (sysmod == NULL)
414 Py_FatalError("Py_Initialize: can't initialize sys");
415 interp->sysdict = PyModule_GetDict(sysmod);
416 if (interp->sysdict == NULL)
417 Py_FatalError("Py_Initialize: can't initialize sys dict");
418 Py_INCREF(interp->sysdict);
Victor Stinner49d3f252010-10-17 01:24:53 +0000419 _PyImport_FixupBuiltin(sysmod, "sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 PySys_SetPath(Py_GetPath());
421 PyDict_SetItemString(interp->sysdict, "modules",
422 interp->modules);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 /* Set up a preliminary stderr printer until we have enough
425 infrastructure for the io module in place. */
426 pstderr = PyFile_NewStdPrinter(fileno(stderr));
427 if (pstderr == NULL)
428 Py_FatalError("Py_Initialize: can't set preliminary stderr");
Victor Stinnerbd303c12013-11-07 23:07:29 +0100429 _PySys_SetObjectId(&PyId_stderr, pstderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000430 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000431 Py_DECREF(pstderr);
Guido van Rossum826d8972007-10-30 18:34:07 +0000432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000433 _PyImport_Init();
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 _PyImportHooks_Init();
Just van Rossum52e14d62002-12-30 22:08:05 +0000436
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000437 /* Initialize _warnings. */
438 _PyWarnings_Init();
439
Antoine Pitroue67f48c2012-06-19 22:29:35 +0200440 if (!install_importlib)
441 return;
442
Brett Cannonfd074152012-04-14 14:10:13 -0400443 import_init(interp, sysmod);
444
Victor Stinnerd5698cb2012-07-31 02:55:49 +0200445 /* initialize the faulthandler module */
446 if (_PyFaulthandler_Init())
447 Py_FatalError("Py_Initialize: can't initialize faulthandler");
448
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +0000449 _PyTime_Init();
450
Victor Stinner793b5312011-04-27 00:24:21 +0200451 if (initfsencoding(interp) < 0)
452 Py_FatalError("Py_Initialize: unable to load the file system codec");
Martin v. Löwis011e8422009-05-05 04:43:17 +0000453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000454 if (install_sigs)
455 initsigs(); /* Signal handling stuff, including initintr() */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000456
Nick Coghlan85e729e2012-07-15 18:09:52 +1000457 initmain(interp); /* Module __main__ */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 if (initstdio() < 0)
459 Py_FatalError(
460 "Py_Initialize: can't initialize sys standard streams");
461
Antoine Pitroucf9f9802010-11-10 13:55:25 +0000462 /* Initialize warnings. */
463 if (PySys_HasWarnOptions()) {
464 PyObject *warnings_module = PyImport_ImportModule("warnings");
465 if (warnings_module == NULL) {
466 fprintf(stderr, "'import warnings' failed; traceback:\n");
467 PyErr_Print();
468 }
469 Py_XDECREF(warnings_module);
470 }
471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 if (!Py_NoSiteFlag)
473 initsite(); /* Module site */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000474}
475
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000476void
Antoine Pitroue67f48c2012-06-19 22:29:35 +0200477Py_InitializeEx(int install_sigs)
478{
479 _Py_InitializeEx_Private(install_sigs, 1);
480}
481
482void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000483Py_Initialize(void)
484{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 Py_InitializeEx(1);
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000486}
487
488
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000489#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000490extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000491#endif
492
Guido van Rossume8432ac2007-07-09 15:04:50 +0000493/* Flush stdout and stderr */
494
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100495static int
496file_is_closed(PyObject *fobj)
497{
498 int r;
499 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
500 if (tmp == NULL) {
501 PyErr_Clear();
502 return 0;
503 }
504 r = PyObject_IsTrue(tmp);
505 Py_DECREF(tmp);
506 if (r < 0)
507 PyErr_Clear();
508 return r > 0;
509}
510
Neal Norwitz2bad9702007-08-27 06:19:22 +0000511static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000512flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000513{
Victor Stinnerbd303c12013-11-07 23:07:29 +0100514 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
515 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 PyObject *tmp;
Guido van Rossume8432ac2007-07-09 15:04:50 +0000517
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100518 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200519 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 if (tmp == NULL)
Antoine Pitroubddc9fe2010-08-08 20:46:42 +0000521 PyErr_WriteUnraisable(fout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 else
523 Py_DECREF(tmp);
524 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000525
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100526 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200527 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 if (tmp == NULL)
529 PyErr_Clear();
530 else
531 Py_DECREF(tmp);
532 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000533}
534
Guido van Rossum25ce5661997-08-02 03:10:38 +0000535/* Undo the effect of Py_Initialize().
536
537 Beware: if multiple interpreter and/or thread states exist, these
538 are not wiped out; only the current thread and interpreter state
539 are deleted. But since everything else is deleted, those other
540 interpreter and thread states should no longer be used.
541
542 (XXX We should do better, e.g. wipe out all interpreters and
543 threads.)
544
545 Locking: as above.
546
547*/
548
549void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000550Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000551{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 PyInterpreterState *interp;
553 PyThreadState *tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 if (!initialized)
556 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000558 wait_for_thread_shutdown();
Antoine Pitrou011bd622009-10-20 21:52:47 +0000559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 /* The interpreter is still entirely intact at this point, and the
561 * exit funcs may be relying on that. In particular, if some thread
562 * or exit func is still waiting to do an import, the import machinery
563 * expects Py_IsInitialized() to return true. So don't say the
564 * interpreter is uninitialized until after the exit funcs have run.
565 * Note that Threading.py uses an exit func to do a join on all the
566 * threads created thru it, so this also protects pending imports in
567 * the threads created via Threading.
568 */
569 call_py_exitfuncs();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000571 /* Get current thread state and interpreter pointer */
572 tstate = PyThreadState_GET();
573 interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000574
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200575 /* Remaining threads (e.g. daemon threads) will automatically exit
576 after taking the GIL (in PyEval_RestoreThread()). */
577 _Py_Finalizing = tstate;
578 initialized = 0;
579
Victor Stinner45956b92013-11-12 16:37:55 +0100580 /* Destroy the state of all threads except of the current thread: in
581 practice, only daemon threads should still be alive. Clear frames of
582 other threads to call objects destructor. Destructors will be called in
583 the current Python thread. Since _Py_Finalizing has been set, no other
584 Python threads can lock the GIL at this point (if they try, they will
Victor Stinnerdcf17f82013-11-12 17:18:51 +0100585 exit immediately). */
Victor Stinner45956b92013-11-12 16:37:55 +0100586 _PyThreadState_DeleteExcept(tstate);
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000588 /* Collect garbage. This may call finalizers; it's nice to call these
589 * before all modules are destroyed.
590 * XXX If a __del__ or weakref callback is triggered here, and tries to
591 * XXX import a module, bad things can happen, because Python no
592 * XXX longer believes it's initialized.
593 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
594 * XXX is easy to provoke that way. I've also seen, e.g.,
595 * XXX Exception exceptions.ImportError: 'No module named sha'
596 * XXX in <function callback at 0x008F5718> ignored
597 * XXX but I'm unclear on exactly how that one happens. In any case,
598 * XXX I haven't seen a real-life report of either of these.
599 */
600 PyGC_Collect();
Victor Stinner45956b92013-11-12 16:37:55 +0100601
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000602#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 /* With COUNT_ALLOCS, it helps to run GC multiple times:
604 each collection might release some types from the type
605 list, so they become garbage. */
606 while (PyGC_Collect() > 0)
607 /* nothing */;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000608#endif
Victor Stinner45956b92013-11-12 16:37:55 +0100609
610 /* Flush stdout+stderr */
611 flush_std_files();
612
613 /* Disable signal handling */
614 PyOS_FiniInterrupts();
615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 /* Destroy all modules */
617 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 /* Flush stdout+stderr (again, in case more was printed) */
620 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 /* Collect final garbage. This disposes of cycles created by
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100623 * class definitions, for example.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624 * XXX This is disabled because it caused too many problems. If
625 * XXX a __del__ or weakref callback triggers here, Python code has
626 * XXX a hard time running, because even the sys module has been
627 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
628 * XXX One symptom is a sequence of information-free messages
629 * XXX coming from threads (if a __del__ or callback is invoked,
630 * XXX other threads can execute too, and any exception they encounter
631 * XXX triggers a comedy of errors as subsystem after subsystem
632 * XXX fails to find what it *expects* to find in sys to help report
633 * XXX the exception and consequent unexpected failures). I've also
634 * XXX seen segfaults then, after adding print statements to the
635 * XXX Python code getting called.
636 */
Tim Peters1d7323e2003-12-01 21:35:27 +0000637#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000639#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
642 _PyImport_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000643
Antoine Pitroufd417cc2013-05-05 08:12:42 +0200644 /* Cleanup typeobject.c's internal caches. */
645 _PyType_Fini();
646
Victor Stinner024e37a2011-03-31 01:31:06 +0200647 /* unload faulthandler module */
648 _PyFaulthandler_Fini();
649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 /* Debugging stuff */
Guido van Rossum1707aad1997-12-08 23:43:45 +0000651#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000653#endif
Christian Heimes985ecdc2013-11-20 11:46:18 +0100654 /* dump hash stats */
655 _PyHash_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000658
Tim Peters9cf25ce2003-04-17 15:21:01 +0000659#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 /* Display all objects still alive -- this can invoke arbitrary
661 * __repr__ overrides, so requires a mostly-intact interpreter.
662 * Alas, a lot of stuff may still be alive now that will be cleaned
663 * up later.
664 */
665 if (Py_GETENV("PYTHONDUMPREFS"))
666 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000667#endif /* Py_TRACE_REFS */
668
Antoine Pitroufd417cc2013-05-05 08:12:42 +0200669 /* Clear interpreter state and all thread states. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 /* Now we decref the exception classes. After this point nothing
673 can raise an exception. That's okay, because each Fini() method
674 below has been checked to make sure no exceptions are ever
675 raised.
676 */
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 _PyExc_Fini();
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000680 /* Sundry finalizers */
681 PyMethod_Fini();
682 PyFrame_Fini();
683 PyCFunction_Fini();
684 PyTuple_Fini();
685 PyList_Fini();
686 PySet_Fini();
687 PyBytes_Fini();
688 PyByteArray_Fini();
689 PyLong_Fini();
690 PyFloat_Fini();
691 PyDict_Fini();
Antoine Pitrouf34a0cd2011-11-18 20:14:34 +0100692 PySlice_Fini();
Antoine Pitrou5f454a02013-05-06 21:15:57 +0200693 _PyGC_Fini();
Antoine Pitrou4879a962013-08-31 00:26:02 +0200694 _PyRandom_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000696 /* Cleanup Unicode implementation */
697 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 /* reset file system default encoding */
Victor Stinnerb744ba12010-05-15 12:27:16 +0000700 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200701 PyMem_RawFree((char*)Py_FileSystemDefaultEncoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 Py_FileSystemDefaultEncoding = NULL;
703 }
Christian Heimesc8967002007-11-30 10:18:26 +0000704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 /* XXX Still allocated:
706 - various static ad-hoc pointers to interned strings
707 - int and float free list blocks
708 - whatever various modules and libraries allocate
709 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000711 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000712
Victor Stinner51fa4582013-07-07 15:50:49 +0200713 /* Cleanup auto-thread-state */
714#ifdef WITH_THREAD
715 _PyGILState_Fini();
716#endif /* WITH_THREAD */
717
718 /* Delete current thread. After this, many C API calls become crashy. */
719 PyThreadState_Swap(NULL);
720 PyInterpreterState_Delete(interp);
721
Tim Peters269b2a62003-04-17 19:52:29 +0000722#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000723 /* Display addresses (& refcnts) of all objects still alive.
724 * An address can be used to find the repr of the object, printed
725 * above by _Py_PrintReferences.
726 */
727 if (Py_GETENV("PYTHONDUMPREFS"))
728 _Py_PrintReferenceAddresses(stderr);
Tim Peters269b2a62003-04-17 19:52:29 +0000729#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000730#ifdef PYMALLOC_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 if (Py_GETENV("PYTHONMALLOCSTATS"))
David Malcolm49526f42012-06-22 14:55:41 -0400732 _PyObject_DebugMallocStats(stderr);
Tim Peters0e871182002-04-13 08:29:14 +0000733#endif
734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000735 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000736}
737
738/* Create and initialize a new interpreter and thread, and return the
739 new thread. This requires that Py_Initialize() has been called
740 first.
741
742 Unsuccessful initialization yields a NULL pointer. Note that *no*
743 exception information is available even in this case -- the
744 exception information is held in the thread, and there is no
745 thread.
746
747 Locking: as above.
748
749*/
750
751PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000752Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000753{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000754 PyInterpreterState *interp;
755 PyThreadState *tstate, *save_tstate;
756 PyObject *bimod, *sysmod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 if (!initialized)
759 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 interp = PyInterpreterState_New();
762 if (interp == NULL)
763 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 tstate = PyThreadState_New(interp);
766 if (tstate == NULL) {
767 PyInterpreterState_Delete(interp);
768 return NULL;
769 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000771 save_tstate = PyThreadState_Swap(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 /* XXX The following is lax in error checking */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 interp->modules = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000776
Victor Stinner49d3f252010-10-17 01:24:53 +0000777 bimod = _PyImport_FindBuiltin("builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 if (bimod != NULL) {
779 interp->builtins = PyModule_GetDict(bimod);
780 if (interp->builtins == NULL)
781 goto handle_error;
782 Py_INCREF(interp->builtins);
783 }
Christian Heimes6a27efa2008-10-30 21:48:26 +0000784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 /* initialize builtin exceptions */
Brett Cannonfd074152012-04-14 14:10:13 -0400786 _PyExc_Init(bimod);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000787
Victor Stinner49d3f252010-10-17 01:24:53 +0000788 sysmod = _PyImport_FindBuiltin("sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 if (bimod != NULL && sysmod != NULL) {
790 PyObject *pstderr;
Brett Cannonfd074152012-04-14 14:10:13 -0400791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 interp->sysdict = PyModule_GetDict(sysmod);
793 if (interp->sysdict == NULL)
794 goto handle_error;
795 Py_INCREF(interp->sysdict);
796 PySys_SetPath(Py_GetPath());
797 PyDict_SetItemString(interp->sysdict, "modules",
798 interp->modules);
799 /* Set up a preliminary stderr printer until we have enough
800 infrastructure for the io module in place. */
801 pstderr = PyFile_NewStdPrinter(fileno(stderr));
802 if (pstderr == NULL)
803 Py_FatalError("Py_Initialize: can't set preliminary stderr");
Victor Stinnerbd303c12013-11-07 23:07:29 +0100804 _PySys_SetObjectId(&PyId_stderr, pstderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000805 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000806 Py_DECREF(pstderr);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 _PyImportHooks_Init();
Victor Stinner793b5312011-04-27 00:24:21 +0200809
Brett Cannonfd074152012-04-14 14:10:13 -0400810 import_init(interp, sysmod);
811
Victor Stinner793b5312011-04-27 00:24:21 +0200812 if (initfsencoding(interp) < 0)
813 goto handle_error;
814
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 if (initstdio() < 0)
816 Py_FatalError(
817 "Py_Initialize: can't initialize sys standard streams");
Nick Coghlan85e729e2012-07-15 18:09:52 +1000818 initmain(interp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 if (!Py_NoSiteFlag)
820 initsite();
821 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 if (!PyErr_Occurred())
824 return tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000825
Thomas Wouters89f507f2006-12-13 04:49:30 +0000826handle_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000827 /* Oops, it didn't work. Undo it all. */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000828
Victor Stinnerc40a3502011-04-27 00:20:27 +0200829 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 PyThreadState_Clear(tstate);
831 PyThreadState_Swap(save_tstate);
832 PyThreadState_Delete(tstate);
833 PyInterpreterState_Delete(interp);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000834
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000836}
837
838/* Delete an interpreter and its last thread. This requires that the
839 given thread state is current, that the thread has no remaining
840 frames, and that it is its interpreter's only remaining thread.
841 It is a fatal error to violate these constraints.
842
843 (Py_Finalize() doesn't have these constraints -- it zaps
844 everything, regardless.)
845
846 Locking: as above.
847
848*/
849
850void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000851Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000852{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 PyInterpreterState *interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 if (tstate != PyThreadState_GET())
856 Py_FatalError("Py_EndInterpreter: thread is not current");
857 if (tstate->frame != NULL)
858 Py_FatalError("Py_EndInterpreter: thread still has a frame");
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200859
860 wait_for_thread_shutdown();
861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 if (tstate != interp->tstate_head || tstate->next != NULL)
863 Py_FatalError("Py_EndInterpreter: not the last thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000865 PyImport_Cleanup();
866 PyInterpreterState_Clear(interp);
867 PyThreadState_Swap(NULL);
868 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000869}
870
Antoine Pitrou01cca5e2012-07-05 20:56:30 +0200871#ifdef MS_WINDOWS
Martin v. Löwis790465f2008-04-05 20:41:37 +0000872static wchar_t *progname = L"python";
Antoine Pitrou01cca5e2012-07-05 20:56:30 +0200873#else
874static wchar_t *progname = L"python3";
875#endif
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000876
877void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000878Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000879{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 if (pn && *pn)
881 progname = pn;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000882}
883
Martin v. Löwis790465f2008-04-05 20:41:37 +0000884wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000885Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000886{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000887 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000888}
889
Martin v. Löwis790465f2008-04-05 20:41:37 +0000890static wchar_t *default_home = NULL;
Victor Stinner55a12202013-08-28 01:47:46 +0200891static wchar_t env_home[MAXPATHLEN+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000892
893void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000894Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000895{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 default_home = home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000897}
898
Martin v. Löwis790465f2008-04-05 20:41:37 +0000899wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000900Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000901{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 wchar_t *home = default_home;
903 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
904 char* chome = Py_GETENV("PYTHONHOME");
905 if (chome) {
Victor Stinner2f5bbc62013-11-15 17:09:24 +0100906 size_t size = Py_ARRAY_LENGTH(env_home);
907 size_t r = mbstowcs(env_home, chome, size);
908 if (r != (size_t)-1 && r < size)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000909 home = env_home;
910 }
Martin v. Löwis790465f2008-04-05 20:41:37 +0000911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 }
913 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000914}
915
Guido van Rossum6135a871995-01-09 17:53:26 +0000916/* Create __main__ module */
917
918static void
Nick Coghlan85e729e2012-07-15 18:09:52 +1000919initmain(PyInterpreterState *interp)
Guido van Rossum6135a871995-01-09 17:53:26 +0000920{
Brett Cannon13853a62013-05-04 17:37:09 -0400921 PyObject *m, *d, *loader;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 m = PyImport_AddModule("__main__");
923 if (m == NULL)
924 Py_FatalError("can't create __main__ module");
925 d = PyModule_GetDict(m);
926 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
927 PyObject *bimod = PyImport_ImportModule("builtins");
Nick Coghlan85e729e2012-07-15 18:09:52 +1000928 if (bimod == NULL) {
929 Py_FatalError("Failed to retrieve builtins module");
930 }
931 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
932 Py_FatalError("Failed to initialize __main__.__builtins__");
933 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 Py_DECREF(bimod);
935 }
Nick Coghlan85e729e2012-07-15 18:09:52 +1000936 /* Main is a little special - imp.is_builtin("__main__") will return
937 * False, but BuiltinImporter is still the most appropriate initial
938 * setting for its __loader__ attribute. A more suitable value will
939 * be set if __main__ gets further initialized later in the startup
940 * process.
941 */
Brett Cannon13853a62013-05-04 17:37:09 -0400942 loader = PyDict_GetItemString(d, "__loader__");
Brett Cannon4c14b5d2013-05-04 13:56:58 -0400943 if (loader == NULL || loader == Py_None) {
Nick Coghlan85e729e2012-07-15 18:09:52 +1000944 PyObject *loader = PyObject_GetAttrString(interp->importlib,
945 "BuiltinImporter");
946 if (loader == NULL) {
947 Py_FatalError("Failed to retrieve BuiltinImporter");
948 }
949 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
950 Py_FatalError("Failed to initialize __main__.__loader__");
951 }
952 Py_DECREF(loader);
953 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000954}
955
Victor Stinner793b5312011-04-27 00:24:21 +0200956static int
957initfsencoding(PyInterpreterState *interp)
Victor Stinnerb744ba12010-05-15 12:27:16 +0000958{
959 PyObject *codec;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000960
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200961 if (Py_FileSystemDefaultEncoding == NULL)
962 {
963 Py_FileSystemDefaultEncoding = get_locale_encoding();
964 if (Py_FileSystemDefaultEncoding == NULL)
Victor Stinnere4743092010-10-19 00:05:51 +0000965 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
Victor Stinnerb744ba12010-05-15 12:27:16 +0000966
Victor Stinnere4743092010-10-19 00:05:51 +0000967 Py_HasFileSystemDefaultEncoding = 0;
Victor Stinner793b5312011-04-27 00:24:21 +0200968 interp->fscodec_initialized = 1;
969 return 0;
Victor Stinner7f84ab52010-06-11 00:36:33 +0000970 }
Victor Stinnerb744ba12010-05-15 12:27:16 +0000971
972 /* the encoding is mbcs, utf-8 or ascii */
973 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
974 if (!codec) {
975 /* Such error can only occurs in critical situations: no more
976 * memory, import a module of the standard library failed,
977 * etc. */
Victor Stinner793b5312011-04-27 00:24:21 +0200978 return -1;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000979 }
Victor Stinner793b5312011-04-27 00:24:21 +0200980 Py_DECREF(codec);
981 interp->fscodec_initialized = 1;
982 return 0;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000983}
984
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000985/* Import the site module (not into __main__ though) */
986
987static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000988initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000989{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 PyObject *m;
991 m = PyImport_ImportModule("site");
992 if (m == NULL) {
Victor Stinner62ce62a2013-07-22 22:53:28 +0200993 fprintf(stderr, "Failed to import the site module\n");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 PyErr_Print();
995 Py_Finalize();
996 exit(1);
997 }
998 else {
999 Py_DECREF(m);
1000 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +00001001}
1002
Antoine Pitrou05608432009-01-09 18:53:14 +00001003static PyObject*
1004create_stdio(PyObject* io,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 int fd, int write_mode, char* name,
1006 char* encoding, char* errors)
Antoine Pitrou05608432009-01-09 18:53:14 +00001007{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1009 const char* mode;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001010 const char* newline;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 PyObject *line_buffering;
1012 int buffering, isatty;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001013 _Py_IDENTIFIER(open);
1014 _Py_IDENTIFIER(isatty);
1015 _Py_IDENTIFIER(TextIOWrapper);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001016 _Py_IDENTIFIER(mode);
Antoine Pitrou05608432009-01-09 18:53:14 +00001017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 /* stdin is always opened in buffered mode, first because it shouldn't
1019 make a difference in common use cases, second because TextIOWrapper
1020 depends on the presence of a read1() method which only exists on
1021 buffered streams.
1022 */
1023 if (Py_UnbufferedStdioFlag && write_mode)
1024 buffering = 0;
1025 else
1026 buffering = -1;
1027 if (write_mode)
1028 mode = "wb";
1029 else
1030 mode = "rb";
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001031 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1032 fd, mode, buffering,
1033 Py_None, Py_None, Py_None, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 if (buf == NULL)
1035 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +00001036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 if (buffering) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001038 _Py_IDENTIFIER(raw);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001039 raw = _PyObject_GetAttrId(buf, &PyId_raw);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 if (raw == NULL)
1041 goto error;
1042 }
1043 else {
1044 raw = buf;
1045 Py_INCREF(raw);
1046 }
Antoine Pitrou05608432009-01-09 18:53:14 +00001047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 text = PyUnicode_FromString(name);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001049 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 goto error;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001051 res = _PyObject_CallMethodId(raw, &PyId_isatty, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 if (res == NULL)
1053 goto error;
1054 isatty = PyObject_IsTrue(res);
1055 Py_DECREF(res);
1056 if (isatty == -1)
1057 goto error;
1058 if (isatty || Py_UnbufferedStdioFlag)
1059 line_buffering = Py_True;
1060 else
1061 line_buffering = Py_False;
Antoine Pitrou91696412009-01-09 22:12:30 +00001062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 Py_CLEAR(raw);
1064 Py_CLEAR(text);
Antoine Pitrou91696412009-01-09 22:12:30 +00001065
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001066#ifdef MS_WINDOWS
Victor Stinner7b3f0fa2012-08-04 01:28:00 +02001067 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1068 newlines to "\n".
1069 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1070 newline = NULL;
1071#else
1072 /* sys.stdin: split lines at "\n".
1073 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1074 newline = "\n";
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001075#endif
1076
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001077 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssO",
1078 buf, encoding, errors,
1079 newline, line_buffering);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 Py_CLEAR(buf);
1081 if (stream == NULL)
1082 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +00001083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 if (write_mode)
1085 mode = "w";
1086 else
1087 mode = "r";
1088 text = PyUnicode_FromString(mode);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001089 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001090 goto error;
1091 Py_CLEAR(text);
1092 return stream;
Antoine Pitrou05608432009-01-09 18:53:14 +00001093
1094error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 Py_XDECREF(buf);
1096 Py_XDECREF(stream);
1097 Py_XDECREF(text);
1098 Py_XDECREF(raw);
1099 return NULL;
Antoine Pitrou05608432009-01-09 18:53:14 +00001100}
1101
Antoine Pitrou11942a52011-11-28 19:08:36 +01001102static int
1103is_valid_fd(int fd)
1104{
1105 int dummy_fd;
1106 if (fd < 0 || !_PyVerify_fd(fd))
1107 return 0;
1108 dummy_fd = dup(fd);
1109 if (dummy_fd < 0)
1110 return 0;
1111 close(dummy_fd);
1112 return 1;
1113}
1114
Georg Brandl1a3284e2007-12-02 09:40:06 +00001115/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001116static int
1117initstdio(void)
1118{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 PyObject *iomod = NULL, *wrapper;
1120 PyObject *bimod = NULL;
1121 PyObject *m;
1122 PyObject *std = NULL;
1123 int status = 0, fd;
1124 PyObject * encoding_attr;
Serhiy Storchakabf28d2d2013-09-13 11:46:24 +03001125 char *pythonioencoding = NULL, *encoding, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001127 /* Hack to avoid a nasty recursion issue when Python is invoked
1128 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1129 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1130 goto error;
1131 }
1132 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001134 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1135 goto error;
1136 }
1137 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001139 if (!(bimod = PyImport_ImportModule("builtins"))) {
1140 goto error;
1141 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 if (!(iomod = PyImport_ImportModule("io"))) {
1144 goto error;
1145 }
1146 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1147 goto error;
1148 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001149
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001150 /* Set builtins.open */
1151 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
Antoine Pitrou5a96b522010-11-20 19:50:57 +00001152 Py_DECREF(wrapper);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 goto error;
1154 }
Antoine Pitrou5a96b522010-11-20 19:50:57 +00001155 Py_DECREF(wrapper);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001156
Nick Coghlan7d270ee2013-10-17 22:35:35 +10001157 encoding = _Py_StandardStreamEncoding;
1158 errors = _Py_StandardStreamErrors;
1159 if (!encoding || !errors) {
1160 pythonioencoding = Py_GETENV("PYTHONIOENCODING");
1161 if (pythonioencoding) {
1162 char *err;
1163 pythonioencoding = _PyMem_Strdup(pythonioencoding);
1164 if (pythonioencoding == NULL) {
1165 PyErr_NoMemory();
1166 goto error;
1167 }
1168 err = strchr(pythonioencoding, ':');
1169 if (err) {
1170 *err = '\0';
1171 err++;
1172 if (*err && !errors) {
1173 errors = err;
1174 }
1175 }
1176 if (*pythonioencoding && !encoding) {
1177 encoding = pythonioencoding;
1178 }
Victor Stinner49fc8ec2013-07-07 23:30:24 +02001179 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001180 }
Martin v. Löwis0f599892008-06-02 11:13:03 +00001181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 /* Set sys.stdin */
1183 fd = fileno(stdin);
1184 /* Under some conditions stdin, stdout and stderr may not be connected
1185 * and fileno() may point to an invalid file descriptor. For example
1186 * GUI apps don't have valid standard streams by default.
1187 */
Antoine Pitrou11942a52011-11-28 19:08:36 +01001188 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 std = Py_None;
1190 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 }
1192 else {
1193 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1194 if (std == NULL)
1195 goto error;
1196 } /* if (fd < 0) */
1197 PySys_SetObject("__stdin__", std);
Victor Stinnerbd303c12013-11-07 23:07:29 +01001198 _PySys_SetObjectId(&PyId_stdin, std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001199 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 /* Set sys.stdout */
1202 fd = fileno(stdout);
Antoine Pitrou11942a52011-11-28 19:08:36 +01001203 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 std = Py_None;
1205 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 }
1207 else {
1208 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1209 if (std == NULL)
1210 goto error;
1211 } /* if (fd < 0) */
1212 PySys_SetObject("__stdout__", std);
Victor Stinnerbd303c12013-11-07 23:07:29 +01001213 _PySys_SetObjectId(&PyId_stdout, std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001215
Guido van Rossum98297ee2007-11-06 21:34:58 +00001216#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 /* Set sys.stderr, replaces the preliminary stderr */
1218 fd = fileno(stderr);
Antoine Pitrou11942a52011-11-28 19:08:36 +01001219 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 std = Py_None;
1221 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001222 }
1223 else {
1224 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1225 if (std == NULL)
1226 goto error;
1227 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +00001228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 /* Same as hack above, pre-import stderr's codec to avoid recursion
1230 when import.c tries to write to stderr in verbose mode. */
1231 encoding_attr = PyObject_GetAttrString(std, "encoding");
1232 if (encoding_attr != NULL) {
Victor Stinner49fc8ec2013-07-07 23:30:24 +02001233 const char * std_encoding;
1234 std_encoding = _PyUnicode_AsString(encoding_attr);
1235 if (std_encoding != NULL) {
1236 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
Antoine Pitrou2fabfac2012-01-18 15:14:46 +01001237 Py_XDECREF(codec_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 }
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +00001239 Py_DECREF(encoding_attr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001240 }
1241 PyErr_Clear(); /* Not a fatal error if codec isn't available */
Trent Nelson39e307e2008-03-19 06:45:48 +00001242
Victor Stinnerba308832013-07-22 23:55:19 +02001243 if (PySys_SetObject("__stderr__", std) < 0) {
1244 Py_DECREF(std);
1245 goto error;
1246 }
Victor Stinnerbd303c12013-11-07 23:07:29 +01001247 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
Victor Stinnerba308832013-07-22 23:55:19 +02001248 Py_DECREF(std);
1249 goto error;
1250 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001251 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001252#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001255 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001256 status = -1;
1257 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001258
Nick Coghlan7d270ee2013-10-17 22:35:35 +10001259 /* We won't need them anymore. */
1260 if (_Py_StandardStreamEncoding) {
1261 PyMem_RawFree(_Py_StandardStreamEncoding);
1262 _Py_StandardStreamEncoding = NULL;
1263 }
1264 if (_Py_StandardStreamErrors) {
1265 PyMem_RawFree(_Py_StandardStreamErrors);
1266 _Py_StandardStreamErrors = NULL;
1267 }
Serhiy Storchakabf28d2d2013-09-13 11:46:24 +03001268 PyMem_Free(pythonioencoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 Py_XDECREF(bimod);
1270 Py_XDECREF(iomod);
1271 return status;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001272}
1273
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001274/* Parse input from a file and execute it */
1275
1276int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001277PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001279{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001280 if (filename == NULL)
1281 filename = "???";
1282 if (Py_FdIsInteractive(fp, filename)) {
1283 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
1284 if (closeit)
1285 fclose(fp);
1286 return err;
1287 }
1288 else
1289 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001290}
1291
1292int
Victor Stinner95701bd2013-11-06 18:41:07 +01001293PyRun_InteractiveLoopFlags(FILE *fp, const char *filename_str, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001294{
Victor Stinner95701bd2013-11-06 18:41:07 +01001295 PyObject *filename, *v;
1296 int ret, err;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001297 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001298
Victor Stinner95701bd2013-11-06 18:41:07 +01001299 filename = PyUnicode_DecodeFSDefault(filename_str);
1300 if (filename == NULL) {
1301 PyErr_Print();
1302 return -1;
1303 }
1304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 if (flags == NULL) {
1306 flags = &local_flags;
1307 local_flags.cf_flags = 0;
1308 }
Victor Stinner09054372013-11-06 22:41:44 +01001309 v = _PySys_GetObjectId(&PyId_ps1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 if (v == NULL) {
Victor Stinner09054372013-11-06 22:41:44 +01001311 _PySys_SetObjectId(&PyId_ps1, v = PyUnicode_FromString(">>> "));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001312 Py_XDECREF(v);
1313 }
Victor Stinner09054372013-11-06 22:41:44 +01001314 v = _PySys_GetObjectId(&PyId_ps2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 if (v == NULL) {
Victor Stinner09054372013-11-06 22:41:44 +01001316 _PySys_SetObjectId(&PyId_ps2, v = PyUnicode_FromString("... "));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001317 Py_XDECREF(v);
1318 }
Victor Stinner95701bd2013-11-06 18:41:07 +01001319 err = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 for (;;) {
Victor Stinner95701bd2013-11-06 18:41:07 +01001321 ret = PyRun_InteractiveOneObject(fp, filename, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001322 PRINT_TOTAL_REFS();
Victor Stinner95701bd2013-11-06 18:41:07 +01001323 if (ret == E_EOF) {
1324 err = 0;
1325 break;
1326 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001327 /*
1328 if (ret == E_NOMEM)
Victor Stinner95701bd2013-11-06 18:41:07 +01001329 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 */
1331 }
Victor Stinner95701bd2013-11-06 18:41:07 +01001332 Py_DECREF(filename);
1333 return err;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001334}
1335
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001336/* compute parser flags based on compiler flags */
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001337static int PARSER_FLAGS(PyCompilerFlags *flags)
1338{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 int parser_flags = 0;
1340 if (!flags)
1341 return 0;
1342 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
1343 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1344 if (flags->cf_flags & PyCF_IGNORE_COOKIE)
1345 parser_flags |= PyPARSE_IGNORE_COOKIE;
1346 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
1347 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1348 return parser_flags;
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001349}
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001350
Thomas Wouters89f507f2006-12-13 04:49:30 +00001351#if 0
1352/* Keep an example of flags with future keyword support. */
1353#define PARSER_FLAGS(flags) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001354 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1355 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1356 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1357 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001358#endif
1359
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001360int
Victor Stinner95701bd2013-11-06 18:41:07 +01001361PyRun_InteractiveOneObject(FILE *fp, PyObject *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001362{
Victor Stinner95701bd2013-11-06 18:41:07 +01001363 PyObject *m, *d, *v, *w, *oenc = NULL, *mod_name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001364 mod_ty mod;
1365 PyArena *arena;
1366 char *ps1 = "", *ps2 = "", *enc = NULL;
1367 int errcode = 0;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001368 _Py_IDENTIFIER(encoding);
Victor Stinner95701bd2013-11-06 18:41:07 +01001369 _Py_IDENTIFIER(__main__);
1370
1371 mod_name = _PyUnicode_FromId(&PyId___main__); /* borrowed */
1372 if (mod_name == NULL) {
1373 PyErr_Print();
1374 return -1;
1375 }
Tim Petersfe2127d2001-07-16 05:37:24 +00001376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001377 if (fp == stdin) {
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -04001378 /* Fetch encoding from sys.stdin if possible. */
Victor Stinnerbd303c12013-11-07 23:07:29 +01001379 v = _PySys_GetObjectId(&PyId_stdin);
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -04001380 if (v && v != Py_None) {
1381 oenc = _PyObject_GetAttrId(v, &PyId_encoding);
1382 if (oenc)
1383 enc = _PyUnicode_AsString(oenc);
1384 if (!enc)
1385 PyErr_Clear();
1386 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001387 }
Victor Stinner09054372013-11-06 22:41:44 +01001388 v = _PySys_GetObjectId(&PyId_ps1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 if (v != NULL) {
1390 v = PyObject_Str(v);
1391 if (v == NULL)
1392 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001393 else if (PyUnicode_Check(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001394 ps1 = _PyUnicode_AsString(v);
Victor Stinner386fe712010-05-19 00:34:15 +00001395 if (ps1 == NULL) {
1396 PyErr_Clear();
1397 ps1 = "";
1398 }
1399 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001400 }
Victor Stinner09054372013-11-06 22:41:44 +01001401 w = _PySys_GetObjectId(&PyId_ps2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001402 if (w != NULL) {
1403 w = PyObject_Str(w);
1404 if (w == NULL)
1405 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001406 else if (PyUnicode_Check(w)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001407 ps2 = _PyUnicode_AsString(w);
Victor Stinner386fe712010-05-19 00:34:15 +00001408 if (ps2 == NULL) {
1409 PyErr_Clear();
1410 ps2 = "";
1411 }
1412 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001413 }
1414 arena = PyArena_New();
1415 if (arena == NULL) {
1416 Py_XDECREF(v);
1417 Py_XDECREF(w);
1418 Py_XDECREF(oenc);
1419 return -1;
1420 }
Victor Stinner95701bd2013-11-06 18:41:07 +01001421 mod = PyParser_ASTFromFileObject(fp, filename, enc,
1422 Py_single_input, ps1, ps2,
1423 flags, &errcode, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001424 Py_XDECREF(v);
1425 Py_XDECREF(w);
1426 Py_XDECREF(oenc);
1427 if (mod == NULL) {
1428 PyArena_Free(arena);
1429 if (errcode == E_EOF) {
1430 PyErr_Clear();
1431 return E_EOF;
1432 }
1433 PyErr_Print();
1434 return -1;
1435 }
Victor Stinner95701bd2013-11-06 18:41:07 +01001436 m = PyImport_AddModuleObject(mod_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001437 if (m == NULL) {
1438 PyArena_Free(arena);
1439 return -1;
1440 }
1441 d = PyModule_GetDict(m);
1442 v = run_mod(mod, filename, d, d, flags, arena);
1443 PyArena_Free(arena);
1444 flush_io();
1445 if (v == NULL) {
1446 PyErr_Print();
1447 return -1;
1448 }
1449 Py_DECREF(v);
1450 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001451}
1452
Victor Stinner95701bd2013-11-06 18:41:07 +01001453int
1454PyRun_InteractiveOneFlags(FILE *fp, const char *filename_str, PyCompilerFlags *flags)
1455{
1456 PyObject *filename;
1457 int res;
1458
1459 filename = PyUnicode_DecodeFSDefault(filename_str);
1460 if (filename == NULL) {
1461 PyErr_Print();
1462 return -1;
1463 }
1464 res = PyRun_InteractiveOneObject(fp, filename, flags);
1465 Py_DECREF(filename);
1466 return res;
1467}
1468
1469
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001470/* Check whether a file maybe a pyc file: Look at the extension,
1471 the file type, and, if we may close it, at the first few bytes. */
1472
1473static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001474maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001475{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001476 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1477 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001479 /* Only look into the file if we are allowed to close it, since
1480 it then should also be seekable. */
1481 if (closeit) {
1482 /* Read only two bytes of the magic. If the file was opened in
1483 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1484 be read as they are on disk. */
1485 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1486 unsigned char buf[2];
1487 /* Mess: In case of -x, the stream is NOT at its start now,
1488 and ungetc() was used to push back the first newline,
1489 which makes the current stream position formally undefined,
1490 and a x-platform nightmare.
1491 Unfortunately, we have no direct way to know whether -x
1492 was specified. So we use a terrible hack: if the current
1493 stream position is not 0, we assume -x was specified, and
1494 give up. Bug 132850 on SourceForge spells out the
1495 hopelessness of trying anything else (fseek and ftell
1496 don't work predictably x-platform for text-mode files).
1497 */
1498 int ispyc = 0;
1499 if (ftell(fp) == 0) {
1500 if (fread(buf, 1, 2, fp) == 2 &&
1501 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
1502 ispyc = 1;
1503 rewind(fp);
1504 }
1505 return ispyc;
1506 }
1507 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001508}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001509
Antoine Pitrou32d483c2013-07-30 21:01:23 +02001510static int
1511set_main_loader(PyObject *d, const char *filename, const char *loader_name)
Nick Coghlan85e729e2012-07-15 18:09:52 +10001512{
1513 PyInterpreterState *interp;
1514 PyThreadState *tstate;
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001515 PyObject *filename_obj, *loader_type, *loader;
Nick Coghlanb7a58942012-07-15 23:21:08 +10001516 int result = 0;
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001517
1518 filename_obj = PyUnicode_DecodeFSDefault(filename);
1519 if (filename_obj == NULL)
1520 return -1;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001521 /* Get current thread state and interpreter pointer */
1522 tstate = PyThreadState_GET();
1523 interp = tstate->interp;
Nick Coghlan3f94cbf2012-07-15 19:10:39 +10001524 loader_type = PyObject_GetAttrString(interp->importlib, loader_name);
1525 if (loader_type == NULL) {
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001526 Py_DECREF(filename_obj);
Nick Coghlan3f94cbf2012-07-15 19:10:39 +10001527 return -1;
1528 }
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001529 loader = PyObject_CallFunction(loader_type, "sN", "__main__", filename_obj);
Nick Coghlanb7a58942012-07-15 23:21:08 +10001530 Py_DECREF(loader_type);
1531 if (loader == NULL) {
Nick Coghlan85e729e2012-07-15 18:09:52 +10001532 return -1;
1533 }
Nick Coghlanb7a58942012-07-15 23:21:08 +10001534 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
1535 result = -1;
1536 }
Nick Coghlan85e729e2012-07-15 18:09:52 +10001537 Py_DECREF(loader);
Nick Coghlanb7a58942012-07-15 23:21:08 +10001538 return result;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001539}
1540
1541int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001542PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001544{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001545 PyObject *m, *d, *v;
1546 const char *ext;
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001547 int set_file_name = 0, ret = -1;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00001548 size_t len;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001550 m = PyImport_AddModule("__main__");
1551 if (m == NULL)
1552 return -1;
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001553 Py_INCREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001554 d = PyModule_GetDict(m);
1555 if (PyDict_GetItemString(d, "__file__") == NULL) {
1556 PyObject *f;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00001557 f = PyUnicode_DecodeFSDefault(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 if (f == NULL)
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001559 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1561 Py_DECREF(f);
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001562 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001563 }
Barry Warsaw916048d2011-09-20 14:45:44 -04001564 if (PyDict_SetItemString(d, "__cached__", Py_None) < 0) {
1565 Py_DECREF(f);
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001566 goto done;
Barry Warsaw916048d2011-09-20 14:45:44 -04001567 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001568 set_file_name = 1;
1569 Py_DECREF(f);
1570 }
1571 len = strlen(filename);
1572 ext = filename + len - (len > 4 ? 4 : 0);
1573 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Christian Heimes04ac4c12012-09-11 15:47:28 +02001574 FILE *pyc_fp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001575 /* Try to run a pyc file. First, re-open in binary */
1576 if (closeit)
1577 fclose(fp);
Victor Stinnerdaf45552013-08-28 00:53:59 +02001578 if ((pyc_fp = _Py_fopen(filename, "rb")) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001579 fprintf(stderr, "python: Can't reopen .pyc file\n");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001580 goto done;
1581 }
1582 /* Turn on optimization if a .pyo file is given */
1583 if (strcmp(ext, ".pyo") == 0)
1584 Py_OptimizeFlag = 1;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001585
1586 if (set_main_loader(d, filename, "SourcelessFileLoader") < 0) {
1587 fprintf(stderr, "python: failed to set __main__.__loader__\n");
1588 ret = -1;
Christian Heimes04ac4c12012-09-11 15:47:28 +02001589 fclose(pyc_fp);
Nick Coghlan85e729e2012-07-15 18:09:52 +10001590 goto done;
1591 }
Christian Heimes04ac4c12012-09-11 15:47:28 +02001592 v = run_pyc_file(pyc_fp, filename, d, d, flags);
1593 fclose(pyc_fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 } else {
Nick Coghlan85e729e2012-07-15 18:09:52 +10001595 /* When running from stdin, leave __main__.__loader__ alone */
1596 if (strcmp(filename, "<stdin>") != 0 &&
1597 set_main_loader(d, filename, "SourceFileLoader") < 0) {
1598 fprintf(stderr, "python: failed to set __main__.__loader__\n");
1599 ret = -1;
1600 goto done;
1601 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001602 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
1603 closeit, flags);
1604 }
1605 flush_io();
1606 if (v == NULL) {
1607 PyErr_Print();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001608 goto done;
1609 }
1610 Py_DECREF(v);
1611 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001612 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1614 PyErr_Clear();
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001615 Py_DECREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001617}
1618
1619int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001620PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001621{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 PyObject *m, *d, *v;
1623 m = PyImport_AddModule("__main__");
1624 if (m == NULL)
1625 return -1;
1626 d = PyModule_GetDict(m);
1627 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
1628 if (v == NULL) {
1629 PyErr_Print();
1630 return -1;
1631 }
1632 Py_DECREF(v);
1633 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001634}
1635
Barry Warsaw035574d1997-08-29 22:07:17 +00001636static int
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001637parse_syntax_error(PyObject *err, PyObject **message, PyObject **filename,
1638 int *lineno, int *offset, PyObject **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001639{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001640 long hold;
1641 PyObject *v;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001642 _Py_IDENTIFIER(msg);
1643 _Py_IDENTIFIER(filename);
1644 _Py_IDENTIFIER(lineno);
1645 _Py_IDENTIFIER(offset);
1646 _Py_IDENTIFIER(text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001647
Benjamin Peterson80d50422012-04-03 00:30:38 -04001648 *message = NULL;
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001649 *filename = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001651 /* new style errors. `err' is an instance */
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001652 *message = _PyObject_GetAttrId(err, &PyId_msg);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001653 if (!*message)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001655
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001656 v = _PyObject_GetAttrId(err, &PyId_filename);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001657 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001659 if (v == Py_None) {
1660 Py_DECREF(v);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001661 *filename = _PyUnicode_FromId(&PyId_string);
1662 if (*filename == NULL)
1663 goto finally;
1664 Py_INCREF(*filename);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001665 }
1666 else {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001667 *filename = v;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001668 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001669
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001670 v = _PyObject_GetAttrId(err, &PyId_lineno);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001671 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001672 goto finally;
1673 hold = PyLong_AsLong(v);
1674 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001675 if (hold < 0 && PyErr_Occurred())
1676 goto finally;
1677 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001678
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001679 v = _PyObject_GetAttrId(err, &PyId_offset);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001680 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001681 goto finally;
1682 if (v == Py_None) {
1683 *offset = -1;
1684 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 } else {
1686 hold = PyLong_AsLong(v);
1687 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001688 if (hold < 0 && PyErr_Occurred())
1689 goto finally;
1690 *offset = (int)hold;
1691 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001692
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001693 v = _PyObject_GetAttrId(err, &PyId_text);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001694 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001695 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001696 if (v == Py_None) {
1697 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001698 *text = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001699 }
1700 else {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001701 *text = v;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001702 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001703 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001704
1705finally:
Benjamin Peterson80d50422012-04-03 00:30:38 -04001706 Py_XDECREF(*message);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001707 Py_XDECREF(*filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001708 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001709}
1710
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001711void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001712PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001713{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001715}
1716
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001717static void
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001718print_error_text(PyObject *f, int offset, PyObject *text_obj)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001719{
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001720 char *text;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 char *nl;
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001722
1723 text = _PyUnicode_AsString(text_obj);
1724 if (text == NULL)
1725 return;
1726
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001727 if (offset >= 0) {
Benjamin Petersona95e9772010-10-29 03:28:14 +00001728 if (offset > 0 && offset == strlen(text) && text[offset - 1] == '\n')
1729 offset--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001730 for (;;) {
1731 nl = strchr(text, '\n');
1732 if (nl == NULL || nl-text >= offset)
1733 break;
1734 offset -= (int)(nl+1-text);
1735 text = nl+1;
1736 }
1737 while (*text == ' ' || *text == '\t') {
1738 text++;
1739 offset--;
1740 }
1741 }
1742 PyFile_WriteString(" ", f);
1743 PyFile_WriteString(text, f);
1744 if (*text == '\0' || text[strlen(text)-1] != '\n')
1745 PyFile_WriteString("\n", f);
1746 if (offset == -1)
1747 return;
1748 PyFile_WriteString(" ", f);
Benjamin Petersona95e9772010-10-29 03:28:14 +00001749 while (--offset > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001750 PyFile_WriteString(" ", f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001751 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001752}
1753
Guido van Rossum66e8e862001-03-23 17:54:43 +00001754static void
1755handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001756{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 PyObject *exception, *value, *tb;
1758 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001759
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001760 if (Py_InspectFlag)
1761 /* Don't exit if -i flag was given. This flag is set to 0
1762 * when entering interactive mode for inspecting. */
1763 return;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 PyErr_Fetch(&exception, &value, &tb);
1766 fflush(stdout);
1767 if (value == NULL || value == Py_None)
1768 goto done;
1769 if (PyExceptionInstance_Check(value)) {
1770 /* The error code should be in the `code' attribute. */
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001771 _Py_IDENTIFIER(code);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001772 PyObject *code = _PyObject_GetAttrId(value, &PyId_code);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001773 if (code) {
1774 Py_DECREF(value);
1775 value = code;
1776 if (value == Py_None)
1777 goto done;
1778 }
1779 /* If we failed to dig out the 'code' attribute,
1780 just let the else clause below print the error. */
1781 }
1782 if (PyLong_Check(value))
1783 exitcode = (int)PyLong_AsLong(value);
1784 else {
Victor Stinnerbd303c12013-11-07 23:07:29 +01001785 PyObject *sys_stderr = _PySys_GetObjectId(&PyId_stderr);
Victor Stinner7126dbc2010-05-21 23:45:42 +00001786 if (sys_stderr != NULL && sys_stderr != Py_None) {
1787 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
1788 } else {
1789 PyObject_Print(value, stderr, Py_PRINT_RAW);
1790 fflush(stderr);
1791 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 PySys_WriteStderr("\n");
1793 exitcode = 1;
1794 }
Tim Peterscf615b52003-04-19 18:47:02 +00001795 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 /* Restore and clear the exception info, in order to properly decref
1797 * the exception, value, and traceback. If we just exit instead,
1798 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1799 * some finalizers from running.
1800 */
1801 PyErr_Restore(exception, value, tb);
1802 PyErr_Clear();
1803 Py_Exit(exitcode);
1804 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001805}
1806
1807void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001808PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001809{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001810 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001812 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1813 handle_system_exit();
1814 }
1815 PyErr_Fetch(&exception, &v, &tb);
1816 if (exception == NULL)
1817 return;
1818 PyErr_NormalizeException(&exception, &v, &tb);
1819 if (tb == NULL) {
1820 tb = Py_None;
1821 Py_INCREF(tb);
1822 }
1823 PyException_SetTraceback(v, tb);
1824 if (exception == NULL)
1825 return;
1826 /* Now we know v != NULL too */
1827 if (set_sys_last_vars) {
Victor Stinner09054372013-11-06 22:41:44 +01001828 _PySys_SetObjectId(&PyId_last_type, exception);
1829 _PySys_SetObjectId(&PyId_last_value, v);
1830 _PySys_SetObjectId(&PyId_last_traceback, tb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001831 }
Victor Stinner09054372013-11-06 22:41:44 +01001832 hook = _PySys_GetObjectId(&PyId_excepthook);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001833 if (hook) {
1834 PyObject *args = PyTuple_Pack(3, exception, v, tb);
1835 PyObject *result = PyEval_CallObject(hook, args);
1836 if (result == NULL) {
1837 PyObject *exception2, *v2, *tb2;
1838 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1839 handle_system_exit();
1840 }
1841 PyErr_Fetch(&exception2, &v2, &tb2);
1842 PyErr_NormalizeException(&exception2, &v2, &tb2);
1843 /* It should not be possible for exception2 or v2
1844 to be NULL. However PyErr_Display() can't
1845 tolerate NULLs, so just be safe. */
1846 if (exception2 == NULL) {
1847 exception2 = Py_None;
1848 Py_INCREF(exception2);
1849 }
1850 if (v2 == NULL) {
1851 v2 = Py_None;
1852 Py_INCREF(v2);
1853 }
1854 fflush(stdout);
1855 PySys_WriteStderr("Error in sys.excepthook:\n");
1856 PyErr_Display(exception2, v2, tb2);
1857 PySys_WriteStderr("\nOriginal exception was:\n");
1858 PyErr_Display(exception, v, tb);
1859 Py_DECREF(exception2);
1860 Py_DECREF(v2);
1861 Py_XDECREF(tb2);
1862 }
1863 Py_XDECREF(result);
1864 Py_XDECREF(args);
1865 } else {
1866 PySys_WriteStderr("sys.excepthook is missing\n");
1867 PyErr_Display(exception, v, tb);
1868 }
1869 Py_XDECREF(exception);
1870 Py_XDECREF(v);
1871 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001872}
1873
Benjamin Petersone6528212008-07-15 15:32:09 +00001874static void
1875print_exception(PyObject *f, PyObject *value)
1876{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001877 int err = 0;
1878 PyObject *type, *tb;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001879 _Py_IDENTIFIER(print_file_and_line);
Benjamin Petersone6528212008-07-15 15:32:09 +00001880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001881 if (!PyExceptionInstance_Check(value)) {
1882 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1883 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1884 PyFile_WriteString(" found\n", f);
1885 return;
1886 }
Benjamin Peterson26582602008-08-23 20:08:07 +00001887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001888 Py_INCREF(value);
1889 fflush(stdout);
1890 type = (PyObject *) Py_TYPE(value);
1891 tb = PyException_GetTraceback(value);
1892 if (tb && tb != Py_None)
1893 err = PyTraceBack_Print(tb, f);
1894 if (err == 0 &&
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001895 _PyObject_HasAttrId(value, &PyId_print_file_and_line))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001896 {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001897 PyObject *message, *filename, *text;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001898 int lineno, offset;
1899 if (!parse_syntax_error(value, &message, &filename,
1900 &lineno, &offset, &text))
1901 PyErr_Clear();
1902 else {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001903 PyObject *line;
1904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 Py_DECREF(value);
1906 value = message;
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001907
1908 line = PyUnicode_FromFormat(" File \"%U\", line %d\n",
1909 filename, lineno);
1910 Py_DECREF(filename);
1911 if (line != NULL) {
1912 PyFile_WriteObject(line, f, Py_PRINT_RAW);
1913 Py_DECREF(line);
1914 }
1915
1916 if (text != NULL) {
1917 print_error_text(f, offset, text);
1918 Py_DECREF(text);
1919 }
1920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001921 /* Can't be bothered to check all those
1922 PyFile_WriteString() calls */
1923 if (PyErr_Occurred())
1924 err = -1;
1925 }
1926 }
1927 if (err) {
1928 /* Don't do anything else */
1929 }
1930 else {
1931 PyObject* moduleName;
1932 char* className;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001933 _Py_IDENTIFIER(__module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001934 assert(PyExceptionClass_Check(type));
1935 className = PyExceptionClass_Name(type);
1936 if (className != NULL) {
1937 char *dot = strrchr(className, '.');
1938 if (dot != NULL)
1939 className = dot+1;
1940 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001941
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001942 moduleName = _PyObject_GetAttrId(type, &PyId___module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001943 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1944 {
Victor Stinner13b21bd2011-05-26 14:25:13 +02001945 Py_XDECREF(moduleName);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001946 err = PyFile_WriteString("<unknown>", f);
1947 }
1948 else {
Victor Stinnerbd303c12013-11-07 23:07:29 +01001949 if (_PyUnicode_CompareWithId(moduleName, &PyId_builtins) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001950 {
Victor Stinner937114f2013-11-07 00:12:30 +01001951 err = PyFile_WriteObject(moduleName, f, Py_PRINT_RAW);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001952 err += PyFile_WriteString(".", f);
1953 }
1954 Py_DECREF(moduleName);
1955 }
1956 if (err == 0) {
1957 if (className == NULL)
1958 err = PyFile_WriteString("<unknown>", f);
1959 else
1960 err = PyFile_WriteString(className, f);
1961 }
1962 }
1963 if (err == 0 && (value != Py_None)) {
1964 PyObject *s = PyObject_Str(value);
1965 /* only print colon if the str() of the
1966 object is not the empty string
1967 */
1968 if (s == NULL)
1969 err = -1;
1970 else if (!PyUnicode_Check(s) ||
Victor Stinnere251d6d2011-11-20 19:20:00 +01001971 PyUnicode_GetLength(s) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001972 err = PyFile_WriteString(": ", f);
1973 if (err == 0)
1974 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1975 Py_XDECREF(s);
1976 }
1977 /* try to write a newline in any case */
1978 err += PyFile_WriteString("\n", f);
1979 Py_XDECREF(tb);
1980 Py_DECREF(value);
1981 /* If an error happened here, don't show it.
1982 XXX This is wrong, but too many callers rely on this behavior. */
1983 if (err != 0)
1984 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001985}
1986
1987static const char *cause_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001988 "\nThe above exception was the direct cause "
1989 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001990
1991static const char *context_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 "\nDuring handling of the above exception, "
1993 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001994
1995static void
1996print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1997{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 int err = 0, res;
1999 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00002000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002001 if (seen != NULL) {
2002 /* Exception chaining */
2003 if (PySet_Add(seen, value) == -1)
2004 PyErr_Clear();
2005 else if (PyExceptionInstance_Check(value)) {
2006 cause = PyException_GetCause(value);
2007 context = PyException_GetContext(value);
Benjamin Petersond5a1c442012-05-14 22:09:31 -07002008 if (cause) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002009 res = PySet_Contains(seen, cause);
2010 if (res == -1)
2011 PyErr_Clear();
2012 if (res == 0) {
2013 print_exception_recursive(
2014 f, cause, seen);
2015 err |= PyFile_WriteString(
2016 cause_message, f);
2017 }
2018 }
Benjamin Petersond5a1c442012-05-14 22:09:31 -07002019 else if (context &&
2020 !((PyBaseExceptionObject *)value)->suppress_context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002021 res = PySet_Contains(seen, context);
2022 if (res == -1)
2023 PyErr_Clear();
2024 if (res == 0) {
2025 print_exception_recursive(
2026 f, context, seen);
2027 err |= PyFile_WriteString(
2028 context_message, f);
2029 }
2030 }
2031 Py_XDECREF(context);
2032 Py_XDECREF(cause);
2033 }
2034 }
2035 print_exception(f, value);
2036 if (err != 0)
2037 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00002038}
2039
Thomas Wouters477c8d52006-05-27 19:21:47 +00002040void
2041PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002042{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002043 PyObject *seen;
Victor Stinnerbd303c12013-11-07 23:07:29 +01002044 PyObject *f = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrou24201d42013-10-13 21:53:13 +02002045 if (PyExceptionInstance_Check(value)
2046 && tb != NULL && PyTraceBack_Check(tb)) {
2047 /* Put the traceback on the exception, otherwise it won't get
2048 displayed. See issue #18776. */
2049 PyObject *cur_tb = PyException_GetTraceback(value);
2050 if (cur_tb == NULL)
2051 PyException_SetTraceback(value, tb);
2052 else
2053 Py_DECREF(cur_tb);
2054 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002055 if (f == Py_None) {
2056 /* pass */
2057 }
2058 else if (f == NULL) {
2059 _PyObject_Dump(value);
2060 fprintf(stderr, "lost sys.stderr\n");
2061 }
2062 else {
2063 /* We choose to ignore seen being possibly NULL, and report
2064 at least the main exception (it could be a MemoryError).
2065 */
2066 seen = PySet_New(NULL);
2067 if (seen == NULL)
2068 PyErr_Clear();
2069 print_exception_recursive(f, value, seen);
2070 Py_XDECREF(seen);
2071 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002072}
2073
Guido van Rossum82598051997-03-05 00:20:32 +00002074PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002075PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002076 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002077{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002078 PyObject *ret = NULL;
2079 mod_ty mod;
Victor Stinner95701bd2013-11-06 18:41:07 +01002080 PyArena *arena;
Victor Stinner95701bd2013-11-06 18:41:07 +01002081 PyObject *filename;
2082
2083 filename = _PyUnicode_FromId(&PyId_string); /* borrowed */
2084 if (filename == NULL)
2085 return NULL;
2086
2087 arena = PyArena_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002088 if (arena == NULL)
2089 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00002090
Victor Stinner95701bd2013-11-06 18:41:07 +01002091 mod = PyParser_ASTFromStringObject(str, filename, start, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002092 if (mod != NULL)
Victor Stinner95701bd2013-11-06 18:41:07 +01002093 ret = run_mod(mod, filename, globals, locals, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002094 PyArena_Free(arena);
2095 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002096}
2097
2098PyObject *
Victor Stinner95701bd2013-11-06 18:41:07 +01002099PyRun_FileExFlags(FILE *fp, const char *filename_str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002100 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002101{
Victor Stinner95701bd2013-11-06 18:41:07 +01002102 PyObject *ret = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002103 mod_ty mod;
Victor Stinner95701bd2013-11-06 18:41:07 +01002104 PyArena *arena = NULL;
2105 PyObject *filename;
Guido van Rossum98297ee2007-11-06 21:34:58 +00002106
Victor Stinner95701bd2013-11-06 18:41:07 +01002107 filename = PyUnicode_DecodeFSDefault(filename_str);
2108 if (filename == NULL)
2109 goto exit;
2110
2111 arena = PyArena_New();
2112 if (arena == NULL)
2113 goto exit;
2114
2115 mod = PyParser_ASTFromFileObject(fp, filename, NULL, start, 0, 0,
2116 flags, NULL, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002117 if (closeit)
2118 fclose(fp);
2119 if (mod == NULL) {
Victor Stinner95701bd2013-11-06 18:41:07 +01002120 goto exit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 }
2122 ret = run_mod(mod, filename, globals, locals, flags, arena);
Victor Stinner95701bd2013-11-06 18:41:07 +01002123
2124exit:
2125 Py_XDECREF(filename);
2126 if (arena != NULL)
2127 PyArena_Free(arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002128 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002129}
2130
Guido van Rossum6c193fa2007-12-05 05:14:58 +00002131static void
2132flush_io(void)
2133{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002134 PyObject *f, *r;
2135 PyObject *type, *value, *traceback;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00002136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 /* Save the current exception */
2138 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00002139
Victor Stinnerbd303c12013-11-07 23:07:29 +01002140 f = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 if (f != NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002142 r = _PyObject_CallMethodId(f, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002143 if (r)
2144 Py_DECREF(r);
2145 else
2146 PyErr_Clear();
2147 }
Victor Stinnerbd303c12013-11-07 23:07:29 +01002148 f = _PySys_GetObjectId(&PyId_stdout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 if (f != NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002150 r = _PyObject_CallMethodId(f, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002151 if (r)
2152 Py_DECREF(r);
2153 else
2154 PyErr_Clear();
2155 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00002156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002157 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00002158}
2159
Guido van Rossum82598051997-03-05 00:20:32 +00002160static PyObject *
Victor Stinner95701bd2013-11-06 18:41:07 +01002161run_mod(mod_ty mod, PyObject *filename, PyObject *globals, PyObject *locals,
2162 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002163{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 PyCodeObject *co;
2165 PyObject *v;
Victor Stinner95701bd2013-11-06 18:41:07 +01002166 co = PyAST_CompileObject(mod, filename, flags, -1, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 if (co == NULL)
2168 return NULL;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002169 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002170 Py_DECREF(co);
2171 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002172}
2173
Guido van Rossum82598051997-03-05 00:20:32 +00002174static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002175run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002176 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00002177{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002178 PyCodeObject *co;
2179 PyObject *v;
2180 long magic;
2181 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00002182
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002183 magic = PyMarshal_ReadLongFromFile(fp);
2184 if (magic != PyImport_GetMagicNumber()) {
2185 PyErr_SetString(PyExc_RuntimeError,
2186 "Bad magic number in .pyc file");
2187 return NULL;
2188 }
Antoine Pitrou5136ac02012-01-13 18:52:16 +01002189 /* Skip mtime and size */
2190 (void) PyMarshal_ReadLongFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002191 (void) PyMarshal_ReadLongFromFile(fp);
2192 v = PyMarshal_ReadLastObjectFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193 if (v == NULL || !PyCode_Check(v)) {
2194 Py_XDECREF(v);
2195 PyErr_SetString(PyExc_RuntimeError,
2196 "Bad code object in .pyc file");
2197 return NULL;
2198 }
2199 co = (PyCodeObject *)v;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002200 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002201 if (v && flags)
2202 flags->cf_flags |= (co->co_flags & PyCF_MASK);
2203 Py_DECREF(co);
2204 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00002205}
2206
Guido van Rossum82598051997-03-05 00:20:32 +00002207PyObject *
Victor Stinner14e461d2013-08-26 22:28:21 +02002208Py_CompileStringObject(const char *str, PyObject *filename, int start,
2209 PyCompilerFlags *flags, int optimize)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002210{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002211 PyCodeObject *co;
2212 mod_ty mod;
2213 PyArena *arena = PyArena_New();
2214 if (arena == NULL)
2215 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002216
Victor Stinner14e461d2013-08-26 22:28:21 +02002217 mod = PyParser_ASTFromStringObject(str, filename, start, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002218 if (mod == NULL) {
2219 PyArena_Free(arena);
2220 return NULL;
2221 }
2222 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
2223 PyObject *result = PyAST_mod2obj(mod);
2224 PyArena_Free(arena);
2225 return result;
2226 }
Victor Stinner14e461d2013-08-26 22:28:21 +02002227 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002228 PyArena_Free(arena);
2229 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00002230}
2231
Victor Stinner14e461d2013-08-26 22:28:21 +02002232PyObject *
2233Py_CompileStringExFlags(const char *str, const char *filename_str, int start,
2234 PyCompilerFlags *flags, int optimize)
2235{
2236 PyObject *filename, *co;
2237 filename = PyUnicode_DecodeFSDefault(filename_str);
2238 if (filename == NULL)
2239 return NULL;
2240 co = Py_CompileStringObject(str, filename, start, flags, optimize);
2241 Py_DECREF(filename);
2242 return co;
2243}
2244
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002245/* For use in Py_LIMITED_API */
2246#undef Py_CompileString
2247PyObject *
2248PyCompileString(const char *str, const char *filename, int start)
2249{
2250 return Py_CompileStringFlags(str, filename, start, NULL);
2251}
2252
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002253struct symtable *
Victor Stinner14e461d2013-08-26 22:28:21 +02002254Py_SymtableStringObject(const char *str, PyObject *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002255{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002256 struct symtable *st;
2257 mod_ty mod;
2258 PyCompilerFlags flags;
Victor Stinner14e461d2013-08-26 22:28:21 +02002259 PyArena *arena;
2260
2261 arena = PyArena_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002262 if (arena == NULL)
2263 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 flags.cf_flags = 0;
Victor Stinner14e461d2013-08-26 22:28:21 +02002266 mod = PyParser_ASTFromStringObject(str, filename, start, &flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002267 if (mod == NULL) {
2268 PyArena_Free(arena);
2269 return NULL;
2270 }
Victor Stinner14e461d2013-08-26 22:28:21 +02002271 st = PySymtable_BuildObject(mod, filename, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002272 PyArena_Free(arena);
2273 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002274}
2275
Victor Stinner14e461d2013-08-26 22:28:21 +02002276struct symtable *
2277Py_SymtableString(const char *str, const char *filename_str, int start)
2278{
2279 PyObject *filename;
2280 struct symtable *st;
2281
2282 filename = PyUnicode_DecodeFSDefault(filename_str);
2283 if (filename == NULL)
2284 return NULL;
2285 st = Py_SymtableStringObject(str, filename, start);
2286 Py_DECREF(filename);
2287 return st;
2288}
2289
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002290/* Preferred access to parser is through AST. */
2291mod_ty
Victor Stinner14e461d2013-08-26 22:28:21 +02002292PyParser_ASTFromStringObject(const char *s, PyObject *filename, int start,
2293 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002294{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 mod_ty mod;
2296 PyCompilerFlags localflags;
2297 perrdetail err;
2298 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00002299
Victor Stinner14e461d2013-08-26 22:28:21 +02002300 node *n = PyParser_ParseStringObject(s, filename,
2301 &_PyParser_Grammar, start, &err,
2302 &iflags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002303 if (flags == NULL) {
2304 localflags.cf_flags = 0;
2305 flags = &localflags;
2306 }
2307 if (n) {
2308 flags->cf_flags |= iflags & PyCF_MASK;
Victor Stinner14e461d2013-08-26 22:28:21 +02002309 mod = PyAST_FromNodeObject(n, flags, filename, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002310 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002311 }
2312 else {
2313 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002314 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002315 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002316 err_free(&err);
2317 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002318}
2319
2320mod_ty
Victor Stinner14e461d2013-08-26 22:28:21 +02002321PyParser_ASTFromString(const char *s, const char *filename_str, int start,
2322 PyCompilerFlags *flags, PyArena *arena)
2323{
2324 PyObject *filename;
2325 mod_ty mod;
2326 filename = PyUnicode_DecodeFSDefault(filename_str);
2327 if (filename == NULL)
2328 return NULL;
2329 mod = PyParser_ASTFromStringObject(s, filename, start, flags, arena);
2330 Py_DECREF(filename);
2331 return mod;
2332}
2333
2334mod_ty
2335PyParser_ASTFromFileObject(FILE *fp, PyObject *filename, const char* enc,
2336 int start, char *ps1,
2337 char *ps2, PyCompilerFlags *flags, int *errcode,
2338 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002339{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002340 mod_ty mod;
2341 PyCompilerFlags localflags;
2342 perrdetail err;
2343 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00002344
Victor Stinner14e461d2013-08-26 22:28:21 +02002345 node *n = PyParser_ParseFileObject(fp, filename, enc,
2346 &_PyParser_Grammar,
2347 start, ps1, ps2, &err, &iflags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002348 if (flags == NULL) {
2349 localflags.cf_flags = 0;
2350 flags = &localflags;
2351 }
2352 if (n) {
2353 flags->cf_flags |= iflags & PyCF_MASK;
Victor Stinner14e461d2013-08-26 22:28:21 +02002354 mod = PyAST_FromNodeObject(n, flags, filename, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002355 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002356 }
2357 else {
2358 err_input(&err);
2359 if (errcode)
2360 *errcode = err.error;
Victor Stinner7f2fee32011-04-05 00:39:01 +02002361 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002362 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002363 err_free(&err);
2364 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002365}
2366
Victor Stinner14e461d2013-08-26 22:28:21 +02002367mod_ty
2368PyParser_ASTFromFile(FILE *fp, const char *filename_str, const char* enc,
2369 int start, char *ps1,
2370 char *ps2, PyCompilerFlags *flags, int *errcode,
2371 PyArena *arena)
2372{
2373 mod_ty mod;
2374 PyObject *filename;
2375 filename = PyUnicode_DecodeFSDefault(filename_str);
2376 if (filename == NULL)
2377 return NULL;
2378 mod = PyParser_ASTFromFileObject(fp, filename, enc, start, ps1, ps2,
2379 flags, errcode, arena);
2380 Py_DECREF(filename);
2381 return mod;
2382}
2383
Guido van Rossuma110aa61994-08-29 12:50:44 +00002384/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002385
Guido van Rossuma110aa61994-08-29 12:50:44 +00002386node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002387PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002388{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002389 perrdetail err;
2390 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
2391 &_PyParser_Grammar,
2392 start, NULL, NULL, &err, flags);
2393 if (n == NULL)
2394 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002395 err_free(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002397 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002398}
2399
Guido van Rossuma110aa61994-08-29 12:50:44 +00002400/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002401
Guido van Rossuma110aa61994-08-29 12:50:44 +00002402node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002403PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00002404{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002405 perrdetail err;
2406 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
2407 start, &err, flags);
2408 if (n == NULL)
2409 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002410 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002411 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00002412}
2413
2414node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002415PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002416 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00002417{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002418 perrdetail err;
2419 node *n = PyParser_ParseStringFlagsFilename(str, filename,
2420 &_PyParser_Grammar, start, &err, flags);
2421 if (n == NULL)
2422 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002423 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002424 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00002425}
2426
2427node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002428PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00002429{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002430 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00002431}
2432
Guido van Rossum66ebd912003-04-17 16:02:26 +00002433/* May want to move a more generalized form of this to parsetok.c or
2434 even parser modules. */
2435
2436void
Victor Stinner7f2fee32011-04-05 00:39:01 +02002437PyParser_ClearError(perrdetail *err)
2438{
2439 err_free(err);
2440}
2441
2442void
Guido van Rossum66ebd912003-04-17 16:02:26 +00002443PyParser_SetError(perrdetail *err)
2444{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002445 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00002446}
2447
Victor Stinner7f2fee32011-04-05 00:39:01 +02002448static void
2449err_free(perrdetail *err)
2450{
2451 Py_CLEAR(err->filename);
2452}
2453
Guido van Rossuma110aa61994-08-29 12:50:44 +00002454/* Set the error appropriate to the given input error code (see errcode.h) */
2455
2456static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002457err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00002458{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002459 PyObject *v, *w, *errtype, *errtext;
2460 PyObject *msg_obj = NULL;
2461 char *msg = NULL;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00002462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002463 errtype = PyExc_SyntaxError;
2464 switch (err->error) {
2465 case E_ERROR:
2466 return;
2467 case E_SYNTAX:
2468 errtype = PyExc_IndentationError;
2469 if (err->expected == INDENT)
2470 msg = "expected an indented block";
2471 else if (err->token == INDENT)
2472 msg = "unexpected indent";
2473 else if (err->token == DEDENT)
2474 msg = "unexpected unindent";
2475 else {
2476 errtype = PyExc_SyntaxError;
2477 msg = "invalid syntax";
2478 }
2479 break;
2480 case E_TOKEN:
2481 msg = "invalid token";
2482 break;
2483 case E_EOFS:
2484 msg = "EOF while scanning triple-quoted string literal";
2485 break;
2486 case E_EOLS:
2487 msg = "EOL while scanning string literal";
2488 break;
2489 case E_INTR:
2490 if (!PyErr_Occurred())
2491 PyErr_SetNone(PyExc_KeyboardInterrupt);
2492 goto cleanup;
2493 case E_NOMEM:
2494 PyErr_NoMemory();
2495 goto cleanup;
2496 case E_EOF:
2497 msg = "unexpected EOF while parsing";
2498 break;
2499 case E_TABSPACE:
2500 errtype = PyExc_TabError;
2501 msg = "inconsistent use of tabs and spaces in indentation";
2502 break;
2503 case E_OVERFLOW:
2504 msg = "expression too long";
2505 break;
2506 case E_DEDENT:
2507 errtype = PyExc_IndentationError;
2508 msg = "unindent does not match any outer indentation level";
2509 break;
2510 case E_TOODEEP:
2511 errtype = PyExc_IndentationError;
2512 msg = "too many levels of indentation";
2513 break;
2514 case E_DECODE: {
2515 PyObject *type, *value, *tb;
2516 PyErr_Fetch(&type, &value, &tb);
2517 msg = "unknown decode error";
2518 if (value != NULL)
2519 msg_obj = PyObject_Str(value);
2520 Py_XDECREF(type);
2521 Py_XDECREF(value);
2522 Py_XDECREF(tb);
2523 break;
2524 }
2525 case E_LINECONT:
2526 msg = "unexpected character after line continuation character";
2527 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00002528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002529 case E_IDENTIFIER:
2530 msg = "invalid character in identifier";
2531 break;
Meador Ingefa21bf02012-01-19 01:08:41 -06002532 case E_BADSINGLE:
2533 msg = "multiple statements found while compiling a single statement";
2534 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002535 default:
2536 fprintf(stderr, "error=%d\n", err->error);
2537 msg = "unknown parsing error";
2538 break;
2539 }
2540 /* err->text may not be UTF-8 in case of decoding errors.
2541 Explicitly convert to an object. */
2542 if (!err->text) {
2543 errtext = Py_None;
2544 Py_INCREF(Py_None);
2545 } else {
2546 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
2547 "replace");
2548 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002549 v = Py_BuildValue("(OiiN)", err->filename,
2550 err->lineno, err->offset, errtext);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002551 if (v != NULL) {
2552 if (msg_obj)
2553 w = Py_BuildValue("(OO)", msg_obj, v);
2554 else
2555 w = Py_BuildValue("(sO)", msg, v);
2556 } else
2557 w = NULL;
2558 Py_XDECREF(v);
2559 PyErr_SetObject(errtype, w);
2560 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00002561cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002562 Py_XDECREF(msg_obj);
2563 if (err->text != NULL) {
2564 PyObject_FREE(err->text);
2565 err->text = NULL;
2566 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002567}
2568
2569/* Print fatal error message and abort */
2570
2571void
Tim Peters7c321a82002-07-09 02:57:01 +00002572Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002573{
Victor Stinner024e37a2011-03-31 01:31:06 +02002574 const int fd = fileno(stderr);
2575 PyThreadState *tstate;
2576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002577 fprintf(stderr, "Fatal Python error: %s\n", msg);
2578 fflush(stderr); /* it helps in Windows debug build */
2579 if (PyErr_Occurred()) {
Victor Stinner55a5c782010-06-08 21:00:13 +00002580 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002581 }
Victor Stinner024e37a2011-03-31 01:31:06 +02002582 else {
2583 tstate = _Py_atomic_load_relaxed(&_PyThreadState_Current);
2584 if (tstate != NULL) {
2585 fputc('\n', stderr);
2586 fflush(stderr);
Victor Stinner7bba62f2011-05-07 12:43:00 +02002587 _Py_DumpTracebackThreads(fd, tstate->interp, tstate);
Victor Stinner024e37a2011-03-31 01:31:06 +02002588 }
Victor Stinnerd727e232011-04-01 12:13:55 +02002589 _PyFaulthandler_Fini();
Victor Stinner024e37a2011-03-31 01:31:06 +02002590 }
2591
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002592#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002593 {
2594 size_t len = strlen(msg);
2595 WCHAR* buffer;
2596 size_t i;
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002597
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002598 /* Convert the message to wchar_t. This uses a simple one-to-one
2599 conversion, assuming that the this error message actually uses ASCII
2600 only. If this ceases to be true, we will have to convert. */
2601 buffer = alloca( (len+1) * (sizeof *buffer));
2602 for( i=0; i<=len; ++i)
2603 buffer[i] = msg[i];
2604 OutputDebugStringW(L"Fatal Python error: ");
2605 OutputDebugStringW(buffer);
2606 OutputDebugStringW(L"\n");
2607 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002608#ifdef _DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002609 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002610#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002611#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002612 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002613}
2614
2615/* Clean up and exit */
2616
Guido van Rossuma110aa61994-08-29 12:50:44 +00002617#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002618#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002619#endif
2620
Collin Winter670e6922007-03-21 02:57:17 +00002621static void (*pyexitfunc)(void) = NULL;
2622/* For the atexit module. */
2623void _Py_PyAtExit(void (*func)(void))
2624{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002625 pyexitfunc = func;
Collin Winter670e6922007-03-21 02:57:17 +00002626}
2627
2628static void
2629call_py_exitfuncs(void)
2630{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002631 if (pyexitfunc == NULL)
2632 return;
Collin Winter670e6922007-03-21 02:57:17 +00002633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002634 (*pyexitfunc)();
2635 PyErr_Clear();
Collin Winter670e6922007-03-21 02:57:17 +00002636}
2637
Antoine Pitrou011bd622009-10-20 21:52:47 +00002638/* Wait until threading._shutdown completes, provided
2639 the threading module was imported in the first place.
2640 The shutdown routine will wait until all non-daemon
2641 "threading" threads have completed. */
2642static void
2643wait_for_thread_shutdown(void)
2644{
2645#ifdef WITH_THREAD
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002646 _Py_IDENTIFIER(_shutdown);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002647 PyObject *result;
2648 PyThreadState *tstate = PyThreadState_GET();
2649 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2650 "threading");
2651 if (threading == NULL) {
2652 /* threading not imported */
2653 PyErr_Clear();
2654 return;
2655 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002656 result = _PyObject_CallMethodId(threading, &PyId__shutdown, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002657 if (result == NULL) {
2658 PyErr_WriteUnraisable(threading);
2659 }
2660 else {
2661 Py_DECREF(result);
2662 }
2663 Py_DECREF(threading);
Antoine Pitrou011bd622009-10-20 21:52:47 +00002664#endif
2665}
2666
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002667#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002668static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002669static int nexitfuncs = 0;
2670
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002671int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002672{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002673 if (nexitfuncs >= NEXITFUNCS)
2674 return -1;
2675 exitfuncs[nexitfuncs++] = func;
2676 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00002677}
2678
Guido van Rossumcc283f51997-08-05 02:22:03 +00002679static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002680call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002681{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002682 while (nexitfuncs > 0)
2683 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002684
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002685 fflush(stdout);
2686 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002687}
2688
2689void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002690Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002691{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002692 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002693
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002694 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002695}
2696
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002697static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002698initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002699{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002700#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002701 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002702#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002703#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002704 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002705#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002706#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002707 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002708#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002709 PyOS_InitInterrupts(); /* May imply initsignal() */
Victor Stinnerd786ad52013-07-21 13:25:51 +02002710 if (PyErr_Occurred()) {
2711 Py_FatalError("Py_Initialize: can't import signal");
2712 }
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002713}
2714
Guido van Rossum7433b121997-02-14 19:45:36 +00002715
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002716/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2717 *
2718 * All of the code in this function must only use async-signal-safe functions,
2719 * listed at `man 7 signal` or
2720 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2721 */
2722void
2723_Py_RestoreSignals(void)
2724{
2725#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002726 PyOS_setsig(SIGPIPE, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002727#endif
2728#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002729 PyOS_setsig(SIGXFZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002730#endif
2731#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002732 PyOS_setsig(SIGXFSZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002733#endif
2734}
2735
2736
Guido van Rossum7433b121997-02-14 19:45:36 +00002737/*
2738 * The file descriptor fd is considered ``interactive'' if either
2739 * a) isatty(fd) is TRUE, or
2740 * b) the -i flag was given, and the filename associated with
2741 * the descriptor is NULL or "<stdin>" or "???".
2742 */
2743int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002744Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002745{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002746 if (isatty((int)fileno(fp)))
2747 return 1;
2748 if (!Py_InteractiveFlag)
2749 return 0;
2750 return (filename == NULL) ||
2751 (strcmp(filename, "<stdin>") == 0) ||
2752 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00002753}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002754
2755
Tim Petersd08e3822003-04-17 15:24:21 +00002756#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002757#if defined(WIN32) && defined(_MSC_VER)
2758
2759/* Stack checking for Microsoft C */
2760
2761#include <malloc.h>
2762#include <excpt.h>
2763
Fred Drakee8de31c2000-08-31 05:38:39 +00002764/*
2765 * Return non-zero when we run out of memory on the stack; zero otherwise.
2766 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002767int
Fred Drake399739f2000-08-31 05:52:44 +00002768PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002769{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002770 __try {
2771 /* alloca throws a stack overflow exception if there's
2772 not enough space left on the stack */
2773 alloca(PYOS_STACK_MARGIN * sizeof(void*));
2774 return 0;
2775 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2776 EXCEPTION_EXECUTE_HANDLER :
2777 EXCEPTION_CONTINUE_SEARCH) {
2778 int errcode = _resetstkoflw();
2779 if (errcode == 0)
2780 {
2781 Py_FatalError("Could not reset the stack!");
2782 }
2783 }
2784 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002785}
2786
2787#endif /* WIN32 && _MSC_VER */
2788
2789/* Alternate implementations can be added here... */
2790
2791#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002792
2793
2794/* Wrappers around sigaction() or signal(). */
2795
2796PyOS_sighandler_t
2797PyOS_getsig(int sig)
2798{
2799#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002800 struct sigaction context;
2801 if (sigaction(sig, NULL, &context) == -1)
2802 return SIG_ERR;
2803 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002804#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002805 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002806/* Special signal handling for the secure CRT in Visual Studio 2005 */
2807#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002808 switch (sig) {
2809 /* Only these signals are valid */
2810 case SIGINT:
2811 case SIGILL:
2812 case SIGFPE:
2813 case SIGSEGV:
2814 case SIGTERM:
2815 case SIGBREAK:
2816 case SIGABRT:
2817 break;
2818 /* Don't call signal() with other values or it will assert */
2819 default:
2820 return SIG_ERR;
2821 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002822#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002823 handler = signal(sig, SIG_IGN);
2824 if (handler != SIG_ERR)
2825 signal(sig, handler);
2826 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002827#endif
2828}
2829
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002830/*
2831 * All of the code in this function must only use async-signal-safe functions,
2832 * listed at `man 7 signal` or
2833 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2834 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002835PyOS_sighandler_t
2836PyOS_setsig(int sig, PyOS_sighandler_t handler)
2837{
2838#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002839 /* Some code in Modules/signalmodule.c depends on sigaction() being
2840 * used here if HAVE_SIGACTION is defined. Fix that if this code
2841 * changes to invalidate that assumption.
2842 */
2843 struct sigaction context, ocontext;
2844 context.sa_handler = handler;
2845 sigemptyset(&context.sa_mask);
2846 context.sa_flags = 0;
2847 if (sigaction(sig, &context, &ocontext) == -1)
2848 return SIG_ERR;
2849 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002850#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002851 PyOS_sighandler_t oldhandler;
2852 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002853#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002854 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002855#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002856 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002857#endif
2858}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002859
2860/* Deprecated C API functions still provided for binary compatiblity */
2861
2862#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002863PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002864PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2865{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002866 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002867}
2868
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002869#undef PyParser_SimpleParseString
2870PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002871PyParser_SimpleParseString(const char *str, int start)
2872{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002873 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002874}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002875
2876#undef PyRun_AnyFile
2877PyAPI_FUNC(int)
2878PyRun_AnyFile(FILE *fp, const char *name)
2879{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002880 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002881}
2882
2883#undef PyRun_AnyFileEx
2884PyAPI_FUNC(int)
2885PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2886{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002887 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002888}
2889
2890#undef PyRun_AnyFileFlags
2891PyAPI_FUNC(int)
2892PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2893{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002894 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002895}
2896
2897#undef PyRun_File
2898PyAPI_FUNC(PyObject *)
2899PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2900{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002901 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002902}
2903
2904#undef PyRun_FileEx
2905PyAPI_FUNC(PyObject *)
2906PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2907{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002908 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002909}
2910
2911#undef PyRun_FileFlags
2912PyAPI_FUNC(PyObject *)
2913PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002914 PyCompilerFlags *flags)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002915{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002916 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002917}
2918
2919#undef PyRun_SimpleFile
2920PyAPI_FUNC(int)
2921PyRun_SimpleFile(FILE *f, const char *p)
2922{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002923 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002924}
2925
2926#undef PyRun_SimpleFileEx
2927PyAPI_FUNC(int)
2928PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2929{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002930 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002931}
2932
2933
2934#undef PyRun_String
2935PyAPI_FUNC(PyObject *)
2936PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2937{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002938 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002939}
2940
2941#undef PyRun_SimpleString
2942PyAPI_FUNC(int)
2943PyRun_SimpleString(const char *s)
2944{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002945 return PyRun_SimpleStringFlags(s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002946}
2947
2948#undef Py_CompileString
2949PyAPI_FUNC(PyObject *)
2950Py_CompileString(const char *str, const char *p, int s)
2951{
Georg Brandl8334fd92010-12-04 10:26:46 +00002952 return Py_CompileStringExFlags(str, p, s, NULL, -1);
2953}
2954
2955#undef Py_CompileStringFlags
2956PyAPI_FUNC(PyObject *)
2957Py_CompileStringFlags(const char *str, const char *p, int s,
2958 PyCompilerFlags *flags)
2959{
2960 return Py_CompileStringExFlags(str, p, s, flags, -1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002961}
2962
2963#undef PyRun_InteractiveOne
2964PyAPI_FUNC(int)
2965PyRun_InteractiveOne(FILE *f, const char *p)
2966{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002967 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002968}
2969
2970#undef PyRun_InteractiveLoop
2971PyAPI_FUNC(int)
2972PyRun_InteractiveLoop(FILE *f, const char *p)
2973{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002974 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002975}
2976
2977#ifdef __cplusplus
2978}
2979#endif