blob: bac39c23b4d3e643124e9990d9eac93f993d288a [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
Victor Stinner00111242014-08-29 16:31:59 +0200455 if (_PyTime_Init() < 0)
456 Py_FatalError("Py_Initialize: can't initialize time");
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +0000457
Victor Stinner793b5312011-04-27 00:24:21 +0200458 if (initfsencoding(interp) < 0)
459 Py_FatalError("Py_Initialize: unable to load the file system codec");
Martin v. Löwis011e8422009-05-05 04:43:17 +0000460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 if (install_sigs)
462 initsigs(); /* Signal handling stuff, including initintr() */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000463
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100464 if (_PyTraceMalloc_Init() < 0)
465 Py_FatalError("Py_Initialize: can't initialize tracemalloc");
466
Nick Coghlan85e729e2012-07-15 18:09:52 +1000467 initmain(interp); /* Module __main__ */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 if (initstdio() < 0)
469 Py_FatalError(
470 "Py_Initialize: can't initialize sys standard streams");
471
Antoine Pitroucf9f9802010-11-10 13:55:25 +0000472 /* Initialize warnings. */
473 if (PySys_HasWarnOptions()) {
474 PyObject *warnings_module = PyImport_ImportModule("warnings");
475 if (warnings_module == NULL) {
476 fprintf(stderr, "'import warnings' failed; traceback:\n");
477 PyErr_Print();
478 }
479 Py_XDECREF(warnings_module);
480 }
481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 if (!Py_NoSiteFlag)
483 initsite(); /* Module site */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000484}
485
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000486void
Antoine Pitroue67f48c2012-06-19 22:29:35 +0200487Py_InitializeEx(int install_sigs)
488{
489 _Py_InitializeEx_Private(install_sigs, 1);
490}
491
492void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000493Py_Initialize(void)
494{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 Py_InitializeEx(1);
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000496}
497
498
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000499#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000500extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000501#endif
502
Guido van Rossume8432ac2007-07-09 15:04:50 +0000503/* Flush stdout and stderr */
504
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100505static int
506file_is_closed(PyObject *fobj)
507{
508 int r;
509 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
510 if (tmp == NULL) {
511 PyErr_Clear();
512 return 0;
513 }
514 r = PyObject_IsTrue(tmp);
515 Py_DECREF(tmp);
516 if (r < 0)
517 PyErr_Clear();
518 return r > 0;
519}
520
Neal Norwitz2bad9702007-08-27 06:19:22 +0000521static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000522flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000523{
Victor Stinnerbd303c12013-11-07 23:07:29 +0100524 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
525 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 PyObject *tmp;
Guido van Rossume8432ac2007-07-09 15:04:50 +0000527
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100528 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200529 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 if (tmp == NULL)
Antoine Pitroubddc9fe2010-08-08 20:46:42 +0000531 PyErr_WriteUnraisable(fout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 else
533 Py_DECREF(tmp);
534 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000535
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100536 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200537 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 if (tmp == NULL)
539 PyErr_Clear();
540 else
541 Py_DECREF(tmp);
542 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000543}
544
Guido van Rossum25ce5661997-08-02 03:10:38 +0000545/* Undo the effect of Py_Initialize().
546
547 Beware: if multiple interpreter and/or thread states exist, these
548 are not wiped out; only the current thread and interpreter state
549 are deleted. But since everything else is deleted, those other
550 interpreter and thread states should no longer be used.
551
552 (XXX We should do better, e.g. wipe out all interpreters and
553 threads.)
554
555 Locking: as above.
556
557*/
558
559void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000560Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000561{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 PyInterpreterState *interp;
563 PyThreadState *tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 if (!initialized)
566 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 wait_for_thread_shutdown();
Antoine Pitrou011bd622009-10-20 21:52:47 +0000569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 /* The interpreter is still entirely intact at this point, and the
571 * exit funcs may be relying on that. In particular, if some thread
572 * or exit func is still waiting to do an import, the import machinery
573 * expects Py_IsInitialized() to return true. So don't say the
574 * interpreter is uninitialized until after the exit funcs have run.
575 * Note that Threading.py uses an exit func to do a join on all the
576 * threads created thru it, so this also protects pending imports in
577 * the threads created via Threading.
578 */
579 call_py_exitfuncs();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 /* Get current thread state and interpreter pointer */
582 tstate = PyThreadState_GET();
583 interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000584
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200585 /* Remaining threads (e.g. daemon threads) will automatically exit
586 after taking the GIL (in PyEval_RestoreThread()). */
587 _Py_Finalizing = tstate;
588 initialized = 0;
589
Victor Stinner15054c12014-02-13 12:48:54 +0100590 /* Flush stdout+stderr */
591 flush_std_files();
592
593 /* Disable signal handling */
594 PyOS_FiniInterrupts();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 /* Collect garbage. This may call finalizers; it's nice to call these
597 * before all modules are destroyed.
598 * XXX If a __del__ or weakref callback is triggered here, and tries to
599 * XXX import a module, bad things can happen, because Python no
600 * XXX longer believes it's initialized.
601 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
602 * XXX is easy to provoke that way. I've also seen, e.g.,
603 * XXX Exception exceptions.ImportError: 'No module named sha'
604 * XXX in <function callback at 0x008F5718> ignored
605 * XXX but I'm unclear on exactly how that one happens. In any case,
606 * XXX I haven't seen a real-life report of either of these.
607 */
608 PyGC_Collect();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000609#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 /* With COUNT_ALLOCS, it helps to run GC multiple times:
611 each collection might release some types from the type
612 list, so they become garbage. */
613 while (PyGC_Collect() > 0)
614 /* nothing */;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000615#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 /* Destroy all modules */
617 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 /* Flush stdout+stderr (again, in case more was printed) */
620 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 /* Collect final garbage. This disposes of cycles created by
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100623 * class definitions, for example.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624 * XXX This is disabled because it caused too many problems. If
625 * XXX a __del__ or weakref callback triggers here, Python code has
626 * XXX a hard time running, because even the sys module has been
627 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
628 * XXX One symptom is a sequence of information-free messages
629 * XXX coming from threads (if a __del__ or callback is invoked,
630 * XXX other threads can execute too, and any exception they encounter
631 * XXX triggers a comedy of errors as subsystem after subsystem
632 * XXX fails to find what it *expects* to find in sys to help report
633 * XXX the exception and consequent unexpected failures). I've also
634 * XXX seen segfaults then, after adding print statements to the
635 * XXX Python code getting called.
636 */
Tim Peters1d7323e2003-12-01 21:35:27 +0000637#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000639#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000640
Victor Stinnerbe0708f2013-12-01 10:03:26 +0100641 /* Disable tracemalloc after all Python objects have been destroyed,
642 so it is possible to use tracemalloc in objects destructor. */
643 _PyTraceMalloc_Fini();
644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
646 _PyImport_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000647
Antoine Pitroufd417cc2013-05-05 08:12:42 +0200648 /* Cleanup typeobject.c's internal caches. */
649 _PyType_Fini();
650
Victor Stinner024e37a2011-03-31 01:31:06 +0200651 /* unload faulthandler module */
652 _PyFaulthandler_Fini();
653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 /* Debugging stuff */
Guido van Rossum1707aad1997-12-08 23:43:45 +0000655#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000656 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000657#endif
Christian Heimes985ecdc2013-11-20 11:46:18 +0100658 /* dump hash stats */
659 _PyHash_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000662
Tim Peters9cf25ce2003-04-17 15:21:01 +0000663#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000664 /* Display all objects still alive -- this can invoke arbitrary
665 * __repr__ overrides, so requires a mostly-intact interpreter.
666 * Alas, a lot of stuff may still be alive now that will be cleaned
667 * up later.
668 */
669 if (Py_GETENV("PYTHONDUMPREFS"))
670 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000671#endif /* Py_TRACE_REFS */
672
Antoine Pitroufd417cc2013-05-05 08:12:42 +0200673 /* Clear interpreter state and all thread states. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 /* Now we decref the exception classes. After this point nothing
677 can raise an exception. That's okay, because each Fini() method
678 below has been checked to make sure no exceptions are ever
679 raised.
680 */
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000681
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000682 _PyExc_Fini();
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 /* Sundry finalizers */
685 PyMethod_Fini();
686 PyFrame_Fini();
687 PyCFunction_Fini();
688 PyTuple_Fini();
689 PyList_Fini();
690 PySet_Fini();
691 PyBytes_Fini();
692 PyByteArray_Fini();
693 PyLong_Fini();
694 PyFloat_Fini();
695 PyDict_Fini();
Antoine Pitrouf34a0cd2011-11-18 20:14:34 +0100696 PySlice_Fini();
Antoine Pitrou5f454a02013-05-06 21:15:57 +0200697 _PyGC_Fini();
Antoine Pitrou4879a962013-08-31 00:26:02 +0200698 _PyRandom_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 /* Cleanup Unicode implementation */
701 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000702
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000703 /* reset file system default encoding */
Victor Stinnerb744ba12010-05-15 12:27:16 +0000704 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200705 PyMem_RawFree((char*)Py_FileSystemDefaultEncoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000706 Py_FileSystemDefaultEncoding = NULL;
707 }
Christian Heimesc8967002007-11-30 10:18:26 +0000708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 /* XXX Still allocated:
710 - various static ad-hoc pointers to interned strings
711 - int and float free list blocks
712 - whatever various modules and libraries allocate
713 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000716
Victor Stinner51fa4582013-07-07 15:50:49 +0200717 /* Cleanup auto-thread-state */
718#ifdef WITH_THREAD
719 _PyGILState_Fini();
720#endif /* WITH_THREAD */
721
722 /* Delete current thread. After this, many C API calls become crashy. */
723 PyThreadState_Swap(NULL);
724 PyInterpreterState_Delete(interp);
725
Tim Peters269b2a62003-04-17 19:52:29 +0000726#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000727 /* Display addresses (& refcnts) of all objects still alive.
728 * An address can be used to find the repr of the object, printed
729 * above by _Py_PrintReferences.
730 */
731 if (Py_GETENV("PYTHONDUMPREFS"))
732 _Py_PrintReferenceAddresses(stderr);
Tim Peters269b2a62003-04-17 19:52:29 +0000733#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000734#ifdef PYMALLOC_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000735 if (Py_GETENV("PYTHONMALLOCSTATS"))
David Malcolm49526f42012-06-22 14:55:41 -0400736 _PyObject_DebugMallocStats(stderr);
Tim Peters0e871182002-04-13 08:29:14 +0000737#endif
738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000740}
741
742/* Create and initialize a new interpreter and thread, and return the
743 new thread. This requires that Py_Initialize() has been called
744 first.
745
746 Unsuccessful initialization yields a NULL pointer. Note that *no*
747 exception information is available even in this case -- the
748 exception information is held in the thread, and there is no
749 thread.
750
751 Locking: as above.
752
753*/
754
755PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000756Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000757{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 PyInterpreterState *interp;
759 PyThreadState *tstate, *save_tstate;
760 PyObject *bimod, *sysmod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000761
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 if (!initialized)
763 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 interp = PyInterpreterState_New();
766 if (interp == NULL)
767 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 tstate = PyThreadState_New(interp);
770 if (tstate == NULL) {
771 PyInterpreterState_Delete(interp);
772 return NULL;
773 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 save_tstate = PyThreadState_Swap(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000777 /* XXX The following is lax in error checking */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 interp->modules = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000780
Victor Stinner49d3f252010-10-17 01:24:53 +0000781 bimod = _PyImport_FindBuiltin("builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 if (bimod != NULL) {
783 interp->builtins = PyModule_GetDict(bimod);
784 if (interp->builtins == NULL)
785 goto handle_error;
786 Py_INCREF(interp->builtins);
787 }
Christian Heimes6a27efa2008-10-30 21:48:26 +0000788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 /* initialize builtin exceptions */
Brett Cannonfd074152012-04-14 14:10:13 -0400790 _PyExc_Init(bimod);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000791
Victor Stinner49d3f252010-10-17 01:24:53 +0000792 sysmod = _PyImport_FindBuiltin("sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 if (bimod != NULL && sysmod != NULL) {
794 PyObject *pstderr;
Brett Cannonfd074152012-04-14 14:10:13 -0400795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 interp->sysdict = PyModule_GetDict(sysmod);
797 if (interp->sysdict == NULL)
798 goto handle_error;
799 Py_INCREF(interp->sysdict);
800 PySys_SetPath(Py_GetPath());
801 PyDict_SetItemString(interp->sysdict, "modules",
802 interp->modules);
803 /* Set up a preliminary stderr printer until we have enough
804 infrastructure for the io module in place. */
805 pstderr = PyFile_NewStdPrinter(fileno(stderr));
806 if (pstderr == NULL)
807 Py_FatalError("Py_Initialize: can't set preliminary stderr");
Victor Stinnerbd303c12013-11-07 23:07:29 +0100808 _PySys_SetObjectId(&PyId_stderr, pstderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000810 Py_DECREF(pstderr);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 _PyImportHooks_Init();
Victor Stinner793b5312011-04-27 00:24:21 +0200813
Brett Cannonfd074152012-04-14 14:10:13 -0400814 import_init(interp, sysmod);
815
Victor Stinner793b5312011-04-27 00:24:21 +0200816 if (initfsencoding(interp) < 0)
817 goto handle_error;
818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 if (initstdio() < 0)
820 Py_FatalError(
821 "Py_Initialize: can't initialize sys standard streams");
Nick Coghlan85e729e2012-07-15 18:09:52 +1000822 initmain(interp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 if (!Py_NoSiteFlag)
824 initsite();
825 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000826
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000827 if (!PyErr_Occurred())
828 return tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000829
Thomas Wouters89f507f2006-12-13 04:49:30 +0000830handle_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 /* Oops, it didn't work. Undo it all. */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000832
Victor Stinnerc40a3502011-04-27 00:20:27 +0200833 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 PyThreadState_Clear(tstate);
835 PyThreadState_Swap(save_tstate);
836 PyThreadState_Delete(tstate);
837 PyInterpreterState_Delete(interp);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000838
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000840}
841
842/* Delete an interpreter and its last thread. This requires that the
843 given thread state is current, that the thread has no remaining
844 frames, and that it is its interpreter's only remaining thread.
845 It is a fatal error to violate these constraints.
846
847 (Py_Finalize() doesn't have these constraints -- it zaps
848 everything, regardless.)
849
850 Locking: as above.
851
852*/
853
854void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000855Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000856{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000857 PyInterpreterState *interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000858
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 if (tstate != PyThreadState_GET())
860 Py_FatalError("Py_EndInterpreter: thread is not current");
861 if (tstate->frame != NULL)
862 Py_FatalError("Py_EndInterpreter: thread still has a frame");
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200863
864 wait_for_thread_shutdown();
865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 if (tstate != interp->tstate_head || tstate->next != NULL)
867 Py_FatalError("Py_EndInterpreter: not the last thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000868
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 PyImport_Cleanup();
870 PyInterpreterState_Clear(interp);
871 PyThreadState_Swap(NULL);
872 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000873}
874
Antoine Pitrou01cca5e2012-07-05 20:56:30 +0200875#ifdef MS_WINDOWS
Martin v. Löwis790465f2008-04-05 20:41:37 +0000876static wchar_t *progname = L"python";
Antoine Pitrou01cca5e2012-07-05 20:56:30 +0200877#else
878static wchar_t *progname = L"python3";
879#endif
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000880
881void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000882Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000883{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 if (pn && *pn)
885 progname = pn;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000886}
887
Martin v. Löwis790465f2008-04-05 20:41:37 +0000888wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000889Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000890{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000892}
893
Martin v. Löwis790465f2008-04-05 20:41:37 +0000894static wchar_t *default_home = NULL;
Victor Stinner55a12202013-08-28 01:47:46 +0200895static wchar_t env_home[MAXPATHLEN+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000896
897void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000898Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000899{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 default_home = home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000901}
902
Martin v. Löwis790465f2008-04-05 20:41:37 +0000903wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000904Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000905{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 wchar_t *home = default_home;
907 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
908 char* chome = Py_GETENV("PYTHONHOME");
909 if (chome) {
Victor Stinner2f5bbc62013-11-15 17:09:24 +0100910 size_t size = Py_ARRAY_LENGTH(env_home);
911 size_t r = mbstowcs(env_home, chome, size);
912 if (r != (size_t)-1 && r < size)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 home = env_home;
914 }
Martin v. Löwis790465f2008-04-05 20:41:37 +0000915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 }
917 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000918}
919
Guido van Rossum6135a871995-01-09 17:53:26 +0000920/* Create __main__ module */
921
922static void
Nick Coghlan85e729e2012-07-15 18:09:52 +1000923initmain(PyInterpreterState *interp)
Guido van Rossum6135a871995-01-09 17:53:26 +0000924{
Brett Cannon13853a62013-05-04 17:37:09 -0400925 PyObject *m, *d, *loader;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 m = PyImport_AddModule("__main__");
927 if (m == NULL)
928 Py_FatalError("can't create __main__ module");
929 d = PyModule_GetDict(m);
930 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
931 PyObject *bimod = PyImport_ImportModule("builtins");
Nick Coghlan85e729e2012-07-15 18:09:52 +1000932 if (bimod == NULL) {
933 Py_FatalError("Failed to retrieve builtins module");
934 }
935 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
936 Py_FatalError("Failed to initialize __main__.__builtins__");
937 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 Py_DECREF(bimod);
939 }
Nick Coghlan85e729e2012-07-15 18:09:52 +1000940 /* Main is a little special - imp.is_builtin("__main__") will return
941 * False, but BuiltinImporter is still the most appropriate initial
942 * setting for its __loader__ attribute. A more suitable value will
943 * be set if __main__ gets further initialized later in the startup
944 * process.
945 */
Brett Cannon13853a62013-05-04 17:37:09 -0400946 loader = PyDict_GetItemString(d, "__loader__");
Brett Cannon4c14b5d2013-05-04 13:56:58 -0400947 if (loader == NULL || loader == Py_None) {
Nick Coghlan85e729e2012-07-15 18:09:52 +1000948 PyObject *loader = PyObject_GetAttrString(interp->importlib,
949 "BuiltinImporter");
950 if (loader == NULL) {
951 Py_FatalError("Failed to retrieve BuiltinImporter");
952 }
953 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
954 Py_FatalError("Failed to initialize __main__.__loader__");
955 }
956 Py_DECREF(loader);
957 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000958}
959
Victor Stinner793b5312011-04-27 00:24:21 +0200960static int
961initfsencoding(PyInterpreterState *interp)
Victor Stinnerb744ba12010-05-15 12:27:16 +0000962{
963 PyObject *codec;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000964
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200965 if (Py_FileSystemDefaultEncoding == NULL)
966 {
967 Py_FileSystemDefaultEncoding = get_locale_encoding();
968 if (Py_FileSystemDefaultEncoding == NULL)
Victor Stinnere4743092010-10-19 00:05:51 +0000969 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
Victor Stinnerb744ba12010-05-15 12:27:16 +0000970
Victor Stinnere4743092010-10-19 00:05:51 +0000971 Py_HasFileSystemDefaultEncoding = 0;
Victor Stinner793b5312011-04-27 00:24:21 +0200972 interp->fscodec_initialized = 1;
973 return 0;
Victor Stinner7f84ab52010-06-11 00:36:33 +0000974 }
Victor Stinnerb744ba12010-05-15 12:27:16 +0000975
976 /* the encoding is mbcs, utf-8 or ascii */
977 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
978 if (!codec) {
979 /* Such error can only occurs in critical situations: no more
980 * memory, import a module of the standard library failed,
981 * etc. */
Victor Stinner793b5312011-04-27 00:24:21 +0200982 return -1;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000983 }
Victor Stinner793b5312011-04-27 00:24:21 +0200984 Py_DECREF(codec);
985 interp->fscodec_initialized = 1;
986 return 0;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000987}
988
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000989/* Import the site module (not into __main__ though) */
990
991static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000992initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000993{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 PyObject *m;
995 m = PyImport_ImportModule("site");
996 if (m == NULL) {
Victor Stinner62ce62a2013-07-22 22:53:28 +0200997 fprintf(stderr, "Failed to import the site module\n");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 PyErr_Print();
999 Py_Finalize();
1000 exit(1);
1001 }
1002 else {
1003 Py_DECREF(m);
1004 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +00001005}
1006
Antoine Pitrou05608432009-01-09 18:53:14 +00001007static PyObject*
1008create_stdio(PyObject* io,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 int fd, int write_mode, char* name,
1010 char* encoding, char* errors)
Antoine Pitrou05608432009-01-09 18:53:14 +00001011{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1013 const char* mode;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001014 const char* newline;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 PyObject *line_buffering;
1016 int buffering, isatty;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001017 _Py_IDENTIFIER(open);
1018 _Py_IDENTIFIER(isatty);
1019 _Py_IDENTIFIER(TextIOWrapper);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001020 _Py_IDENTIFIER(mode);
Antoine Pitrou05608432009-01-09 18:53:14 +00001021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 /* stdin is always opened in buffered mode, first because it shouldn't
1023 make a difference in common use cases, second because TextIOWrapper
1024 depends on the presence of a read1() method which only exists on
1025 buffered streams.
1026 */
1027 if (Py_UnbufferedStdioFlag && write_mode)
1028 buffering = 0;
1029 else
1030 buffering = -1;
1031 if (write_mode)
1032 mode = "wb";
1033 else
1034 mode = "rb";
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001035 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1036 fd, mode, buffering,
1037 Py_None, Py_None, Py_None, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 if (buf == NULL)
1039 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +00001040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 if (buffering) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001042 _Py_IDENTIFIER(raw);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001043 raw = _PyObject_GetAttrId(buf, &PyId_raw);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 if (raw == NULL)
1045 goto error;
1046 }
1047 else {
1048 raw = buf;
1049 Py_INCREF(raw);
1050 }
Antoine Pitrou05608432009-01-09 18:53:14 +00001051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 text = PyUnicode_FromString(name);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001053 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 goto error;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001055 res = _PyObject_CallMethodId(raw, &PyId_isatty, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 if (res == NULL)
1057 goto error;
1058 isatty = PyObject_IsTrue(res);
1059 Py_DECREF(res);
1060 if (isatty == -1)
1061 goto error;
1062 if (isatty || Py_UnbufferedStdioFlag)
1063 line_buffering = Py_True;
1064 else
1065 line_buffering = Py_False;
Antoine Pitrou91696412009-01-09 22:12:30 +00001066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 Py_CLEAR(raw);
1068 Py_CLEAR(text);
Antoine Pitrou91696412009-01-09 22:12:30 +00001069
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001070#ifdef MS_WINDOWS
Victor Stinner7b3f0fa2012-08-04 01:28:00 +02001071 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1072 newlines to "\n".
1073 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1074 newline = NULL;
1075#else
1076 /* sys.stdin: split lines at "\n".
1077 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1078 newline = "\n";
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001079#endif
1080
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001081 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssO",
1082 buf, encoding, errors,
1083 newline, line_buffering);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 Py_CLEAR(buf);
1085 if (stream == NULL)
1086 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +00001087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001088 if (write_mode)
1089 mode = "w";
1090 else
1091 mode = "r";
1092 text = PyUnicode_FromString(mode);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001093 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 goto error;
1095 Py_CLEAR(text);
1096 return stream;
Antoine Pitrou05608432009-01-09 18:53:14 +00001097
1098error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099 Py_XDECREF(buf);
1100 Py_XDECREF(stream);
1101 Py_XDECREF(text);
1102 Py_XDECREF(raw);
1103 return NULL;
Antoine Pitrou05608432009-01-09 18:53:14 +00001104}
1105
Antoine Pitrou11942a52011-11-28 19:08:36 +01001106static int
1107is_valid_fd(int fd)
1108{
1109 int dummy_fd;
1110 if (fd < 0 || !_PyVerify_fd(fd))
1111 return 0;
1112 dummy_fd = dup(fd);
1113 if (dummy_fd < 0)
1114 return 0;
1115 close(dummy_fd);
1116 return 1;
1117}
1118
Georg Brandl1a3284e2007-12-02 09:40:06 +00001119/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001120static int
1121initstdio(void)
1122{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 PyObject *iomod = NULL, *wrapper;
1124 PyObject *bimod = NULL;
1125 PyObject *m;
1126 PyObject *std = NULL;
1127 int status = 0, fd;
1128 PyObject * encoding_attr;
Serhiy Storchakabf28d2d2013-09-13 11:46:24 +03001129 char *pythonioencoding = NULL, *encoding, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 /* Hack to avoid a nasty recursion issue when Python is invoked
1132 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1133 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1134 goto error;
1135 }
1136 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001138 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1139 goto error;
1140 }
1141 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 if (!(bimod = PyImport_ImportModule("builtins"))) {
1144 goto error;
1145 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 if (!(iomod = PyImport_ImportModule("io"))) {
1148 goto error;
1149 }
1150 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1151 goto error;
1152 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 /* Set builtins.open */
1155 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
Antoine Pitrou5a96b522010-11-20 19:50:57 +00001156 Py_DECREF(wrapper);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001157 goto error;
1158 }
Antoine Pitrou5a96b522010-11-20 19:50:57 +00001159 Py_DECREF(wrapper);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001160
Nick Coghlan7d270ee2013-10-17 22:35:35 +10001161 encoding = _Py_StandardStreamEncoding;
1162 errors = _Py_StandardStreamErrors;
1163 if (!encoding || !errors) {
Victor Stinner71430292014-03-18 01:18:21 +01001164 if (!errors) {
1165 /* When the LC_CTYPE locale is the POSIX locale ("C locale"),
1166 stdin and stdout use the surrogateescape error handler by
1167 default, instead of the strict error handler. */
1168 char *loc = setlocale(LC_CTYPE, NULL);
1169 if (loc != NULL && strcmp(loc, "C") == 0)
1170 errors = "surrogateescape";
1171 }
1172
Nick Coghlan7d270ee2013-10-17 22:35:35 +10001173 pythonioencoding = Py_GETENV("PYTHONIOENCODING");
1174 if (pythonioencoding) {
1175 char *err;
1176 pythonioencoding = _PyMem_Strdup(pythonioencoding);
1177 if (pythonioencoding == NULL) {
1178 PyErr_NoMemory();
1179 goto error;
1180 }
1181 err = strchr(pythonioencoding, ':');
1182 if (err) {
1183 *err = '\0';
1184 err++;
Victor Stinner71430292014-03-18 01:18:21 +01001185 if (*err && !_Py_StandardStreamErrors) {
Nick Coghlan7d270ee2013-10-17 22:35:35 +10001186 errors = err;
1187 }
1188 }
1189 if (*pythonioencoding && !encoding) {
1190 encoding = pythonioencoding;
1191 }
Victor Stinner49fc8ec2013-07-07 23:30:24 +02001192 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001193 }
Martin v. Löwis0f599892008-06-02 11:13:03 +00001194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 /* Set sys.stdin */
1196 fd = fileno(stdin);
1197 /* Under some conditions stdin, stdout and stderr may not be connected
1198 * and fileno() may point to an invalid file descriptor. For example
1199 * GUI apps don't have valid standard streams by default.
1200 */
Antoine Pitrou11942a52011-11-28 19:08:36 +01001201 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 std = Py_None;
1203 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 }
1205 else {
1206 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1207 if (std == NULL)
1208 goto error;
1209 } /* if (fd < 0) */
1210 PySys_SetObject("__stdin__", std);
Victor Stinnerbd303c12013-11-07 23:07:29 +01001211 _PySys_SetObjectId(&PyId_stdin, std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001212 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214 /* Set sys.stdout */
1215 fd = fileno(stdout);
Antoine Pitrou11942a52011-11-28 19:08:36 +01001216 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 std = Py_None;
1218 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001219 }
1220 else {
1221 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1222 if (std == NULL)
1223 goto error;
1224 } /* if (fd < 0) */
1225 PySys_SetObject("__stdout__", std);
Victor Stinnerbd303c12013-11-07 23:07:29 +01001226 _PySys_SetObjectId(&PyId_stdout, std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001228
Guido van Rossum98297ee2007-11-06 21:34:58 +00001229#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001230 /* Set sys.stderr, replaces the preliminary stderr */
1231 fd = fileno(stderr);
Antoine Pitrou11942a52011-11-28 19:08:36 +01001232 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001233 std = Py_None;
1234 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001235 }
1236 else {
1237 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1238 if (std == NULL)
1239 goto error;
1240 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +00001241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001242 /* Same as hack above, pre-import stderr's codec to avoid recursion
1243 when import.c tries to write to stderr in verbose mode. */
1244 encoding_attr = PyObject_GetAttrString(std, "encoding");
1245 if (encoding_attr != NULL) {
Victor Stinner49fc8ec2013-07-07 23:30:24 +02001246 const char * std_encoding;
1247 std_encoding = _PyUnicode_AsString(encoding_attr);
1248 if (std_encoding != NULL) {
1249 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
Antoine Pitrou2fabfac2012-01-18 15:14:46 +01001250 Py_XDECREF(codec_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001251 }
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +00001252 Py_DECREF(encoding_attr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 }
1254 PyErr_Clear(); /* Not a fatal error if codec isn't available */
Trent Nelson39e307e2008-03-19 06:45:48 +00001255
Victor Stinnerba308832013-07-22 23:55:19 +02001256 if (PySys_SetObject("__stderr__", std) < 0) {
1257 Py_DECREF(std);
1258 goto error;
1259 }
Victor Stinnerbd303c12013-11-07 23:07:29 +01001260 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
Victor Stinnerba308832013-07-22 23:55:19 +02001261 Py_DECREF(std);
1262 goto error;
1263 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001265#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001267 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001268 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 status = -1;
1270 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001271
Nick Coghlan7d270ee2013-10-17 22:35:35 +10001272 /* We won't need them anymore. */
1273 if (_Py_StandardStreamEncoding) {
1274 PyMem_RawFree(_Py_StandardStreamEncoding);
1275 _Py_StandardStreamEncoding = NULL;
1276 }
1277 if (_Py_StandardStreamErrors) {
1278 PyMem_RawFree(_Py_StandardStreamErrors);
1279 _Py_StandardStreamErrors = NULL;
1280 }
Serhiy Storchakabf28d2d2013-09-13 11:46:24 +03001281 PyMem_Free(pythonioencoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001282 Py_XDECREF(bimod);
1283 Py_XDECREF(iomod);
1284 return status;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001285}
1286
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001287/* Parse input from a file and execute it */
1288
1289int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001290PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001291 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001292{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 if (filename == NULL)
1294 filename = "???";
1295 if (Py_FdIsInteractive(fp, filename)) {
1296 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
1297 if (closeit)
1298 fclose(fp);
1299 return err;
1300 }
1301 else
1302 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001303}
1304
1305int
Victor Stinner95701bd2013-11-06 18:41:07 +01001306PyRun_InteractiveLoopFlags(FILE *fp, const char *filename_str, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001307{
Victor Stinner95701bd2013-11-06 18:41:07 +01001308 PyObject *filename, *v;
1309 int ret, err;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001311
Victor Stinner95701bd2013-11-06 18:41:07 +01001312 filename = PyUnicode_DecodeFSDefault(filename_str);
1313 if (filename == NULL) {
1314 PyErr_Print();
1315 return -1;
1316 }
1317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001318 if (flags == NULL) {
1319 flags = &local_flags;
1320 local_flags.cf_flags = 0;
1321 }
Victor Stinner09054372013-11-06 22:41:44 +01001322 v = _PySys_GetObjectId(&PyId_ps1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001323 if (v == NULL) {
Victor Stinner09054372013-11-06 22:41:44 +01001324 _PySys_SetObjectId(&PyId_ps1, v = PyUnicode_FromString(">>> "));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 Py_XDECREF(v);
1326 }
Victor Stinner09054372013-11-06 22:41:44 +01001327 v = _PySys_GetObjectId(&PyId_ps2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328 if (v == NULL) {
Victor Stinner09054372013-11-06 22:41:44 +01001329 _PySys_SetObjectId(&PyId_ps2, v = PyUnicode_FromString("... "));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 Py_XDECREF(v);
1331 }
Victor Stinner95701bd2013-11-06 18:41:07 +01001332 err = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 for (;;) {
Victor Stinner95701bd2013-11-06 18:41:07 +01001334 ret = PyRun_InteractiveOneObject(fp, filename, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 PRINT_TOTAL_REFS();
Victor Stinner95701bd2013-11-06 18:41:07 +01001336 if (ret == E_EOF) {
1337 err = 0;
1338 break;
1339 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001340 /*
1341 if (ret == E_NOMEM)
Victor Stinner95701bd2013-11-06 18:41:07 +01001342 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001343 */
1344 }
Victor Stinner95701bd2013-11-06 18:41:07 +01001345 Py_DECREF(filename);
1346 return err;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001347}
1348
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001349/* compute parser flags based on compiler flags */
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001350static int PARSER_FLAGS(PyCompilerFlags *flags)
1351{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001352 int parser_flags = 0;
1353 if (!flags)
1354 return 0;
1355 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
1356 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1357 if (flags->cf_flags & PyCF_IGNORE_COOKIE)
1358 parser_flags |= PyPARSE_IGNORE_COOKIE;
1359 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
1360 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1361 return parser_flags;
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001362}
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001363
Thomas Wouters89f507f2006-12-13 04:49:30 +00001364#if 0
1365/* Keep an example of flags with future keyword support. */
1366#define PARSER_FLAGS(flags) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001367 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1368 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1369 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1370 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001371#endif
1372
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001373int
Victor Stinner95701bd2013-11-06 18:41:07 +01001374PyRun_InteractiveOneObject(FILE *fp, PyObject *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001375{
Victor Stinner95701bd2013-11-06 18:41:07 +01001376 PyObject *m, *d, *v, *w, *oenc = NULL, *mod_name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001377 mod_ty mod;
1378 PyArena *arena;
1379 char *ps1 = "", *ps2 = "", *enc = NULL;
1380 int errcode = 0;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001381 _Py_IDENTIFIER(encoding);
Victor Stinner95701bd2013-11-06 18:41:07 +01001382 _Py_IDENTIFIER(__main__);
1383
1384 mod_name = _PyUnicode_FromId(&PyId___main__); /* borrowed */
1385 if (mod_name == NULL) {
1386 PyErr_Print();
1387 return -1;
1388 }
Tim Petersfe2127d2001-07-16 05:37:24 +00001389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001390 if (fp == stdin) {
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -04001391 /* Fetch encoding from sys.stdin if possible. */
Victor Stinnerbd303c12013-11-07 23:07:29 +01001392 v = _PySys_GetObjectId(&PyId_stdin);
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -04001393 if (v && v != Py_None) {
1394 oenc = _PyObject_GetAttrId(v, &PyId_encoding);
1395 if (oenc)
1396 enc = _PyUnicode_AsString(oenc);
1397 if (!enc)
1398 PyErr_Clear();
1399 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001400 }
Victor Stinner09054372013-11-06 22:41:44 +01001401 v = _PySys_GetObjectId(&PyId_ps1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001402 if (v != NULL) {
1403 v = PyObject_Str(v);
1404 if (v == NULL)
1405 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001406 else if (PyUnicode_Check(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001407 ps1 = _PyUnicode_AsString(v);
Victor Stinner386fe712010-05-19 00:34:15 +00001408 if (ps1 == NULL) {
1409 PyErr_Clear();
1410 ps1 = "";
1411 }
1412 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001413 }
Victor Stinner09054372013-11-06 22:41:44 +01001414 w = _PySys_GetObjectId(&PyId_ps2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 if (w != NULL) {
1416 w = PyObject_Str(w);
1417 if (w == NULL)
1418 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001419 else if (PyUnicode_Check(w)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001420 ps2 = _PyUnicode_AsString(w);
Victor Stinner386fe712010-05-19 00:34:15 +00001421 if (ps2 == NULL) {
1422 PyErr_Clear();
1423 ps2 = "";
1424 }
1425 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 }
1427 arena = PyArena_New();
1428 if (arena == NULL) {
1429 Py_XDECREF(v);
1430 Py_XDECREF(w);
1431 Py_XDECREF(oenc);
1432 return -1;
1433 }
Victor Stinner95701bd2013-11-06 18:41:07 +01001434 mod = PyParser_ASTFromFileObject(fp, filename, enc,
1435 Py_single_input, ps1, ps2,
1436 flags, &errcode, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001437 Py_XDECREF(v);
1438 Py_XDECREF(w);
1439 Py_XDECREF(oenc);
1440 if (mod == NULL) {
1441 PyArena_Free(arena);
1442 if (errcode == E_EOF) {
1443 PyErr_Clear();
1444 return E_EOF;
1445 }
1446 PyErr_Print();
1447 return -1;
1448 }
Victor Stinner95701bd2013-11-06 18:41:07 +01001449 m = PyImport_AddModuleObject(mod_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001450 if (m == NULL) {
1451 PyArena_Free(arena);
1452 return -1;
1453 }
1454 d = PyModule_GetDict(m);
1455 v = run_mod(mod, filename, d, d, flags, arena);
1456 PyArena_Free(arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001457 if (v == NULL) {
1458 PyErr_Print();
Antoine Pitrou9845c7e2014-05-11 13:42:17 +02001459 flush_io();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001460 return -1;
1461 }
1462 Py_DECREF(v);
Antoine Pitrou9845c7e2014-05-11 13:42:17 +02001463 flush_io();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001464 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001465}
1466
Victor Stinner95701bd2013-11-06 18:41:07 +01001467int
1468PyRun_InteractiveOneFlags(FILE *fp, const char *filename_str, PyCompilerFlags *flags)
1469{
1470 PyObject *filename;
1471 int res;
1472
1473 filename = PyUnicode_DecodeFSDefault(filename_str);
1474 if (filename == NULL) {
1475 PyErr_Print();
1476 return -1;
1477 }
1478 res = PyRun_InteractiveOneObject(fp, filename, flags);
1479 Py_DECREF(filename);
1480 return res;
1481}
1482
1483
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001484/* Check whether a file maybe a pyc file: Look at the extension,
1485 the file type, and, if we may close it, at the first few bytes. */
1486
1487static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001488maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001489{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001490 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1491 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001493 /* Only look into the file if we are allowed to close it, since
1494 it then should also be seekable. */
1495 if (closeit) {
1496 /* Read only two bytes of the magic. If the file was opened in
1497 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1498 be read as they are on disk. */
1499 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1500 unsigned char buf[2];
1501 /* Mess: In case of -x, the stream is NOT at its start now,
1502 and ungetc() was used to push back the first newline,
1503 which makes the current stream position formally undefined,
1504 and a x-platform nightmare.
1505 Unfortunately, we have no direct way to know whether -x
1506 was specified. So we use a terrible hack: if the current
1507 stream position is not 0, we assume -x was specified, and
1508 give up. Bug 132850 on SourceForge spells out the
1509 hopelessness of trying anything else (fseek and ftell
1510 don't work predictably x-platform for text-mode files).
1511 */
1512 int ispyc = 0;
1513 if (ftell(fp) == 0) {
1514 if (fread(buf, 1, 2, fp) == 2 &&
1515 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
1516 ispyc = 1;
1517 rewind(fp);
1518 }
1519 return ispyc;
1520 }
1521 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001522}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001523
Antoine Pitrou32d483c2013-07-30 21:01:23 +02001524static int
1525set_main_loader(PyObject *d, const char *filename, const char *loader_name)
Nick Coghlan85e729e2012-07-15 18:09:52 +10001526{
1527 PyInterpreterState *interp;
1528 PyThreadState *tstate;
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001529 PyObject *filename_obj, *loader_type, *loader;
Nick Coghlanb7a58942012-07-15 23:21:08 +10001530 int result = 0;
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001531
1532 filename_obj = PyUnicode_DecodeFSDefault(filename);
1533 if (filename_obj == NULL)
1534 return -1;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001535 /* Get current thread state and interpreter pointer */
1536 tstate = PyThreadState_GET();
1537 interp = tstate->interp;
Nick Coghlan3f94cbf2012-07-15 19:10:39 +10001538 loader_type = PyObject_GetAttrString(interp->importlib, loader_name);
1539 if (loader_type == NULL) {
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001540 Py_DECREF(filename_obj);
Nick Coghlan3f94cbf2012-07-15 19:10:39 +10001541 return -1;
1542 }
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001543 loader = PyObject_CallFunction(loader_type, "sN", "__main__", filename_obj);
Nick Coghlanb7a58942012-07-15 23:21:08 +10001544 Py_DECREF(loader_type);
1545 if (loader == NULL) {
Nick Coghlan85e729e2012-07-15 18:09:52 +10001546 return -1;
1547 }
Nick Coghlanb7a58942012-07-15 23:21:08 +10001548 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
1549 result = -1;
1550 }
Nick Coghlan85e729e2012-07-15 18:09:52 +10001551 Py_DECREF(loader);
Nick Coghlanb7a58942012-07-15 23:21:08 +10001552 return result;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001553}
1554
1555int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001556PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001557 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001558{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 PyObject *m, *d, *v;
1560 const char *ext;
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001561 int set_file_name = 0, ret = -1;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00001562 size_t len;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001564 m = PyImport_AddModule("__main__");
1565 if (m == NULL)
1566 return -1;
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001567 Py_INCREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001568 d = PyModule_GetDict(m);
1569 if (PyDict_GetItemString(d, "__file__") == NULL) {
1570 PyObject *f;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00001571 f = PyUnicode_DecodeFSDefault(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 if (f == NULL)
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001573 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001574 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1575 Py_DECREF(f);
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001576 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001577 }
Barry Warsaw916048d2011-09-20 14:45:44 -04001578 if (PyDict_SetItemString(d, "__cached__", Py_None) < 0) {
1579 Py_DECREF(f);
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001580 goto done;
Barry Warsaw916048d2011-09-20 14:45:44 -04001581 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001582 set_file_name = 1;
1583 Py_DECREF(f);
1584 }
1585 len = strlen(filename);
1586 ext = filename + len - (len > 4 ? 4 : 0);
1587 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Christian Heimes04ac4c12012-09-11 15:47:28 +02001588 FILE *pyc_fp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001589 /* Try to run a pyc file. First, re-open in binary */
1590 if (closeit)
1591 fclose(fp);
Victor Stinnerdaf45552013-08-28 00:53:59 +02001592 if ((pyc_fp = _Py_fopen(filename, "rb")) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001593 fprintf(stderr, "python: Can't reopen .pyc file\n");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 goto done;
1595 }
1596 /* Turn on optimization if a .pyo file is given */
1597 if (strcmp(ext, ".pyo") == 0)
1598 Py_OptimizeFlag = 1;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001599
1600 if (set_main_loader(d, filename, "SourcelessFileLoader") < 0) {
1601 fprintf(stderr, "python: failed to set __main__.__loader__\n");
1602 ret = -1;
Christian Heimes04ac4c12012-09-11 15:47:28 +02001603 fclose(pyc_fp);
Nick Coghlan85e729e2012-07-15 18:09:52 +10001604 goto done;
1605 }
Christian Heimes04ac4c12012-09-11 15:47:28 +02001606 v = run_pyc_file(pyc_fp, filename, d, d, flags);
1607 fclose(pyc_fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001608 } else {
Nick Coghlan85e729e2012-07-15 18:09:52 +10001609 /* When running from stdin, leave __main__.__loader__ alone */
1610 if (strcmp(filename, "<stdin>") != 0 &&
1611 set_main_loader(d, filename, "SourceFileLoader") < 0) {
1612 fprintf(stderr, "python: failed to set __main__.__loader__\n");
1613 ret = -1;
1614 goto done;
1615 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
1617 closeit, flags);
1618 }
1619 flush_io();
1620 if (v == NULL) {
1621 PyErr_Print();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 goto done;
1623 }
1624 Py_DECREF(v);
1625 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001626 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001627 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1628 PyErr_Clear();
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001629 Py_DECREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001630 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001631}
1632
1633int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001634PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001635{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001636 PyObject *m, *d, *v;
1637 m = PyImport_AddModule("__main__");
1638 if (m == NULL)
1639 return -1;
1640 d = PyModule_GetDict(m);
1641 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
1642 if (v == NULL) {
1643 PyErr_Print();
1644 return -1;
1645 }
1646 Py_DECREF(v);
1647 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001648}
1649
Barry Warsaw035574d1997-08-29 22:07:17 +00001650static int
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001651parse_syntax_error(PyObject *err, PyObject **message, PyObject **filename,
1652 int *lineno, int *offset, PyObject **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001653{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 long hold;
1655 PyObject *v;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001656 _Py_IDENTIFIER(msg);
1657 _Py_IDENTIFIER(filename);
1658 _Py_IDENTIFIER(lineno);
1659 _Py_IDENTIFIER(offset);
1660 _Py_IDENTIFIER(text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001661
Benjamin Peterson80d50422012-04-03 00:30:38 -04001662 *message = NULL;
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001663 *filename = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001665 /* new style errors. `err' is an instance */
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001666 *message = _PyObject_GetAttrId(err, &PyId_msg);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001667 if (!*message)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001668 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001669
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001670 v = _PyObject_GetAttrId(err, &PyId_filename);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001671 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001672 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001673 if (v == Py_None) {
1674 Py_DECREF(v);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001675 *filename = _PyUnicode_FromId(&PyId_string);
1676 if (*filename == NULL)
1677 goto finally;
1678 Py_INCREF(*filename);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001679 }
1680 else {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001681 *filename = v;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001682 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001683
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001684 v = _PyObject_GetAttrId(err, &PyId_lineno);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001685 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001686 goto finally;
1687 hold = PyLong_AsLong(v);
1688 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001689 if (hold < 0 && PyErr_Occurred())
1690 goto finally;
1691 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001692
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001693 v = _PyObject_GetAttrId(err, &PyId_offset);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001694 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001695 goto finally;
1696 if (v == Py_None) {
1697 *offset = -1;
1698 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001699 } else {
1700 hold = PyLong_AsLong(v);
1701 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 if (hold < 0 && PyErr_Occurred())
1703 goto finally;
1704 *offset = (int)hold;
1705 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001706
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001707 v = _PyObject_GetAttrId(err, &PyId_text);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001708 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001710 if (v == Py_None) {
1711 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001712 *text = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001713 }
1714 else {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001715 *text = v;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001716 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001717 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001718
1719finally:
Benjamin Peterson80d50422012-04-03 00:30:38 -04001720 Py_XDECREF(*message);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001721 Py_XDECREF(*filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001722 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001723}
1724
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001725void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001726PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001727{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001728 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001729}
1730
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001731static void
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001732print_error_text(PyObject *f, int offset, PyObject *text_obj)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001733{
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001734 char *text;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 char *nl;
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001736
1737 text = _PyUnicode_AsString(text_obj);
1738 if (text == NULL)
1739 return;
1740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001741 if (offset >= 0) {
Victor Stinner98ea54c2014-08-15 23:30:40 +02001742 if (offset > 0 && (size_t)offset == strlen(text) && text[offset - 1] == '\n')
Benjamin Petersona95e9772010-10-29 03:28:14 +00001743 offset--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001744 for (;;) {
1745 nl = strchr(text, '\n');
1746 if (nl == NULL || nl-text >= offset)
1747 break;
1748 offset -= (int)(nl+1-text);
1749 text = nl+1;
1750 }
1751 while (*text == ' ' || *text == '\t') {
1752 text++;
1753 offset--;
1754 }
1755 }
1756 PyFile_WriteString(" ", f);
1757 PyFile_WriteString(text, f);
1758 if (*text == '\0' || text[strlen(text)-1] != '\n')
1759 PyFile_WriteString("\n", f);
1760 if (offset == -1)
1761 return;
1762 PyFile_WriteString(" ", f);
Benjamin Petersona95e9772010-10-29 03:28:14 +00001763 while (--offset > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001764 PyFile_WriteString(" ", f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001766}
1767
Guido van Rossum66e8e862001-03-23 17:54:43 +00001768static void
1769handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001770{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001771 PyObject *exception, *value, *tb;
1772 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 if (Py_InspectFlag)
1775 /* Don't exit if -i flag was given. This flag is set to 0
1776 * when entering interactive mode for inspecting. */
1777 return;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001779 PyErr_Fetch(&exception, &value, &tb);
1780 fflush(stdout);
1781 if (value == NULL || value == Py_None)
1782 goto done;
1783 if (PyExceptionInstance_Check(value)) {
1784 /* The error code should be in the `code' attribute. */
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001785 _Py_IDENTIFIER(code);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001786 PyObject *code = _PyObject_GetAttrId(value, &PyId_code);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 if (code) {
1788 Py_DECREF(value);
1789 value = code;
1790 if (value == Py_None)
1791 goto done;
1792 }
1793 /* If we failed to dig out the 'code' attribute,
1794 just let the else clause below print the error. */
1795 }
1796 if (PyLong_Check(value))
1797 exitcode = (int)PyLong_AsLong(value);
1798 else {
Victor Stinnerbd303c12013-11-07 23:07:29 +01001799 PyObject *sys_stderr = _PySys_GetObjectId(&PyId_stderr);
Nick Coghland979e432014-02-09 10:43:21 +10001800 /* We clear the exception here to avoid triggering the assertion
1801 * in PyObject_Str that ensures it won't silently lose exception
1802 * details.
1803 */
1804 PyErr_Clear();
Victor Stinner7126dbc2010-05-21 23:45:42 +00001805 if (sys_stderr != NULL && sys_stderr != Py_None) {
1806 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
1807 } else {
1808 PyObject_Print(value, stderr, Py_PRINT_RAW);
1809 fflush(stderr);
1810 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001811 PySys_WriteStderr("\n");
1812 exitcode = 1;
1813 }
Tim Peterscf615b52003-04-19 18:47:02 +00001814 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001815 /* Restore and clear the exception info, in order to properly decref
1816 * the exception, value, and traceback. If we just exit instead,
1817 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1818 * some finalizers from running.
1819 */
1820 PyErr_Restore(exception, value, tb);
1821 PyErr_Clear();
1822 Py_Exit(exitcode);
1823 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001824}
1825
1826void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001827PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001828{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001829 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001831 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1832 handle_system_exit();
1833 }
1834 PyErr_Fetch(&exception, &v, &tb);
1835 if (exception == NULL)
1836 return;
1837 PyErr_NormalizeException(&exception, &v, &tb);
1838 if (tb == NULL) {
1839 tb = Py_None;
1840 Py_INCREF(tb);
1841 }
1842 PyException_SetTraceback(v, tb);
1843 if (exception == NULL)
1844 return;
1845 /* Now we know v != NULL too */
1846 if (set_sys_last_vars) {
Victor Stinner09054372013-11-06 22:41:44 +01001847 _PySys_SetObjectId(&PyId_last_type, exception);
1848 _PySys_SetObjectId(&PyId_last_value, v);
1849 _PySys_SetObjectId(&PyId_last_traceback, tb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 }
Victor Stinner09054372013-11-06 22:41:44 +01001851 hook = _PySys_GetObjectId(&PyId_excepthook);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001852 if (hook) {
1853 PyObject *args = PyTuple_Pack(3, exception, v, tb);
1854 PyObject *result = PyEval_CallObject(hook, args);
1855 if (result == NULL) {
1856 PyObject *exception2, *v2, *tb2;
1857 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1858 handle_system_exit();
1859 }
1860 PyErr_Fetch(&exception2, &v2, &tb2);
1861 PyErr_NormalizeException(&exception2, &v2, &tb2);
1862 /* It should not be possible for exception2 or v2
1863 to be NULL. However PyErr_Display() can't
1864 tolerate NULLs, so just be safe. */
1865 if (exception2 == NULL) {
1866 exception2 = Py_None;
1867 Py_INCREF(exception2);
1868 }
1869 if (v2 == NULL) {
1870 v2 = Py_None;
1871 Py_INCREF(v2);
1872 }
1873 fflush(stdout);
1874 PySys_WriteStderr("Error in sys.excepthook:\n");
1875 PyErr_Display(exception2, v2, tb2);
1876 PySys_WriteStderr("\nOriginal exception was:\n");
1877 PyErr_Display(exception, v, tb);
1878 Py_DECREF(exception2);
1879 Py_DECREF(v2);
1880 Py_XDECREF(tb2);
1881 }
1882 Py_XDECREF(result);
1883 Py_XDECREF(args);
1884 } else {
1885 PySys_WriteStderr("sys.excepthook is missing\n");
1886 PyErr_Display(exception, v, tb);
1887 }
1888 Py_XDECREF(exception);
1889 Py_XDECREF(v);
1890 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001891}
1892
Benjamin Petersone6528212008-07-15 15:32:09 +00001893static void
1894print_exception(PyObject *f, PyObject *value)
1895{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001896 int err = 0;
1897 PyObject *type, *tb;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001898 _Py_IDENTIFIER(print_file_and_line);
Benjamin Petersone6528212008-07-15 15:32:09 +00001899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001900 if (!PyExceptionInstance_Check(value)) {
Victor Stinner52ce3b02013-12-09 02:10:08 +01001901 err = PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1902 err += PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1903 err += PyFile_WriteString(" found\n", f);
1904 if (err)
1905 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001906 return;
1907 }
Benjamin Peterson26582602008-08-23 20:08:07 +00001908
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001909 Py_INCREF(value);
1910 fflush(stdout);
1911 type = (PyObject *) Py_TYPE(value);
1912 tb = PyException_GetTraceback(value);
1913 if (tb && tb != Py_None)
1914 err = PyTraceBack_Print(tb, f);
1915 if (err == 0 &&
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001916 _PyObject_HasAttrId(value, &PyId_print_file_and_line))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001917 {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001918 PyObject *message, *filename, *text;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001919 int lineno, offset;
1920 if (!parse_syntax_error(value, &message, &filename,
1921 &lineno, &offset, &text))
1922 PyErr_Clear();
1923 else {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001924 PyObject *line;
1925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001926 Py_DECREF(value);
1927 value = message;
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001928
1929 line = PyUnicode_FromFormat(" File \"%U\", line %d\n",
1930 filename, lineno);
1931 Py_DECREF(filename);
1932 if (line != NULL) {
1933 PyFile_WriteObject(line, f, Py_PRINT_RAW);
1934 Py_DECREF(line);
1935 }
1936
1937 if (text != NULL) {
1938 print_error_text(f, offset, text);
1939 Py_DECREF(text);
1940 }
1941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001942 /* Can't be bothered to check all those
1943 PyFile_WriteString() calls */
1944 if (PyErr_Occurred())
1945 err = -1;
1946 }
1947 }
1948 if (err) {
1949 /* Don't do anything else */
1950 }
1951 else {
1952 PyObject* moduleName;
1953 char* className;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001954 _Py_IDENTIFIER(__module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001955 assert(PyExceptionClass_Check(type));
1956 className = PyExceptionClass_Name(type);
1957 if (className != NULL) {
1958 char *dot = strrchr(className, '.');
1959 if (dot != NULL)
1960 className = dot+1;
1961 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001962
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001963 moduleName = _PyObject_GetAttrId(type, &PyId___module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001964 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1965 {
Victor Stinner13b21bd2011-05-26 14:25:13 +02001966 Py_XDECREF(moduleName);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001967 err = PyFile_WriteString("<unknown>", f);
1968 }
1969 else {
Victor Stinnerbd303c12013-11-07 23:07:29 +01001970 if (_PyUnicode_CompareWithId(moduleName, &PyId_builtins) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001971 {
Victor Stinner937114f2013-11-07 00:12:30 +01001972 err = PyFile_WriteObject(moduleName, f, Py_PRINT_RAW);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001973 err += PyFile_WriteString(".", f);
1974 }
1975 Py_DECREF(moduleName);
1976 }
1977 if (err == 0) {
1978 if (className == NULL)
1979 err = PyFile_WriteString("<unknown>", f);
1980 else
1981 err = PyFile_WriteString(className, f);
1982 }
1983 }
1984 if (err == 0 && (value != Py_None)) {
1985 PyObject *s = PyObject_Str(value);
1986 /* only print colon if the str() of the
1987 object is not the empty string
1988 */
1989 if (s == NULL)
1990 err = -1;
1991 else if (!PyUnicode_Check(s) ||
Victor Stinnere251d6d2011-11-20 19:20:00 +01001992 PyUnicode_GetLength(s) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 err = PyFile_WriteString(": ", f);
1994 if (err == 0)
1995 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1996 Py_XDECREF(s);
1997 }
1998 /* try to write a newline in any case */
1999 err += PyFile_WriteString("\n", f);
2000 Py_XDECREF(tb);
2001 Py_DECREF(value);
2002 /* If an error happened here, don't show it.
2003 XXX This is wrong, but too many callers rely on this behavior. */
2004 if (err != 0)
2005 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00002006}
2007
2008static const char *cause_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002009 "\nThe above exception was the direct cause "
2010 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00002011
2012static const char *context_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002013 "\nDuring handling of the above exception, "
2014 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00002015
2016static void
2017print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
2018{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002019 int err = 0, res;
2020 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00002021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002022 if (seen != NULL) {
2023 /* Exception chaining */
2024 if (PySet_Add(seen, value) == -1)
2025 PyErr_Clear();
2026 else if (PyExceptionInstance_Check(value)) {
2027 cause = PyException_GetCause(value);
2028 context = PyException_GetContext(value);
Benjamin Petersond5a1c442012-05-14 22:09:31 -07002029 if (cause) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 res = PySet_Contains(seen, cause);
2031 if (res == -1)
2032 PyErr_Clear();
2033 if (res == 0) {
2034 print_exception_recursive(
2035 f, cause, seen);
2036 err |= PyFile_WriteString(
2037 cause_message, f);
2038 }
2039 }
Benjamin Petersond5a1c442012-05-14 22:09:31 -07002040 else if (context &&
2041 !((PyBaseExceptionObject *)value)->suppress_context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002042 res = PySet_Contains(seen, context);
2043 if (res == -1)
2044 PyErr_Clear();
2045 if (res == 0) {
2046 print_exception_recursive(
2047 f, context, seen);
2048 err |= PyFile_WriteString(
2049 context_message, f);
2050 }
2051 }
2052 Py_XDECREF(context);
2053 Py_XDECREF(cause);
2054 }
2055 }
2056 print_exception(f, value);
2057 if (err != 0)
2058 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00002059}
2060
Thomas Wouters477c8d52006-05-27 19:21:47 +00002061void
2062PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002063{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 PyObject *seen;
Victor Stinnerbd303c12013-11-07 23:07:29 +01002065 PyObject *f = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrou24201d42013-10-13 21:53:13 +02002066 if (PyExceptionInstance_Check(value)
2067 && tb != NULL && PyTraceBack_Check(tb)) {
2068 /* Put the traceback on the exception, otherwise it won't get
2069 displayed. See issue #18776. */
2070 PyObject *cur_tb = PyException_GetTraceback(value);
2071 if (cur_tb == NULL)
2072 PyException_SetTraceback(value, tb);
2073 else
2074 Py_DECREF(cur_tb);
2075 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002076 if (f == Py_None) {
2077 /* pass */
2078 }
2079 else if (f == NULL) {
2080 _PyObject_Dump(value);
2081 fprintf(stderr, "lost sys.stderr\n");
2082 }
2083 else {
2084 /* We choose to ignore seen being possibly NULL, and report
2085 at least the main exception (it could be a MemoryError).
2086 */
2087 seen = PySet_New(NULL);
2088 if (seen == NULL)
2089 PyErr_Clear();
2090 print_exception_recursive(f, value, seen);
2091 Py_XDECREF(seen);
2092 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002093}
2094
Guido van Rossum82598051997-03-05 00:20:32 +00002095PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002096PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002097 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002098{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002099 PyObject *ret = NULL;
2100 mod_ty mod;
Victor Stinner95701bd2013-11-06 18:41:07 +01002101 PyArena *arena;
Victor Stinner95701bd2013-11-06 18:41:07 +01002102 PyObject *filename;
2103
2104 filename = _PyUnicode_FromId(&PyId_string); /* borrowed */
2105 if (filename == NULL)
2106 return NULL;
2107
2108 arena = PyArena_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002109 if (arena == NULL)
2110 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00002111
Victor Stinner95701bd2013-11-06 18:41:07 +01002112 mod = PyParser_ASTFromStringObject(str, filename, start, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002113 if (mod != NULL)
Victor Stinner95701bd2013-11-06 18:41:07 +01002114 ret = run_mod(mod, filename, globals, locals, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 PyArena_Free(arena);
2116 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002117}
2118
2119PyObject *
Victor Stinner95701bd2013-11-06 18:41:07 +01002120PyRun_FileExFlags(FILE *fp, const char *filename_str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002122{
Victor Stinner95701bd2013-11-06 18:41:07 +01002123 PyObject *ret = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 mod_ty mod;
Victor Stinner95701bd2013-11-06 18:41:07 +01002125 PyArena *arena = NULL;
2126 PyObject *filename;
Guido van Rossum98297ee2007-11-06 21:34:58 +00002127
Victor Stinner95701bd2013-11-06 18:41:07 +01002128 filename = PyUnicode_DecodeFSDefault(filename_str);
2129 if (filename == NULL)
2130 goto exit;
2131
2132 arena = PyArena_New();
2133 if (arena == NULL)
2134 goto exit;
2135
2136 mod = PyParser_ASTFromFileObject(fp, filename, NULL, start, 0, 0,
2137 flags, NULL, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002138 if (closeit)
2139 fclose(fp);
2140 if (mod == NULL) {
Victor Stinner95701bd2013-11-06 18:41:07 +01002141 goto exit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002142 }
2143 ret = run_mod(mod, filename, globals, locals, flags, arena);
Victor Stinner95701bd2013-11-06 18:41:07 +01002144
2145exit:
2146 Py_XDECREF(filename);
2147 if (arena != NULL)
2148 PyArena_Free(arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002150}
2151
Guido van Rossum6c193fa2007-12-05 05:14:58 +00002152static void
2153flush_io(void)
2154{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155 PyObject *f, *r;
2156 PyObject *type, *value, *traceback;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00002157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002158 /* Save the current exception */
2159 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00002160
Victor Stinnerbd303c12013-11-07 23:07:29 +01002161 f = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002162 if (f != NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002163 r = _PyObject_CallMethodId(f, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 if (r)
2165 Py_DECREF(r);
2166 else
2167 PyErr_Clear();
2168 }
Victor Stinnerbd303c12013-11-07 23:07:29 +01002169 f = _PySys_GetObjectId(&PyId_stdout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002170 if (f != NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002171 r = _PyObject_CallMethodId(f, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002172 if (r)
2173 Py_DECREF(r);
2174 else
2175 PyErr_Clear();
2176 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00002177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002178 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00002179}
2180
Guido van Rossum82598051997-03-05 00:20:32 +00002181static PyObject *
Victor Stinner95701bd2013-11-06 18:41:07 +01002182run_mod(mod_ty mod, PyObject *filename, PyObject *globals, PyObject *locals,
2183 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002184{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002185 PyCodeObject *co;
2186 PyObject *v;
Victor Stinner95701bd2013-11-06 18:41:07 +01002187 co = PyAST_CompileObject(mod, filename, flags, -1, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002188 if (co == NULL)
2189 return NULL;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002190 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002191 Py_DECREF(co);
2192 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002193}
2194
Guido van Rossum82598051997-03-05 00:20:32 +00002195static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002196run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00002198{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002199 PyCodeObject *co;
2200 PyObject *v;
2201 long magic;
2202 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00002203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002204 magic = PyMarshal_ReadLongFromFile(fp);
2205 if (magic != PyImport_GetMagicNumber()) {
2206 PyErr_SetString(PyExc_RuntimeError,
2207 "Bad magic number in .pyc file");
2208 return NULL;
2209 }
Antoine Pitrou5136ac02012-01-13 18:52:16 +01002210 /* Skip mtime and size */
2211 (void) PyMarshal_ReadLongFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002212 (void) PyMarshal_ReadLongFromFile(fp);
2213 v = PyMarshal_ReadLastObjectFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002214 if (v == NULL || !PyCode_Check(v)) {
2215 Py_XDECREF(v);
2216 PyErr_SetString(PyExc_RuntimeError,
2217 "Bad code object in .pyc file");
2218 return NULL;
2219 }
2220 co = (PyCodeObject *)v;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002221 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002222 if (v && flags)
2223 flags->cf_flags |= (co->co_flags & PyCF_MASK);
2224 Py_DECREF(co);
2225 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00002226}
2227
Guido van Rossum82598051997-03-05 00:20:32 +00002228PyObject *
Victor Stinner14e461d2013-08-26 22:28:21 +02002229Py_CompileStringObject(const char *str, PyObject *filename, int start,
2230 PyCompilerFlags *flags, int optimize)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002231{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002232 PyCodeObject *co;
2233 mod_ty mod;
2234 PyArena *arena = PyArena_New();
2235 if (arena == NULL)
2236 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002237
Victor Stinner14e461d2013-08-26 22:28:21 +02002238 mod = PyParser_ASTFromStringObject(str, filename, start, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002239 if (mod == NULL) {
2240 PyArena_Free(arena);
2241 return NULL;
2242 }
2243 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
2244 PyObject *result = PyAST_mod2obj(mod);
2245 PyArena_Free(arena);
2246 return result;
2247 }
Victor Stinner14e461d2013-08-26 22:28:21 +02002248 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249 PyArena_Free(arena);
2250 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00002251}
2252
Victor Stinner14e461d2013-08-26 22:28:21 +02002253PyObject *
2254Py_CompileStringExFlags(const char *str, const char *filename_str, int start,
2255 PyCompilerFlags *flags, int optimize)
2256{
2257 PyObject *filename, *co;
2258 filename = PyUnicode_DecodeFSDefault(filename_str);
2259 if (filename == NULL)
2260 return NULL;
2261 co = Py_CompileStringObject(str, filename, start, flags, optimize);
2262 Py_DECREF(filename);
2263 return co;
2264}
2265
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002266/* For use in Py_LIMITED_API */
2267#undef Py_CompileString
2268PyObject *
2269PyCompileString(const char *str, const char *filename, int start)
2270{
2271 return Py_CompileStringFlags(str, filename, start, NULL);
2272}
2273
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002274struct symtable *
Victor Stinner14e461d2013-08-26 22:28:21 +02002275Py_SymtableStringObject(const char *str, PyObject *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002276{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002277 struct symtable *st;
2278 mod_ty mod;
2279 PyCompilerFlags flags;
Victor Stinner14e461d2013-08-26 22:28:21 +02002280 PyArena *arena;
2281
2282 arena = PyArena_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002283 if (arena == NULL)
2284 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002286 flags.cf_flags = 0;
Victor Stinner14e461d2013-08-26 22:28:21 +02002287 mod = PyParser_ASTFromStringObject(str, filename, start, &flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002288 if (mod == NULL) {
2289 PyArena_Free(arena);
2290 return NULL;
2291 }
Victor Stinner14e461d2013-08-26 22:28:21 +02002292 st = PySymtable_BuildObject(mod, filename, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002293 PyArena_Free(arena);
2294 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002295}
2296
Victor Stinner14e461d2013-08-26 22:28:21 +02002297struct symtable *
2298Py_SymtableString(const char *str, const char *filename_str, int start)
2299{
2300 PyObject *filename;
2301 struct symtable *st;
2302
2303 filename = PyUnicode_DecodeFSDefault(filename_str);
2304 if (filename == NULL)
2305 return NULL;
2306 st = Py_SymtableStringObject(str, filename, start);
2307 Py_DECREF(filename);
2308 return st;
2309}
2310
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002311/* Preferred access to parser is through AST. */
2312mod_ty
Victor Stinner14e461d2013-08-26 22:28:21 +02002313PyParser_ASTFromStringObject(const char *s, PyObject *filename, int start,
2314 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002315{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002316 mod_ty mod;
2317 PyCompilerFlags localflags;
2318 perrdetail err;
2319 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00002320
Victor Stinner14e461d2013-08-26 22:28:21 +02002321 node *n = PyParser_ParseStringObject(s, filename,
2322 &_PyParser_Grammar, start, &err,
2323 &iflags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 if (flags == NULL) {
2325 localflags.cf_flags = 0;
2326 flags = &localflags;
2327 }
2328 if (n) {
2329 flags->cf_flags |= iflags & PyCF_MASK;
Victor Stinner14e461d2013-08-26 22:28:21 +02002330 mod = PyAST_FromNodeObject(n, flags, filename, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002331 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002332 }
2333 else {
2334 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002335 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002336 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002337 err_free(&err);
2338 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002339}
2340
2341mod_ty
Victor Stinner14e461d2013-08-26 22:28:21 +02002342PyParser_ASTFromString(const char *s, const char *filename_str, int start,
2343 PyCompilerFlags *flags, PyArena *arena)
2344{
2345 PyObject *filename;
2346 mod_ty mod;
2347 filename = PyUnicode_DecodeFSDefault(filename_str);
2348 if (filename == NULL)
2349 return NULL;
2350 mod = PyParser_ASTFromStringObject(s, filename, start, flags, arena);
2351 Py_DECREF(filename);
2352 return mod;
2353}
2354
2355mod_ty
2356PyParser_ASTFromFileObject(FILE *fp, PyObject *filename, const char* enc,
2357 int start, char *ps1,
2358 char *ps2, PyCompilerFlags *flags, int *errcode,
2359 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002360{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002361 mod_ty mod;
2362 PyCompilerFlags localflags;
2363 perrdetail err;
2364 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00002365
Victor Stinner14e461d2013-08-26 22:28:21 +02002366 node *n = PyParser_ParseFileObject(fp, filename, enc,
2367 &_PyParser_Grammar,
2368 start, ps1, ps2, &err, &iflags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002369 if (flags == NULL) {
2370 localflags.cf_flags = 0;
2371 flags = &localflags;
2372 }
2373 if (n) {
2374 flags->cf_flags |= iflags & PyCF_MASK;
Victor Stinner14e461d2013-08-26 22:28:21 +02002375 mod = PyAST_FromNodeObject(n, flags, filename, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002376 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002377 }
2378 else {
2379 err_input(&err);
2380 if (errcode)
2381 *errcode = err.error;
Victor Stinner7f2fee32011-04-05 00:39:01 +02002382 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002383 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002384 err_free(&err);
2385 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002386}
2387
Victor Stinner14e461d2013-08-26 22:28:21 +02002388mod_ty
2389PyParser_ASTFromFile(FILE *fp, const char *filename_str, const char* enc,
2390 int start, char *ps1,
2391 char *ps2, PyCompilerFlags *flags, int *errcode,
2392 PyArena *arena)
2393{
2394 mod_ty mod;
2395 PyObject *filename;
2396 filename = PyUnicode_DecodeFSDefault(filename_str);
2397 if (filename == NULL)
2398 return NULL;
2399 mod = PyParser_ASTFromFileObject(fp, filename, enc, start, ps1, ps2,
2400 flags, errcode, arena);
2401 Py_DECREF(filename);
2402 return mod;
2403}
2404
Guido van Rossuma110aa61994-08-29 12:50:44 +00002405/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002406
Guido van Rossuma110aa61994-08-29 12:50:44 +00002407node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002408PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002409{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002410 perrdetail err;
2411 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
2412 &_PyParser_Grammar,
2413 start, NULL, NULL, &err, flags);
2414 if (n == NULL)
2415 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002416 err_free(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002418 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002419}
2420
Guido van Rossuma110aa61994-08-29 12:50:44 +00002421/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002422
Guido van Rossuma110aa61994-08-29 12:50:44 +00002423node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002424PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00002425{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002426 perrdetail err;
2427 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
2428 start, &err, flags);
2429 if (n == NULL)
2430 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002431 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002432 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00002433}
2434
2435node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002436PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002437 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00002438{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002439 perrdetail err;
2440 node *n = PyParser_ParseStringFlagsFilename(str, filename,
2441 &_PyParser_Grammar, start, &err, flags);
2442 if (n == NULL)
2443 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002444 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002445 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00002446}
2447
2448node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002449PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00002450{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002451 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00002452}
2453
Guido van Rossum66ebd912003-04-17 16:02:26 +00002454/* May want to move a more generalized form of this to parsetok.c or
2455 even parser modules. */
2456
2457void
Victor Stinner7f2fee32011-04-05 00:39:01 +02002458PyParser_ClearError(perrdetail *err)
2459{
2460 err_free(err);
2461}
2462
2463void
Guido van Rossum66ebd912003-04-17 16:02:26 +00002464PyParser_SetError(perrdetail *err)
2465{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002466 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00002467}
2468
Victor Stinner7f2fee32011-04-05 00:39:01 +02002469static void
2470err_free(perrdetail *err)
2471{
2472 Py_CLEAR(err->filename);
2473}
2474
Guido van Rossuma110aa61994-08-29 12:50:44 +00002475/* Set the error appropriate to the given input error code (see errcode.h) */
2476
2477static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002478err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00002479{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002480 PyObject *v, *w, *errtype, *errtext;
2481 PyObject *msg_obj = NULL;
2482 char *msg = NULL;
Serhiy Storchaka65fd0592014-01-21 22:26:52 +02002483 int offset = err->offset;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00002484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002485 errtype = PyExc_SyntaxError;
2486 switch (err->error) {
2487 case E_ERROR:
2488 return;
2489 case E_SYNTAX:
2490 errtype = PyExc_IndentationError;
2491 if (err->expected == INDENT)
2492 msg = "expected an indented block";
2493 else if (err->token == INDENT)
2494 msg = "unexpected indent";
2495 else if (err->token == DEDENT)
2496 msg = "unexpected unindent";
2497 else {
2498 errtype = PyExc_SyntaxError;
2499 msg = "invalid syntax";
2500 }
2501 break;
2502 case E_TOKEN:
2503 msg = "invalid token";
2504 break;
2505 case E_EOFS:
2506 msg = "EOF while scanning triple-quoted string literal";
2507 break;
2508 case E_EOLS:
2509 msg = "EOL while scanning string literal";
2510 break;
2511 case E_INTR:
2512 if (!PyErr_Occurred())
2513 PyErr_SetNone(PyExc_KeyboardInterrupt);
2514 goto cleanup;
2515 case E_NOMEM:
2516 PyErr_NoMemory();
2517 goto cleanup;
2518 case E_EOF:
2519 msg = "unexpected EOF while parsing";
2520 break;
2521 case E_TABSPACE:
2522 errtype = PyExc_TabError;
2523 msg = "inconsistent use of tabs and spaces in indentation";
2524 break;
2525 case E_OVERFLOW:
2526 msg = "expression too long";
2527 break;
2528 case E_DEDENT:
2529 errtype = PyExc_IndentationError;
2530 msg = "unindent does not match any outer indentation level";
2531 break;
2532 case E_TOODEEP:
2533 errtype = PyExc_IndentationError;
2534 msg = "too many levels of indentation";
2535 break;
2536 case E_DECODE: {
2537 PyObject *type, *value, *tb;
2538 PyErr_Fetch(&type, &value, &tb);
2539 msg = "unknown decode error";
2540 if (value != NULL)
2541 msg_obj = PyObject_Str(value);
2542 Py_XDECREF(type);
2543 Py_XDECREF(value);
2544 Py_XDECREF(tb);
2545 break;
2546 }
2547 case E_LINECONT:
2548 msg = "unexpected character after line continuation character";
2549 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00002550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002551 case E_IDENTIFIER:
2552 msg = "invalid character in identifier";
2553 break;
Meador Ingefa21bf02012-01-19 01:08:41 -06002554 case E_BADSINGLE:
2555 msg = "multiple statements found while compiling a single statement";
2556 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002557 default:
2558 fprintf(stderr, "error=%d\n", err->error);
2559 msg = "unknown parsing error";
2560 break;
2561 }
2562 /* err->text may not be UTF-8 in case of decoding errors.
2563 Explicitly convert to an object. */
2564 if (!err->text) {
2565 errtext = Py_None;
2566 Py_INCREF(Py_None);
2567 } else {
Serhiy Storchaka65fd0592014-01-21 22:26:52 +02002568 errtext = PyUnicode_DecodeUTF8(err->text, err->offset,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002569 "replace");
Serhiy Storchaka65fd0592014-01-21 22:26:52 +02002570 if (errtext != NULL) {
2571 Py_ssize_t len = strlen(err->text);
2572 offset = (int)PyUnicode_GET_LENGTH(errtext);
2573 if (len != err->offset) {
2574 Py_DECREF(errtext);
2575 errtext = PyUnicode_DecodeUTF8(err->text, len,
2576 "replace");
2577 }
2578 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002579 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002580 v = Py_BuildValue("(OiiN)", err->filename,
Serhiy Storchaka65fd0592014-01-21 22:26:52 +02002581 err->lineno, offset, errtext);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002582 if (v != NULL) {
2583 if (msg_obj)
2584 w = Py_BuildValue("(OO)", msg_obj, v);
2585 else
2586 w = Py_BuildValue("(sO)", msg, v);
2587 } else
2588 w = NULL;
2589 Py_XDECREF(v);
2590 PyErr_SetObject(errtype, w);
2591 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00002592cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002593 Py_XDECREF(msg_obj);
2594 if (err->text != NULL) {
2595 PyObject_FREE(err->text);
2596 err->text = NULL;
2597 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002598}
2599
2600/* Print fatal error message and abort */
2601
2602void
Tim Peters7c321a82002-07-09 02:57:01 +00002603Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002604{
Victor Stinner024e37a2011-03-31 01:31:06 +02002605 const int fd = fileno(stderr);
2606 PyThreadState *tstate;
2607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002608 fprintf(stderr, "Fatal Python error: %s\n", msg);
2609 fflush(stderr); /* it helps in Windows debug build */
2610 if (PyErr_Occurred()) {
Victor Stinner55a5c782010-06-08 21:00:13 +00002611 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002612 }
Victor Stinner024e37a2011-03-31 01:31:06 +02002613 else {
2614 tstate = _Py_atomic_load_relaxed(&_PyThreadState_Current);
2615 if (tstate != NULL) {
2616 fputc('\n', stderr);
2617 fflush(stderr);
Victor Stinner7bba62f2011-05-07 12:43:00 +02002618 _Py_DumpTracebackThreads(fd, tstate->interp, tstate);
Victor Stinner024e37a2011-03-31 01:31:06 +02002619 }
Victor Stinnerd727e232011-04-01 12:13:55 +02002620 _PyFaulthandler_Fini();
Victor Stinner024e37a2011-03-31 01:31:06 +02002621 }
2622
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002623#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002624 {
2625 size_t len = strlen(msg);
2626 WCHAR* buffer;
2627 size_t i;
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002629 /* Convert the message to wchar_t. This uses a simple one-to-one
2630 conversion, assuming that the this error message actually uses ASCII
2631 only. If this ceases to be true, we will have to convert. */
2632 buffer = alloca( (len+1) * (sizeof *buffer));
2633 for( i=0; i<=len; ++i)
2634 buffer[i] = msg[i];
2635 OutputDebugStringW(L"Fatal Python error: ");
2636 OutputDebugStringW(buffer);
2637 OutputDebugStringW(L"\n");
2638 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002639#ifdef _DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002640 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002641#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002642#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002643 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002644}
2645
2646/* Clean up and exit */
2647
Guido van Rossuma110aa61994-08-29 12:50:44 +00002648#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002649#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002650#endif
2651
Collin Winter670e6922007-03-21 02:57:17 +00002652static void (*pyexitfunc)(void) = NULL;
2653/* For the atexit module. */
2654void _Py_PyAtExit(void (*func)(void))
2655{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002656 pyexitfunc = func;
Collin Winter670e6922007-03-21 02:57:17 +00002657}
2658
2659static void
2660call_py_exitfuncs(void)
2661{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002662 if (pyexitfunc == NULL)
2663 return;
Collin Winter670e6922007-03-21 02:57:17 +00002664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002665 (*pyexitfunc)();
2666 PyErr_Clear();
Collin Winter670e6922007-03-21 02:57:17 +00002667}
2668
Antoine Pitrou011bd622009-10-20 21:52:47 +00002669/* Wait until threading._shutdown completes, provided
2670 the threading module was imported in the first place.
2671 The shutdown routine will wait until all non-daemon
2672 "threading" threads have completed. */
2673static void
2674wait_for_thread_shutdown(void)
2675{
2676#ifdef WITH_THREAD
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002677 _Py_IDENTIFIER(_shutdown);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002678 PyObject *result;
2679 PyThreadState *tstate = PyThreadState_GET();
2680 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2681 "threading");
2682 if (threading == NULL) {
2683 /* threading not imported */
2684 PyErr_Clear();
2685 return;
2686 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002687 result = _PyObject_CallMethodId(threading, &PyId__shutdown, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002688 if (result == NULL) {
2689 PyErr_WriteUnraisable(threading);
2690 }
2691 else {
2692 Py_DECREF(result);
2693 }
2694 Py_DECREF(threading);
Antoine Pitrou011bd622009-10-20 21:52:47 +00002695#endif
2696}
2697
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002698#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002699static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002700static int nexitfuncs = 0;
2701
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002702int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002703{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002704 if (nexitfuncs >= NEXITFUNCS)
2705 return -1;
2706 exitfuncs[nexitfuncs++] = func;
2707 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00002708}
2709
Guido van Rossumcc283f51997-08-05 02:22:03 +00002710static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002711call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002712{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002713 while (nexitfuncs > 0)
2714 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002716 fflush(stdout);
2717 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002718}
2719
2720void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002721Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002722{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002723 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002725 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002726}
2727
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002728static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002729initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002730{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002731#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002732 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002733#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002734#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002735 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002736#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002737#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002738 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002739#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002740 PyOS_InitInterrupts(); /* May imply initsignal() */
Victor Stinnerd786ad52013-07-21 13:25:51 +02002741 if (PyErr_Occurred()) {
2742 Py_FatalError("Py_Initialize: can't import signal");
2743 }
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002744}
2745
Guido van Rossum7433b121997-02-14 19:45:36 +00002746
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002747/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2748 *
2749 * All of the code in this function must only use async-signal-safe functions,
2750 * listed at `man 7 signal` or
2751 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2752 */
2753void
2754_Py_RestoreSignals(void)
2755{
2756#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002757 PyOS_setsig(SIGPIPE, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002758#endif
2759#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002760 PyOS_setsig(SIGXFZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002761#endif
2762#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002763 PyOS_setsig(SIGXFSZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002764#endif
2765}
2766
2767
Guido van Rossum7433b121997-02-14 19:45:36 +00002768/*
2769 * The file descriptor fd is considered ``interactive'' if either
2770 * a) isatty(fd) is TRUE, or
2771 * b) the -i flag was given, and the filename associated with
2772 * the descriptor is NULL or "<stdin>" or "???".
2773 */
2774int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002775Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002776{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002777 if (isatty((int)fileno(fp)))
2778 return 1;
2779 if (!Py_InteractiveFlag)
2780 return 0;
2781 return (filename == NULL) ||
2782 (strcmp(filename, "<stdin>") == 0) ||
2783 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00002784}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002785
2786
Tim Petersd08e3822003-04-17 15:24:21 +00002787#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002788#if defined(WIN32) && defined(_MSC_VER)
2789
2790/* Stack checking for Microsoft C */
2791
2792#include <malloc.h>
2793#include <excpt.h>
2794
Fred Drakee8de31c2000-08-31 05:38:39 +00002795/*
2796 * Return non-zero when we run out of memory on the stack; zero otherwise.
2797 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002798int
Fred Drake399739f2000-08-31 05:52:44 +00002799PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002800{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002801 __try {
2802 /* alloca throws a stack overflow exception if there's
2803 not enough space left on the stack */
2804 alloca(PYOS_STACK_MARGIN * sizeof(void*));
2805 return 0;
2806 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2807 EXCEPTION_EXECUTE_HANDLER :
2808 EXCEPTION_CONTINUE_SEARCH) {
2809 int errcode = _resetstkoflw();
2810 if (errcode == 0)
2811 {
2812 Py_FatalError("Could not reset the stack!");
2813 }
2814 }
2815 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002816}
2817
2818#endif /* WIN32 && _MSC_VER */
2819
2820/* Alternate implementations can be added here... */
2821
2822#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002823
2824
2825/* Wrappers around sigaction() or signal(). */
2826
2827PyOS_sighandler_t
2828PyOS_getsig(int sig)
2829{
2830#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002831 struct sigaction context;
2832 if (sigaction(sig, NULL, &context) == -1)
2833 return SIG_ERR;
2834 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002835#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002836 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002837/* Special signal handling for the secure CRT in Visual Studio 2005 */
2838#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002839 switch (sig) {
2840 /* Only these signals are valid */
2841 case SIGINT:
2842 case SIGILL:
2843 case SIGFPE:
2844 case SIGSEGV:
2845 case SIGTERM:
2846 case SIGBREAK:
2847 case SIGABRT:
2848 break;
2849 /* Don't call signal() with other values or it will assert */
2850 default:
2851 return SIG_ERR;
2852 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002853#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002854 handler = signal(sig, SIG_IGN);
2855 if (handler != SIG_ERR)
2856 signal(sig, handler);
2857 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002858#endif
2859}
2860
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002861/*
2862 * All of the code in this function must only use async-signal-safe functions,
2863 * listed at `man 7 signal` or
2864 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2865 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002866PyOS_sighandler_t
2867PyOS_setsig(int sig, PyOS_sighandler_t handler)
2868{
2869#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002870 /* Some code in Modules/signalmodule.c depends on sigaction() being
2871 * used here if HAVE_SIGACTION is defined. Fix that if this code
2872 * changes to invalidate that assumption.
2873 */
2874 struct sigaction context, ocontext;
2875 context.sa_handler = handler;
2876 sigemptyset(&context.sa_mask);
2877 context.sa_flags = 0;
2878 if (sigaction(sig, &context, &ocontext) == -1)
2879 return SIG_ERR;
2880 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002881#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002882 PyOS_sighandler_t oldhandler;
2883 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002884#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002885 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002886#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002887 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002888#endif
2889}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002890
2891/* Deprecated C API functions still provided for binary compatiblity */
2892
2893#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002894PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002895PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2896{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002897 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002898}
2899
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002900#undef PyParser_SimpleParseString
2901PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002902PyParser_SimpleParseString(const char *str, int start)
2903{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002904 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002905}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002906
2907#undef PyRun_AnyFile
2908PyAPI_FUNC(int)
2909PyRun_AnyFile(FILE *fp, const char *name)
2910{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002911 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002912}
2913
2914#undef PyRun_AnyFileEx
2915PyAPI_FUNC(int)
2916PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2917{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002918 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002919}
2920
2921#undef PyRun_AnyFileFlags
2922PyAPI_FUNC(int)
2923PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2924{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002925 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002926}
2927
2928#undef PyRun_File
2929PyAPI_FUNC(PyObject *)
2930PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2931{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002932 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002933}
2934
2935#undef PyRun_FileEx
2936PyAPI_FUNC(PyObject *)
2937PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2938{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002939 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002940}
2941
2942#undef PyRun_FileFlags
2943PyAPI_FUNC(PyObject *)
2944PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002945 PyCompilerFlags *flags)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002946{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002947 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002948}
2949
2950#undef PyRun_SimpleFile
2951PyAPI_FUNC(int)
2952PyRun_SimpleFile(FILE *f, const char *p)
2953{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002954 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002955}
2956
2957#undef PyRun_SimpleFileEx
2958PyAPI_FUNC(int)
2959PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2960{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002961 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002962}
2963
2964
2965#undef PyRun_String
2966PyAPI_FUNC(PyObject *)
2967PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2968{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002969 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002970}
2971
2972#undef PyRun_SimpleString
2973PyAPI_FUNC(int)
2974PyRun_SimpleString(const char *s)
2975{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002976 return PyRun_SimpleStringFlags(s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002977}
2978
2979#undef Py_CompileString
2980PyAPI_FUNC(PyObject *)
2981Py_CompileString(const char *str, const char *p, int s)
2982{
Georg Brandl8334fd92010-12-04 10:26:46 +00002983 return Py_CompileStringExFlags(str, p, s, NULL, -1);
2984}
2985
2986#undef Py_CompileStringFlags
2987PyAPI_FUNC(PyObject *)
2988Py_CompileStringFlags(const char *str, const char *p, int s,
2989 PyCompilerFlags *flags)
2990{
2991 return Py_CompileStringExFlags(str, p, s, flags, -1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002992}
2993
2994#undef PyRun_InteractiveOne
2995PyAPI_FUNC(int)
2996PyRun_InteractiveOne(FILE *f, const char *p)
2997{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002998 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002999}
3000
3001#undef PyRun_InteractiveLoop
3002PyAPI_FUNC(int)
3003PyRun_InteractiveLoop(FILE *f, const char *p)
3004{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003005 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003006}
3007
3008#ifdef __cplusplus
3009}
3010#endif