blob: b2d54641910359ff0775c6732a32c5d5014bb130 [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"
Victor Stinner518e6102014-03-18 02:06:38 +010018#include <locale.h>
Guido van Rossum1984f1e1992-08-04 12:41:02 +000019
Thomas Wouters0e3f5912006-08-11 14:57:12 +000020#ifdef HAVE_SIGNAL_H
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000021#include <signal.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000022#endif
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000023
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000024#ifdef MS_WINDOWS
Martin v. Löwis5c88d812009-01-02 20:47:48 +000025#include "malloc.h" /* for alloca */
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000026#endif
Martin v. Löwis5c88d812009-01-02 20:47:48 +000027
Martin v. Löwis73d538b2003-03-05 15:13:47 +000028#ifdef HAVE_LANGINFO_H
Martin v. Löwis73d538b2003-03-05 15:13:47 +000029#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
doko@ubuntu.com4a173bc2014-04-17 19:47:16 +020038#ifdef __gnu_hurd__
39#define PATH_MAX MAXPATHLEN
40#endif
41
Victor Stinnerbd303c12013-11-07 23:07:29 +010042_Py_IDENTIFIER(builtins);
Victor Stinner09054372013-11-06 22:41:44 +010043_Py_IDENTIFIER(excepthook);
Victor Stinner3f36a572013-11-12 21:39:02 +010044_Py_IDENTIFIER(flush);
Victor Stinnerbd303c12013-11-07 23:07:29 +010045_Py_IDENTIFIER(last_traceback);
Victor Stinner09054372013-11-06 22:41:44 +010046_Py_IDENTIFIER(last_type);
47_Py_IDENTIFIER(last_value);
Victor Stinner3f36a572013-11-12 21:39:02 +010048_Py_IDENTIFIER(name);
Victor Stinnerbd303c12013-11-07 23:07:29 +010049_Py_IDENTIFIER(ps1);
50_Py_IDENTIFIER(ps2);
51_Py_IDENTIFIER(stdin);
52_Py_IDENTIFIER(stdout);
53_Py_IDENTIFIER(stderr);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +010054_Py_static_string(PyId_string, "<string>");
Victor Stinner09054372013-11-06 22:41:44 +010055
Ezio Melotti1f8898a2013-03-26 01:59:56 +020056#ifdef Py_REF_DEBUG
Antoine Pitrou208ac5c2013-04-24 20:17:53 +020057static
58void _print_total_refs(void) {
Victor Stinner4ee41c52013-11-06 18:28:21 +010059 PyObject *xoptions, *value;
60 _Py_IDENTIFIER(showrefcount);
61
Ezio Melotti1f8898a2013-03-26 01:59:56 +020062 xoptions = PySys_GetXOptions();
63 if (xoptions == NULL)
64 return;
Victor Stinner4ee41c52013-11-06 18:28:21 +010065 value = _PyDict_GetItemId(xoptions, &PyId_showrefcount);
Ezio Melotti1f8898a2013-03-26 01:59:56 +020066 if (value == Py_True)
67 fprintf(stderr,
68 "[%" PY_FORMAT_SIZE_T "d refs, "
69 "%" PY_FORMAT_SIZE_T "d blocks]\n",
70 _Py_GetRefTotal(), _Py_GetAllocatedBlocks());
71}
72#endif
73
Neal Norwitz4281cef2006-03-04 19:58:13 +000074#ifndef Py_REF_DEBUG
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000075#define PRINT_TOTAL_REFS()
Neal Norwitz4281cef2006-03-04 19:58:13 +000076#else /* Py_REF_DEBUG */
Ezio Melotti1f8898a2013-03-26 01:59:56 +020077#define PRINT_TOTAL_REFS() _print_total_refs()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000078#endif
79
80#ifdef __cplusplus
81extern "C" {
Neal Norwitz4281cef2006-03-04 19:58:13 +000082#endif
83
Martin v. Löwis790465f2008-04-05 20:41:37 +000084extern wchar_t *Py_GetPath(void);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000085
Guido van Rossum82598051997-03-05 00:20:32 +000086extern grammar _PyParser_Grammar; /* From graminit.c */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000087
Guido van Rossumb73cc041993-11-01 16:28:59 +000088/* Forward */
Nick Coghlan85e729e2012-07-15 18:09:52 +100089static void initmain(PyInterpreterState *interp);
Victor Stinner793b5312011-04-27 00:24:21 +020090static int initfsencoding(PyInterpreterState *interp);
Tim Petersdbd9ba62000-07-09 03:09:57 +000091static void initsite(void);
Guido van Rossumce3a72a2007-10-19 23:16:50 +000092static int initstdio(void);
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +000093static void flush_io(void);
Victor Stinner95701bd2013-11-06 18:41:07 +010094static PyObject *run_mod(mod_ty, PyObject *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000095 PyCompilerFlags *, PyArena *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000096static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000097 PyCompilerFlags *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000098static void err_input(perrdetail *);
Victor Stinner7f2fee32011-04-05 00:39:01 +020099static void err_free(perrdetail *);
Tim Petersdbd9ba62000-07-09 03:09:57 +0000100static void initsigs(void);
Collin Winter670e6922007-03-21 02:57:17 +0000101static void call_py_exitfuncs(void);
Antoine Pitrou011bd622009-10-20 21:52:47 +0000102static void wait_for_thread_shutdown(void);
Tim Petersdbd9ba62000-07-09 03:09:57 +0000103static void call_ll_exitfuncs(void);
Victor Stinner3a50e702011-10-18 21:21:00 +0200104extern int _PyUnicode_Init(void);
Victor Stinner26f91992013-07-17 01:22:45 +0200105extern int _PyStructSequence_Init(void);
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000106extern void _PyUnicode_Fini(void);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000107extern int _PyLong_Init(void);
108extern void PyLong_Fini(void);
Victor Stinner024e37a2011-03-31 01:31:06 +0200109extern int _PyFaulthandler_Init(void);
110extern void _PyFaulthandler_Fini(void);
Christian Heimes985ecdc2013-11-20 11:46:18 +0100111extern void _PyHash_Fini(void);
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100112extern int _PyTraceMalloc_Init(void);
Victor Stinnerbe0708f2013-12-01 10:03:26 +0100113extern int _PyTraceMalloc_Fini(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +0000114
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000115#ifdef WITH_THREAD
116extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
117extern void _PyGILState_Fini(void);
118#endif /* WITH_THREAD */
119
Guido van Rossum82598051997-03-05 00:20:32 +0000120int Py_DebugFlag; /* Needed by parser.c */
121int Py_VerboseFlag; /* Needed by import.c */
Georg Brandl8aa7e992010-12-28 18:30:18 +0000122int Py_QuietFlag; /* Needed by sysmodule.c */
Guido van Rossum7433b121997-02-14 19:45:36 +0000123int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Georg Brandl0b2489e2011-05-15 08:49:12 +0200124int Py_InspectFlag; /* Needed to determine whether to exit at SystemExit */
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000125int Py_NoSiteFlag; /* Suppress 'import site' */
Guido van Rossum98297ee2007-11-06 21:34:58 +0000126int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
Christian Heimes790c8232008-01-07 21:14:23 +0000127int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.py[co]) */
Barry Warsaw3ce09642000-05-02 19:18:59 +0000128int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +0000129int Py_FrozenFlag; /* Needed by getpath.c */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000130int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Christian Heimes8dc226f2008-05-06 23:45:46 +0000131int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
Antoine Pitrou05608432009-01-09 18:53:14 +0000132int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100133int Py_HashRandomizationFlag = 0; /* for -R and PYTHONHASHSEED */
Christian Heimesad73a9c2013-08-10 16:36:18 +0200134int Py_IsolatedFlag = 0; /* for -I, isolate from user's env */
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000135
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200136PyThreadState *_Py_Finalizing = NULL;
137
Christian Heimes49e61802013-10-22 10:22:29 +0200138/* Hack to force loading of object files */
139int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
140 PyOS_mystrnicmp; /* Python/pystrcmp.o */
141
Christian Heimes33fe8092008-04-13 13:53:33 +0000142/* PyModule_GetWarningsModule is no longer necessary as of 2.6
143since _warnings is builtin. This API should not be used. */
144PyObject *
145PyModule_GetWarningsModule(void)
Mark Hammondedd07732003-07-15 23:03:55 +0000146{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000147 return PyImport_ImportModule("warnings");
Mark Hammondedd07732003-07-15 23:03:55 +0000148}
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000149
Guido van Rossum25ce5661997-08-02 03:10:38 +0000150static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000151
Thomas Wouters7e474022000-07-16 12:04:32 +0000152/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000153
154int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000155Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000156{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000157 return initialized;
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000158}
159
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000160/* Helper to allow an embedding application to override the normal
161 * mechanism that attempts to figure out an appropriate IO encoding
162 */
163
164static char *_Py_StandardStreamEncoding = NULL;
165static char *_Py_StandardStreamErrors = NULL;
166
167int
168Py_SetStandardStreamEncoding(const char *encoding, const char *errors)
169{
170 if (Py_IsInitialized()) {
171 /* This is too late to have any effect */
172 return -1;
173 }
Nick Coghlan1805a622013-10-18 23:11:47 +1000174 /* Can't call PyErr_NoMemory() on errors, as Python hasn't been
175 * initialised yet.
176 *
177 * However, the raw memory allocators are initialised appropriately
178 * as C static variables, so _PyMem_RawStrdup is OK even though
179 * Py_Initialize hasn't been called yet.
180 */
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000181 if (encoding) {
182 _Py_StandardStreamEncoding = _PyMem_RawStrdup(encoding);
183 if (!_Py_StandardStreamEncoding) {
Nick Coghlan1805a622013-10-18 23:11:47 +1000184 return -2;
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000185 }
186 }
187 if (errors) {
188 _Py_StandardStreamErrors = _PyMem_RawStrdup(errors);
189 if (!_Py_StandardStreamErrors) {
190 if (_Py_StandardStreamEncoding) {
191 PyMem_RawFree(_Py_StandardStreamEncoding);
192 }
Nick Coghlan1805a622013-10-18 23:11:47 +1000193 return -3;
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000194 }
195 }
196 return 0;
197}
198
Guido van Rossum25ce5661997-08-02 03:10:38 +0000199/* Global initializations. Can be undone by Py_Finalize(). Don't
200 call this twice without an intervening Py_Finalize() call. When
201 initializations fail, a fatal error is issued and the function does
202 not return. On return, the first thread and interpreter state have
203 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000204
Guido van Rossum25ce5661997-08-02 03:10:38 +0000205 Locking: you must hold the interpreter lock while calling this.
206 (If the lock has not yet been initialized, that's equivalent to
207 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000208
Guido van Rossum25ce5661997-08-02 03:10:38 +0000209*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000210
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000211static int
212add_flag(int flag, const char *envs)
213{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000214 int env = atoi(envs);
215 if (flag < env)
216 flag = env;
217 if (flag < 1)
218 flag = 1;
219 return flag;
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000220}
221
Christian Heimes5833a2f2008-10-30 21:40:04 +0000222static char*
Victor Stinner94908bb2010-08-18 21:23:25 +0000223get_codec_name(const char *encoding)
Christian Heimes5833a2f2008-10-30 21:40:04 +0000224{
Victor Stinner94908bb2010-08-18 21:23:25 +0000225 char *name_utf8, *name_str;
Victor Stinner386fe712010-05-19 00:34:15 +0000226 PyObject *codec, *name = NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000227
Victor Stinner94908bb2010-08-18 21:23:25 +0000228 codec = _PyCodec_Lookup(encoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 if (!codec)
230 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000231
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200232 name = _PyObject_GetAttrId(codec, &PyId_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233 Py_CLEAR(codec);
234 if (!name)
235 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000236
Victor Stinner94908bb2010-08-18 21:23:25 +0000237 name_utf8 = _PyUnicode_AsString(name);
Victor Stinner4ca28092011-03-20 23:09:03 +0100238 if (name_utf8 == NULL)
Victor Stinner386fe712010-05-19 00:34:15 +0000239 goto error;
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200240 name_str = _PyMem_RawStrdup(name_utf8);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000241 Py_DECREF(name);
Victor Stinner94908bb2010-08-18 21:23:25 +0000242 if (name_str == NULL) {
243 PyErr_NoMemory();
244 return NULL;
245 }
246 return name_str;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000247
248error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 Py_XDECREF(codec);
Victor Stinner386fe712010-05-19 00:34:15 +0000250 Py_XDECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000252}
Victor Stinner94908bb2010-08-18 21:23:25 +0000253
Victor Stinner94908bb2010-08-18 21:23:25 +0000254static char*
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200255get_locale_encoding(void)
Victor Stinner94908bb2010-08-18 21:23:25 +0000256{
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200257#ifdef MS_WINDOWS
258 char codepage[100];
259 PyOS_snprintf(codepage, sizeof(codepage), "cp%d", GetACP());
260 return get_codec_name(codepage);
261#elif defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94908bb2010-08-18 21:23:25 +0000262 char* codeset = nl_langinfo(CODESET);
263 if (!codeset || codeset[0] == '\0') {
264 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
265 return NULL;
266 }
267 return get_codec_name(codeset);
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200268#else
269 PyErr_SetNone(PyExc_NotImplementedError);
270 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000271#endif
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200272}
Christian Heimes5833a2f2008-10-30 21:40:04 +0000273
Brett Cannonfd074152012-04-14 14:10:13 -0400274static void
275import_init(PyInterpreterState *interp, PyObject *sysmod)
276{
277 PyObject *importlib;
278 PyObject *impmod;
279 PyObject *sys_modules;
280 PyObject *value;
281
282 /* Import _importlib through its frozen version, _frozen_importlib. */
Brett Cannonfd074152012-04-14 14:10:13 -0400283 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
284 Py_FatalError("Py_Initialize: can't import _frozen_importlib");
285 }
286 else if (Py_VerboseFlag) {
287 PySys_FormatStderr("import _frozen_importlib # frozen\n");
288 }
289 importlib = PyImport_AddModule("_frozen_importlib");
290 if (importlib == NULL) {
291 Py_FatalError("Py_Initialize: couldn't get _frozen_importlib from "
292 "sys.modules");
293 }
294 interp->importlib = importlib;
295 Py_INCREF(interp->importlib);
296
297 /* Install _importlib as __import__ */
298 impmod = PyInit_imp();
299 if (impmod == NULL) {
300 Py_FatalError("Py_Initialize: can't import imp");
301 }
302 else if (Py_VerboseFlag) {
303 PySys_FormatStderr("import imp # builtin\n");
304 }
305 sys_modules = PyImport_GetModuleDict();
306 if (Py_VerboseFlag) {
307 PySys_FormatStderr("import sys # builtin\n");
308 }
Brett Cannon6f44d662012-04-15 16:08:47 -0400309 if (PyDict_SetItemString(sys_modules, "_imp", impmod) < 0) {
310 Py_FatalError("Py_Initialize: can't save _imp to sys.modules");
Brett Cannonfd074152012-04-14 14:10:13 -0400311 }
312
Brett Cannone0d88a12012-04-25 20:54:04 -0400313 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
Brett Cannonfd074152012-04-14 14:10:13 -0400314 if (value == NULL) {
315 PyErr_Print();
316 Py_FatalError("Py_Initialize: importlib install failed");
317 }
318 Py_DECREF(value);
Brett Cannonfc9ca272012-04-15 01:35:05 -0400319 Py_DECREF(impmod);
Brett Cannonfd074152012-04-14 14:10:13 -0400320
321 _PyImportZip_Init();
322}
323
324
Guido van Rossuma027efa1997-05-05 20:56:21 +0000325void
Antoine Pitroue67f48c2012-06-19 22:29:35 +0200326_Py_InitializeEx_Private(int install_sigs, int install_importlib)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000327{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000328 PyInterpreterState *interp;
329 PyThreadState *tstate;
330 PyObject *bimod, *sysmod, *pstderr;
331 char *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 if (initialized)
335 return;
336 initialized = 1;
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200337 _Py_Finalizing = NULL;
Tim Petersd08e3822003-04-17 15:24:21 +0000338
Andrew M. Kuchlingb2ceb3a2010-02-22 23:26:10 +0000339#if defined(HAVE_LANGINFO_H) && defined(HAVE_SETLOCALE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000340 /* Set up the LC_CTYPE locale, so we can obtain
341 the locale's charset without having to switch
342 locales. */
343 setlocale(LC_CTYPE, "");
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +0000344#endif
345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000346 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
347 Py_DebugFlag = add_flag(Py_DebugFlag, p);
348 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
349 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
350 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
351 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
352 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
353 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100354 /* The variable is only tested for existence here; _PyRandom_Init will
355 check its value further. */
356 if ((p = Py_GETENV("PYTHONHASHSEED")) && *p != '\0')
357 Py_HashRandomizationFlag = add_flag(Py_HashRandomizationFlag, p);
358
359 _PyRandom_Init();
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000361 interp = PyInterpreterState_New();
362 if (interp == NULL)
363 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000365 tstate = PyThreadState_New(interp);
366 if (tstate == NULL)
367 Py_FatalError("Py_Initialize: can't make first thread");
368 (void) PyThreadState_Swap(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000369
Victor Stinner6961bd62010-08-17 22:26:51 +0000370#ifdef WITH_THREAD
Antoine Pitroub0b384b2010-09-20 20:13:48 +0000371 /* We can't call _PyEval_FiniThreads() in Py_Finalize because
372 destroying the GIL might fail when it is being referenced from
373 another running thread (see issue #9901).
374 Instead we destroy the previously created GIL here, which ensures
375 that we can call Py_Initialize / Py_Finalize multiple times. */
376 _PyEval_FiniThreads();
377
378 /* Auto-thread-state API */
Victor Stinner6961bd62010-08-17 22:26:51 +0000379 _PyGILState_Init(interp, tstate);
380#endif /* WITH_THREAD */
381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 if (!_PyFrame_Init())
385 Py_FatalError("Py_Initialize: can't init frames");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000387 if (!_PyLong_Init())
388 Py_FatalError("Py_Initialize: can't init longs");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000390 if (!PyByteArray_Init())
391 Py_FatalError("Py_Initialize: can't init bytearray");
Neal Norwitz6968b052007-02-27 19:02:19 +0000392
Victor Stinner1c8f0592013-07-22 22:24:54 +0200393 if (!_PyFloat_Init())
394 Py_FatalError("Py_Initialize: can't init float");
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000396 interp->modules = PyDict_New();
397 if (interp->modules == NULL)
398 Py_FatalError("Py_Initialize: can't make modules dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 /* Init Unicode implementation; relies on the codec registry */
Victor Stinner3a50e702011-10-18 21:21:00 +0200401 if (_PyUnicode_Init() < 0)
402 Py_FatalError("Py_Initialize: can't initialize unicode");
Victor Stinner26f91992013-07-17 01:22:45 +0200403 if (_PyStructSequence_Init() < 0)
404 Py_FatalError("Py_Initialize: can't initialize structseq");
Guido van Rossumc94044c2000-03-10 23:03:54 +0000405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000406 bimod = _PyBuiltin_Init();
407 if (bimod == NULL)
408 Py_FatalError("Py_Initialize: can't initialize builtins modules");
Victor Stinner49d3f252010-10-17 01:24:53 +0000409 _PyImport_FixupBuiltin(bimod, "builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000410 interp->builtins = PyModule_GetDict(bimod);
411 if (interp->builtins == NULL)
412 Py_FatalError("Py_Initialize: can't initialize builtins dict");
413 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415 /* initialize builtin exceptions */
Brett Cannonfd074152012-04-14 14:10:13 -0400416 _PyExc_Init(bimod);
Christian Heimes9a68f8c2007-11-14 00:16:07 +0000417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 sysmod = _PySys_Init();
419 if (sysmod == NULL)
420 Py_FatalError("Py_Initialize: can't initialize sys");
421 interp->sysdict = PyModule_GetDict(sysmod);
422 if (interp->sysdict == NULL)
423 Py_FatalError("Py_Initialize: can't initialize sys dict");
424 Py_INCREF(interp->sysdict);
Victor Stinner49d3f252010-10-17 01:24:53 +0000425 _PyImport_FixupBuiltin(sysmod, "sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 PySys_SetPath(Py_GetPath());
427 PyDict_SetItemString(interp->sysdict, "modules",
428 interp->modules);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000430 /* Set up a preliminary stderr printer until we have enough
431 infrastructure for the io module in place. */
432 pstderr = PyFile_NewStdPrinter(fileno(stderr));
433 if (pstderr == NULL)
434 Py_FatalError("Py_Initialize: can't set preliminary stderr");
Victor Stinnerbd303c12013-11-07 23:07:29 +0100435 _PySys_SetObjectId(&PyId_stderr, pstderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000436 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000437 Py_DECREF(pstderr);
Guido van Rossum826d8972007-10-30 18:34:07 +0000438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 _PyImport_Init();
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000441 _PyImportHooks_Init();
Just van Rossum52e14d62002-12-30 22:08:05 +0000442
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000443 /* Initialize _warnings. */
444 _PyWarnings_Init();
445
Antoine Pitroue67f48c2012-06-19 22:29:35 +0200446 if (!install_importlib)
447 return;
448
Brett Cannonfd074152012-04-14 14:10:13 -0400449 import_init(interp, sysmod);
450
Victor Stinnerd5698cb2012-07-31 02:55:49 +0200451 /* initialize the faulthandler module */
452 if (_PyFaulthandler_Init())
453 Py_FatalError("Py_Initialize: can't initialize faulthandler");
454
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +0000455 _PyTime_Init();
456
Victor Stinner793b5312011-04-27 00:24:21 +0200457 if (initfsencoding(interp) < 0)
458 Py_FatalError("Py_Initialize: unable to load the file system codec");
Martin v. Löwis011e8422009-05-05 04:43:17 +0000459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 if (install_sigs)
461 initsigs(); /* Signal handling stuff, including initintr() */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000462
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100463 if (_PyTraceMalloc_Init() < 0)
464 Py_FatalError("Py_Initialize: can't initialize tracemalloc");
465
Nick Coghlan85e729e2012-07-15 18:09:52 +1000466 initmain(interp); /* Module __main__ */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 if (initstdio() < 0)
468 Py_FatalError(
469 "Py_Initialize: can't initialize sys standard streams");
470
Antoine Pitroucf9f9802010-11-10 13:55:25 +0000471 /* Initialize warnings. */
472 if (PySys_HasWarnOptions()) {
473 PyObject *warnings_module = PyImport_ImportModule("warnings");
474 if (warnings_module == NULL) {
475 fprintf(stderr, "'import warnings' failed; traceback:\n");
476 PyErr_Print();
477 }
478 Py_XDECREF(warnings_module);
479 }
480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 if (!Py_NoSiteFlag)
482 initsite(); /* Module site */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000483}
484
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000485void
Antoine Pitroue67f48c2012-06-19 22:29:35 +0200486Py_InitializeEx(int install_sigs)
487{
488 _Py_InitializeEx_Private(install_sigs, 1);
489}
490
491void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000492Py_Initialize(void)
493{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 Py_InitializeEx(1);
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000495}
496
497
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000498#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000499extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000500#endif
501
Guido van Rossume8432ac2007-07-09 15:04:50 +0000502/* Flush stdout and stderr */
503
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100504static int
505file_is_closed(PyObject *fobj)
506{
507 int r;
508 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
509 if (tmp == NULL) {
510 PyErr_Clear();
511 return 0;
512 }
513 r = PyObject_IsTrue(tmp);
514 Py_DECREF(tmp);
515 if (r < 0)
516 PyErr_Clear();
517 return r > 0;
518}
519
Neal Norwitz2bad9702007-08-27 06:19:22 +0000520static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000521flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000522{
Victor Stinnerbd303c12013-11-07 23:07:29 +0100523 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
524 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 PyObject *tmp;
Guido van Rossume8432ac2007-07-09 15:04:50 +0000526
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100527 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200528 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000529 if (tmp == NULL)
Antoine Pitroubddc9fe2010-08-08 20:46:42 +0000530 PyErr_WriteUnraisable(fout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 else
532 Py_DECREF(tmp);
533 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000534
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100535 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200536 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 if (tmp == NULL)
538 PyErr_Clear();
539 else
540 Py_DECREF(tmp);
541 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000542}
543
Guido van Rossum25ce5661997-08-02 03:10:38 +0000544/* Undo the effect of Py_Initialize().
545
546 Beware: if multiple interpreter and/or thread states exist, these
547 are not wiped out; only the current thread and interpreter state
548 are deleted. But since everything else is deleted, those other
549 interpreter and thread states should no longer be used.
550
551 (XXX We should do better, e.g. wipe out all interpreters and
552 threads.)
553
554 Locking: as above.
555
556*/
557
558void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000559Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000560{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 PyInterpreterState *interp;
562 PyThreadState *tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564 if (!initialized)
565 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 wait_for_thread_shutdown();
Antoine Pitrou011bd622009-10-20 21:52:47 +0000568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000569 /* The interpreter is still entirely intact at this point, and the
570 * exit funcs may be relying on that. In particular, if some thread
571 * or exit func is still waiting to do an import, the import machinery
572 * expects Py_IsInitialized() to return true. So don't say the
573 * interpreter is uninitialized until after the exit funcs have run.
574 * Note that Threading.py uses an exit func to do a join on all the
575 * threads created thru it, so this also protects pending imports in
576 * the threads created via Threading.
577 */
578 call_py_exitfuncs();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 /* Get current thread state and interpreter pointer */
581 tstate = PyThreadState_GET();
582 interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000583
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200584 /* Remaining threads (e.g. daemon threads) will automatically exit
585 after taking the GIL (in PyEval_RestoreThread()). */
586 _Py_Finalizing = tstate;
587 initialized = 0;
588
Victor Stinner15054c12014-02-13 12:48:54 +0100589 /* Flush stdout+stderr */
590 flush_std_files();
591
592 /* Disable signal handling */
593 PyOS_FiniInterrupts();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 /* Collect garbage. This may call finalizers; it's nice to call these
596 * before all modules are destroyed.
597 * XXX If a __del__ or weakref callback is triggered here, and tries to
598 * XXX import a module, bad things can happen, because Python no
599 * XXX longer believes it's initialized.
600 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
601 * XXX is easy to provoke that way. I've also seen, e.g.,
602 * XXX Exception exceptions.ImportError: 'No module named sha'
603 * XXX in <function callback at 0x008F5718> ignored
604 * XXX but I'm unclear on exactly how that one happens. In any case,
605 * XXX I haven't seen a real-life report of either of these.
606 */
607 PyGC_Collect();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000608#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 /* With COUNT_ALLOCS, it helps to run GC multiple times:
610 each collection might release some types from the type
611 list, so they become garbage. */
612 while (PyGC_Collect() > 0)
613 /* nothing */;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000614#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 /* Destroy all modules */
616 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 /* Flush stdout+stderr (again, in case more was printed) */
619 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 /* Collect final garbage. This disposes of cycles created by
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100622 * class definitions, for example.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000623 * XXX This is disabled because it caused too many problems. If
624 * XXX a __del__ or weakref callback triggers here, Python code has
625 * XXX a hard time running, because even the sys module has been
626 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
627 * XXX One symptom is a sequence of information-free messages
628 * XXX coming from threads (if a __del__ or callback is invoked,
629 * XXX other threads can execute too, and any exception they encounter
630 * XXX triggers a comedy of errors as subsystem after subsystem
631 * XXX fails to find what it *expects* to find in sys to help report
632 * XXX the exception and consequent unexpected failures). I've also
633 * XXX seen segfaults then, after adding print statements to the
634 * XXX Python code getting called.
635 */
Tim Peters1d7323e2003-12-01 21:35:27 +0000636#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000637 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000638#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000639
Victor Stinnerbe0708f2013-12-01 10:03:26 +0100640 /* Disable tracemalloc after all Python objects have been destroyed,
641 so it is possible to use tracemalloc in objects destructor. */
642 _PyTraceMalloc_Fini();
643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
645 _PyImport_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000646
Antoine Pitroufd417cc2013-05-05 08:12:42 +0200647 /* Cleanup typeobject.c's internal caches. */
648 _PyType_Fini();
649
Victor Stinner024e37a2011-03-31 01:31:06 +0200650 /* unload faulthandler module */
651 _PyFaulthandler_Fini();
652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 /* Debugging stuff */
Guido van Rossum1707aad1997-12-08 23:43:45 +0000654#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000656#endif
Christian Heimes985ecdc2013-11-20 11:46:18 +0100657 /* dump hash stats */
658 _PyHash_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000659
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000661
Tim Peters9cf25ce2003-04-17 15:21:01 +0000662#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000663 /* Display all objects still alive -- this can invoke arbitrary
664 * __repr__ overrides, so requires a mostly-intact interpreter.
665 * Alas, a lot of stuff may still be alive now that will be cleaned
666 * up later.
667 */
668 if (Py_GETENV("PYTHONDUMPREFS"))
669 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000670#endif /* Py_TRACE_REFS */
671
Antoine Pitroufd417cc2013-05-05 08:12:42 +0200672 /* Clear interpreter state and all thread states. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000673 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 /* Now we decref the exception classes. After this point nothing
676 can raise an exception. That's okay, because each Fini() method
677 below has been checked to make sure no exceptions are ever
678 raised.
679 */
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 _PyExc_Fini();
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000682
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000683 /* Sundry finalizers */
684 PyMethod_Fini();
685 PyFrame_Fini();
686 PyCFunction_Fini();
687 PyTuple_Fini();
688 PyList_Fini();
689 PySet_Fini();
690 PyBytes_Fini();
691 PyByteArray_Fini();
692 PyLong_Fini();
693 PyFloat_Fini();
694 PyDict_Fini();
Antoine Pitrouf34a0cd2011-11-18 20:14:34 +0100695 PySlice_Fini();
Antoine Pitrou5f454a02013-05-06 21:15:57 +0200696 _PyGC_Fini();
Antoine Pitrou4879a962013-08-31 00:26:02 +0200697 _PyRandom_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 /* Cleanup Unicode implementation */
700 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 /* reset file system default encoding */
Victor Stinnerb744ba12010-05-15 12:27:16 +0000703 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200704 PyMem_RawFree((char*)Py_FileSystemDefaultEncoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 Py_FileSystemDefaultEncoding = NULL;
706 }
Christian Heimesc8967002007-11-30 10:18:26 +0000707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 /* XXX Still allocated:
709 - various static ad-hoc pointers to interned strings
710 - int and float free list blocks
711 - whatever various modules and libraries allocate
712 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000715
Victor Stinner51fa4582013-07-07 15:50:49 +0200716 /* Cleanup auto-thread-state */
717#ifdef WITH_THREAD
718 _PyGILState_Fini();
719#endif /* WITH_THREAD */
720
721 /* Delete current thread. After this, many C API calls become crashy. */
722 PyThreadState_Swap(NULL);
723 PyInterpreterState_Delete(interp);
724
Tim Peters269b2a62003-04-17 19:52:29 +0000725#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 /* Display addresses (& refcnts) of all objects still alive.
727 * An address can be used to find the repr of the object, printed
728 * above by _Py_PrintReferences.
729 */
730 if (Py_GETENV("PYTHONDUMPREFS"))
731 _Py_PrintReferenceAddresses(stderr);
Tim Peters269b2a62003-04-17 19:52:29 +0000732#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000733#ifdef PYMALLOC_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 if (Py_GETENV("PYTHONMALLOCSTATS"))
David Malcolm49526f42012-06-22 14:55:41 -0400735 _PyObject_DebugMallocStats(stderr);
Tim Peters0e871182002-04-13 08:29:14 +0000736#endif
737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000738 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000739}
740
741/* Create and initialize a new interpreter and thread, and return the
742 new thread. This requires that Py_Initialize() has been called
743 first.
744
745 Unsuccessful initialization yields a NULL pointer. Note that *no*
746 exception information is available even in this case -- the
747 exception information is held in the thread, and there is no
748 thread.
749
750 Locking: as above.
751
752*/
753
754PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000755Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000756{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000757 PyInterpreterState *interp;
758 PyThreadState *tstate, *save_tstate;
759 PyObject *bimod, *sysmod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 if (!initialized)
762 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 interp = PyInterpreterState_New();
765 if (interp == NULL)
766 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 tstate = PyThreadState_New(interp);
769 if (tstate == NULL) {
770 PyInterpreterState_Delete(interp);
771 return NULL;
772 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 save_tstate = PyThreadState_Swap(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000776 /* XXX The following is lax in error checking */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 interp->modules = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000779
Victor Stinner49d3f252010-10-17 01:24:53 +0000780 bimod = _PyImport_FindBuiltin("builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 if (bimod != NULL) {
782 interp->builtins = PyModule_GetDict(bimod);
783 if (interp->builtins == NULL)
784 goto handle_error;
785 Py_INCREF(interp->builtins);
786 }
Christian Heimes6a27efa2008-10-30 21:48:26 +0000787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000788 /* initialize builtin exceptions */
Brett Cannonfd074152012-04-14 14:10:13 -0400789 _PyExc_Init(bimod);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000790
Victor Stinner49d3f252010-10-17 01:24:53 +0000791 sysmod = _PyImport_FindBuiltin("sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 if (bimod != NULL && sysmod != NULL) {
793 PyObject *pstderr;
Brett Cannonfd074152012-04-14 14:10:13 -0400794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 interp->sysdict = PyModule_GetDict(sysmod);
796 if (interp->sysdict == NULL)
797 goto handle_error;
798 Py_INCREF(interp->sysdict);
799 PySys_SetPath(Py_GetPath());
800 PyDict_SetItemString(interp->sysdict, "modules",
801 interp->modules);
802 /* Set up a preliminary stderr printer until we have enough
803 infrastructure for the io module in place. */
804 pstderr = PyFile_NewStdPrinter(fileno(stderr));
805 if (pstderr == NULL)
806 Py_FatalError("Py_Initialize: can't set preliminary stderr");
Victor Stinnerbd303c12013-11-07 23:07:29 +0100807 _PySys_SetObjectId(&PyId_stderr, pstderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000809 Py_DECREF(pstderr);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 _PyImportHooks_Init();
Victor Stinner793b5312011-04-27 00:24:21 +0200812
Brett Cannonfd074152012-04-14 14:10:13 -0400813 import_init(interp, sysmod);
814
Victor Stinner793b5312011-04-27 00:24:21 +0200815 if (initfsencoding(interp) < 0)
816 goto handle_error;
817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000818 if (initstdio() < 0)
819 Py_FatalError(
820 "Py_Initialize: can't initialize sys standard streams");
Nick Coghlan85e729e2012-07-15 18:09:52 +1000821 initmain(interp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000822 if (!Py_NoSiteFlag)
823 initsite();
824 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 if (!PyErr_Occurred())
827 return tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000828
Thomas Wouters89f507f2006-12-13 04:49:30 +0000829handle_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 /* Oops, it didn't work. Undo it all. */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000831
Victor Stinnerc40a3502011-04-27 00:20:27 +0200832 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 PyThreadState_Clear(tstate);
834 PyThreadState_Swap(save_tstate);
835 PyThreadState_Delete(tstate);
836 PyInterpreterState_Delete(interp);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000839}
840
841/* Delete an interpreter and its last thread. This requires that the
842 given thread state is current, that the thread has no remaining
843 frames, and that it is its interpreter's only remaining thread.
844 It is a fatal error to violate these constraints.
845
846 (Py_Finalize() doesn't have these constraints -- it zaps
847 everything, regardless.)
848
849 Locking: as above.
850
851*/
852
853void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000854Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000855{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856 PyInterpreterState *interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 if (tstate != PyThreadState_GET())
859 Py_FatalError("Py_EndInterpreter: thread is not current");
860 if (tstate->frame != NULL)
861 Py_FatalError("Py_EndInterpreter: thread still has a frame");
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200862
863 wait_for_thread_shutdown();
864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000865 if (tstate != interp->tstate_head || tstate->next != NULL)
866 Py_FatalError("Py_EndInterpreter: not the last thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 PyImport_Cleanup();
869 PyInterpreterState_Clear(interp);
870 PyThreadState_Swap(NULL);
871 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000872}
873
Antoine Pitrou01cca5e2012-07-05 20:56:30 +0200874#ifdef MS_WINDOWS
Martin v. Löwis790465f2008-04-05 20:41:37 +0000875static wchar_t *progname = L"python";
Antoine Pitrou01cca5e2012-07-05 20:56:30 +0200876#else
877static wchar_t *progname = L"python3";
878#endif
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000879
880void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000881Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000882{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 if (pn && *pn)
884 progname = pn;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000885}
886
Martin v. Löwis790465f2008-04-05 20:41:37 +0000887wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000888Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000889{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000891}
892
Martin v. Löwis790465f2008-04-05 20:41:37 +0000893static wchar_t *default_home = NULL;
Victor Stinner55a12202013-08-28 01:47:46 +0200894static wchar_t env_home[MAXPATHLEN+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000895
896void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000897Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000898{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 default_home = home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000900}
901
Martin v. Löwis790465f2008-04-05 20:41:37 +0000902wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000903Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000904{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 wchar_t *home = default_home;
906 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
907 char* chome = Py_GETENV("PYTHONHOME");
908 if (chome) {
Victor Stinner2f5bbc62013-11-15 17:09:24 +0100909 size_t size = Py_ARRAY_LENGTH(env_home);
910 size_t r = mbstowcs(env_home, chome, size);
911 if (r != (size_t)-1 && r < size)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 home = env_home;
913 }
Martin v. Löwis790465f2008-04-05 20:41:37 +0000914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 }
916 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000917}
918
Guido van Rossum6135a871995-01-09 17:53:26 +0000919/* Create __main__ module */
920
921static void
Nick Coghlan85e729e2012-07-15 18:09:52 +1000922initmain(PyInterpreterState *interp)
Guido van Rossum6135a871995-01-09 17:53:26 +0000923{
Brett Cannon13853a62013-05-04 17:37:09 -0400924 PyObject *m, *d, *loader;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 m = PyImport_AddModule("__main__");
926 if (m == NULL)
927 Py_FatalError("can't create __main__ module");
928 d = PyModule_GetDict(m);
929 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
930 PyObject *bimod = PyImport_ImportModule("builtins");
Nick Coghlan85e729e2012-07-15 18:09:52 +1000931 if (bimod == NULL) {
932 Py_FatalError("Failed to retrieve builtins module");
933 }
934 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
935 Py_FatalError("Failed to initialize __main__.__builtins__");
936 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 Py_DECREF(bimod);
938 }
Nick Coghlan85e729e2012-07-15 18:09:52 +1000939 /* Main is a little special - imp.is_builtin("__main__") will return
940 * False, but BuiltinImporter is still the most appropriate initial
941 * setting for its __loader__ attribute. A more suitable value will
942 * be set if __main__ gets further initialized later in the startup
943 * process.
944 */
Brett Cannon13853a62013-05-04 17:37:09 -0400945 loader = PyDict_GetItemString(d, "__loader__");
Brett Cannon4c14b5d2013-05-04 13:56:58 -0400946 if (loader == NULL || loader == Py_None) {
Nick Coghlan85e729e2012-07-15 18:09:52 +1000947 PyObject *loader = PyObject_GetAttrString(interp->importlib,
948 "BuiltinImporter");
949 if (loader == NULL) {
950 Py_FatalError("Failed to retrieve BuiltinImporter");
951 }
952 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
953 Py_FatalError("Failed to initialize __main__.__loader__");
954 }
955 Py_DECREF(loader);
956 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000957}
958
Victor Stinner793b5312011-04-27 00:24:21 +0200959static int
960initfsencoding(PyInterpreterState *interp)
Victor Stinnerb744ba12010-05-15 12:27:16 +0000961{
962 PyObject *codec;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000963
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200964 if (Py_FileSystemDefaultEncoding == NULL)
965 {
966 Py_FileSystemDefaultEncoding = get_locale_encoding();
967 if (Py_FileSystemDefaultEncoding == NULL)
Victor Stinnere4743092010-10-19 00:05:51 +0000968 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
Victor Stinnerb744ba12010-05-15 12:27:16 +0000969
Victor Stinnere4743092010-10-19 00:05:51 +0000970 Py_HasFileSystemDefaultEncoding = 0;
Victor Stinner793b5312011-04-27 00:24:21 +0200971 interp->fscodec_initialized = 1;
972 return 0;
Victor Stinner7f84ab52010-06-11 00:36:33 +0000973 }
Victor Stinnerb744ba12010-05-15 12:27:16 +0000974
975 /* the encoding is mbcs, utf-8 or ascii */
976 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
977 if (!codec) {
978 /* Such error can only occurs in critical situations: no more
979 * memory, import a module of the standard library failed,
980 * etc. */
Victor Stinner793b5312011-04-27 00:24:21 +0200981 return -1;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000982 }
Victor Stinner793b5312011-04-27 00:24:21 +0200983 Py_DECREF(codec);
984 interp->fscodec_initialized = 1;
985 return 0;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000986}
987
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000988/* Import the site module (not into __main__ though) */
989
990static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000991initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000992{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 PyObject *m;
994 m = PyImport_ImportModule("site");
995 if (m == NULL) {
Victor Stinner62ce62a2013-07-22 22:53:28 +0200996 fprintf(stderr, "Failed to import the site module\n");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 PyErr_Print();
998 Py_Finalize();
999 exit(1);
1000 }
1001 else {
1002 Py_DECREF(m);
1003 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +00001004}
1005
Antoine Pitrou05608432009-01-09 18:53:14 +00001006static PyObject*
1007create_stdio(PyObject* io,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 int fd, int write_mode, char* name,
1009 char* encoding, char* errors)
Antoine Pitrou05608432009-01-09 18:53:14 +00001010{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1012 const char* mode;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001013 const char* newline;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 PyObject *line_buffering;
1015 int buffering, isatty;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001016 _Py_IDENTIFIER(open);
1017 _Py_IDENTIFIER(isatty);
1018 _Py_IDENTIFIER(TextIOWrapper);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001019 _Py_IDENTIFIER(mode);
Antoine Pitrou05608432009-01-09 18:53:14 +00001020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 /* stdin is always opened in buffered mode, first because it shouldn't
1022 make a difference in common use cases, second because TextIOWrapper
1023 depends on the presence of a read1() method which only exists on
1024 buffered streams.
1025 */
1026 if (Py_UnbufferedStdioFlag && write_mode)
1027 buffering = 0;
1028 else
1029 buffering = -1;
1030 if (write_mode)
1031 mode = "wb";
1032 else
1033 mode = "rb";
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001034 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1035 fd, mode, buffering,
1036 Py_None, Py_None, Py_None, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 if (buf == NULL)
1038 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +00001039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 if (buffering) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001041 _Py_IDENTIFIER(raw);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001042 raw = _PyObject_GetAttrId(buf, &PyId_raw);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 if (raw == NULL)
1044 goto error;
1045 }
1046 else {
1047 raw = buf;
1048 Py_INCREF(raw);
1049 }
Antoine Pitrou05608432009-01-09 18:53:14 +00001050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 text = PyUnicode_FromString(name);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001052 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 goto error;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001054 res = _PyObject_CallMethodId(raw, &PyId_isatty, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 if (res == NULL)
1056 goto error;
1057 isatty = PyObject_IsTrue(res);
1058 Py_DECREF(res);
1059 if (isatty == -1)
1060 goto error;
1061 if (isatty || Py_UnbufferedStdioFlag)
1062 line_buffering = Py_True;
1063 else
1064 line_buffering = Py_False;
Antoine Pitrou91696412009-01-09 22:12:30 +00001065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001066 Py_CLEAR(raw);
1067 Py_CLEAR(text);
Antoine Pitrou91696412009-01-09 22:12:30 +00001068
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001069#ifdef MS_WINDOWS
Victor Stinner7b3f0fa2012-08-04 01:28:00 +02001070 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1071 newlines to "\n".
1072 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1073 newline = NULL;
1074#else
1075 /* sys.stdin: split lines at "\n".
1076 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1077 newline = "\n";
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001078#endif
1079
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001080 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssO",
1081 buf, encoding, errors,
1082 newline, line_buffering);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 Py_CLEAR(buf);
1084 if (stream == NULL)
1085 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +00001086
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 if (write_mode)
1088 mode = "w";
1089 else
1090 mode = "r";
1091 text = PyUnicode_FromString(mode);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001092 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093 goto error;
1094 Py_CLEAR(text);
1095 return stream;
Antoine Pitrou05608432009-01-09 18:53:14 +00001096
1097error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 Py_XDECREF(buf);
1099 Py_XDECREF(stream);
1100 Py_XDECREF(text);
1101 Py_XDECREF(raw);
1102 return NULL;
Antoine Pitrou05608432009-01-09 18:53:14 +00001103}
1104
Antoine Pitrou11942a52011-11-28 19:08:36 +01001105static int
1106is_valid_fd(int fd)
1107{
1108 int dummy_fd;
1109 if (fd < 0 || !_PyVerify_fd(fd))
1110 return 0;
1111 dummy_fd = dup(fd);
1112 if (dummy_fd < 0)
1113 return 0;
1114 close(dummy_fd);
1115 return 1;
1116}
1117
Georg Brandl1a3284e2007-12-02 09:40:06 +00001118/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001119static int
1120initstdio(void)
1121{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 PyObject *iomod = NULL, *wrapper;
1123 PyObject *bimod = NULL;
1124 PyObject *m;
1125 PyObject *std = NULL;
1126 int status = 0, fd;
1127 PyObject * encoding_attr;
Serhiy Storchakabf28d2d2013-09-13 11:46:24 +03001128 char *pythonioencoding = NULL, *encoding, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 /* Hack to avoid a nasty recursion issue when Python is invoked
1131 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1132 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1133 goto error;
1134 }
1135 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001137 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1138 goto error;
1139 }
1140 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 if (!(bimod = PyImport_ImportModule("builtins"))) {
1143 goto error;
1144 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 if (!(iomod = PyImport_ImportModule("io"))) {
1147 goto error;
1148 }
1149 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1150 goto error;
1151 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 /* Set builtins.open */
1154 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
Antoine Pitrou5a96b522010-11-20 19:50:57 +00001155 Py_DECREF(wrapper);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001156 goto error;
1157 }
Antoine Pitrou5a96b522010-11-20 19:50:57 +00001158 Py_DECREF(wrapper);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001159
Nick Coghlan7d270ee2013-10-17 22:35:35 +10001160 encoding = _Py_StandardStreamEncoding;
1161 errors = _Py_StandardStreamErrors;
1162 if (!encoding || !errors) {
Victor Stinner71430292014-03-18 01:18:21 +01001163 if (!errors) {
1164 /* When the LC_CTYPE locale is the POSIX locale ("C locale"),
1165 stdin and stdout use the surrogateescape error handler by
1166 default, instead of the strict error handler. */
1167 char *loc = setlocale(LC_CTYPE, NULL);
1168 if (loc != NULL && strcmp(loc, "C") == 0)
1169 errors = "surrogateescape";
1170 }
1171
Nick Coghlan7d270ee2013-10-17 22:35:35 +10001172 pythonioencoding = Py_GETENV("PYTHONIOENCODING");
1173 if (pythonioencoding) {
1174 char *err;
1175 pythonioencoding = _PyMem_Strdup(pythonioencoding);
1176 if (pythonioencoding == NULL) {
1177 PyErr_NoMemory();
1178 goto error;
1179 }
1180 err = strchr(pythonioencoding, ':');
1181 if (err) {
1182 *err = '\0';
1183 err++;
Victor Stinner71430292014-03-18 01:18:21 +01001184 if (*err && !_Py_StandardStreamErrors) {
Nick Coghlan7d270ee2013-10-17 22:35:35 +10001185 errors = err;
1186 }
1187 }
1188 if (*pythonioencoding && !encoding) {
1189 encoding = pythonioencoding;
1190 }
Victor Stinner49fc8ec2013-07-07 23:30:24 +02001191 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 }
Martin v. Löwis0f599892008-06-02 11:13:03 +00001193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 /* Set sys.stdin */
1195 fd = fileno(stdin);
1196 /* Under some conditions stdin, stdout and stderr may not be connected
1197 * and fileno() may point to an invalid file descriptor. For example
1198 * GUI apps don't have valid standard streams by default.
1199 */
Antoine Pitrou11942a52011-11-28 19:08:36 +01001200 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 std = Py_None;
1202 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001203 }
1204 else {
1205 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1206 if (std == NULL)
1207 goto error;
1208 } /* if (fd < 0) */
1209 PySys_SetObject("__stdin__", std);
Victor Stinnerbd303c12013-11-07 23:07:29 +01001210 _PySys_SetObjectId(&PyId_stdin, std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001211 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 /* Set sys.stdout */
1214 fd = fileno(stdout);
Antoine Pitrou11942a52011-11-28 19:08:36 +01001215 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216 std = Py_None;
1217 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001218 }
1219 else {
1220 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1221 if (std == NULL)
1222 goto error;
1223 } /* if (fd < 0) */
1224 PySys_SetObject("__stdout__", std);
Victor Stinnerbd303c12013-11-07 23:07:29 +01001225 _PySys_SetObjectId(&PyId_stdout, std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001226 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001227
Guido van Rossum98297ee2007-11-06 21:34:58 +00001228#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 /* Set sys.stderr, replaces the preliminary stderr */
1230 fd = fileno(stderr);
Antoine Pitrou11942a52011-11-28 19:08:36 +01001231 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 std = Py_None;
1233 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 }
1235 else {
1236 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1237 if (std == NULL)
1238 goto error;
1239 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +00001240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 /* Same as hack above, pre-import stderr's codec to avoid recursion
1242 when import.c tries to write to stderr in verbose mode. */
1243 encoding_attr = PyObject_GetAttrString(std, "encoding");
1244 if (encoding_attr != NULL) {
Victor Stinner49fc8ec2013-07-07 23:30:24 +02001245 const char * std_encoding;
1246 std_encoding = _PyUnicode_AsString(encoding_attr);
1247 if (std_encoding != NULL) {
1248 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
Antoine Pitrou2fabfac2012-01-18 15:14:46 +01001249 Py_XDECREF(codec_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001250 }
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +00001251 Py_DECREF(encoding_attr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001252 }
1253 PyErr_Clear(); /* Not a fatal error if codec isn't available */
Trent Nelson39e307e2008-03-19 06:45:48 +00001254
Victor Stinnerba308832013-07-22 23:55:19 +02001255 if (PySys_SetObject("__stderr__", std) < 0) {
1256 Py_DECREF(std);
1257 goto error;
1258 }
Victor Stinnerbd303c12013-11-07 23:07:29 +01001259 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
Victor Stinnerba308832013-07-22 23:55:19 +02001260 Py_DECREF(std);
1261 goto error;
1262 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001264#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001266 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001267 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 status = -1;
1269 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001270
Nick Coghlan7d270ee2013-10-17 22:35:35 +10001271 /* We won't need them anymore. */
1272 if (_Py_StandardStreamEncoding) {
1273 PyMem_RawFree(_Py_StandardStreamEncoding);
1274 _Py_StandardStreamEncoding = NULL;
1275 }
1276 if (_Py_StandardStreamErrors) {
1277 PyMem_RawFree(_Py_StandardStreamErrors);
1278 _Py_StandardStreamErrors = NULL;
1279 }
Serhiy Storchakabf28d2d2013-09-13 11:46:24 +03001280 PyMem_Free(pythonioencoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001281 Py_XDECREF(bimod);
1282 Py_XDECREF(iomod);
1283 return status;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001284}
1285
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001286/* Parse input from a file and execute it */
1287
1288int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001289PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001291{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001292 if (filename == NULL)
1293 filename = "???";
1294 if (Py_FdIsInteractive(fp, filename)) {
1295 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
1296 if (closeit)
1297 fclose(fp);
1298 return err;
1299 }
1300 else
1301 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001302}
1303
1304int
Victor Stinner95701bd2013-11-06 18:41:07 +01001305PyRun_InteractiveLoopFlags(FILE *fp, const char *filename_str, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001306{
Victor Stinner95701bd2013-11-06 18:41:07 +01001307 PyObject *filename, *v;
1308 int ret, err;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001310
Victor Stinner95701bd2013-11-06 18:41:07 +01001311 filename = PyUnicode_DecodeFSDefault(filename_str);
1312 if (filename == NULL) {
1313 PyErr_Print();
1314 return -1;
1315 }
1316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001317 if (flags == NULL) {
1318 flags = &local_flags;
1319 local_flags.cf_flags = 0;
1320 }
Victor Stinner09054372013-11-06 22:41:44 +01001321 v = _PySys_GetObjectId(&PyId_ps1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001322 if (v == NULL) {
Victor Stinner09054372013-11-06 22:41:44 +01001323 _PySys_SetObjectId(&PyId_ps1, v = PyUnicode_FromString(">>> "));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001324 Py_XDECREF(v);
1325 }
Victor Stinner09054372013-11-06 22:41:44 +01001326 v = _PySys_GetObjectId(&PyId_ps2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001327 if (v == NULL) {
Victor Stinner09054372013-11-06 22:41:44 +01001328 _PySys_SetObjectId(&PyId_ps2, v = PyUnicode_FromString("... "));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 Py_XDECREF(v);
1330 }
Victor Stinner95701bd2013-11-06 18:41:07 +01001331 err = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 for (;;) {
Victor Stinner95701bd2013-11-06 18:41:07 +01001333 ret = PyRun_InteractiveOneObject(fp, filename, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 PRINT_TOTAL_REFS();
Victor Stinner95701bd2013-11-06 18:41:07 +01001335 if (ret == E_EOF) {
1336 err = 0;
1337 break;
1338 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 /*
1340 if (ret == E_NOMEM)
Victor Stinner95701bd2013-11-06 18:41:07 +01001341 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 */
1343 }
Victor Stinner95701bd2013-11-06 18:41:07 +01001344 Py_DECREF(filename);
1345 return err;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001346}
1347
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001348/* compute parser flags based on compiler flags */
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001349static int PARSER_FLAGS(PyCompilerFlags *flags)
1350{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 int parser_flags = 0;
1352 if (!flags)
1353 return 0;
1354 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
1355 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1356 if (flags->cf_flags & PyCF_IGNORE_COOKIE)
1357 parser_flags |= PyPARSE_IGNORE_COOKIE;
1358 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
1359 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1360 return parser_flags;
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001361}
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001362
Thomas Wouters89f507f2006-12-13 04:49:30 +00001363#if 0
1364/* Keep an example of flags with future keyword support. */
1365#define PARSER_FLAGS(flags) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001366 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1367 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1368 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1369 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001370#endif
1371
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001372int
Victor Stinner95701bd2013-11-06 18:41:07 +01001373PyRun_InteractiveOneObject(FILE *fp, PyObject *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001374{
Victor Stinner95701bd2013-11-06 18:41:07 +01001375 PyObject *m, *d, *v, *w, *oenc = NULL, *mod_name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001376 mod_ty mod;
1377 PyArena *arena;
1378 char *ps1 = "", *ps2 = "", *enc = NULL;
1379 int errcode = 0;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001380 _Py_IDENTIFIER(encoding);
Victor Stinner95701bd2013-11-06 18:41:07 +01001381 _Py_IDENTIFIER(__main__);
1382
1383 mod_name = _PyUnicode_FromId(&PyId___main__); /* borrowed */
1384 if (mod_name == NULL) {
1385 PyErr_Print();
1386 return -1;
1387 }
Tim Petersfe2127d2001-07-16 05:37:24 +00001388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 if (fp == stdin) {
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -04001390 /* Fetch encoding from sys.stdin if possible. */
Victor Stinnerbd303c12013-11-07 23:07:29 +01001391 v = _PySys_GetObjectId(&PyId_stdin);
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -04001392 if (v && v != Py_None) {
1393 oenc = _PyObject_GetAttrId(v, &PyId_encoding);
1394 if (oenc)
1395 enc = _PyUnicode_AsString(oenc);
1396 if (!enc)
1397 PyErr_Clear();
1398 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001399 }
Victor Stinner09054372013-11-06 22:41:44 +01001400 v = _PySys_GetObjectId(&PyId_ps1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001401 if (v != NULL) {
1402 v = PyObject_Str(v);
1403 if (v == NULL)
1404 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001405 else if (PyUnicode_Check(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001406 ps1 = _PyUnicode_AsString(v);
Victor Stinner386fe712010-05-19 00:34:15 +00001407 if (ps1 == NULL) {
1408 PyErr_Clear();
1409 ps1 = "";
1410 }
1411 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 }
Victor Stinner09054372013-11-06 22:41:44 +01001413 w = _PySys_GetObjectId(&PyId_ps2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 if (w != NULL) {
1415 w = PyObject_Str(w);
1416 if (w == NULL)
1417 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001418 else if (PyUnicode_Check(w)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001419 ps2 = _PyUnicode_AsString(w);
Victor Stinner386fe712010-05-19 00:34:15 +00001420 if (ps2 == NULL) {
1421 PyErr_Clear();
1422 ps2 = "";
1423 }
1424 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 }
1426 arena = PyArena_New();
1427 if (arena == NULL) {
1428 Py_XDECREF(v);
1429 Py_XDECREF(w);
1430 Py_XDECREF(oenc);
1431 return -1;
1432 }
Victor Stinner95701bd2013-11-06 18:41:07 +01001433 mod = PyParser_ASTFromFileObject(fp, filename, enc,
1434 Py_single_input, ps1, ps2,
1435 flags, &errcode, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001436 Py_XDECREF(v);
1437 Py_XDECREF(w);
1438 Py_XDECREF(oenc);
1439 if (mod == NULL) {
1440 PyArena_Free(arena);
1441 if (errcode == E_EOF) {
1442 PyErr_Clear();
1443 return E_EOF;
1444 }
1445 PyErr_Print();
1446 return -1;
1447 }
Victor Stinner95701bd2013-11-06 18:41:07 +01001448 m = PyImport_AddModuleObject(mod_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001449 if (m == NULL) {
1450 PyArena_Free(arena);
1451 return -1;
1452 }
1453 d = PyModule_GetDict(m);
1454 v = run_mod(mod, filename, d, d, flags, arena);
1455 PyArena_Free(arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001456 if (v == NULL) {
1457 PyErr_Print();
Antoine Pitrou9845c7e2014-05-11 13:42:17 +02001458 flush_io();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001459 return -1;
1460 }
1461 Py_DECREF(v);
Antoine Pitrou9845c7e2014-05-11 13:42:17 +02001462 flush_io();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001463 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001464}
1465
Victor Stinner95701bd2013-11-06 18:41:07 +01001466int
1467PyRun_InteractiveOneFlags(FILE *fp, const char *filename_str, PyCompilerFlags *flags)
1468{
1469 PyObject *filename;
1470 int res;
1471
1472 filename = PyUnicode_DecodeFSDefault(filename_str);
1473 if (filename == NULL) {
1474 PyErr_Print();
1475 return -1;
1476 }
1477 res = PyRun_InteractiveOneObject(fp, filename, flags);
1478 Py_DECREF(filename);
1479 return res;
1480}
1481
1482
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001483/* Check whether a file maybe a pyc file: Look at the extension,
1484 the file type, and, if we may close it, at the first few bytes. */
1485
1486static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001487maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001488{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001489 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1490 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001492 /* Only look into the file if we are allowed to close it, since
1493 it then should also be seekable. */
1494 if (closeit) {
1495 /* Read only two bytes of the magic. If the file was opened in
1496 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1497 be read as they are on disk. */
1498 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1499 unsigned char buf[2];
1500 /* Mess: In case of -x, the stream is NOT at its start now,
1501 and ungetc() was used to push back the first newline,
1502 which makes the current stream position formally undefined,
1503 and a x-platform nightmare.
1504 Unfortunately, we have no direct way to know whether -x
1505 was specified. So we use a terrible hack: if the current
1506 stream position is not 0, we assume -x was specified, and
1507 give up. Bug 132850 on SourceForge spells out the
1508 hopelessness of trying anything else (fseek and ftell
1509 don't work predictably x-platform for text-mode files).
1510 */
1511 int ispyc = 0;
1512 if (ftell(fp) == 0) {
1513 if (fread(buf, 1, 2, fp) == 2 &&
1514 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
1515 ispyc = 1;
1516 rewind(fp);
1517 }
1518 return ispyc;
1519 }
1520 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001521}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001522
Antoine Pitrou32d483c2013-07-30 21:01:23 +02001523static int
1524set_main_loader(PyObject *d, const char *filename, const char *loader_name)
Nick Coghlan85e729e2012-07-15 18:09:52 +10001525{
1526 PyInterpreterState *interp;
1527 PyThreadState *tstate;
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001528 PyObject *filename_obj, *loader_type, *loader;
Nick Coghlanb7a58942012-07-15 23:21:08 +10001529 int result = 0;
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001530
1531 filename_obj = PyUnicode_DecodeFSDefault(filename);
1532 if (filename_obj == NULL)
1533 return -1;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001534 /* Get current thread state and interpreter pointer */
1535 tstate = PyThreadState_GET();
1536 interp = tstate->interp;
Nick Coghlan3f94cbf2012-07-15 19:10:39 +10001537 loader_type = PyObject_GetAttrString(interp->importlib, loader_name);
1538 if (loader_type == NULL) {
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001539 Py_DECREF(filename_obj);
Nick Coghlan3f94cbf2012-07-15 19:10:39 +10001540 return -1;
1541 }
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001542 loader = PyObject_CallFunction(loader_type, "sN", "__main__", filename_obj);
Nick Coghlanb7a58942012-07-15 23:21:08 +10001543 Py_DECREF(loader_type);
1544 if (loader == NULL) {
Nick Coghlan85e729e2012-07-15 18:09:52 +10001545 return -1;
1546 }
Nick Coghlanb7a58942012-07-15 23:21:08 +10001547 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
1548 result = -1;
1549 }
Nick Coghlan85e729e2012-07-15 18:09:52 +10001550 Py_DECREF(loader);
Nick Coghlanb7a58942012-07-15 23:21:08 +10001551 return result;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001552}
1553
1554int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001555PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001556 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001557{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 PyObject *m, *d, *v;
1559 const char *ext;
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001560 int set_file_name = 0, ret = -1;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00001561 size_t len;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001563 m = PyImport_AddModule("__main__");
1564 if (m == NULL)
1565 return -1;
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001566 Py_INCREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001567 d = PyModule_GetDict(m);
1568 if (PyDict_GetItemString(d, "__file__") == NULL) {
1569 PyObject *f;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00001570 f = PyUnicode_DecodeFSDefault(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001571 if (f == NULL)
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001572 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001573 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1574 Py_DECREF(f);
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001575 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 }
Barry Warsaw916048d2011-09-20 14:45:44 -04001577 if (PyDict_SetItemString(d, "__cached__", Py_None) < 0) {
1578 Py_DECREF(f);
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001579 goto done;
Barry Warsaw916048d2011-09-20 14:45:44 -04001580 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001581 set_file_name = 1;
1582 Py_DECREF(f);
1583 }
1584 len = strlen(filename);
1585 ext = filename + len - (len > 4 ? 4 : 0);
1586 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Christian Heimes04ac4c12012-09-11 15:47:28 +02001587 FILE *pyc_fp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 /* Try to run a pyc file. First, re-open in binary */
1589 if (closeit)
1590 fclose(fp);
Victor Stinnerdaf45552013-08-28 00:53:59 +02001591 if ((pyc_fp = _Py_fopen(filename, "rb")) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 fprintf(stderr, "python: Can't reopen .pyc file\n");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001593 goto done;
1594 }
1595 /* Turn on optimization if a .pyo file is given */
1596 if (strcmp(ext, ".pyo") == 0)
1597 Py_OptimizeFlag = 1;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001598
1599 if (set_main_loader(d, filename, "SourcelessFileLoader") < 0) {
1600 fprintf(stderr, "python: failed to set __main__.__loader__\n");
1601 ret = -1;
Christian Heimes04ac4c12012-09-11 15:47:28 +02001602 fclose(pyc_fp);
Nick Coghlan85e729e2012-07-15 18:09:52 +10001603 goto done;
1604 }
Christian Heimes04ac4c12012-09-11 15:47:28 +02001605 v = run_pyc_file(pyc_fp, filename, d, d, flags);
1606 fclose(pyc_fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 } else {
Nick Coghlan85e729e2012-07-15 18:09:52 +10001608 /* When running from stdin, leave __main__.__loader__ alone */
1609 if (strcmp(filename, "<stdin>") != 0 &&
1610 set_main_loader(d, filename, "SourceFileLoader") < 0) {
1611 fprintf(stderr, "python: failed to set __main__.__loader__\n");
1612 ret = -1;
1613 goto done;
1614 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001615 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
1616 closeit, flags);
1617 }
1618 flush_io();
1619 if (v == NULL) {
1620 PyErr_Print();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001621 goto done;
1622 }
1623 Py_DECREF(v);
1624 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001625 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001626 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1627 PyErr_Clear();
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001628 Py_DECREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001629 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001630}
1631
1632int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001633PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001634{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001635 PyObject *m, *d, *v;
1636 m = PyImport_AddModule("__main__");
1637 if (m == NULL)
1638 return -1;
1639 d = PyModule_GetDict(m);
1640 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
1641 if (v == NULL) {
1642 PyErr_Print();
1643 return -1;
1644 }
1645 Py_DECREF(v);
1646 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001647}
1648
Barry Warsaw035574d1997-08-29 22:07:17 +00001649static int
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001650parse_syntax_error(PyObject *err, PyObject **message, PyObject **filename,
1651 int *lineno, int *offset, PyObject **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001652{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001653 long hold;
1654 PyObject *v;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001655 _Py_IDENTIFIER(msg);
1656 _Py_IDENTIFIER(filename);
1657 _Py_IDENTIFIER(lineno);
1658 _Py_IDENTIFIER(offset);
1659 _Py_IDENTIFIER(text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001660
Benjamin Peterson80d50422012-04-03 00:30:38 -04001661 *message = NULL;
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001662 *filename = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001664 /* new style errors. `err' is an instance */
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001665 *message = _PyObject_GetAttrId(err, &PyId_msg);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001666 if (!*message)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001667 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001668
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001669 v = _PyObject_GetAttrId(err, &PyId_filename);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001670 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001671 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001672 if (v == Py_None) {
1673 Py_DECREF(v);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001674 *filename = _PyUnicode_FromId(&PyId_string);
1675 if (*filename == NULL)
1676 goto finally;
1677 Py_INCREF(*filename);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001678 }
1679 else {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001680 *filename = v;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001681 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001682
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001683 v = _PyObject_GetAttrId(err, &PyId_lineno);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001684 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 goto finally;
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 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001691
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001692 v = _PyObject_GetAttrId(err, &PyId_offset);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001693 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001694 goto finally;
1695 if (v == Py_None) {
1696 *offset = -1;
1697 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001698 } else {
1699 hold = PyLong_AsLong(v);
1700 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 if (hold < 0 && PyErr_Occurred())
1702 goto finally;
1703 *offset = (int)hold;
1704 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001705
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001706 v = _PyObject_GetAttrId(err, &PyId_text);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001707 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001708 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001709 if (v == Py_None) {
1710 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001711 *text = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001712 }
1713 else {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001714 *text = v;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001715 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001716 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001717
1718finally:
Benjamin Peterson80d50422012-04-03 00:30:38 -04001719 Py_XDECREF(*message);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001720 Py_XDECREF(*filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001722}
1723
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001724void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001725PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001726{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001727 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001728}
1729
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001730static void
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001731print_error_text(PyObject *f, int offset, PyObject *text_obj)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001732{
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001733 char *text;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001734 char *nl;
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001735
1736 text = _PyUnicode_AsString(text_obj);
1737 if (text == NULL)
1738 return;
1739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001740 if (offset >= 0) {
Benjamin Petersona95e9772010-10-29 03:28:14 +00001741 if (offset > 0 && offset == strlen(text) && text[offset - 1] == '\n')
1742 offset--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001743 for (;;) {
1744 nl = strchr(text, '\n');
1745 if (nl == NULL || nl-text >= offset)
1746 break;
1747 offset -= (int)(nl+1-text);
1748 text = nl+1;
1749 }
1750 while (*text == ' ' || *text == '\t') {
1751 text++;
1752 offset--;
1753 }
1754 }
1755 PyFile_WriteString(" ", f);
1756 PyFile_WriteString(text, f);
1757 if (*text == '\0' || text[strlen(text)-1] != '\n')
1758 PyFile_WriteString("\n", f);
1759 if (offset == -1)
1760 return;
1761 PyFile_WriteString(" ", f);
Benjamin Petersona95e9772010-10-29 03:28:14 +00001762 while (--offset > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001763 PyFile_WriteString(" ", f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001764 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001765}
1766
Guido van Rossum66e8e862001-03-23 17:54:43 +00001767static void
1768handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001769{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001770 PyObject *exception, *value, *tb;
1771 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001773 if (Py_InspectFlag)
1774 /* Don't exit if -i flag was given. This flag is set to 0
1775 * when entering interactive mode for inspecting. */
1776 return;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001778 PyErr_Fetch(&exception, &value, &tb);
1779 fflush(stdout);
1780 if (value == NULL || value == Py_None)
1781 goto done;
1782 if (PyExceptionInstance_Check(value)) {
1783 /* The error code should be in the `code' attribute. */
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001784 _Py_IDENTIFIER(code);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001785 PyObject *code = _PyObject_GetAttrId(value, &PyId_code);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001786 if (code) {
1787 Py_DECREF(value);
1788 value = code;
1789 if (value == Py_None)
1790 goto done;
1791 }
1792 /* If we failed to dig out the 'code' attribute,
1793 just let the else clause below print the error. */
1794 }
1795 if (PyLong_Check(value))
1796 exitcode = (int)PyLong_AsLong(value);
1797 else {
Victor Stinnerbd303c12013-11-07 23:07:29 +01001798 PyObject *sys_stderr = _PySys_GetObjectId(&PyId_stderr);
Nick Coghland979e432014-02-09 10:43:21 +10001799 /* We clear the exception here to avoid triggering the assertion
1800 * in PyObject_Str that ensures it won't silently lose exception
1801 * details.
1802 */
1803 PyErr_Clear();
Victor Stinner7126dbc2010-05-21 23:45:42 +00001804 if (sys_stderr != NULL && sys_stderr != Py_None) {
1805 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
1806 } else {
1807 PyObject_Print(value, stderr, Py_PRINT_RAW);
1808 fflush(stderr);
1809 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001810 PySys_WriteStderr("\n");
1811 exitcode = 1;
1812 }
Tim Peterscf615b52003-04-19 18:47:02 +00001813 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001814 /* Restore and clear the exception info, in order to properly decref
1815 * the exception, value, and traceback. If we just exit instead,
1816 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1817 * some finalizers from running.
1818 */
1819 PyErr_Restore(exception, value, tb);
1820 PyErr_Clear();
1821 Py_Exit(exitcode);
1822 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001823}
1824
1825void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001826PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001827{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001828 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001830 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1831 handle_system_exit();
1832 }
1833 PyErr_Fetch(&exception, &v, &tb);
1834 if (exception == NULL)
1835 return;
1836 PyErr_NormalizeException(&exception, &v, &tb);
1837 if (tb == NULL) {
1838 tb = Py_None;
1839 Py_INCREF(tb);
1840 }
1841 PyException_SetTraceback(v, tb);
1842 if (exception == NULL)
1843 return;
1844 /* Now we know v != NULL too */
1845 if (set_sys_last_vars) {
Victor Stinner09054372013-11-06 22:41:44 +01001846 _PySys_SetObjectId(&PyId_last_type, exception);
1847 _PySys_SetObjectId(&PyId_last_value, v);
1848 _PySys_SetObjectId(&PyId_last_traceback, tb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 }
Victor Stinner09054372013-11-06 22:41:44 +01001850 hook = _PySys_GetObjectId(&PyId_excepthook);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001851 if (hook) {
1852 PyObject *args = PyTuple_Pack(3, exception, v, tb);
1853 PyObject *result = PyEval_CallObject(hook, args);
1854 if (result == NULL) {
1855 PyObject *exception2, *v2, *tb2;
1856 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1857 handle_system_exit();
1858 }
1859 PyErr_Fetch(&exception2, &v2, &tb2);
1860 PyErr_NormalizeException(&exception2, &v2, &tb2);
1861 /* It should not be possible for exception2 or v2
1862 to be NULL. However PyErr_Display() can't
1863 tolerate NULLs, so just be safe. */
1864 if (exception2 == NULL) {
1865 exception2 = Py_None;
1866 Py_INCREF(exception2);
1867 }
1868 if (v2 == NULL) {
1869 v2 = Py_None;
1870 Py_INCREF(v2);
1871 }
1872 fflush(stdout);
1873 PySys_WriteStderr("Error in sys.excepthook:\n");
1874 PyErr_Display(exception2, v2, tb2);
1875 PySys_WriteStderr("\nOriginal exception was:\n");
1876 PyErr_Display(exception, v, tb);
1877 Py_DECREF(exception2);
1878 Py_DECREF(v2);
1879 Py_XDECREF(tb2);
1880 }
1881 Py_XDECREF(result);
1882 Py_XDECREF(args);
1883 } else {
1884 PySys_WriteStderr("sys.excepthook is missing\n");
1885 PyErr_Display(exception, v, tb);
1886 }
1887 Py_XDECREF(exception);
1888 Py_XDECREF(v);
1889 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001890}
1891
Benjamin Petersone6528212008-07-15 15:32:09 +00001892static void
1893print_exception(PyObject *f, PyObject *value)
1894{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 int err = 0;
1896 PyObject *type, *tb;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001897 _Py_IDENTIFIER(print_file_and_line);
Benjamin Petersone6528212008-07-15 15:32:09 +00001898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001899 if (!PyExceptionInstance_Check(value)) {
Victor Stinner52ce3b02013-12-09 02:10:08 +01001900 err = PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1901 err += PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1902 err += PyFile_WriteString(" found\n", f);
1903 if (err)
1904 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 return;
1906 }
Benjamin Peterson26582602008-08-23 20:08:07 +00001907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001908 Py_INCREF(value);
1909 fflush(stdout);
1910 type = (PyObject *) Py_TYPE(value);
1911 tb = PyException_GetTraceback(value);
1912 if (tb && tb != Py_None)
1913 err = PyTraceBack_Print(tb, f);
1914 if (err == 0 &&
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001915 _PyObject_HasAttrId(value, &PyId_print_file_and_line))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001916 {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001917 PyObject *message, *filename, *text;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 int lineno, offset;
1919 if (!parse_syntax_error(value, &message, &filename,
1920 &lineno, &offset, &text))
1921 PyErr_Clear();
1922 else {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001923 PyObject *line;
1924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001925 Py_DECREF(value);
1926 value = message;
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001927
1928 line = PyUnicode_FromFormat(" File \"%U\", line %d\n",
1929 filename, lineno);
1930 Py_DECREF(filename);
1931 if (line != NULL) {
1932 PyFile_WriteObject(line, f, Py_PRINT_RAW);
1933 Py_DECREF(line);
1934 }
1935
1936 if (text != NULL) {
1937 print_error_text(f, offset, text);
1938 Py_DECREF(text);
1939 }
1940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001941 /* Can't be bothered to check all those
1942 PyFile_WriteString() calls */
1943 if (PyErr_Occurred())
1944 err = -1;
1945 }
1946 }
1947 if (err) {
1948 /* Don't do anything else */
1949 }
1950 else {
1951 PyObject* moduleName;
1952 char* className;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001953 _Py_IDENTIFIER(__module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001954 assert(PyExceptionClass_Check(type));
1955 className = PyExceptionClass_Name(type);
1956 if (className != NULL) {
1957 char *dot = strrchr(className, '.');
1958 if (dot != NULL)
1959 className = dot+1;
1960 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001961
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001962 moduleName = _PyObject_GetAttrId(type, &PyId___module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001963 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1964 {
Victor Stinner13b21bd2011-05-26 14:25:13 +02001965 Py_XDECREF(moduleName);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001966 err = PyFile_WriteString("<unknown>", f);
1967 }
1968 else {
Victor Stinnerbd303c12013-11-07 23:07:29 +01001969 if (_PyUnicode_CompareWithId(moduleName, &PyId_builtins) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001970 {
Victor Stinner937114f2013-11-07 00:12:30 +01001971 err = PyFile_WriteObject(moduleName, f, Py_PRINT_RAW);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001972 err += PyFile_WriteString(".", f);
1973 }
1974 Py_DECREF(moduleName);
1975 }
1976 if (err == 0) {
1977 if (className == NULL)
1978 err = PyFile_WriteString("<unknown>", f);
1979 else
1980 err = PyFile_WriteString(className, f);
1981 }
1982 }
1983 if (err == 0 && (value != Py_None)) {
1984 PyObject *s = PyObject_Str(value);
1985 /* only print colon if the str() of the
1986 object is not the empty string
1987 */
1988 if (s == NULL)
1989 err = -1;
1990 else if (!PyUnicode_Check(s) ||
Victor Stinnere251d6d2011-11-20 19:20:00 +01001991 PyUnicode_GetLength(s) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 err = PyFile_WriteString(": ", f);
1993 if (err == 0)
1994 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1995 Py_XDECREF(s);
1996 }
1997 /* try to write a newline in any case */
1998 err += PyFile_WriteString("\n", f);
1999 Py_XDECREF(tb);
2000 Py_DECREF(value);
2001 /* If an error happened here, don't show it.
2002 XXX This is wrong, but too many callers rely on this behavior. */
2003 if (err != 0)
2004 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00002005}
2006
2007static const char *cause_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002008 "\nThe above exception was the direct cause "
2009 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00002010
2011static const char *context_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012 "\nDuring handling of the above exception, "
2013 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00002014
2015static void
2016print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
2017{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002018 int err = 0, res;
2019 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00002020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002021 if (seen != NULL) {
2022 /* Exception chaining */
2023 if (PySet_Add(seen, value) == -1)
2024 PyErr_Clear();
2025 else if (PyExceptionInstance_Check(value)) {
2026 cause = PyException_GetCause(value);
2027 context = PyException_GetContext(value);
Benjamin Petersond5a1c442012-05-14 22:09:31 -07002028 if (cause) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002029 res = PySet_Contains(seen, cause);
2030 if (res == -1)
2031 PyErr_Clear();
2032 if (res == 0) {
2033 print_exception_recursive(
2034 f, cause, seen);
2035 err |= PyFile_WriteString(
2036 cause_message, f);
2037 }
2038 }
Benjamin Petersond5a1c442012-05-14 22:09:31 -07002039 else if (context &&
2040 !((PyBaseExceptionObject *)value)->suppress_context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002041 res = PySet_Contains(seen, context);
2042 if (res == -1)
2043 PyErr_Clear();
2044 if (res == 0) {
2045 print_exception_recursive(
2046 f, context, seen);
2047 err |= PyFile_WriteString(
2048 context_message, f);
2049 }
2050 }
2051 Py_XDECREF(context);
2052 Py_XDECREF(cause);
2053 }
2054 }
2055 print_exception(f, value);
2056 if (err != 0)
2057 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00002058}
2059
Thomas Wouters477c8d52006-05-27 19:21:47 +00002060void
2061PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002062{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 PyObject *seen;
Victor Stinnerbd303c12013-11-07 23:07:29 +01002064 PyObject *f = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrou24201d42013-10-13 21:53:13 +02002065 if (PyExceptionInstance_Check(value)
2066 && tb != NULL && PyTraceBack_Check(tb)) {
2067 /* Put the traceback on the exception, otherwise it won't get
2068 displayed. See issue #18776. */
2069 PyObject *cur_tb = PyException_GetTraceback(value);
2070 if (cur_tb == NULL)
2071 PyException_SetTraceback(value, tb);
2072 else
2073 Py_DECREF(cur_tb);
2074 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002075 if (f == Py_None) {
2076 /* pass */
2077 }
2078 else if (f == NULL) {
2079 _PyObject_Dump(value);
2080 fprintf(stderr, "lost sys.stderr\n");
2081 }
2082 else {
2083 /* We choose to ignore seen being possibly NULL, and report
2084 at least the main exception (it could be a MemoryError).
2085 */
2086 seen = PySet_New(NULL);
2087 if (seen == NULL)
2088 PyErr_Clear();
2089 print_exception_recursive(f, value, seen);
2090 Py_XDECREF(seen);
2091 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002092}
2093
Guido van Rossum82598051997-03-05 00:20:32 +00002094PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002095PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002096 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002097{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002098 PyObject *ret = NULL;
2099 mod_ty mod;
Victor Stinner95701bd2013-11-06 18:41:07 +01002100 PyArena *arena;
Victor Stinner95701bd2013-11-06 18:41:07 +01002101 PyObject *filename;
2102
2103 filename = _PyUnicode_FromId(&PyId_string); /* borrowed */
2104 if (filename == NULL)
2105 return NULL;
2106
2107 arena = PyArena_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002108 if (arena == NULL)
2109 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00002110
Victor Stinner95701bd2013-11-06 18:41:07 +01002111 mod = PyParser_ASTFromStringObject(str, filename, start, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002112 if (mod != NULL)
Victor Stinner95701bd2013-11-06 18:41:07 +01002113 ret = run_mod(mod, filename, globals, locals, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002114 PyArena_Free(arena);
2115 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002116}
2117
2118PyObject *
Victor Stinner95701bd2013-11-06 18:41:07 +01002119PyRun_FileExFlags(FILE *fp, const char *filename_str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002120 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002121{
Victor Stinner95701bd2013-11-06 18:41:07 +01002122 PyObject *ret = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002123 mod_ty mod;
Victor Stinner95701bd2013-11-06 18:41:07 +01002124 PyArena *arena = NULL;
2125 PyObject *filename;
Guido van Rossum98297ee2007-11-06 21:34:58 +00002126
Victor Stinner95701bd2013-11-06 18:41:07 +01002127 filename = PyUnicode_DecodeFSDefault(filename_str);
2128 if (filename == NULL)
2129 goto exit;
2130
2131 arena = PyArena_New();
2132 if (arena == NULL)
2133 goto exit;
2134
2135 mod = PyParser_ASTFromFileObject(fp, filename, NULL, start, 0, 0,
2136 flags, NULL, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 if (closeit)
2138 fclose(fp);
2139 if (mod == NULL) {
Victor Stinner95701bd2013-11-06 18:41:07 +01002140 goto exit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 }
2142 ret = run_mod(mod, filename, globals, locals, flags, arena);
Victor Stinner95701bd2013-11-06 18:41:07 +01002143
2144exit:
2145 Py_XDECREF(filename);
2146 if (arena != NULL)
2147 PyArena_Free(arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002148 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002149}
2150
Guido van Rossum6c193fa2007-12-05 05:14:58 +00002151static void
2152flush_io(void)
2153{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002154 PyObject *f, *r;
2155 PyObject *type, *value, *traceback;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00002156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002157 /* Save the current exception */
2158 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00002159
Victor Stinnerbd303c12013-11-07 23:07:29 +01002160 f = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002161 if (f != NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002162 r = _PyObject_CallMethodId(f, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 if (r)
2164 Py_DECREF(r);
2165 else
2166 PyErr_Clear();
2167 }
Victor Stinnerbd303c12013-11-07 23:07:29 +01002168 f = _PySys_GetObjectId(&PyId_stdout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002169 if (f != NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002170 r = _PyObject_CallMethodId(f, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171 if (r)
2172 Py_DECREF(r);
2173 else
2174 PyErr_Clear();
2175 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00002176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002177 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00002178}
2179
Guido van Rossum82598051997-03-05 00:20:32 +00002180static PyObject *
Victor Stinner95701bd2013-11-06 18:41:07 +01002181run_mod(mod_ty mod, PyObject *filename, PyObject *globals, PyObject *locals,
2182 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002183{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002184 PyCodeObject *co;
2185 PyObject *v;
Victor Stinner95701bd2013-11-06 18:41:07 +01002186 co = PyAST_CompileObject(mod, filename, flags, -1, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002187 if (co == NULL)
2188 return NULL;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002189 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002190 Py_DECREF(co);
2191 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002192}
2193
Guido van Rossum82598051997-03-05 00:20:32 +00002194static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002195run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002196 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00002197{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002198 PyCodeObject *co;
2199 PyObject *v;
2200 long magic;
2201 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00002202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002203 magic = PyMarshal_ReadLongFromFile(fp);
2204 if (magic != PyImport_GetMagicNumber()) {
2205 PyErr_SetString(PyExc_RuntimeError,
2206 "Bad magic number in .pyc file");
2207 return NULL;
2208 }
Antoine Pitrou5136ac02012-01-13 18:52:16 +01002209 /* Skip mtime and size */
2210 (void) PyMarshal_ReadLongFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002211 (void) PyMarshal_ReadLongFromFile(fp);
2212 v = PyMarshal_ReadLastObjectFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002213 if (v == NULL || !PyCode_Check(v)) {
2214 Py_XDECREF(v);
2215 PyErr_SetString(PyExc_RuntimeError,
2216 "Bad code object in .pyc file");
2217 return NULL;
2218 }
2219 co = (PyCodeObject *)v;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002220 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002221 if (v && flags)
2222 flags->cf_flags |= (co->co_flags & PyCF_MASK);
2223 Py_DECREF(co);
2224 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00002225}
2226
Guido van Rossum82598051997-03-05 00:20:32 +00002227PyObject *
Victor Stinner14e461d2013-08-26 22:28:21 +02002228Py_CompileStringObject(const char *str, PyObject *filename, int start,
2229 PyCompilerFlags *flags, int optimize)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002230{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002231 PyCodeObject *co;
2232 mod_ty mod;
2233 PyArena *arena = PyArena_New();
2234 if (arena == NULL)
2235 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002236
Victor Stinner14e461d2013-08-26 22:28:21 +02002237 mod = PyParser_ASTFromStringObject(str, filename, start, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002238 if (mod == NULL) {
2239 PyArena_Free(arena);
2240 return NULL;
2241 }
2242 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
2243 PyObject *result = PyAST_mod2obj(mod);
2244 PyArena_Free(arena);
2245 return result;
2246 }
Victor Stinner14e461d2013-08-26 22:28:21 +02002247 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002248 PyArena_Free(arena);
2249 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00002250}
2251
Victor Stinner14e461d2013-08-26 22:28:21 +02002252PyObject *
2253Py_CompileStringExFlags(const char *str, const char *filename_str, int start,
2254 PyCompilerFlags *flags, int optimize)
2255{
2256 PyObject *filename, *co;
2257 filename = PyUnicode_DecodeFSDefault(filename_str);
2258 if (filename == NULL)
2259 return NULL;
2260 co = Py_CompileStringObject(str, filename, start, flags, optimize);
2261 Py_DECREF(filename);
2262 return co;
2263}
2264
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002265/* For use in Py_LIMITED_API */
2266#undef Py_CompileString
2267PyObject *
2268PyCompileString(const char *str, const char *filename, int start)
2269{
2270 return Py_CompileStringFlags(str, filename, start, NULL);
2271}
2272
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002273struct symtable *
Victor Stinner14e461d2013-08-26 22:28:21 +02002274Py_SymtableStringObject(const char *str, PyObject *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002275{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002276 struct symtable *st;
2277 mod_ty mod;
2278 PyCompilerFlags flags;
Victor Stinner14e461d2013-08-26 22:28:21 +02002279 PyArena *arena;
2280
2281 arena = PyArena_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002282 if (arena == NULL)
2283 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002285 flags.cf_flags = 0;
Victor Stinner14e461d2013-08-26 22:28:21 +02002286 mod = PyParser_ASTFromStringObject(str, filename, start, &flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002287 if (mod == NULL) {
2288 PyArena_Free(arena);
2289 return NULL;
2290 }
Victor Stinner14e461d2013-08-26 22:28:21 +02002291 st = PySymtable_BuildObject(mod, filename, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002292 PyArena_Free(arena);
2293 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002294}
2295
Victor Stinner14e461d2013-08-26 22:28:21 +02002296struct symtable *
2297Py_SymtableString(const char *str, const char *filename_str, int start)
2298{
2299 PyObject *filename;
2300 struct symtable *st;
2301
2302 filename = PyUnicode_DecodeFSDefault(filename_str);
2303 if (filename == NULL)
2304 return NULL;
2305 st = Py_SymtableStringObject(str, filename, start);
2306 Py_DECREF(filename);
2307 return st;
2308}
2309
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002310/* Preferred access to parser is through AST. */
2311mod_ty
Victor Stinner14e461d2013-08-26 22:28:21 +02002312PyParser_ASTFromStringObject(const char *s, PyObject *filename, int start,
2313 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002314{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002315 mod_ty mod;
2316 PyCompilerFlags localflags;
2317 perrdetail err;
2318 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00002319
Victor Stinner14e461d2013-08-26 22:28:21 +02002320 node *n = PyParser_ParseStringObject(s, filename,
2321 &_PyParser_Grammar, start, &err,
2322 &iflags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002323 if (flags == NULL) {
2324 localflags.cf_flags = 0;
2325 flags = &localflags;
2326 }
2327 if (n) {
2328 flags->cf_flags |= iflags & PyCF_MASK;
Victor Stinner14e461d2013-08-26 22:28:21 +02002329 mod = PyAST_FromNodeObject(n, flags, filename, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002330 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002331 }
2332 else {
2333 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002334 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002335 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002336 err_free(&err);
2337 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002338}
2339
2340mod_ty
Victor Stinner14e461d2013-08-26 22:28:21 +02002341PyParser_ASTFromString(const char *s, const char *filename_str, int start,
2342 PyCompilerFlags *flags, PyArena *arena)
2343{
2344 PyObject *filename;
2345 mod_ty mod;
2346 filename = PyUnicode_DecodeFSDefault(filename_str);
2347 if (filename == NULL)
2348 return NULL;
2349 mod = PyParser_ASTFromStringObject(s, filename, start, flags, arena);
2350 Py_DECREF(filename);
2351 return mod;
2352}
2353
2354mod_ty
2355PyParser_ASTFromFileObject(FILE *fp, PyObject *filename, const char* enc,
2356 int start, char *ps1,
2357 char *ps2, PyCompilerFlags *flags, int *errcode,
2358 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002359{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002360 mod_ty mod;
2361 PyCompilerFlags localflags;
2362 perrdetail err;
2363 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00002364
Victor Stinner14e461d2013-08-26 22:28:21 +02002365 node *n = PyParser_ParseFileObject(fp, filename, enc,
2366 &_PyParser_Grammar,
2367 start, ps1, ps2, &err, &iflags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002368 if (flags == NULL) {
2369 localflags.cf_flags = 0;
2370 flags = &localflags;
2371 }
2372 if (n) {
2373 flags->cf_flags |= iflags & PyCF_MASK;
Victor Stinner14e461d2013-08-26 22:28:21 +02002374 mod = PyAST_FromNodeObject(n, flags, filename, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002375 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002376 }
2377 else {
2378 err_input(&err);
2379 if (errcode)
2380 *errcode = err.error;
Victor Stinner7f2fee32011-04-05 00:39:01 +02002381 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002382 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002383 err_free(&err);
2384 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002385}
2386
Victor Stinner14e461d2013-08-26 22:28:21 +02002387mod_ty
2388PyParser_ASTFromFile(FILE *fp, const char *filename_str, const char* enc,
2389 int start, char *ps1,
2390 char *ps2, PyCompilerFlags *flags, int *errcode,
2391 PyArena *arena)
2392{
2393 mod_ty mod;
2394 PyObject *filename;
2395 filename = PyUnicode_DecodeFSDefault(filename_str);
2396 if (filename == NULL)
2397 return NULL;
2398 mod = PyParser_ASTFromFileObject(fp, filename, enc, start, ps1, ps2,
2399 flags, errcode, arena);
2400 Py_DECREF(filename);
2401 return mod;
2402}
2403
Guido van Rossuma110aa61994-08-29 12:50:44 +00002404/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002405
Guido van Rossuma110aa61994-08-29 12:50:44 +00002406node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002407PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002408{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002409 perrdetail err;
2410 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
2411 &_PyParser_Grammar,
2412 start, NULL, NULL, &err, flags);
2413 if (n == NULL)
2414 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002415 err_free(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002417 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002418}
2419
Guido van Rossuma110aa61994-08-29 12:50:44 +00002420/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002421
Guido van Rossuma110aa61994-08-29 12:50:44 +00002422node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002423PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00002424{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002425 perrdetail err;
2426 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
2427 start, &err, flags);
2428 if (n == NULL)
2429 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002430 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002431 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00002432}
2433
2434node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002435PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002436 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00002437{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002438 perrdetail err;
2439 node *n = PyParser_ParseStringFlagsFilename(str, filename,
2440 &_PyParser_Grammar, start, &err, flags);
2441 if (n == NULL)
2442 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002443 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002444 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00002445}
2446
2447node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002448PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00002449{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002450 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00002451}
2452
Guido van Rossum66ebd912003-04-17 16:02:26 +00002453/* May want to move a more generalized form of this to parsetok.c or
2454 even parser modules. */
2455
2456void
Victor Stinner7f2fee32011-04-05 00:39:01 +02002457PyParser_ClearError(perrdetail *err)
2458{
2459 err_free(err);
2460}
2461
2462void
Guido van Rossum66ebd912003-04-17 16:02:26 +00002463PyParser_SetError(perrdetail *err)
2464{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002465 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00002466}
2467
Victor Stinner7f2fee32011-04-05 00:39:01 +02002468static void
2469err_free(perrdetail *err)
2470{
2471 Py_CLEAR(err->filename);
2472}
2473
Guido van Rossuma110aa61994-08-29 12:50:44 +00002474/* Set the error appropriate to the given input error code (see errcode.h) */
2475
2476static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002477err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00002478{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002479 PyObject *v, *w, *errtype, *errtext;
2480 PyObject *msg_obj = NULL;
2481 char *msg = NULL;
Serhiy Storchaka65fd0592014-01-21 22:26:52 +02002482 int offset = err->offset;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00002483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002484 errtype = PyExc_SyntaxError;
2485 switch (err->error) {
2486 case E_ERROR:
2487 return;
2488 case E_SYNTAX:
2489 errtype = PyExc_IndentationError;
2490 if (err->expected == INDENT)
2491 msg = "expected an indented block";
2492 else if (err->token == INDENT)
2493 msg = "unexpected indent";
2494 else if (err->token == DEDENT)
2495 msg = "unexpected unindent";
2496 else {
2497 errtype = PyExc_SyntaxError;
2498 msg = "invalid syntax";
2499 }
2500 break;
2501 case E_TOKEN:
2502 msg = "invalid token";
2503 break;
2504 case E_EOFS:
2505 msg = "EOF while scanning triple-quoted string literal";
2506 break;
2507 case E_EOLS:
2508 msg = "EOL while scanning string literal";
2509 break;
2510 case E_INTR:
2511 if (!PyErr_Occurred())
2512 PyErr_SetNone(PyExc_KeyboardInterrupt);
2513 goto cleanup;
2514 case E_NOMEM:
2515 PyErr_NoMemory();
2516 goto cleanup;
2517 case E_EOF:
2518 msg = "unexpected EOF while parsing";
2519 break;
2520 case E_TABSPACE:
2521 errtype = PyExc_TabError;
2522 msg = "inconsistent use of tabs and spaces in indentation";
2523 break;
2524 case E_OVERFLOW:
2525 msg = "expression too long";
2526 break;
2527 case E_DEDENT:
2528 errtype = PyExc_IndentationError;
2529 msg = "unindent does not match any outer indentation level";
2530 break;
2531 case E_TOODEEP:
2532 errtype = PyExc_IndentationError;
2533 msg = "too many levels of indentation";
2534 break;
2535 case E_DECODE: {
2536 PyObject *type, *value, *tb;
2537 PyErr_Fetch(&type, &value, &tb);
2538 msg = "unknown decode error";
2539 if (value != NULL)
2540 msg_obj = PyObject_Str(value);
2541 Py_XDECREF(type);
2542 Py_XDECREF(value);
2543 Py_XDECREF(tb);
2544 break;
2545 }
2546 case E_LINECONT:
2547 msg = "unexpected character after line continuation character";
2548 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00002549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002550 case E_IDENTIFIER:
2551 msg = "invalid character in identifier";
2552 break;
Meador Ingefa21bf02012-01-19 01:08:41 -06002553 case E_BADSINGLE:
2554 msg = "multiple statements found while compiling a single statement";
2555 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002556 default:
2557 fprintf(stderr, "error=%d\n", err->error);
2558 msg = "unknown parsing error";
2559 break;
2560 }
2561 /* err->text may not be UTF-8 in case of decoding errors.
2562 Explicitly convert to an object. */
2563 if (!err->text) {
2564 errtext = Py_None;
2565 Py_INCREF(Py_None);
2566 } else {
Serhiy Storchaka65fd0592014-01-21 22:26:52 +02002567 errtext = PyUnicode_DecodeUTF8(err->text, err->offset,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002568 "replace");
Serhiy Storchaka65fd0592014-01-21 22:26:52 +02002569 if (errtext != NULL) {
2570 Py_ssize_t len = strlen(err->text);
2571 offset = (int)PyUnicode_GET_LENGTH(errtext);
2572 if (len != err->offset) {
2573 Py_DECREF(errtext);
2574 errtext = PyUnicode_DecodeUTF8(err->text, len,
2575 "replace");
2576 }
2577 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002578 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002579 v = Py_BuildValue("(OiiN)", err->filename,
Serhiy Storchaka65fd0592014-01-21 22:26:52 +02002580 err->lineno, offset, errtext);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002581 if (v != NULL) {
2582 if (msg_obj)
2583 w = Py_BuildValue("(OO)", msg_obj, v);
2584 else
2585 w = Py_BuildValue("(sO)", msg, v);
2586 } else
2587 w = NULL;
2588 Py_XDECREF(v);
2589 PyErr_SetObject(errtype, w);
2590 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00002591cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002592 Py_XDECREF(msg_obj);
2593 if (err->text != NULL) {
2594 PyObject_FREE(err->text);
2595 err->text = NULL;
2596 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002597}
2598
2599/* Print fatal error message and abort */
2600
2601void
Tim Peters7c321a82002-07-09 02:57:01 +00002602Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002603{
Victor Stinner024e37a2011-03-31 01:31:06 +02002604 const int fd = fileno(stderr);
2605 PyThreadState *tstate;
2606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002607 fprintf(stderr, "Fatal Python error: %s\n", msg);
2608 fflush(stderr); /* it helps in Windows debug build */
2609 if (PyErr_Occurred()) {
Victor Stinner55a5c782010-06-08 21:00:13 +00002610 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002611 }
Victor Stinner024e37a2011-03-31 01:31:06 +02002612 else {
2613 tstate = _Py_atomic_load_relaxed(&_PyThreadState_Current);
2614 if (tstate != NULL) {
2615 fputc('\n', stderr);
2616 fflush(stderr);
Victor Stinner7bba62f2011-05-07 12:43:00 +02002617 _Py_DumpTracebackThreads(fd, tstate->interp, tstate);
Victor Stinner024e37a2011-03-31 01:31:06 +02002618 }
Victor Stinnerd727e232011-04-01 12:13:55 +02002619 _PyFaulthandler_Fini();
Victor Stinner024e37a2011-03-31 01:31:06 +02002620 }
2621
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002622#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002623 {
2624 size_t len = strlen(msg);
2625 WCHAR* buffer;
2626 size_t i;
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002628 /* Convert the message to wchar_t. This uses a simple one-to-one
2629 conversion, assuming that the this error message actually uses ASCII
2630 only. If this ceases to be true, we will have to convert. */
2631 buffer = alloca( (len+1) * (sizeof *buffer));
2632 for( i=0; i<=len; ++i)
2633 buffer[i] = msg[i];
2634 OutputDebugStringW(L"Fatal Python error: ");
2635 OutputDebugStringW(buffer);
2636 OutputDebugStringW(L"\n");
2637 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002638#ifdef _DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002639 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002640#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002641#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002642 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002643}
2644
2645/* Clean up and exit */
2646
Guido van Rossuma110aa61994-08-29 12:50:44 +00002647#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002648#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002649#endif
2650
Collin Winter670e6922007-03-21 02:57:17 +00002651static void (*pyexitfunc)(void) = NULL;
2652/* For the atexit module. */
2653void _Py_PyAtExit(void (*func)(void))
2654{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002655 pyexitfunc = func;
Collin Winter670e6922007-03-21 02:57:17 +00002656}
2657
2658static void
2659call_py_exitfuncs(void)
2660{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002661 if (pyexitfunc == NULL)
2662 return;
Collin Winter670e6922007-03-21 02:57:17 +00002663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002664 (*pyexitfunc)();
2665 PyErr_Clear();
Collin Winter670e6922007-03-21 02:57:17 +00002666}
2667
Antoine Pitrou011bd622009-10-20 21:52:47 +00002668/* Wait until threading._shutdown completes, provided
2669 the threading module was imported in the first place.
2670 The shutdown routine will wait until all non-daemon
2671 "threading" threads have completed. */
2672static void
2673wait_for_thread_shutdown(void)
2674{
2675#ifdef WITH_THREAD
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002676 _Py_IDENTIFIER(_shutdown);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002677 PyObject *result;
2678 PyThreadState *tstate = PyThreadState_GET();
2679 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2680 "threading");
2681 if (threading == NULL) {
2682 /* threading not imported */
2683 PyErr_Clear();
2684 return;
2685 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002686 result = _PyObject_CallMethodId(threading, &PyId__shutdown, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002687 if (result == NULL) {
2688 PyErr_WriteUnraisable(threading);
2689 }
2690 else {
2691 Py_DECREF(result);
2692 }
2693 Py_DECREF(threading);
Antoine Pitrou011bd622009-10-20 21:52:47 +00002694#endif
2695}
2696
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002697#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002698static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002699static int nexitfuncs = 0;
2700
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002701int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002702{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002703 if (nexitfuncs >= NEXITFUNCS)
2704 return -1;
2705 exitfuncs[nexitfuncs++] = func;
2706 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00002707}
2708
Guido van Rossumcc283f51997-08-05 02:22:03 +00002709static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002710call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002711{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002712 while (nexitfuncs > 0)
2713 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002715 fflush(stdout);
2716 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002717}
2718
2719void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002720Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002721{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002722 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002724 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002725}
2726
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002727static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002728initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002729{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002730#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002731 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002732#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002733#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002734 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002735#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002736#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002737 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002738#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002739 PyOS_InitInterrupts(); /* May imply initsignal() */
Victor Stinnerd786ad52013-07-21 13:25:51 +02002740 if (PyErr_Occurred()) {
2741 Py_FatalError("Py_Initialize: can't import signal");
2742 }
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002743}
2744
Guido van Rossum7433b121997-02-14 19:45:36 +00002745
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002746/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2747 *
2748 * All of the code in this function must only use async-signal-safe functions,
2749 * listed at `man 7 signal` or
2750 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2751 */
2752void
2753_Py_RestoreSignals(void)
2754{
2755#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002756 PyOS_setsig(SIGPIPE, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002757#endif
2758#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002759 PyOS_setsig(SIGXFZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002760#endif
2761#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002762 PyOS_setsig(SIGXFSZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002763#endif
2764}
2765
2766
Guido van Rossum7433b121997-02-14 19:45:36 +00002767/*
2768 * The file descriptor fd is considered ``interactive'' if either
2769 * a) isatty(fd) is TRUE, or
2770 * b) the -i flag was given, and the filename associated with
2771 * the descriptor is NULL or "<stdin>" or "???".
2772 */
2773int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002774Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002775{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002776 if (isatty((int)fileno(fp)))
2777 return 1;
2778 if (!Py_InteractiveFlag)
2779 return 0;
2780 return (filename == NULL) ||
2781 (strcmp(filename, "<stdin>") == 0) ||
2782 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00002783}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002784
2785
Tim Petersd08e3822003-04-17 15:24:21 +00002786#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002787#if defined(WIN32) && defined(_MSC_VER)
2788
2789/* Stack checking for Microsoft C */
2790
2791#include <malloc.h>
2792#include <excpt.h>
2793
Fred Drakee8de31c2000-08-31 05:38:39 +00002794/*
2795 * Return non-zero when we run out of memory on the stack; zero otherwise.
2796 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002797int
Fred Drake399739f2000-08-31 05:52:44 +00002798PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002799{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002800 __try {
2801 /* alloca throws a stack overflow exception if there's
2802 not enough space left on the stack */
2803 alloca(PYOS_STACK_MARGIN * sizeof(void*));
2804 return 0;
2805 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2806 EXCEPTION_EXECUTE_HANDLER :
2807 EXCEPTION_CONTINUE_SEARCH) {
2808 int errcode = _resetstkoflw();
2809 if (errcode == 0)
2810 {
2811 Py_FatalError("Could not reset the stack!");
2812 }
2813 }
2814 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002815}
2816
2817#endif /* WIN32 && _MSC_VER */
2818
2819/* Alternate implementations can be added here... */
2820
2821#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002822
2823
2824/* Wrappers around sigaction() or signal(). */
2825
2826PyOS_sighandler_t
2827PyOS_getsig(int sig)
2828{
2829#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002830 struct sigaction context;
2831 if (sigaction(sig, NULL, &context) == -1)
2832 return SIG_ERR;
2833 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002834#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002835 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002836/* Special signal handling for the secure CRT in Visual Studio 2005 */
2837#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002838 switch (sig) {
2839 /* Only these signals are valid */
2840 case SIGINT:
2841 case SIGILL:
2842 case SIGFPE:
2843 case SIGSEGV:
2844 case SIGTERM:
2845 case SIGBREAK:
2846 case SIGABRT:
2847 break;
2848 /* Don't call signal() with other values or it will assert */
2849 default:
2850 return SIG_ERR;
2851 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002852#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002853 handler = signal(sig, SIG_IGN);
2854 if (handler != SIG_ERR)
2855 signal(sig, handler);
2856 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002857#endif
2858}
2859
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002860/*
2861 * All of the code in this function must only use async-signal-safe functions,
2862 * listed at `man 7 signal` or
2863 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2864 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002865PyOS_sighandler_t
2866PyOS_setsig(int sig, PyOS_sighandler_t handler)
2867{
2868#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002869 /* Some code in Modules/signalmodule.c depends on sigaction() being
2870 * used here if HAVE_SIGACTION is defined. Fix that if this code
2871 * changes to invalidate that assumption.
2872 */
2873 struct sigaction context, ocontext;
2874 context.sa_handler = handler;
2875 sigemptyset(&context.sa_mask);
2876 context.sa_flags = 0;
2877 if (sigaction(sig, &context, &ocontext) == -1)
2878 return SIG_ERR;
2879 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002880#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002881 PyOS_sighandler_t oldhandler;
2882 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002883#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002884 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002885#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002886 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002887#endif
2888}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002889
2890/* Deprecated C API functions still provided for binary compatiblity */
2891
2892#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002893PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002894PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2895{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002896 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002897}
2898
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002899#undef PyParser_SimpleParseString
2900PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002901PyParser_SimpleParseString(const char *str, int start)
2902{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002903 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002904}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002905
2906#undef PyRun_AnyFile
2907PyAPI_FUNC(int)
2908PyRun_AnyFile(FILE *fp, const char *name)
2909{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002910 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002911}
2912
2913#undef PyRun_AnyFileEx
2914PyAPI_FUNC(int)
2915PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2916{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002917 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002918}
2919
2920#undef PyRun_AnyFileFlags
2921PyAPI_FUNC(int)
2922PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2923{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002924 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002925}
2926
2927#undef PyRun_File
2928PyAPI_FUNC(PyObject *)
2929PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2930{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002931 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002932}
2933
2934#undef PyRun_FileEx
2935PyAPI_FUNC(PyObject *)
2936PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2937{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002938 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002939}
2940
2941#undef PyRun_FileFlags
2942PyAPI_FUNC(PyObject *)
2943PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002944 PyCompilerFlags *flags)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002945{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002946 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002947}
2948
2949#undef PyRun_SimpleFile
2950PyAPI_FUNC(int)
2951PyRun_SimpleFile(FILE *f, const char *p)
2952{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002953 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002954}
2955
2956#undef PyRun_SimpleFileEx
2957PyAPI_FUNC(int)
2958PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2959{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002960 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002961}
2962
2963
2964#undef PyRun_String
2965PyAPI_FUNC(PyObject *)
2966PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2967{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002968 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002969}
2970
2971#undef PyRun_SimpleString
2972PyAPI_FUNC(int)
2973PyRun_SimpleString(const char *s)
2974{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002975 return PyRun_SimpleStringFlags(s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002976}
2977
2978#undef Py_CompileString
2979PyAPI_FUNC(PyObject *)
2980Py_CompileString(const char *str, const char *p, int s)
2981{
Georg Brandl8334fd92010-12-04 10:26:46 +00002982 return Py_CompileStringExFlags(str, p, s, NULL, -1);
2983}
2984
2985#undef Py_CompileStringFlags
2986PyAPI_FUNC(PyObject *)
2987Py_CompileStringFlags(const char *str, const char *p, int s,
2988 PyCompilerFlags *flags)
2989{
2990 return Py_CompileStringExFlags(str, p, s, flags, -1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002991}
2992
2993#undef PyRun_InteractiveOne
2994PyAPI_FUNC(int)
2995PyRun_InteractiveOne(FILE *f, const char *p)
2996{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002997 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002998}
2999
3000#undef PyRun_InteractiveLoop
3001PyAPI_FUNC(int)
3002PyRun_InteractiveLoop(FILE *f, const char *p)
3003{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003004 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003005}
3006
3007#ifdef __cplusplus
3008}
3009#endif