blob: ccf82af36badd3f71db9c4983a230d0a91fefbaf [file] [log] [blame]
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001
2/* Python interpreter top-level routines, including init/exit */
3
Guido van Rossum82598051997-03-05 00:20:32 +00004#include "Python.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +00005
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006#include "Python-ast.h"
Guido van Rossumd8faa362007-04-27 19:54:29 +00007#undef Yield /* undefine macro conflicting with winbase.h */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00008#include "grammar.h"
9#include "node.h"
Fred Drake85f36392000-07-11 17:53:00 +000010#include "token.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000011#include "parsetok.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000012#include "errcode.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013#include "code.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000014#include "symtable.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000015#include "ast.h"
Guido van Rossumfdef2711994-09-14 13:31:04 +000016#include "marshal.h"
Martin v. Löwis790465f2008-04-05 20:41:37 +000017#include "osdefs.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000018
Thomas Wouters0e3f5912006-08-11 14:57:12 +000019#ifdef HAVE_SIGNAL_H
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000020#include <signal.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000021#endif
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000022
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000023#ifdef MS_WINDOWS
Martin v. Löwis5c88d812009-01-02 20:47:48 +000024#include "malloc.h" /* for alloca */
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000025#endif
Martin v. Löwis5c88d812009-01-02 20:47:48 +000026
Martin v. Löwis73d538b2003-03-05 15:13:47 +000027#ifdef HAVE_LANGINFO_H
28#include <locale.h>
29#include <langinfo.h>
30#endif
31
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000032#ifdef MS_WINDOWS
Guido van Rossuma44823b1995-03-14 15:01:17 +000033#undef BYTE
34#include "windows.h"
Martin v. Löwis790465f2008-04-05 20:41:37 +000035#define PATH_MAX MAXPATHLEN
Guido van Rossuma44823b1995-03-14 15:01:17 +000036#endif
37
Victor Stinnerbd303c12013-11-07 23:07:29 +010038_Py_IDENTIFIER(builtins);
Victor Stinner09054372013-11-06 22:41:44 +010039_Py_IDENTIFIER(excepthook);
Victor Stinner3f36a572013-11-12 21:39:02 +010040_Py_IDENTIFIER(flush);
Victor Stinnerbd303c12013-11-07 23:07:29 +010041_Py_IDENTIFIER(last_traceback);
Victor Stinner09054372013-11-06 22:41:44 +010042_Py_IDENTIFIER(last_type);
43_Py_IDENTIFIER(last_value);
Victor Stinner3f36a572013-11-12 21:39:02 +010044_Py_IDENTIFIER(name);
Victor Stinnerbd303c12013-11-07 23:07:29 +010045_Py_IDENTIFIER(ps1);
46_Py_IDENTIFIER(ps2);
47_Py_IDENTIFIER(stdin);
48_Py_IDENTIFIER(stdout);
49_Py_IDENTIFIER(stderr);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +010050_Py_static_string(PyId_string, "<string>");
Victor Stinner09054372013-11-06 22:41:44 +010051
Ezio Melotti1f8898a2013-03-26 01:59:56 +020052#ifdef Py_REF_DEBUG
Antoine Pitrou208ac5c2013-04-24 20:17:53 +020053static
54void _print_total_refs(void) {
Victor Stinner4ee41c52013-11-06 18:28:21 +010055 PyObject *xoptions, *value;
56 _Py_IDENTIFIER(showrefcount);
57
Ezio Melotti1f8898a2013-03-26 01:59:56 +020058 xoptions = PySys_GetXOptions();
59 if (xoptions == NULL)
60 return;
Victor Stinner4ee41c52013-11-06 18:28:21 +010061 value = _PyDict_GetItemId(xoptions, &PyId_showrefcount);
Ezio Melotti1f8898a2013-03-26 01:59:56 +020062 if (value == Py_True)
63 fprintf(stderr,
64 "[%" PY_FORMAT_SIZE_T "d refs, "
65 "%" PY_FORMAT_SIZE_T "d blocks]\n",
66 _Py_GetRefTotal(), _Py_GetAllocatedBlocks());
67}
68#endif
69
Neal Norwitz4281cef2006-03-04 19:58:13 +000070#ifndef Py_REF_DEBUG
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000071#define PRINT_TOTAL_REFS()
Neal Norwitz4281cef2006-03-04 19:58:13 +000072#else /* Py_REF_DEBUG */
Ezio Melotti1f8898a2013-03-26 01:59:56 +020073#define PRINT_TOTAL_REFS() _print_total_refs()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000074#endif
75
76#ifdef __cplusplus
77extern "C" {
Neal Norwitz4281cef2006-03-04 19:58:13 +000078#endif
79
Martin v. Löwis790465f2008-04-05 20:41:37 +000080extern wchar_t *Py_GetPath(void);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000081
Guido van Rossum82598051997-03-05 00:20:32 +000082extern grammar _PyParser_Grammar; /* From graminit.c */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000083
Guido van Rossumb73cc041993-11-01 16:28:59 +000084/* Forward */
Nick Coghlan85e729e2012-07-15 18:09:52 +100085static void initmain(PyInterpreterState *interp);
Victor Stinner793b5312011-04-27 00:24:21 +020086static int initfsencoding(PyInterpreterState *interp);
Tim Petersdbd9ba62000-07-09 03:09:57 +000087static void initsite(void);
Guido van Rossumce3a72a2007-10-19 23:16:50 +000088static int initstdio(void);
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +000089static void flush_io(void);
Victor Stinner95701bd2013-11-06 18:41:07 +010090static PyObject *run_mod(mod_ty, PyObject *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000091 PyCompilerFlags *, PyArena *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000092static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000093 PyCompilerFlags *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000094static void err_input(perrdetail *);
Victor Stinner7f2fee32011-04-05 00:39:01 +020095static void err_free(perrdetail *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000096static void initsigs(void);
Collin Winter670e6922007-03-21 02:57:17 +000097static void call_py_exitfuncs(void);
Antoine Pitrou011bd622009-10-20 21:52:47 +000098static void wait_for_thread_shutdown(void);
Tim Petersdbd9ba62000-07-09 03:09:57 +000099static void call_ll_exitfuncs(void);
Victor Stinner3a50e702011-10-18 21:21:00 +0200100extern int _PyUnicode_Init(void);
Victor Stinner26f91992013-07-17 01:22:45 +0200101extern int _PyStructSequence_Init(void);
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000102extern void _PyUnicode_Fini(void);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000103extern int _PyLong_Init(void);
104extern void PyLong_Fini(void);
Victor Stinner024e37a2011-03-31 01:31:06 +0200105extern int _PyFaulthandler_Init(void);
106extern void _PyFaulthandler_Fini(void);
Christian Heimes985ecdc2013-11-20 11:46:18 +0100107extern void _PyHash_Fini(void);
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100108extern int _PyTraceMalloc_Init(void);
Victor Stinnerbe0708f2013-12-01 10:03:26 +0100109extern int _PyTraceMalloc_Fini(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +0000110
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000111#ifdef WITH_THREAD
112extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
113extern void _PyGILState_Fini(void);
114#endif /* WITH_THREAD */
115
Guido van Rossum82598051997-03-05 00:20:32 +0000116int Py_DebugFlag; /* Needed by parser.c */
117int Py_VerboseFlag; /* Needed by import.c */
Georg Brandl8aa7e992010-12-28 18:30:18 +0000118int Py_QuietFlag; /* Needed by sysmodule.c */
Guido van Rossum7433b121997-02-14 19:45:36 +0000119int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Georg Brandl0b2489e2011-05-15 08:49:12 +0200120int Py_InspectFlag; /* Needed to determine whether to exit at SystemExit */
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000121int Py_NoSiteFlag; /* Suppress 'import site' */
Guido van Rossum98297ee2007-11-06 21:34:58 +0000122int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
Christian Heimes790c8232008-01-07 21:14:23 +0000123int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.py[co]) */
Barry Warsaw3ce09642000-05-02 19:18:59 +0000124int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +0000125int Py_FrozenFlag; /* Needed by getpath.c */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000126int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Christian Heimes8dc226f2008-05-06 23:45:46 +0000127int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
Antoine Pitrou05608432009-01-09 18:53:14 +0000128int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100129int Py_HashRandomizationFlag = 0; /* for -R and PYTHONHASHSEED */
Christian Heimesad73a9c2013-08-10 16:36:18 +0200130int Py_IsolatedFlag = 0; /* for -I, isolate from user's env */
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000131
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200132PyThreadState *_Py_Finalizing = NULL;
133
Christian Heimes49e61802013-10-22 10:22:29 +0200134/* Hack to force loading of object files */
135int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
136 PyOS_mystrnicmp; /* Python/pystrcmp.o */
137
Christian Heimes33fe8092008-04-13 13:53:33 +0000138/* PyModule_GetWarningsModule is no longer necessary as of 2.6
139since _warnings is builtin. This API should not be used. */
140PyObject *
141PyModule_GetWarningsModule(void)
Mark Hammondedd07732003-07-15 23:03:55 +0000142{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000143 return PyImport_ImportModule("warnings");
Mark Hammondedd07732003-07-15 23:03:55 +0000144}
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000145
Guido van Rossum25ce5661997-08-02 03:10:38 +0000146static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000147
Thomas Wouters7e474022000-07-16 12:04:32 +0000148/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000149
150int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000151Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000152{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000153 return initialized;
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000154}
155
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000156/* Helper to allow an embedding application to override the normal
157 * mechanism that attempts to figure out an appropriate IO encoding
158 */
159
160static char *_Py_StandardStreamEncoding = NULL;
161static char *_Py_StandardStreamErrors = NULL;
162
163int
164Py_SetStandardStreamEncoding(const char *encoding, const char *errors)
165{
166 if (Py_IsInitialized()) {
167 /* This is too late to have any effect */
168 return -1;
169 }
Nick Coghlan1805a622013-10-18 23:11:47 +1000170 /* Can't call PyErr_NoMemory() on errors, as Python hasn't been
171 * initialised yet.
172 *
173 * However, the raw memory allocators are initialised appropriately
174 * as C static variables, so _PyMem_RawStrdup is OK even though
175 * Py_Initialize hasn't been called yet.
176 */
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000177 if (encoding) {
178 _Py_StandardStreamEncoding = _PyMem_RawStrdup(encoding);
179 if (!_Py_StandardStreamEncoding) {
Nick Coghlan1805a622013-10-18 23:11:47 +1000180 return -2;
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000181 }
182 }
183 if (errors) {
184 _Py_StandardStreamErrors = _PyMem_RawStrdup(errors);
185 if (!_Py_StandardStreamErrors) {
186 if (_Py_StandardStreamEncoding) {
187 PyMem_RawFree(_Py_StandardStreamEncoding);
188 }
Nick Coghlan1805a622013-10-18 23:11:47 +1000189 return -3;
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000190 }
191 }
192 return 0;
193}
194
Guido van Rossum25ce5661997-08-02 03:10:38 +0000195/* Global initializations. Can be undone by Py_Finalize(). Don't
196 call this twice without an intervening Py_Finalize() call. When
197 initializations fail, a fatal error is issued and the function does
198 not return. On return, the first thread and interpreter state have
199 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000200
Guido van Rossum25ce5661997-08-02 03:10:38 +0000201 Locking: you must hold the interpreter lock while calling this.
202 (If the lock has not yet been initialized, that's equivalent to
203 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000204
Guido van Rossum25ce5661997-08-02 03:10:38 +0000205*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000206
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000207static int
208add_flag(int flag, const char *envs)
209{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000210 int env = atoi(envs);
211 if (flag < env)
212 flag = env;
213 if (flag < 1)
214 flag = 1;
215 return flag;
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000216}
217
Christian Heimes5833a2f2008-10-30 21:40:04 +0000218static char*
Victor Stinner94908bb2010-08-18 21:23:25 +0000219get_codec_name(const char *encoding)
Christian Heimes5833a2f2008-10-30 21:40:04 +0000220{
Victor Stinner94908bb2010-08-18 21:23:25 +0000221 char *name_utf8, *name_str;
Victor Stinner386fe712010-05-19 00:34:15 +0000222 PyObject *codec, *name = NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000223
Victor Stinner94908bb2010-08-18 21:23:25 +0000224 codec = _PyCodec_Lookup(encoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000225 if (!codec)
226 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000227
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200228 name = _PyObject_GetAttrId(codec, &PyId_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 Py_CLEAR(codec);
230 if (!name)
231 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000232
Victor Stinner94908bb2010-08-18 21:23:25 +0000233 name_utf8 = _PyUnicode_AsString(name);
Victor Stinner4ca28092011-03-20 23:09:03 +0100234 if (name_utf8 == NULL)
Victor Stinner386fe712010-05-19 00:34:15 +0000235 goto error;
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200236 name_str = _PyMem_RawStrdup(name_utf8);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 Py_DECREF(name);
Victor Stinner94908bb2010-08-18 21:23:25 +0000238 if (name_str == NULL) {
239 PyErr_NoMemory();
240 return NULL;
241 }
242 return name_str;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000243
244error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 Py_XDECREF(codec);
Victor Stinner386fe712010-05-19 00:34:15 +0000246 Py_XDECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000248}
Victor Stinner94908bb2010-08-18 21:23:25 +0000249
Victor Stinner94908bb2010-08-18 21:23:25 +0000250static char*
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200251get_locale_encoding(void)
Victor Stinner94908bb2010-08-18 21:23:25 +0000252{
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200253#ifdef MS_WINDOWS
254 char codepage[100];
255 PyOS_snprintf(codepage, sizeof(codepage), "cp%d", GetACP());
256 return get_codec_name(codepage);
257#elif defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94908bb2010-08-18 21:23:25 +0000258 char* codeset = nl_langinfo(CODESET);
259 if (!codeset || codeset[0] == '\0') {
260 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
261 return NULL;
262 }
263 return get_codec_name(codeset);
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200264#else
265 PyErr_SetNone(PyExc_NotImplementedError);
266 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000267#endif
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200268}
Christian Heimes5833a2f2008-10-30 21:40:04 +0000269
Brett Cannonfd074152012-04-14 14:10:13 -0400270static void
271import_init(PyInterpreterState *interp, PyObject *sysmod)
272{
273 PyObject *importlib;
274 PyObject *impmod;
275 PyObject *sys_modules;
276 PyObject *value;
277
278 /* Import _importlib through its frozen version, _frozen_importlib. */
Brett Cannonfd074152012-04-14 14:10:13 -0400279 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
280 Py_FatalError("Py_Initialize: can't import _frozen_importlib");
281 }
282 else if (Py_VerboseFlag) {
283 PySys_FormatStderr("import _frozen_importlib # frozen\n");
284 }
285 importlib = PyImport_AddModule("_frozen_importlib");
286 if (importlib == NULL) {
287 Py_FatalError("Py_Initialize: couldn't get _frozen_importlib from "
288 "sys.modules");
289 }
290 interp->importlib = importlib;
291 Py_INCREF(interp->importlib);
292
293 /* Install _importlib as __import__ */
294 impmod = PyInit_imp();
295 if (impmod == NULL) {
296 Py_FatalError("Py_Initialize: can't import imp");
297 }
298 else if (Py_VerboseFlag) {
299 PySys_FormatStderr("import imp # builtin\n");
300 }
301 sys_modules = PyImport_GetModuleDict();
302 if (Py_VerboseFlag) {
303 PySys_FormatStderr("import sys # builtin\n");
304 }
Brett Cannon6f44d662012-04-15 16:08:47 -0400305 if (PyDict_SetItemString(sys_modules, "_imp", impmod) < 0) {
306 Py_FatalError("Py_Initialize: can't save _imp to sys.modules");
Brett Cannonfd074152012-04-14 14:10:13 -0400307 }
308
Brett Cannone0d88a12012-04-25 20:54:04 -0400309 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
Brett Cannonfd074152012-04-14 14:10:13 -0400310 if (value == NULL) {
311 PyErr_Print();
312 Py_FatalError("Py_Initialize: importlib install failed");
313 }
314 Py_DECREF(value);
Brett Cannonfc9ca272012-04-15 01:35:05 -0400315 Py_DECREF(impmod);
Brett Cannonfd074152012-04-14 14:10:13 -0400316
317 _PyImportZip_Init();
318}
319
320
Guido van Rossuma027efa1997-05-05 20:56:21 +0000321void
Antoine Pitroue67f48c2012-06-19 22:29:35 +0200322_Py_InitializeEx_Private(int install_sigs, int install_importlib)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000323{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 PyInterpreterState *interp;
325 PyThreadState *tstate;
326 PyObject *bimod, *sysmod, *pstderr;
327 char *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000328 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 if (initialized)
331 return;
332 initialized = 1;
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200333 _Py_Finalizing = NULL;
Tim Petersd08e3822003-04-17 15:24:21 +0000334
Andrew M. Kuchlingb2ceb3a2010-02-22 23:26:10 +0000335#if defined(HAVE_LANGINFO_H) && defined(HAVE_SETLOCALE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336 /* Set up the LC_CTYPE locale, so we can obtain
337 the locale's charset without having to switch
338 locales. */
339 setlocale(LC_CTYPE, "");
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +0000340#endif
341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
343 Py_DebugFlag = add_flag(Py_DebugFlag, p);
344 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
345 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
346 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
347 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
348 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
349 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100350 /* The variable is only tested for existence here; _PyRandom_Init will
351 check its value further. */
352 if ((p = Py_GETENV("PYTHONHASHSEED")) && *p != '\0')
353 Py_HashRandomizationFlag = add_flag(Py_HashRandomizationFlag, p);
354
355 _PyRandom_Init();
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000357 interp = PyInterpreterState_New();
358 if (interp == NULL)
359 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000361 tstate = PyThreadState_New(interp);
362 if (tstate == NULL)
363 Py_FatalError("Py_Initialize: can't make first thread");
364 (void) PyThreadState_Swap(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000365
Victor Stinner6961bd62010-08-17 22:26:51 +0000366#ifdef WITH_THREAD
Antoine Pitroub0b384b2010-09-20 20:13:48 +0000367 /* We can't call _PyEval_FiniThreads() in Py_Finalize because
368 destroying the GIL might fail when it is being referenced from
369 another running thread (see issue #9901).
370 Instead we destroy the previously created GIL here, which ensures
371 that we can call Py_Initialize / Py_Finalize multiple times. */
372 _PyEval_FiniThreads();
373
374 /* Auto-thread-state API */
Victor Stinner6961bd62010-08-17 22:26:51 +0000375 _PyGILState_Init(interp, tstate);
376#endif /* WITH_THREAD */
377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000378 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 if (!_PyFrame_Init())
381 Py_FatalError("Py_Initialize: can't init frames");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 if (!_PyLong_Init())
384 Py_FatalError("Py_Initialize: can't init longs");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000386 if (!PyByteArray_Init())
387 Py_FatalError("Py_Initialize: can't init bytearray");
Neal Norwitz6968b052007-02-27 19:02:19 +0000388
Victor Stinner1c8f0592013-07-22 22:24:54 +0200389 if (!_PyFloat_Init())
390 Py_FatalError("Py_Initialize: can't init float");
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 interp->modules = PyDict_New();
393 if (interp->modules == NULL)
394 Py_FatalError("Py_Initialize: can't make modules dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000396 /* Init Unicode implementation; relies on the codec registry */
Victor Stinner3a50e702011-10-18 21:21:00 +0200397 if (_PyUnicode_Init() < 0)
398 Py_FatalError("Py_Initialize: can't initialize unicode");
Victor Stinner26f91992013-07-17 01:22:45 +0200399 if (_PyStructSequence_Init() < 0)
400 Py_FatalError("Py_Initialize: can't initialize structseq");
Guido van Rossumc94044c2000-03-10 23:03:54 +0000401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 bimod = _PyBuiltin_Init();
403 if (bimod == NULL)
404 Py_FatalError("Py_Initialize: can't initialize builtins modules");
Victor Stinner49d3f252010-10-17 01:24:53 +0000405 _PyImport_FixupBuiltin(bimod, "builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000406 interp->builtins = PyModule_GetDict(bimod);
407 if (interp->builtins == NULL)
408 Py_FatalError("Py_Initialize: can't initialize builtins dict");
409 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 /* initialize builtin exceptions */
Brett Cannonfd074152012-04-14 14:10:13 -0400412 _PyExc_Init(bimod);
Christian Heimes9a68f8c2007-11-14 00:16:07 +0000413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 sysmod = _PySys_Init();
415 if (sysmod == NULL)
416 Py_FatalError("Py_Initialize: can't initialize sys");
417 interp->sysdict = PyModule_GetDict(sysmod);
418 if (interp->sysdict == NULL)
419 Py_FatalError("Py_Initialize: can't initialize sys dict");
420 Py_INCREF(interp->sysdict);
Victor Stinner49d3f252010-10-17 01:24:53 +0000421 _PyImport_FixupBuiltin(sysmod, "sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 PySys_SetPath(Py_GetPath());
423 PyDict_SetItemString(interp->sysdict, "modules",
424 interp->modules);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 /* Set up a preliminary stderr printer until we have enough
427 infrastructure for the io module in place. */
428 pstderr = PyFile_NewStdPrinter(fileno(stderr));
429 if (pstderr == NULL)
430 Py_FatalError("Py_Initialize: can't set preliminary stderr");
Victor Stinnerbd303c12013-11-07 23:07:29 +0100431 _PySys_SetObjectId(&PyId_stderr, pstderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000432 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000433 Py_DECREF(pstderr);
Guido van Rossum826d8972007-10-30 18:34:07 +0000434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 _PyImport_Init();
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000437 _PyImportHooks_Init();
Just van Rossum52e14d62002-12-30 22:08:05 +0000438
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000439 /* Initialize _warnings. */
440 _PyWarnings_Init();
441
Antoine Pitroue67f48c2012-06-19 22:29:35 +0200442 if (!install_importlib)
443 return;
444
Brett Cannonfd074152012-04-14 14:10:13 -0400445 import_init(interp, sysmod);
446
Victor Stinnerd5698cb2012-07-31 02:55:49 +0200447 /* initialize the faulthandler module */
448 if (_PyFaulthandler_Init())
449 Py_FatalError("Py_Initialize: can't initialize faulthandler");
450
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +0000451 _PyTime_Init();
452
Victor Stinner793b5312011-04-27 00:24:21 +0200453 if (initfsencoding(interp) < 0)
454 Py_FatalError("Py_Initialize: unable to load the file system codec");
Martin v. Löwis011e8422009-05-05 04:43:17 +0000455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 if (install_sigs)
457 initsigs(); /* Signal handling stuff, including initintr() */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000458
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100459 if (_PyTraceMalloc_Init() < 0)
460 Py_FatalError("Py_Initialize: can't initialize tracemalloc");
461
Nick Coghlan85e729e2012-07-15 18:09:52 +1000462 initmain(interp); /* Module __main__ */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 if (initstdio() < 0)
464 Py_FatalError(
465 "Py_Initialize: can't initialize sys standard streams");
466
Antoine Pitroucf9f9802010-11-10 13:55:25 +0000467 /* Initialize warnings. */
468 if (PySys_HasWarnOptions()) {
469 PyObject *warnings_module = PyImport_ImportModule("warnings");
470 if (warnings_module == NULL) {
471 fprintf(stderr, "'import warnings' failed; traceback:\n");
472 PyErr_Print();
473 }
474 Py_XDECREF(warnings_module);
475 }
476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 if (!Py_NoSiteFlag)
478 initsite(); /* Module site */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000479}
480
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000481void
Antoine Pitroue67f48c2012-06-19 22:29:35 +0200482Py_InitializeEx(int install_sigs)
483{
484 _Py_InitializeEx_Private(install_sigs, 1);
485}
486
487void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000488Py_Initialize(void)
489{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 Py_InitializeEx(1);
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000491}
492
493
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000494#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000495extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000496#endif
497
Guido van Rossume8432ac2007-07-09 15:04:50 +0000498/* Flush stdout and stderr */
499
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100500static int
501file_is_closed(PyObject *fobj)
502{
503 int r;
504 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
505 if (tmp == NULL) {
506 PyErr_Clear();
507 return 0;
508 }
509 r = PyObject_IsTrue(tmp);
510 Py_DECREF(tmp);
511 if (r < 0)
512 PyErr_Clear();
513 return r > 0;
514}
515
Neal Norwitz2bad9702007-08-27 06:19:22 +0000516static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000517flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000518{
Victor Stinnerbd303c12013-11-07 23:07:29 +0100519 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
520 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 PyObject *tmp;
Guido van Rossume8432ac2007-07-09 15:04:50 +0000522
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100523 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200524 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 if (tmp == NULL)
Antoine Pitroubddc9fe2010-08-08 20:46:42 +0000526 PyErr_WriteUnraisable(fout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000527 else
528 Py_DECREF(tmp);
529 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000530
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100531 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200532 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 if (tmp == NULL)
534 PyErr_Clear();
535 else
536 Py_DECREF(tmp);
537 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000538}
539
Guido van Rossum25ce5661997-08-02 03:10:38 +0000540/* Undo the effect of Py_Initialize().
541
542 Beware: if multiple interpreter and/or thread states exist, these
543 are not wiped out; only the current thread and interpreter state
544 are deleted. But since everything else is deleted, those other
545 interpreter and thread states should no longer be used.
546
547 (XXX We should do better, e.g. wipe out all interpreters and
548 threads.)
549
550 Locking: as above.
551
552*/
553
554void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000555Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000556{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 PyInterpreterState *interp;
558 PyThreadState *tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 if (!initialized)
561 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 wait_for_thread_shutdown();
Antoine Pitrou011bd622009-10-20 21:52:47 +0000564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 /* The interpreter is still entirely intact at this point, and the
566 * exit funcs may be relying on that. In particular, if some thread
567 * or exit func is still waiting to do an import, the import machinery
568 * expects Py_IsInitialized() to return true. So don't say the
569 * interpreter is uninitialized until after the exit funcs have run.
570 * Note that Threading.py uses an exit func to do a join on all the
571 * threads created thru it, so this also protects pending imports in
572 * the threads created via Threading.
573 */
574 call_py_exitfuncs();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 /* Get current thread state and interpreter pointer */
577 tstate = PyThreadState_GET();
578 interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000579
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200580 /* Remaining threads (e.g. daemon threads) will automatically exit
581 after taking the GIL (in PyEval_RestoreThread()). */
582 _Py_Finalizing = tstate;
583 initialized = 0;
584
Victor Stinner45956b92013-11-12 16:37:55 +0100585 /* Destroy the state of all threads except of the current thread: in
586 practice, only daemon threads should still be alive. Clear frames of
587 other threads to call objects destructor. Destructors will be called in
588 the current Python thread. Since _Py_Finalizing has been set, no other
589 Python threads can lock the GIL at this point (if they try, they will
Victor Stinnerdcf17f82013-11-12 17:18:51 +0100590 exit immediately). */
Victor Stinner45956b92013-11-12 16:37:55 +0100591 _PyThreadState_DeleteExcept(tstate);
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 /* Collect garbage. This may call finalizers; it's nice to call these
594 * before all modules are destroyed.
595 * XXX If a __del__ or weakref callback is triggered here, and tries to
596 * XXX import a module, bad things can happen, because Python no
597 * XXX longer believes it's initialized.
598 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
599 * XXX is easy to provoke that way. I've also seen, e.g.,
600 * XXX Exception exceptions.ImportError: 'No module named sha'
601 * XXX in <function callback at 0x008F5718> ignored
602 * XXX but I'm unclear on exactly how that one happens. In any case,
603 * XXX I haven't seen a real-life report of either of these.
604 */
605 PyGC_Collect();
Victor Stinner45956b92013-11-12 16:37:55 +0100606
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000607#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000608 /* With COUNT_ALLOCS, it helps to run GC multiple times:
609 each collection might release some types from the type
610 list, so they become garbage. */
611 while (PyGC_Collect() > 0)
612 /* nothing */;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000613#endif
Victor Stinner45956b92013-11-12 16:37:55 +0100614
615 /* Flush stdout+stderr */
616 flush_std_files();
617
618 /* Disable signal handling */
619 PyOS_FiniInterrupts();
620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 /* Destroy all modules */
622 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624 /* Flush stdout+stderr (again, in case more was printed) */
625 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 /* Collect final garbage. This disposes of cycles created by
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100628 * class definitions, for example.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 * XXX This is disabled because it caused too many problems. If
630 * XXX a __del__ or weakref callback triggers here, Python code has
631 * XXX a hard time running, because even the sys module has been
632 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
633 * XXX One symptom is a sequence of information-free messages
634 * XXX coming from threads (if a __del__ or callback is invoked,
635 * XXX other threads can execute too, and any exception they encounter
636 * XXX triggers a comedy of errors as subsystem after subsystem
637 * XXX fails to find what it *expects* to find in sys to help report
638 * XXX the exception and consequent unexpected failures). I've also
639 * XXX seen segfaults then, after adding print statements to the
640 * XXX Python code getting called.
641 */
Tim Peters1d7323e2003-12-01 21:35:27 +0000642#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000644#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000645
Victor Stinnerbe0708f2013-12-01 10:03:26 +0100646 /* Disable tracemalloc after all Python objects have been destroyed,
647 so it is possible to use tracemalloc in objects destructor. */
648 _PyTraceMalloc_Fini();
649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
651 _PyImport_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000652
Antoine Pitroufd417cc2013-05-05 08:12:42 +0200653 /* Cleanup typeobject.c's internal caches. */
654 _PyType_Fini();
655
Victor Stinner024e37a2011-03-31 01:31:06 +0200656 /* unload faulthandler module */
657 _PyFaulthandler_Fini();
658
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000659 /* Debugging stuff */
Guido van Rossum1707aad1997-12-08 23:43:45 +0000660#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000662#endif
Christian Heimes985ecdc2013-11-20 11:46:18 +0100663 /* dump hash stats */
664 _PyHash_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000665
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000666 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000667
Tim Peters9cf25ce2003-04-17 15:21:01 +0000668#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000669 /* Display all objects still alive -- this can invoke arbitrary
670 * __repr__ overrides, so requires a mostly-intact interpreter.
671 * Alas, a lot of stuff may still be alive now that will be cleaned
672 * up later.
673 */
674 if (Py_GETENV("PYTHONDUMPREFS"))
675 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000676#endif /* Py_TRACE_REFS */
677
Antoine Pitroufd417cc2013-05-05 08:12:42 +0200678 /* Clear interpreter state and all thread states. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 /* Now we decref the exception classes. After this point nothing
682 can raise an exception. That's okay, because each Fini() method
683 below has been checked to make sure no exceptions are ever
684 raised.
685 */
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000686
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000687 _PyExc_Fini();
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000689 /* Sundry finalizers */
690 PyMethod_Fini();
691 PyFrame_Fini();
692 PyCFunction_Fini();
693 PyTuple_Fini();
694 PyList_Fini();
695 PySet_Fini();
696 PyBytes_Fini();
697 PyByteArray_Fini();
698 PyLong_Fini();
699 PyFloat_Fini();
700 PyDict_Fini();
Antoine Pitrouf34a0cd2011-11-18 20:14:34 +0100701 PySlice_Fini();
Antoine Pitrou5f454a02013-05-06 21:15:57 +0200702 _PyGC_Fini();
Antoine Pitrou4879a962013-08-31 00:26:02 +0200703 _PyRandom_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 /* Cleanup Unicode implementation */
706 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 /* reset file system default encoding */
Victor Stinnerb744ba12010-05-15 12:27:16 +0000709 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200710 PyMem_RawFree((char*)Py_FileSystemDefaultEncoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000711 Py_FileSystemDefaultEncoding = NULL;
712 }
Christian Heimesc8967002007-11-30 10:18:26 +0000713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 /* XXX Still allocated:
715 - various static ad-hoc pointers to interned strings
716 - int and float free list blocks
717 - whatever various modules and libraries allocate
718 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000721
Victor Stinner51fa4582013-07-07 15:50:49 +0200722 /* Cleanup auto-thread-state */
723#ifdef WITH_THREAD
724 _PyGILState_Fini();
725#endif /* WITH_THREAD */
726
727 /* Delete current thread. After this, many C API calls become crashy. */
728 PyThreadState_Swap(NULL);
729 PyInterpreterState_Delete(interp);
730
Tim Peters269b2a62003-04-17 19:52:29 +0000731#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 /* Display addresses (& refcnts) of all objects still alive.
733 * An address can be used to find the repr of the object, printed
734 * above by _Py_PrintReferences.
735 */
736 if (Py_GETENV("PYTHONDUMPREFS"))
737 _Py_PrintReferenceAddresses(stderr);
Tim Peters269b2a62003-04-17 19:52:29 +0000738#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000739#ifdef PYMALLOC_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 if (Py_GETENV("PYTHONMALLOCSTATS"))
David Malcolm49526f42012-06-22 14:55:41 -0400741 _PyObject_DebugMallocStats(stderr);
Tim Peters0e871182002-04-13 08:29:14 +0000742#endif
743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000745}
746
747/* Create and initialize a new interpreter and thread, and return the
748 new thread. This requires that Py_Initialize() has been called
749 first.
750
751 Unsuccessful initialization yields a NULL pointer. Note that *no*
752 exception information is available even in this case -- the
753 exception information is held in the thread, and there is no
754 thread.
755
756 Locking: as above.
757
758*/
759
760PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000761Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000762{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000763 PyInterpreterState *interp;
764 PyThreadState *tstate, *save_tstate;
765 PyObject *bimod, *sysmod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000766
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000767 if (!initialized)
768 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000770 interp = PyInterpreterState_New();
771 if (interp == NULL)
772 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 tstate = PyThreadState_New(interp);
775 if (tstate == NULL) {
776 PyInterpreterState_Delete(interp);
777 return NULL;
778 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 save_tstate = PyThreadState_Swap(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 /* XXX The following is lax in error checking */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 interp->modules = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000785
Victor Stinner49d3f252010-10-17 01:24:53 +0000786 bimod = _PyImport_FindBuiltin("builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 if (bimod != NULL) {
788 interp->builtins = PyModule_GetDict(bimod);
789 if (interp->builtins == NULL)
790 goto handle_error;
791 Py_INCREF(interp->builtins);
792 }
Christian Heimes6a27efa2008-10-30 21:48:26 +0000793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 /* initialize builtin exceptions */
Brett Cannonfd074152012-04-14 14:10:13 -0400795 _PyExc_Init(bimod);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000796
Victor Stinner49d3f252010-10-17 01:24:53 +0000797 sysmod = _PyImport_FindBuiltin("sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 if (bimod != NULL && sysmod != NULL) {
799 PyObject *pstderr;
Brett Cannonfd074152012-04-14 14:10:13 -0400800
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000801 interp->sysdict = PyModule_GetDict(sysmod);
802 if (interp->sysdict == NULL)
803 goto handle_error;
804 Py_INCREF(interp->sysdict);
805 PySys_SetPath(Py_GetPath());
806 PyDict_SetItemString(interp->sysdict, "modules",
807 interp->modules);
808 /* Set up a preliminary stderr printer until we have enough
809 infrastructure for the io module in place. */
810 pstderr = PyFile_NewStdPrinter(fileno(stderr));
811 if (pstderr == NULL)
812 Py_FatalError("Py_Initialize: can't set preliminary stderr");
Victor Stinnerbd303c12013-11-07 23:07:29 +0100813 _PySys_SetObjectId(&PyId_stderr, pstderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000815 Py_DECREF(pstderr);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 _PyImportHooks_Init();
Victor Stinner793b5312011-04-27 00:24:21 +0200818
Brett Cannonfd074152012-04-14 14:10:13 -0400819 import_init(interp, sysmod);
820
Victor Stinner793b5312011-04-27 00:24:21 +0200821 if (initfsencoding(interp) < 0)
822 goto handle_error;
823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000824 if (initstdio() < 0)
825 Py_FatalError(
826 "Py_Initialize: can't initialize sys standard streams");
Nick Coghlan85e729e2012-07-15 18:09:52 +1000827 initmain(interp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000828 if (!Py_NoSiteFlag)
829 initsite();
830 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000832 if (!PyErr_Occurred())
833 return tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000834
Thomas Wouters89f507f2006-12-13 04:49:30 +0000835handle_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 /* Oops, it didn't work. Undo it all. */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000837
Victor Stinnerc40a3502011-04-27 00:20:27 +0200838 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 PyThreadState_Clear(tstate);
840 PyThreadState_Swap(save_tstate);
841 PyThreadState_Delete(tstate);
842 PyInterpreterState_Delete(interp);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000845}
846
847/* Delete an interpreter and its last thread. This requires that the
848 given thread state is current, that the thread has no remaining
849 frames, and that it is its interpreter's only remaining thread.
850 It is a fatal error to violate these constraints.
851
852 (Py_Finalize() doesn't have these constraints -- it zaps
853 everything, regardless.)
854
855 Locking: as above.
856
857*/
858
859void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000860Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000861{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 PyInterpreterState *interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 if (tstate != PyThreadState_GET())
865 Py_FatalError("Py_EndInterpreter: thread is not current");
866 if (tstate->frame != NULL)
867 Py_FatalError("Py_EndInterpreter: thread still has a frame");
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200868
869 wait_for_thread_shutdown();
870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000871 if (tstate != interp->tstate_head || tstate->next != NULL)
872 Py_FatalError("Py_EndInterpreter: not the last thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 PyImport_Cleanup();
875 PyInterpreterState_Clear(interp);
876 PyThreadState_Swap(NULL);
877 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000878}
879
Antoine Pitrou01cca5e2012-07-05 20:56:30 +0200880#ifdef MS_WINDOWS
Martin v. Löwis790465f2008-04-05 20:41:37 +0000881static wchar_t *progname = L"python";
Antoine Pitrou01cca5e2012-07-05 20:56:30 +0200882#else
883static wchar_t *progname = L"python3";
884#endif
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000885
886void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000887Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000888{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 if (pn && *pn)
890 progname = pn;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000891}
892
Martin v. Löwis790465f2008-04-05 20:41:37 +0000893wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000894Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000895{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000897}
898
Martin v. Löwis790465f2008-04-05 20:41:37 +0000899static wchar_t *default_home = NULL;
Victor Stinner55a12202013-08-28 01:47:46 +0200900static wchar_t env_home[MAXPATHLEN+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000901
902void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000903Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000904{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 default_home = home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000906}
907
Martin v. Löwis790465f2008-04-05 20:41:37 +0000908wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000909Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000910{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911 wchar_t *home = default_home;
912 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
913 char* chome = Py_GETENV("PYTHONHOME");
914 if (chome) {
Victor Stinner2f5bbc62013-11-15 17:09:24 +0100915 size_t size = Py_ARRAY_LENGTH(env_home);
916 size_t r = mbstowcs(env_home, chome, size);
917 if (r != (size_t)-1 && r < size)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 home = env_home;
919 }
Martin v. Löwis790465f2008-04-05 20:41:37 +0000920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 }
922 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000923}
924
Guido van Rossum6135a871995-01-09 17:53:26 +0000925/* Create __main__ module */
926
927static void
Nick Coghlan85e729e2012-07-15 18:09:52 +1000928initmain(PyInterpreterState *interp)
Guido van Rossum6135a871995-01-09 17:53:26 +0000929{
Brett Cannon13853a62013-05-04 17:37:09 -0400930 PyObject *m, *d, *loader;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 m = PyImport_AddModule("__main__");
932 if (m == NULL)
933 Py_FatalError("can't create __main__ module");
934 d = PyModule_GetDict(m);
935 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
936 PyObject *bimod = PyImport_ImportModule("builtins");
Nick Coghlan85e729e2012-07-15 18:09:52 +1000937 if (bimod == NULL) {
938 Py_FatalError("Failed to retrieve builtins module");
939 }
940 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
941 Py_FatalError("Failed to initialize __main__.__builtins__");
942 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 Py_DECREF(bimod);
944 }
Nick Coghlan85e729e2012-07-15 18:09:52 +1000945 /* Main is a little special - imp.is_builtin("__main__") will return
946 * False, but BuiltinImporter is still the most appropriate initial
947 * setting for its __loader__ attribute. A more suitable value will
948 * be set if __main__ gets further initialized later in the startup
949 * process.
950 */
Brett Cannon13853a62013-05-04 17:37:09 -0400951 loader = PyDict_GetItemString(d, "__loader__");
Brett Cannon4c14b5d2013-05-04 13:56:58 -0400952 if (loader == NULL || loader == Py_None) {
Nick Coghlan85e729e2012-07-15 18:09:52 +1000953 PyObject *loader = PyObject_GetAttrString(interp->importlib,
954 "BuiltinImporter");
955 if (loader == NULL) {
956 Py_FatalError("Failed to retrieve BuiltinImporter");
957 }
958 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
959 Py_FatalError("Failed to initialize __main__.__loader__");
960 }
961 Py_DECREF(loader);
962 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000963}
964
Victor Stinner793b5312011-04-27 00:24:21 +0200965static int
966initfsencoding(PyInterpreterState *interp)
Victor Stinnerb744ba12010-05-15 12:27:16 +0000967{
968 PyObject *codec;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000969
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200970 if (Py_FileSystemDefaultEncoding == NULL)
971 {
972 Py_FileSystemDefaultEncoding = get_locale_encoding();
973 if (Py_FileSystemDefaultEncoding == NULL)
Victor Stinnere4743092010-10-19 00:05:51 +0000974 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
Victor Stinnerb744ba12010-05-15 12:27:16 +0000975
Victor Stinnere4743092010-10-19 00:05:51 +0000976 Py_HasFileSystemDefaultEncoding = 0;
Victor Stinner793b5312011-04-27 00:24:21 +0200977 interp->fscodec_initialized = 1;
978 return 0;
Victor Stinner7f84ab52010-06-11 00:36:33 +0000979 }
Victor Stinnerb744ba12010-05-15 12:27:16 +0000980
981 /* the encoding is mbcs, utf-8 or ascii */
982 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
983 if (!codec) {
984 /* Such error can only occurs in critical situations: no more
985 * memory, import a module of the standard library failed,
986 * etc. */
Victor Stinner793b5312011-04-27 00:24:21 +0200987 return -1;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000988 }
Victor Stinner793b5312011-04-27 00:24:21 +0200989 Py_DECREF(codec);
990 interp->fscodec_initialized = 1;
991 return 0;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000992}
993
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000994/* Import the site module (not into __main__ though) */
995
996static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000997initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000998{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 PyObject *m;
1000 m = PyImport_ImportModule("site");
1001 if (m == NULL) {
Victor Stinner62ce62a2013-07-22 22:53:28 +02001002 fprintf(stderr, "Failed to import the site module\n");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 PyErr_Print();
1004 Py_Finalize();
1005 exit(1);
1006 }
1007 else {
1008 Py_DECREF(m);
1009 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +00001010}
1011
Antoine Pitrou05608432009-01-09 18:53:14 +00001012static PyObject*
1013create_stdio(PyObject* io,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 int fd, int write_mode, char* name,
1015 char* encoding, char* errors)
Antoine Pitrou05608432009-01-09 18:53:14 +00001016{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1018 const char* mode;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001019 const char* newline;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 PyObject *line_buffering;
1021 int buffering, isatty;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001022 _Py_IDENTIFIER(open);
1023 _Py_IDENTIFIER(isatty);
1024 _Py_IDENTIFIER(TextIOWrapper);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001025 _Py_IDENTIFIER(mode);
Antoine Pitrou05608432009-01-09 18:53:14 +00001026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 /* stdin is always opened in buffered mode, first because it shouldn't
1028 make a difference in common use cases, second because TextIOWrapper
1029 depends on the presence of a read1() method which only exists on
1030 buffered streams.
1031 */
1032 if (Py_UnbufferedStdioFlag && write_mode)
1033 buffering = 0;
1034 else
1035 buffering = -1;
1036 if (write_mode)
1037 mode = "wb";
1038 else
1039 mode = "rb";
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001040 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1041 fd, mode, buffering,
1042 Py_None, Py_None, Py_None, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 if (buf == NULL)
1044 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +00001045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 if (buffering) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001047 _Py_IDENTIFIER(raw);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001048 raw = _PyObject_GetAttrId(buf, &PyId_raw);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 if (raw == NULL)
1050 goto error;
1051 }
1052 else {
1053 raw = buf;
1054 Py_INCREF(raw);
1055 }
Antoine Pitrou05608432009-01-09 18:53:14 +00001056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 text = PyUnicode_FromString(name);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001058 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 goto error;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001060 res = _PyObject_CallMethodId(raw, &PyId_isatty, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001061 if (res == NULL)
1062 goto error;
1063 isatty = PyObject_IsTrue(res);
1064 Py_DECREF(res);
1065 if (isatty == -1)
1066 goto error;
1067 if (isatty || Py_UnbufferedStdioFlag)
1068 line_buffering = Py_True;
1069 else
1070 line_buffering = Py_False;
Antoine Pitrou91696412009-01-09 22:12:30 +00001071
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 Py_CLEAR(raw);
1073 Py_CLEAR(text);
Antoine Pitrou91696412009-01-09 22:12:30 +00001074
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001075#ifdef MS_WINDOWS
Victor Stinner7b3f0fa2012-08-04 01:28:00 +02001076 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1077 newlines to "\n".
1078 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1079 newline = NULL;
1080#else
1081 /* sys.stdin: split lines at "\n".
1082 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1083 newline = "\n";
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001084#endif
1085
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001086 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssO",
1087 buf, encoding, errors,
1088 newline, line_buffering);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 Py_CLEAR(buf);
1090 if (stream == NULL)
1091 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +00001092
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093 if (write_mode)
1094 mode = "w";
1095 else
1096 mode = "r";
1097 text = PyUnicode_FromString(mode);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001098 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099 goto error;
1100 Py_CLEAR(text);
1101 return stream;
Antoine Pitrou05608432009-01-09 18:53:14 +00001102
1103error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 Py_XDECREF(buf);
1105 Py_XDECREF(stream);
1106 Py_XDECREF(text);
1107 Py_XDECREF(raw);
1108 return NULL;
Antoine Pitrou05608432009-01-09 18:53:14 +00001109}
1110
Antoine Pitrou11942a52011-11-28 19:08:36 +01001111static int
1112is_valid_fd(int fd)
1113{
1114 int dummy_fd;
1115 if (fd < 0 || !_PyVerify_fd(fd))
1116 return 0;
1117 dummy_fd = dup(fd);
1118 if (dummy_fd < 0)
1119 return 0;
1120 close(dummy_fd);
1121 return 1;
1122}
1123
Georg Brandl1a3284e2007-12-02 09:40:06 +00001124/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001125static int
1126initstdio(void)
1127{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001128 PyObject *iomod = NULL, *wrapper;
1129 PyObject *bimod = NULL;
1130 PyObject *m;
1131 PyObject *std = NULL;
1132 int status = 0, fd;
1133 PyObject * encoding_attr;
Serhiy Storchakabf28d2d2013-09-13 11:46:24 +03001134 char *pythonioencoding = NULL, *encoding, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 /* Hack to avoid a nasty recursion issue when Python is invoked
1137 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1138 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
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 (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1144 goto error;
1145 }
1146 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 if (!(bimod = PyImport_ImportModule("builtins"))) {
1149 goto error;
1150 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001152 if (!(iomod = PyImport_ImportModule("io"))) {
1153 goto error;
1154 }
1155 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1156 goto error;
1157 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 /* Set builtins.open */
1160 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
Antoine Pitrou5a96b522010-11-20 19:50:57 +00001161 Py_DECREF(wrapper);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 goto error;
1163 }
Antoine Pitrou5a96b522010-11-20 19:50:57 +00001164 Py_DECREF(wrapper);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001165
Nick Coghlan7d270ee2013-10-17 22:35:35 +10001166 encoding = _Py_StandardStreamEncoding;
1167 errors = _Py_StandardStreamErrors;
1168 if (!encoding || !errors) {
1169 pythonioencoding = Py_GETENV("PYTHONIOENCODING");
1170 if (pythonioencoding) {
1171 char *err;
1172 pythonioencoding = _PyMem_Strdup(pythonioencoding);
1173 if (pythonioencoding == NULL) {
1174 PyErr_NoMemory();
1175 goto error;
1176 }
1177 err = strchr(pythonioencoding, ':');
1178 if (err) {
1179 *err = '\0';
1180 err++;
1181 if (*err && !errors) {
1182 errors = err;
1183 }
1184 }
1185 if (*pythonioencoding && !encoding) {
1186 encoding = pythonioencoding;
1187 }
Victor Stinner49fc8ec2013-07-07 23:30:24 +02001188 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 }
Martin v. Löwis0f599892008-06-02 11:13:03 +00001190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 /* Set sys.stdin */
1192 fd = fileno(stdin);
1193 /* Under some conditions stdin, stdout and stderr may not be connected
1194 * and fileno() may point to an invalid file descriptor. For example
1195 * GUI apps don't have valid standard streams by default.
1196 */
Antoine Pitrou11942a52011-11-28 19:08:36 +01001197 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 std = Py_None;
1199 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001200 }
1201 else {
1202 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1203 if (std == NULL)
1204 goto error;
1205 } /* if (fd < 0) */
1206 PySys_SetObject("__stdin__", std);
Victor Stinnerbd303c12013-11-07 23:07:29 +01001207 _PySys_SetObjectId(&PyId_stdin, std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 /* Set sys.stdout */
1211 fd = fileno(stdout);
Antoine Pitrou11942a52011-11-28 19:08:36 +01001212 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 std = Py_None;
1214 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 }
1216 else {
1217 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1218 if (std == NULL)
1219 goto error;
1220 } /* if (fd < 0) */
1221 PySys_SetObject("__stdout__", std);
Victor Stinnerbd303c12013-11-07 23:07:29 +01001222 _PySys_SetObjectId(&PyId_stdout, std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001223 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001224
Guido van Rossum98297ee2007-11-06 21:34:58 +00001225#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001226 /* Set sys.stderr, replaces the preliminary stderr */
1227 fd = fileno(stderr);
Antoine Pitrou11942a52011-11-28 19:08:36 +01001228 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 std = Py_None;
1230 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 }
1232 else {
1233 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1234 if (std == NULL)
1235 goto error;
1236 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +00001237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 /* Same as hack above, pre-import stderr's codec to avoid recursion
1239 when import.c tries to write to stderr in verbose mode. */
1240 encoding_attr = PyObject_GetAttrString(std, "encoding");
1241 if (encoding_attr != NULL) {
Victor Stinner49fc8ec2013-07-07 23:30:24 +02001242 const char * std_encoding;
1243 std_encoding = _PyUnicode_AsString(encoding_attr);
1244 if (std_encoding != NULL) {
1245 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
Antoine Pitrou2fabfac2012-01-18 15:14:46 +01001246 Py_XDECREF(codec_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 }
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +00001248 Py_DECREF(encoding_attr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001249 }
1250 PyErr_Clear(); /* Not a fatal error if codec isn't available */
Trent Nelson39e307e2008-03-19 06:45:48 +00001251
Victor Stinnerba308832013-07-22 23:55:19 +02001252 if (PySys_SetObject("__stderr__", std) < 0) {
1253 Py_DECREF(std);
1254 goto error;
1255 }
Victor Stinnerbd303c12013-11-07 23:07:29 +01001256 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
Victor Stinnerba308832013-07-22 23:55:19 +02001257 Py_DECREF(std);
1258 goto error;
1259 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001261#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001264 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 status = -1;
1266 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001267
Nick Coghlan7d270ee2013-10-17 22:35:35 +10001268 /* We won't need them anymore. */
1269 if (_Py_StandardStreamEncoding) {
1270 PyMem_RawFree(_Py_StandardStreamEncoding);
1271 _Py_StandardStreamEncoding = NULL;
1272 }
1273 if (_Py_StandardStreamErrors) {
1274 PyMem_RawFree(_Py_StandardStreamErrors);
1275 _Py_StandardStreamErrors = NULL;
1276 }
Serhiy Storchakabf28d2d2013-09-13 11:46:24 +03001277 PyMem_Free(pythonioencoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 Py_XDECREF(bimod);
1279 Py_XDECREF(iomod);
1280 return status;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001281}
1282
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001283/* Parse input from a file and execute it */
1284
1285int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001286PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001288{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001289 if (filename == NULL)
1290 filename = "???";
1291 if (Py_FdIsInteractive(fp, filename)) {
1292 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
1293 if (closeit)
1294 fclose(fp);
1295 return err;
1296 }
1297 else
1298 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001299}
1300
1301int
Victor Stinner95701bd2013-11-06 18:41:07 +01001302PyRun_InteractiveLoopFlags(FILE *fp, const char *filename_str, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001303{
Victor Stinner95701bd2013-11-06 18:41:07 +01001304 PyObject *filename, *v;
1305 int ret, err;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001306 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001307
Victor Stinner95701bd2013-11-06 18:41:07 +01001308 filename = PyUnicode_DecodeFSDefault(filename_str);
1309 if (filename == NULL) {
1310 PyErr_Print();
1311 return -1;
1312 }
1313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 if (flags == NULL) {
1315 flags = &local_flags;
1316 local_flags.cf_flags = 0;
1317 }
Victor Stinner09054372013-11-06 22:41:44 +01001318 v = _PySys_GetObjectId(&PyId_ps1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 if (v == NULL) {
Victor Stinner09054372013-11-06 22:41:44 +01001320 _PySys_SetObjectId(&PyId_ps1, v = PyUnicode_FromString(">>> "));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001321 Py_XDECREF(v);
1322 }
Victor Stinner09054372013-11-06 22:41:44 +01001323 v = _PySys_GetObjectId(&PyId_ps2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001324 if (v == NULL) {
Victor Stinner09054372013-11-06 22:41:44 +01001325 _PySys_SetObjectId(&PyId_ps2, v = PyUnicode_FromString("... "));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001326 Py_XDECREF(v);
1327 }
Victor Stinner95701bd2013-11-06 18:41:07 +01001328 err = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 for (;;) {
Victor Stinner95701bd2013-11-06 18:41:07 +01001330 ret = PyRun_InteractiveOneObject(fp, filename, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001331 PRINT_TOTAL_REFS();
Victor Stinner95701bd2013-11-06 18:41:07 +01001332 if (ret == E_EOF) {
1333 err = 0;
1334 break;
1335 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 /*
1337 if (ret == E_NOMEM)
Victor Stinner95701bd2013-11-06 18:41:07 +01001338 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 */
1340 }
Victor Stinner95701bd2013-11-06 18:41:07 +01001341 Py_DECREF(filename);
1342 return err;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001343}
1344
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001345/* compute parser flags based on compiler flags */
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001346static int PARSER_FLAGS(PyCompilerFlags *flags)
1347{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348 int parser_flags = 0;
1349 if (!flags)
1350 return 0;
1351 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
1352 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1353 if (flags->cf_flags & PyCF_IGNORE_COOKIE)
1354 parser_flags |= PyPARSE_IGNORE_COOKIE;
1355 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
1356 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1357 return parser_flags;
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001358}
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001359
Thomas Wouters89f507f2006-12-13 04:49:30 +00001360#if 0
1361/* Keep an example of flags with future keyword support. */
1362#define PARSER_FLAGS(flags) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001363 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1364 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1365 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1366 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001367#endif
1368
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001369int
Victor Stinner95701bd2013-11-06 18:41:07 +01001370PyRun_InteractiveOneObject(FILE *fp, PyObject *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001371{
Victor Stinner95701bd2013-11-06 18:41:07 +01001372 PyObject *m, *d, *v, *w, *oenc = NULL, *mod_name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001373 mod_ty mod;
1374 PyArena *arena;
1375 char *ps1 = "", *ps2 = "", *enc = NULL;
1376 int errcode = 0;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001377 _Py_IDENTIFIER(encoding);
Victor Stinner95701bd2013-11-06 18:41:07 +01001378 _Py_IDENTIFIER(__main__);
1379
1380 mod_name = _PyUnicode_FromId(&PyId___main__); /* borrowed */
1381 if (mod_name == NULL) {
1382 PyErr_Print();
1383 return -1;
1384 }
Tim Petersfe2127d2001-07-16 05:37:24 +00001385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001386 if (fp == stdin) {
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -04001387 /* Fetch encoding from sys.stdin if possible. */
Victor Stinnerbd303c12013-11-07 23:07:29 +01001388 v = _PySys_GetObjectId(&PyId_stdin);
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -04001389 if (v && v != Py_None) {
1390 oenc = _PyObject_GetAttrId(v, &PyId_encoding);
1391 if (oenc)
1392 enc = _PyUnicode_AsString(oenc);
1393 if (!enc)
1394 PyErr_Clear();
1395 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001396 }
Victor Stinner09054372013-11-06 22:41:44 +01001397 v = _PySys_GetObjectId(&PyId_ps1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398 if (v != NULL) {
1399 v = PyObject_Str(v);
1400 if (v == NULL)
1401 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001402 else if (PyUnicode_Check(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 ps1 = _PyUnicode_AsString(v);
Victor Stinner386fe712010-05-19 00:34:15 +00001404 if (ps1 == NULL) {
1405 PyErr_Clear();
1406 ps1 = "";
1407 }
1408 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001409 }
Victor Stinner09054372013-11-06 22:41:44 +01001410 w = _PySys_GetObjectId(&PyId_ps2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001411 if (w != NULL) {
1412 w = PyObject_Str(w);
1413 if (w == NULL)
1414 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001415 else if (PyUnicode_Check(w)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001416 ps2 = _PyUnicode_AsString(w);
Victor Stinner386fe712010-05-19 00:34:15 +00001417 if (ps2 == NULL) {
1418 PyErr_Clear();
1419 ps2 = "";
1420 }
1421 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 }
1423 arena = PyArena_New();
1424 if (arena == NULL) {
1425 Py_XDECREF(v);
1426 Py_XDECREF(w);
1427 Py_XDECREF(oenc);
1428 return -1;
1429 }
Victor Stinner95701bd2013-11-06 18:41:07 +01001430 mod = PyParser_ASTFromFileObject(fp, filename, enc,
1431 Py_single_input, ps1, ps2,
1432 flags, &errcode, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001433 Py_XDECREF(v);
1434 Py_XDECREF(w);
1435 Py_XDECREF(oenc);
1436 if (mod == NULL) {
1437 PyArena_Free(arena);
1438 if (errcode == E_EOF) {
1439 PyErr_Clear();
1440 return E_EOF;
1441 }
1442 PyErr_Print();
1443 return -1;
1444 }
Victor Stinner95701bd2013-11-06 18:41:07 +01001445 m = PyImport_AddModuleObject(mod_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446 if (m == NULL) {
1447 PyArena_Free(arena);
1448 return -1;
1449 }
1450 d = PyModule_GetDict(m);
1451 v = run_mod(mod, filename, d, d, flags, arena);
1452 PyArena_Free(arena);
1453 flush_io();
1454 if (v == NULL) {
1455 PyErr_Print();
1456 return -1;
1457 }
1458 Py_DECREF(v);
1459 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001460}
1461
Victor Stinner95701bd2013-11-06 18:41:07 +01001462int
1463PyRun_InteractiveOneFlags(FILE *fp, const char *filename_str, PyCompilerFlags *flags)
1464{
1465 PyObject *filename;
1466 int res;
1467
1468 filename = PyUnicode_DecodeFSDefault(filename_str);
1469 if (filename == NULL) {
1470 PyErr_Print();
1471 return -1;
1472 }
1473 res = PyRun_InteractiveOneObject(fp, filename, flags);
1474 Py_DECREF(filename);
1475 return res;
1476}
1477
1478
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001479/* Check whether a file maybe a pyc file: Look at the extension,
1480 the file type, and, if we may close it, at the first few bytes. */
1481
1482static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001483maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001484{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001485 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1486 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001488 /* Only look into the file if we are allowed to close it, since
1489 it then should also be seekable. */
1490 if (closeit) {
1491 /* Read only two bytes of the magic. If the file was opened in
1492 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1493 be read as they are on disk. */
1494 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1495 unsigned char buf[2];
1496 /* Mess: In case of -x, the stream is NOT at its start now,
1497 and ungetc() was used to push back the first newline,
1498 which makes the current stream position formally undefined,
1499 and a x-platform nightmare.
1500 Unfortunately, we have no direct way to know whether -x
1501 was specified. So we use a terrible hack: if the current
1502 stream position is not 0, we assume -x was specified, and
1503 give up. Bug 132850 on SourceForge spells out the
1504 hopelessness of trying anything else (fseek and ftell
1505 don't work predictably x-platform for text-mode files).
1506 */
1507 int ispyc = 0;
1508 if (ftell(fp) == 0) {
1509 if (fread(buf, 1, 2, fp) == 2 &&
1510 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
1511 ispyc = 1;
1512 rewind(fp);
1513 }
1514 return ispyc;
1515 }
1516 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001517}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001518
Antoine Pitrou32d483c2013-07-30 21:01:23 +02001519static int
1520set_main_loader(PyObject *d, const char *filename, const char *loader_name)
Nick Coghlan85e729e2012-07-15 18:09:52 +10001521{
1522 PyInterpreterState *interp;
1523 PyThreadState *tstate;
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001524 PyObject *filename_obj, *loader_type, *loader;
Nick Coghlanb7a58942012-07-15 23:21:08 +10001525 int result = 0;
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001526
1527 filename_obj = PyUnicode_DecodeFSDefault(filename);
1528 if (filename_obj == NULL)
1529 return -1;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001530 /* Get current thread state and interpreter pointer */
1531 tstate = PyThreadState_GET();
1532 interp = tstate->interp;
Nick Coghlan3f94cbf2012-07-15 19:10:39 +10001533 loader_type = PyObject_GetAttrString(interp->importlib, loader_name);
1534 if (loader_type == NULL) {
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001535 Py_DECREF(filename_obj);
Nick Coghlan3f94cbf2012-07-15 19:10:39 +10001536 return -1;
1537 }
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001538 loader = PyObject_CallFunction(loader_type, "sN", "__main__", filename_obj);
Nick Coghlanb7a58942012-07-15 23:21:08 +10001539 Py_DECREF(loader_type);
1540 if (loader == NULL) {
Nick Coghlan85e729e2012-07-15 18:09:52 +10001541 return -1;
1542 }
Nick Coghlanb7a58942012-07-15 23:21:08 +10001543 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
1544 result = -1;
1545 }
Nick Coghlan85e729e2012-07-15 18:09:52 +10001546 Py_DECREF(loader);
Nick Coghlanb7a58942012-07-15 23:21:08 +10001547 return result;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001548}
1549
1550int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001551PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001552 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001553{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001554 PyObject *m, *d, *v;
1555 const char *ext;
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001556 int set_file_name = 0, ret = -1;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00001557 size_t len;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 m = PyImport_AddModule("__main__");
1560 if (m == NULL)
1561 return -1;
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001562 Py_INCREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001563 d = PyModule_GetDict(m);
1564 if (PyDict_GetItemString(d, "__file__") == NULL) {
1565 PyObject *f;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00001566 f = PyUnicode_DecodeFSDefault(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001567 if (f == NULL)
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001568 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001569 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1570 Py_DECREF(f);
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001571 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 }
Barry Warsaw916048d2011-09-20 14:45:44 -04001573 if (PyDict_SetItemString(d, "__cached__", Py_None) < 0) {
1574 Py_DECREF(f);
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001575 goto done;
Barry Warsaw916048d2011-09-20 14:45:44 -04001576 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001577 set_file_name = 1;
1578 Py_DECREF(f);
1579 }
1580 len = strlen(filename);
1581 ext = filename + len - (len > 4 ? 4 : 0);
1582 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Christian Heimes04ac4c12012-09-11 15:47:28 +02001583 FILE *pyc_fp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001584 /* Try to run a pyc file. First, re-open in binary */
1585 if (closeit)
1586 fclose(fp);
Victor Stinnerdaf45552013-08-28 00:53:59 +02001587 if ((pyc_fp = _Py_fopen(filename, "rb")) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 fprintf(stderr, "python: Can't reopen .pyc file\n");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001589 goto done;
1590 }
1591 /* Turn on optimization if a .pyo file is given */
1592 if (strcmp(ext, ".pyo") == 0)
1593 Py_OptimizeFlag = 1;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001594
1595 if (set_main_loader(d, filename, "SourcelessFileLoader") < 0) {
1596 fprintf(stderr, "python: failed to set __main__.__loader__\n");
1597 ret = -1;
Christian Heimes04ac4c12012-09-11 15:47:28 +02001598 fclose(pyc_fp);
Nick Coghlan85e729e2012-07-15 18:09:52 +10001599 goto done;
1600 }
Christian Heimes04ac4c12012-09-11 15:47:28 +02001601 v = run_pyc_file(pyc_fp, filename, d, d, flags);
1602 fclose(pyc_fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 } else {
Nick Coghlan85e729e2012-07-15 18:09:52 +10001604 /* When running from stdin, leave __main__.__loader__ alone */
1605 if (strcmp(filename, "<stdin>") != 0 &&
1606 set_main_loader(d, filename, "SourceFileLoader") < 0) {
1607 fprintf(stderr, "python: failed to set __main__.__loader__\n");
1608 ret = -1;
1609 goto done;
1610 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001611 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
1612 closeit, flags);
1613 }
1614 flush_io();
1615 if (v == NULL) {
1616 PyErr_Print();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001617 goto done;
1618 }
1619 Py_DECREF(v);
1620 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001621 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1623 PyErr_Clear();
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001624 Py_DECREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001625 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001626}
1627
1628int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001629PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001630{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001631 PyObject *m, *d, *v;
1632 m = PyImport_AddModule("__main__");
1633 if (m == NULL)
1634 return -1;
1635 d = PyModule_GetDict(m);
1636 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
1637 if (v == NULL) {
1638 PyErr_Print();
1639 return -1;
1640 }
1641 Py_DECREF(v);
1642 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001643}
1644
Barry Warsaw035574d1997-08-29 22:07:17 +00001645static int
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001646parse_syntax_error(PyObject *err, PyObject **message, PyObject **filename,
1647 int *lineno, int *offset, PyObject **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001648{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001649 long hold;
1650 PyObject *v;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001651 _Py_IDENTIFIER(msg);
1652 _Py_IDENTIFIER(filename);
1653 _Py_IDENTIFIER(lineno);
1654 _Py_IDENTIFIER(offset);
1655 _Py_IDENTIFIER(text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001656
Benjamin Peterson80d50422012-04-03 00:30:38 -04001657 *message = NULL;
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001658 *filename = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001659
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001660 /* new style errors. `err' is an instance */
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001661 *message = _PyObject_GetAttrId(err, &PyId_msg);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001662 if (!*message)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001663 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001664
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001665 v = _PyObject_GetAttrId(err, &PyId_filename);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001666 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001667 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001668 if (v == Py_None) {
1669 Py_DECREF(v);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001670 *filename = _PyUnicode_FromId(&PyId_string);
1671 if (*filename == NULL)
1672 goto finally;
1673 Py_INCREF(*filename);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001674 }
1675 else {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001676 *filename = v;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001677 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001678
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001679 v = _PyObject_GetAttrId(err, &PyId_lineno);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001680 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001681 goto finally;
1682 hold = PyLong_AsLong(v);
1683 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001684 if (hold < 0 && PyErr_Occurred())
1685 goto finally;
1686 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001687
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001688 v = _PyObject_GetAttrId(err, &PyId_offset);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001689 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001690 goto finally;
1691 if (v == Py_None) {
1692 *offset = -1;
1693 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001694 } else {
1695 hold = PyLong_AsLong(v);
1696 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001697 if (hold < 0 && PyErr_Occurred())
1698 goto finally;
1699 *offset = (int)hold;
1700 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001701
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001702 v = _PyObject_GetAttrId(err, &PyId_text);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001703 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001704 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001705 if (v == Py_None) {
1706 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001707 *text = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001708 }
1709 else {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001710 *text = v;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001711 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001712 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001713
1714finally:
Benjamin Peterson80d50422012-04-03 00:30:38 -04001715 Py_XDECREF(*message);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001716 Py_XDECREF(*filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001717 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001718}
1719
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001720void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001721PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001722{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001723 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001724}
1725
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001726static void
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001727print_error_text(PyObject *f, int offset, PyObject *text_obj)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001728{
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001729 char *text;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001730 char *nl;
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001731
1732 text = _PyUnicode_AsString(text_obj);
1733 if (text == NULL)
1734 return;
1735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 if (offset >= 0) {
Benjamin Petersona95e9772010-10-29 03:28:14 +00001737 if (offset > 0 && offset == strlen(text) && text[offset - 1] == '\n')
1738 offset--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001739 for (;;) {
1740 nl = strchr(text, '\n');
1741 if (nl == NULL || nl-text >= offset)
1742 break;
1743 offset -= (int)(nl+1-text);
1744 text = nl+1;
1745 }
1746 while (*text == ' ' || *text == '\t') {
1747 text++;
1748 offset--;
1749 }
1750 }
1751 PyFile_WriteString(" ", f);
1752 PyFile_WriteString(text, f);
1753 if (*text == '\0' || text[strlen(text)-1] != '\n')
1754 PyFile_WriteString("\n", f);
1755 if (offset == -1)
1756 return;
1757 PyFile_WriteString(" ", f);
Benjamin Petersona95e9772010-10-29 03:28:14 +00001758 while (--offset > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 PyFile_WriteString(" ", f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001760 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001761}
1762
Guido van Rossum66e8e862001-03-23 17:54:43 +00001763static void
1764handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001765{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 PyObject *exception, *value, *tb;
1767 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001769 if (Py_InspectFlag)
1770 /* Don't exit if -i flag was given. This flag is set to 0
1771 * when entering interactive mode for inspecting. */
1772 return;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 PyErr_Fetch(&exception, &value, &tb);
1775 fflush(stdout);
1776 if (value == NULL || value == Py_None)
1777 goto done;
1778 if (PyExceptionInstance_Check(value)) {
1779 /* The error code should be in the `code' attribute. */
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001780 _Py_IDENTIFIER(code);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001781 PyObject *code = _PyObject_GetAttrId(value, &PyId_code);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001782 if (code) {
1783 Py_DECREF(value);
1784 value = code;
1785 if (value == Py_None)
1786 goto done;
1787 }
1788 /* If we failed to dig out the 'code' attribute,
1789 just let the else clause below print the error. */
1790 }
1791 if (PyLong_Check(value))
1792 exitcode = (int)PyLong_AsLong(value);
1793 else {
Victor Stinnerbd303c12013-11-07 23:07:29 +01001794 PyObject *sys_stderr = _PySys_GetObjectId(&PyId_stderr);
Victor Stinner7126dbc2010-05-21 23:45:42 +00001795 if (sys_stderr != NULL && sys_stderr != Py_None) {
1796 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
1797 } else {
1798 PyObject_Print(value, stderr, Py_PRINT_RAW);
1799 fflush(stderr);
1800 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 PySys_WriteStderr("\n");
1802 exitcode = 1;
1803 }
Tim Peterscf615b52003-04-19 18:47:02 +00001804 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 /* Restore and clear the exception info, in order to properly decref
1806 * the exception, value, and traceback. If we just exit instead,
1807 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1808 * some finalizers from running.
1809 */
1810 PyErr_Restore(exception, value, tb);
1811 PyErr_Clear();
1812 Py_Exit(exitcode);
1813 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001814}
1815
1816void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001817PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001818{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001819 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001820
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001821 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1822 handle_system_exit();
1823 }
1824 PyErr_Fetch(&exception, &v, &tb);
1825 if (exception == NULL)
1826 return;
1827 PyErr_NormalizeException(&exception, &v, &tb);
1828 if (tb == NULL) {
1829 tb = Py_None;
1830 Py_INCREF(tb);
1831 }
1832 PyException_SetTraceback(v, tb);
1833 if (exception == NULL)
1834 return;
1835 /* Now we know v != NULL too */
1836 if (set_sys_last_vars) {
Victor Stinner09054372013-11-06 22:41:44 +01001837 _PySys_SetObjectId(&PyId_last_type, exception);
1838 _PySys_SetObjectId(&PyId_last_value, v);
1839 _PySys_SetObjectId(&PyId_last_traceback, tb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001840 }
Victor Stinner09054372013-11-06 22:41:44 +01001841 hook = _PySys_GetObjectId(&PyId_excepthook);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001842 if (hook) {
1843 PyObject *args = PyTuple_Pack(3, exception, v, tb);
1844 PyObject *result = PyEval_CallObject(hook, args);
1845 if (result == NULL) {
1846 PyObject *exception2, *v2, *tb2;
1847 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1848 handle_system_exit();
1849 }
1850 PyErr_Fetch(&exception2, &v2, &tb2);
1851 PyErr_NormalizeException(&exception2, &v2, &tb2);
1852 /* It should not be possible for exception2 or v2
1853 to be NULL. However PyErr_Display() can't
1854 tolerate NULLs, so just be safe. */
1855 if (exception2 == NULL) {
1856 exception2 = Py_None;
1857 Py_INCREF(exception2);
1858 }
1859 if (v2 == NULL) {
1860 v2 = Py_None;
1861 Py_INCREF(v2);
1862 }
1863 fflush(stdout);
1864 PySys_WriteStderr("Error in sys.excepthook:\n");
1865 PyErr_Display(exception2, v2, tb2);
1866 PySys_WriteStderr("\nOriginal exception was:\n");
1867 PyErr_Display(exception, v, tb);
1868 Py_DECREF(exception2);
1869 Py_DECREF(v2);
1870 Py_XDECREF(tb2);
1871 }
1872 Py_XDECREF(result);
1873 Py_XDECREF(args);
1874 } else {
1875 PySys_WriteStderr("sys.excepthook is missing\n");
1876 PyErr_Display(exception, v, tb);
1877 }
1878 Py_XDECREF(exception);
1879 Py_XDECREF(v);
1880 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001881}
1882
Benjamin Petersone6528212008-07-15 15:32:09 +00001883static void
1884print_exception(PyObject *f, PyObject *value)
1885{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001886 int err = 0;
1887 PyObject *type, *tb;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001888 _Py_IDENTIFIER(print_file_and_line);
Benjamin Petersone6528212008-07-15 15:32:09 +00001889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001890 if (!PyExceptionInstance_Check(value)) {
1891 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1892 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1893 PyFile_WriteString(" found\n", f);
1894 return;
1895 }
Benjamin Peterson26582602008-08-23 20:08:07 +00001896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001897 Py_INCREF(value);
1898 fflush(stdout);
1899 type = (PyObject *) Py_TYPE(value);
1900 tb = PyException_GetTraceback(value);
1901 if (tb && tb != Py_None)
1902 err = PyTraceBack_Print(tb, f);
1903 if (err == 0 &&
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001904 _PyObject_HasAttrId(value, &PyId_print_file_and_line))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001906 PyObject *message, *filename, *text;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001907 int lineno, offset;
1908 if (!parse_syntax_error(value, &message, &filename,
1909 &lineno, &offset, &text))
1910 PyErr_Clear();
1911 else {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001912 PyObject *line;
1913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001914 Py_DECREF(value);
1915 value = message;
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001916
1917 line = PyUnicode_FromFormat(" File \"%U\", line %d\n",
1918 filename, lineno);
1919 Py_DECREF(filename);
1920 if (line != NULL) {
1921 PyFile_WriteObject(line, f, Py_PRINT_RAW);
1922 Py_DECREF(line);
1923 }
1924
1925 if (text != NULL) {
1926 print_error_text(f, offset, text);
1927 Py_DECREF(text);
1928 }
1929
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001930 /* Can't be bothered to check all those
1931 PyFile_WriteString() calls */
1932 if (PyErr_Occurred())
1933 err = -1;
1934 }
1935 }
1936 if (err) {
1937 /* Don't do anything else */
1938 }
1939 else {
1940 PyObject* moduleName;
1941 char* className;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001942 _Py_IDENTIFIER(__module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001943 assert(PyExceptionClass_Check(type));
1944 className = PyExceptionClass_Name(type);
1945 if (className != NULL) {
1946 char *dot = strrchr(className, '.');
1947 if (dot != NULL)
1948 className = dot+1;
1949 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001950
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001951 moduleName = _PyObject_GetAttrId(type, &PyId___module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001952 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1953 {
Victor Stinner13b21bd2011-05-26 14:25:13 +02001954 Py_XDECREF(moduleName);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001955 err = PyFile_WriteString("<unknown>", f);
1956 }
1957 else {
Victor Stinnerbd303c12013-11-07 23:07:29 +01001958 if (_PyUnicode_CompareWithId(moduleName, &PyId_builtins) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001959 {
Victor Stinner937114f2013-11-07 00:12:30 +01001960 err = PyFile_WriteObject(moduleName, f, Py_PRINT_RAW);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001961 err += PyFile_WriteString(".", f);
1962 }
1963 Py_DECREF(moduleName);
1964 }
1965 if (err == 0) {
1966 if (className == NULL)
1967 err = PyFile_WriteString("<unknown>", f);
1968 else
1969 err = PyFile_WriteString(className, f);
1970 }
1971 }
1972 if (err == 0 && (value != Py_None)) {
1973 PyObject *s = PyObject_Str(value);
1974 /* only print colon if the str() of the
1975 object is not the empty string
1976 */
1977 if (s == NULL)
1978 err = -1;
1979 else if (!PyUnicode_Check(s) ||
Victor Stinnere251d6d2011-11-20 19:20:00 +01001980 PyUnicode_GetLength(s) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 err = PyFile_WriteString(": ", f);
1982 if (err == 0)
1983 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1984 Py_XDECREF(s);
1985 }
1986 /* try to write a newline in any case */
1987 err += PyFile_WriteString("\n", f);
1988 Py_XDECREF(tb);
1989 Py_DECREF(value);
1990 /* If an error happened here, don't show it.
1991 XXX This is wrong, but too many callers rely on this behavior. */
1992 if (err != 0)
1993 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001994}
1995
1996static const char *cause_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001997 "\nThe above exception was the direct cause "
1998 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001999
2000static const char *context_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002001 "\nDuring handling of the above exception, "
2002 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00002003
2004static void
2005print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
2006{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002007 int err = 0, res;
2008 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00002009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002010 if (seen != NULL) {
2011 /* Exception chaining */
2012 if (PySet_Add(seen, value) == -1)
2013 PyErr_Clear();
2014 else if (PyExceptionInstance_Check(value)) {
2015 cause = PyException_GetCause(value);
2016 context = PyException_GetContext(value);
Benjamin Petersond5a1c442012-05-14 22:09:31 -07002017 if (cause) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002018 res = PySet_Contains(seen, cause);
2019 if (res == -1)
2020 PyErr_Clear();
2021 if (res == 0) {
2022 print_exception_recursive(
2023 f, cause, seen);
2024 err |= PyFile_WriteString(
2025 cause_message, f);
2026 }
2027 }
Benjamin Petersond5a1c442012-05-14 22:09:31 -07002028 else if (context &&
2029 !((PyBaseExceptionObject *)value)->suppress_context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 res = PySet_Contains(seen, context);
2031 if (res == -1)
2032 PyErr_Clear();
2033 if (res == 0) {
2034 print_exception_recursive(
2035 f, context, seen);
2036 err |= PyFile_WriteString(
2037 context_message, f);
2038 }
2039 }
2040 Py_XDECREF(context);
2041 Py_XDECREF(cause);
2042 }
2043 }
2044 print_exception(f, value);
2045 if (err != 0)
2046 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00002047}
2048
Thomas Wouters477c8d52006-05-27 19:21:47 +00002049void
2050PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002051{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002052 PyObject *seen;
Victor Stinnerbd303c12013-11-07 23:07:29 +01002053 PyObject *f = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrou24201d42013-10-13 21:53:13 +02002054 if (PyExceptionInstance_Check(value)
2055 && tb != NULL && PyTraceBack_Check(tb)) {
2056 /* Put the traceback on the exception, otherwise it won't get
2057 displayed. See issue #18776. */
2058 PyObject *cur_tb = PyException_GetTraceback(value);
2059 if (cur_tb == NULL)
2060 PyException_SetTraceback(value, tb);
2061 else
2062 Py_DECREF(cur_tb);
2063 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 if (f == Py_None) {
2065 /* pass */
2066 }
2067 else if (f == NULL) {
2068 _PyObject_Dump(value);
2069 fprintf(stderr, "lost sys.stderr\n");
2070 }
2071 else {
2072 /* We choose to ignore seen being possibly NULL, and report
2073 at least the main exception (it could be a MemoryError).
2074 */
2075 seen = PySet_New(NULL);
2076 if (seen == NULL)
2077 PyErr_Clear();
2078 print_exception_recursive(f, value, seen);
2079 Py_XDECREF(seen);
2080 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002081}
2082
Guido van Rossum82598051997-03-05 00:20:32 +00002083PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002084PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002085 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002086{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002087 PyObject *ret = NULL;
2088 mod_ty mod;
Victor Stinner95701bd2013-11-06 18:41:07 +01002089 PyArena *arena;
Victor Stinner95701bd2013-11-06 18:41:07 +01002090 PyObject *filename;
2091
2092 filename = _PyUnicode_FromId(&PyId_string); /* borrowed */
2093 if (filename == NULL)
2094 return NULL;
2095
2096 arena = PyArena_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002097 if (arena == NULL)
2098 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00002099
Victor Stinner95701bd2013-11-06 18:41:07 +01002100 mod = PyParser_ASTFromStringObject(str, filename, start, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002101 if (mod != NULL)
Victor Stinner95701bd2013-11-06 18:41:07 +01002102 ret = run_mod(mod, filename, globals, locals, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002103 PyArena_Free(arena);
2104 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002105}
2106
2107PyObject *
Victor Stinner95701bd2013-11-06 18:41:07 +01002108PyRun_FileExFlags(FILE *fp, const char *filename_str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002109 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002110{
Victor Stinner95701bd2013-11-06 18:41:07 +01002111 PyObject *ret = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002112 mod_ty mod;
Victor Stinner95701bd2013-11-06 18:41:07 +01002113 PyArena *arena = NULL;
2114 PyObject *filename;
Guido van Rossum98297ee2007-11-06 21:34:58 +00002115
Victor Stinner95701bd2013-11-06 18:41:07 +01002116 filename = PyUnicode_DecodeFSDefault(filename_str);
2117 if (filename == NULL)
2118 goto exit;
2119
2120 arena = PyArena_New();
2121 if (arena == NULL)
2122 goto exit;
2123
2124 mod = PyParser_ASTFromFileObject(fp, filename, NULL, start, 0, 0,
2125 flags, NULL, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002126 if (closeit)
2127 fclose(fp);
2128 if (mod == NULL) {
Victor Stinner95701bd2013-11-06 18:41:07 +01002129 goto exit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 }
2131 ret = run_mod(mod, filename, globals, locals, flags, arena);
Victor Stinner95701bd2013-11-06 18:41:07 +01002132
2133exit:
2134 Py_XDECREF(filename);
2135 if (arena != NULL)
2136 PyArena_Free(arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002138}
2139
Guido van Rossum6c193fa2007-12-05 05:14:58 +00002140static void
2141flush_io(void)
2142{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002143 PyObject *f, *r;
2144 PyObject *type, *value, *traceback;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00002145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002146 /* Save the current exception */
2147 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00002148
Victor Stinnerbd303c12013-11-07 23:07:29 +01002149 f = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002150 if (f != NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002151 r = _PyObject_CallMethodId(f, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002152 if (r)
2153 Py_DECREF(r);
2154 else
2155 PyErr_Clear();
2156 }
Victor Stinnerbd303c12013-11-07 23:07:29 +01002157 f = _PySys_GetObjectId(&PyId_stdout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002158 if (f != NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002159 r = _PyObject_CallMethodId(f, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 if (r)
2161 Py_DECREF(r);
2162 else
2163 PyErr_Clear();
2164 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00002165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002166 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00002167}
2168
Guido van Rossum82598051997-03-05 00:20:32 +00002169static PyObject *
Victor Stinner95701bd2013-11-06 18:41:07 +01002170run_mod(mod_ty mod, PyObject *filename, PyObject *globals, PyObject *locals,
2171 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002172{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002173 PyCodeObject *co;
2174 PyObject *v;
Victor Stinner95701bd2013-11-06 18:41:07 +01002175 co = PyAST_CompileObject(mod, filename, flags, -1, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002176 if (co == NULL)
2177 return NULL;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002178 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002179 Py_DECREF(co);
2180 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002181}
2182
Guido van Rossum82598051997-03-05 00:20:32 +00002183static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002184run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002185 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00002186{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002187 PyCodeObject *co;
2188 PyObject *v;
2189 long magic;
2190 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00002191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002192 magic = PyMarshal_ReadLongFromFile(fp);
2193 if (magic != PyImport_GetMagicNumber()) {
2194 PyErr_SetString(PyExc_RuntimeError,
2195 "Bad magic number in .pyc file");
2196 return NULL;
2197 }
Antoine Pitrou5136ac02012-01-13 18:52:16 +01002198 /* Skip mtime and size */
2199 (void) PyMarshal_ReadLongFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002200 (void) PyMarshal_ReadLongFromFile(fp);
2201 v = PyMarshal_ReadLastObjectFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002202 if (v == NULL || !PyCode_Check(v)) {
2203 Py_XDECREF(v);
2204 PyErr_SetString(PyExc_RuntimeError,
2205 "Bad code object in .pyc file");
2206 return NULL;
2207 }
2208 co = (PyCodeObject *)v;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002209 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002210 if (v && flags)
2211 flags->cf_flags |= (co->co_flags & PyCF_MASK);
2212 Py_DECREF(co);
2213 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00002214}
2215
Guido van Rossum82598051997-03-05 00:20:32 +00002216PyObject *
Victor Stinner14e461d2013-08-26 22:28:21 +02002217Py_CompileStringObject(const char *str, PyObject *filename, int start,
2218 PyCompilerFlags *flags, int optimize)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002219{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002220 PyCodeObject *co;
2221 mod_ty mod;
2222 PyArena *arena = PyArena_New();
2223 if (arena == NULL)
2224 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002225
Victor Stinner14e461d2013-08-26 22:28:21 +02002226 mod = PyParser_ASTFromStringObject(str, filename, start, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002227 if (mod == NULL) {
2228 PyArena_Free(arena);
2229 return NULL;
2230 }
2231 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
2232 PyObject *result = PyAST_mod2obj(mod);
2233 PyArena_Free(arena);
2234 return result;
2235 }
Victor Stinner14e461d2013-08-26 22:28:21 +02002236 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237 PyArena_Free(arena);
2238 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00002239}
2240
Victor Stinner14e461d2013-08-26 22:28:21 +02002241PyObject *
2242Py_CompileStringExFlags(const char *str, const char *filename_str, int start,
2243 PyCompilerFlags *flags, int optimize)
2244{
2245 PyObject *filename, *co;
2246 filename = PyUnicode_DecodeFSDefault(filename_str);
2247 if (filename == NULL)
2248 return NULL;
2249 co = Py_CompileStringObject(str, filename, start, flags, optimize);
2250 Py_DECREF(filename);
2251 return co;
2252}
2253
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002254/* For use in Py_LIMITED_API */
2255#undef Py_CompileString
2256PyObject *
2257PyCompileString(const char *str, const char *filename, int start)
2258{
2259 return Py_CompileStringFlags(str, filename, start, NULL);
2260}
2261
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002262struct symtable *
Victor Stinner14e461d2013-08-26 22:28:21 +02002263Py_SymtableStringObject(const char *str, PyObject *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002264{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 struct symtable *st;
2266 mod_ty mod;
2267 PyCompilerFlags flags;
Victor Stinner14e461d2013-08-26 22:28:21 +02002268 PyArena *arena;
2269
2270 arena = PyArena_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002271 if (arena == NULL)
2272 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 flags.cf_flags = 0;
Victor Stinner14e461d2013-08-26 22:28:21 +02002275 mod = PyParser_ASTFromStringObject(str, filename, start, &flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002276 if (mod == NULL) {
2277 PyArena_Free(arena);
2278 return NULL;
2279 }
Victor Stinner14e461d2013-08-26 22:28:21 +02002280 st = PySymtable_BuildObject(mod, filename, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002281 PyArena_Free(arena);
2282 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002283}
2284
Victor Stinner14e461d2013-08-26 22:28:21 +02002285struct symtable *
2286Py_SymtableString(const char *str, const char *filename_str, int start)
2287{
2288 PyObject *filename;
2289 struct symtable *st;
2290
2291 filename = PyUnicode_DecodeFSDefault(filename_str);
2292 if (filename == NULL)
2293 return NULL;
2294 st = Py_SymtableStringObject(str, filename, start);
2295 Py_DECREF(filename);
2296 return st;
2297}
2298
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002299/* Preferred access to parser is through AST. */
2300mod_ty
Victor Stinner14e461d2013-08-26 22:28:21 +02002301PyParser_ASTFromStringObject(const char *s, PyObject *filename, int start,
2302 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002303{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002304 mod_ty mod;
2305 PyCompilerFlags localflags;
2306 perrdetail err;
2307 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00002308
Victor Stinner14e461d2013-08-26 22:28:21 +02002309 node *n = PyParser_ParseStringObject(s, filename,
2310 &_PyParser_Grammar, start, &err,
2311 &iflags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002312 if (flags == NULL) {
2313 localflags.cf_flags = 0;
2314 flags = &localflags;
2315 }
2316 if (n) {
2317 flags->cf_flags |= iflags & PyCF_MASK;
Victor Stinner14e461d2013-08-26 22:28:21 +02002318 mod = PyAST_FromNodeObject(n, flags, filename, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002319 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002320 }
2321 else {
2322 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002323 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002325 err_free(&err);
2326 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002327}
2328
2329mod_ty
Victor Stinner14e461d2013-08-26 22:28:21 +02002330PyParser_ASTFromString(const char *s, const char *filename_str, int start,
2331 PyCompilerFlags *flags, PyArena *arena)
2332{
2333 PyObject *filename;
2334 mod_ty mod;
2335 filename = PyUnicode_DecodeFSDefault(filename_str);
2336 if (filename == NULL)
2337 return NULL;
2338 mod = PyParser_ASTFromStringObject(s, filename, start, flags, arena);
2339 Py_DECREF(filename);
2340 return mod;
2341}
2342
2343mod_ty
2344PyParser_ASTFromFileObject(FILE *fp, PyObject *filename, const char* enc,
2345 int start, char *ps1,
2346 char *ps2, PyCompilerFlags *flags, int *errcode,
2347 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002348{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002349 mod_ty mod;
2350 PyCompilerFlags localflags;
2351 perrdetail err;
2352 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00002353
Victor Stinner14e461d2013-08-26 22:28:21 +02002354 node *n = PyParser_ParseFileObject(fp, filename, enc,
2355 &_PyParser_Grammar,
2356 start, ps1, ps2, &err, &iflags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002357 if (flags == NULL) {
2358 localflags.cf_flags = 0;
2359 flags = &localflags;
2360 }
2361 if (n) {
2362 flags->cf_flags |= iflags & PyCF_MASK;
Victor Stinner14e461d2013-08-26 22:28:21 +02002363 mod = PyAST_FromNodeObject(n, flags, filename, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002364 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002365 }
2366 else {
2367 err_input(&err);
2368 if (errcode)
2369 *errcode = err.error;
Victor Stinner7f2fee32011-04-05 00:39:01 +02002370 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002371 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002372 err_free(&err);
2373 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002374}
2375
Victor Stinner14e461d2013-08-26 22:28:21 +02002376mod_ty
2377PyParser_ASTFromFile(FILE *fp, const char *filename_str, const char* enc,
2378 int start, char *ps1,
2379 char *ps2, PyCompilerFlags *flags, int *errcode,
2380 PyArena *arena)
2381{
2382 mod_ty mod;
2383 PyObject *filename;
2384 filename = PyUnicode_DecodeFSDefault(filename_str);
2385 if (filename == NULL)
2386 return NULL;
2387 mod = PyParser_ASTFromFileObject(fp, filename, enc, start, ps1, ps2,
2388 flags, errcode, arena);
2389 Py_DECREF(filename);
2390 return mod;
2391}
2392
Guido van Rossuma110aa61994-08-29 12:50:44 +00002393/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002394
Guido van Rossuma110aa61994-08-29 12:50:44 +00002395node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002396PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002397{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002398 perrdetail err;
2399 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
2400 &_PyParser_Grammar,
2401 start, NULL, NULL, &err, flags);
2402 if (n == NULL)
2403 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002404 err_free(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002406 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002407}
2408
Guido van Rossuma110aa61994-08-29 12:50:44 +00002409/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002410
Guido van Rossuma110aa61994-08-29 12:50:44 +00002411node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002412PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00002413{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002414 perrdetail err;
2415 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
2416 start, &err, flags);
2417 if (n == NULL)
2418 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002419 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002420 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00002421}
2422
2423node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002424PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002425 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00002426{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002427 perrdetail err;
2428 node *n = PyParser_ParseStringFlagsFilename(str, filename,
2429 &_PyParser_Grammar, start, &err, flags);
2430 if (n == NULL)
2431 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002432 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002433 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00002434}
2435
2436node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002437PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00002438{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002439 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00002440}
2441
Guido van Rossum66ebd912003-04-17 16:02:26 +00002442/* May want to move a more generalized form of this to parsetok.c or
2443 even parser modules. */
2444
2445void
Victor Stinner7f2fee32011-04-05 00:39:01 +02002446PyParser_ClearError(perrdetail *err)
2447{
2448 err_free(err);
2449}
2450
2451void
Guido van Rossum66ebd912003-04-17 16:02:26 +00002452PyParser_SetError(perrdetail *err)
2453{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002454 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00002455}
2456
Victor Stinner7f2fee32011-04-05 00:39:01 +02002457static void
2458err_free(perrdetail *err)
2459{
2460 Py_CLEAR(err->filename);
2461}
2462
Guido van Rossuma110aa61994-08-29 12:50:44 +00002463/* Set the error appropriate to the given input error code (see errcode.h) */
2464
2465static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002466err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00002467{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002468 PyObject *v, *w, *errtype, *errtext;
2469 PyObject *msg_obj = NULL;
2470 char *msg = NULL;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00002471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002472 errtype = PyExc_SyntaxError;
2473 switch (err->error) {
2474 case E_ERROR:
2475 return;
2476 case E_SYNTAX:
2477 errtype = PyExc_IndentationError;
2478 if (err->expected == INDENT)
2479 msg = "expected an indented block";
2480 else if (err->token == INDENT)
2481 msg = "unexpected indent";
2482 else if (err->token == DEDENT)
2483 msg = "unexpected unindent";
2484 else {
2485 errtype = PyExc_SyntaxError;
2486 msg = "invalid syntax";
2487 }
2488 break;
2489 case E_TOKEN:
2490 msg = "invalid token";
2491 break;
2492 case E_EOFS:
2493 msg = "EOF while scanning triple-quoted string literal";
2494 break;
2495 case E_EOLS:
2496 msg = "EOL while scanning string literal";
2497 break;
2498 case E_INTR:
2499 if (!PyErr_Occurred())
2500 PyErr_SetNone(PyExc_KeyboardInterrupt);
2501 goto cleanup;
2502 case E_NOMEM:
2503 PyErr_NoMemory();
2504 goto cleanup;
2505 case E_EOF:
2506 msg = "unexpected EOF while parsing";
2507 break;
2508 case E_TABSPACE:
2509 errtype = PyExc_TabError;
2510 msg = "inconsistent use of tabs and spaces in indentation";
2511 break;
2512 case E_OVERFLOW:
2513 msg = "expression too long";
2514 break;
2515 case E_DEDENT:
2516 errtype = PyExc_IndentationError;
2517 msg = "unindent does not match any outer indentation level";
2518 break;
2519 case E_TOODEEP:
2520 errtype = PyExc_IndentationError;
2521 msg = "too many levels of indentation";
2522 break;
2523 case E_DECODE: {
2524 PyObject *type, *value, *tb;
2525 PyErr_Fetch(&type, &value, &tb);
2526 msg = "unknown decode error";
2527 if (value != NULL)
2528 msg_obj = PyObject_Str(value);
2529 Py_XDECREF(type);
2530 Py_XDECREF(value);
2531 Py_XDECREF(tb);
2532 break;
2533 }
2534 case E_LINECONT:
2535 msg = "unexpected character after line continuation character";
2536 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00002537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002538 case E_IDENTIFIER:
2539 msg = "invalid character in identifier";
2540 break;
Meador Ingefa21bf02012-01-19 01:08:41 -06002541 case E_BADSINGLE:
2542 msg = "multiple statements found while compiling a single statement";
2543 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002544 default:
2545 fprintf(stderr, "error=%d\n", err->error);
2546 msg = "unknown parsing error";
2547 break;
2548 }
2549 /* err->text may not be UTF-8 in case of decoding errors.
2550 Explicitly convert to an object. */
2551 if (!err->text) {
2552 errtext = Py_None;
2553 Py_INCREF(Py_None);
2554 } else {
2555 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
2556 "replace");
2557 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002558 v = Py_BuildValue("(OiiN)", err->filename,
2559 err->lineno, err->offset, errtext);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002560 if (v != NULL) {
2561 if (msg_obj)
2562 w = Py_BuildValue("(OO)", msg_obj, v);
2563 else
2564 w = Py_BuildValue("(sO)", msg, v);
2565 } else
2566 w = NULL;
2567 Py_XDECREF(v);
2568 PyErr_SetObject(errtype, w);
2569 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00002570cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002571 Py_XDECREF(msg_obj);
2572 if (err->text != NULL) {
2573 PyObject_FREE(err->text);
2574 err->text = NULL;
2575 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002576}
2577
2578/* Print fatal error message and abort */
2579
2580void
Tim Peters7c321a82002-07-09 02:57:01 +00002581Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002582{
Victor Stinner024e37a2011-03-31 01:31:06 +02002583 const int fd = fileno(stderr);
2584 PyThreadState *tstate;
2585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002586 fprintf(stderr, "Fatal Python error: %s\n", msg);
2587 fflush(stderr); /* it helps in Windows debug build */
2588 if (PyErr_Occurred()) {
Victor Stinner55a5c782010-06-08 21:00:13 +00002589 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002590 }
Victor Stinner024e37a2011-03-31 01:31:06 +02002591 else {
2592 tstate = _Py_atomic_load_relaxed(&_PyThreadState_Current);
2593 if (tstate != NULL) {
2594 fputc('\n', stderr);
2595 fflush(stderr);
Victor Stinner7bba62f2011-05-07 12:43:00 +02002596 _Py_DumpTracebackThreads(fd, tstate->interp, tstate);
Victor Stinner024e37a2011-03-31 01:31:06 +02002597 }
Victor Stinnerd727e232011-04-01 12:13:55 +02002598 _PyFaulthandler_Fini();
Victor Stinner024e37a2011-03-31 01:31:06 +02002599 }
2600
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002601#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002602 {
2603 size_t len = strlen(msg);
2604 WCHAR* buffer;
2605 size_t i;
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002607 /* Convert the message to wchar_t. This uses a simple one-to-one
2608 conversion, assuming that the this error message actually uses ASCII
2609 only. If this ceases to be true, we will have to convert. */
2610 buffer = alloca( (len+1) * (sizeof *buffer));
2611 for( i=0; i<=len; ++i)
2612 buffer[i] = msg[i];
2613 OutputDebugStringW(L"Fatal Python error: ");
2614 OutputDebugStringW(buffer);
2615 OutputDebugStringW(L"\n");
2616 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002617#ifdef _DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002618 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002619#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002620#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002621 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002622}
2623
2624/* Clean up and exit */
2625
Guido van Rossuma110aa61994-08-29 12:50:44 +00002626#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002627#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002628#endif
2629
Collin Winter670e6922007-03-21 02:57:17 +00002630static void (*pyexitfunc)(void) = NULL;
2631/* For the atexit module. */
2632void _Py_PyAtExit(void (*func)(void))
2633{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002634 pyexitfunc = func;
Collin Winter670e6922007-03-21 02:57:17 +00002635}
2636
2637static void
2638call_py_exitfuncs(void)
2639{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002640 if (pyexitfunc == NULL)
2641 return;
Collin Winter670e6922007-03-21 02:57:17 +00002642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002643 (*pyexitfunc)();
2644 PyErr_Clear();
Collin Winter670e6922007-03-21 02:57:17 +00002645}
2646
Antoine Pitrou011bd622009-10-20 21:52:47 +00002647/* Wait until threading._shutdown completes, provided
2648 the threading module was imported in the first place.
2649 The shutdown routine will wait until all non-daemon
2650 "threading" threads have completed. */
2651static void
2652wait_for_thread_shutdown(void)
2653{
2654#ifdef WITH_THREAD
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002655 _Py_IDENTIFIER(_shutdown);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002656 PyObject *result;
2657 PyThreadState *tstate = PyThreadState_GET();
2658 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2659 "threading");
2660 if (threading == NULL) {
2661 /* threading not imported */
2662 PyErr_Clear();
2663 return;
2664 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002665 result = _PyObject_CallMethodId(threading, &PyId__shutdown, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002666 if (result == NULL) {
2667 PyErr_WriteUnraisable(threading);
2668 }
2669 else {
2670 Py_DECREF(result);
2671 }
2672 Py_DECREF(threading);
Antoine Pitrou011bd622009-10-20 21:52:47 +00002673#endif
2674}
2675
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002676#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002677static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002678static int nexitfuncs = 0;
2679
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002680int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002681{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002682 if (nexitfuncs >= NEXITFUNCS)
2683 return -1;
2684 exitfuncs[nexitfuncs++] = func;
2685 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00002686}
2687
Guido van Rossumcc283f51997-08-05 02:22:03 +00002688static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002689call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002690{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002691 while (nexitfuncs > 0)
2692 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002693
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002694 fflush(stdout);
2695 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002696}
2697
2698void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002699Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002700{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002701 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002702
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002703 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002704}
2705
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002706static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002707initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002708{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002709#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002710 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002711#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002712#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002713 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002714#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002715#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002716 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002717#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002718 PyOS_InitInterrupts(); /* May imply initsignal() */
Victor Stinnerd786ad52013-07-21 13:25:51 +02002719 if (PyErr_Occurred()) {
2720 Py_FatalError("Py_Initialize: can't import signal");
2721 }
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002722}
2723
Guido van Rossum7433b121997-02-14 19:45:36 +00002724
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002725/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2726 *
2727 * All of the code in this function must only use async-signal-safe functions,
2728 * listed at `man 7 signal` or
2729 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2730 */
2731void
2732_Py_RestoreSignals(void)
2733{
2734#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002735 PyOS_setsig(SIGPIPE, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002736#endif
2737#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002738 PyOS_setsig(SIGXFZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002739#endif
2740#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002741 PyOS_setsig(SIGXFSZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002742#endif
2743}
2744
2745
Guido van Rossum7433b121997-02-14 19:45:36 +00002746/*
2747 * The file descriptor fd is considered ``interactive'' if either
2748 * a) isatty(fd) is TRUE, or
2749 * b) the -i flag was given, and the filename associated with
2750 * the descriptor is NULL or "<stdin>" or "???".
2751 */
2752int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002753Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002754{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002755 if (isatty((int)fileno(fp)))
2756 return 1;
2757 if (!Py_InteractiveFlag)
2758 return 0;
2759 return (filename == NULL) ||
2760 (strcmp(filename, "<stdin>") == 0) ||
2761 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00002762}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002763
2764
Tim Petersd08e3822003-04-17 15:24:21 +00002765#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002766#if defined(WIN32) && defined(_MSC_VER)
2767
2768/* Stack checking for Microsoft C */
2769
2770#include <malloc.h>
2771#include <excpt.h>
2772
Fred Drakee8de31c2000-08-31 05:38:39 +00002773/*
2774 * Return non-zero when we run out of memory on the stack; zero otherwise.
2775 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002776int
Fred Drake399739f2000-08-31 05:52:44 +00002777PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002778{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002779 __try {
2780 /* alloca throws a stack overflow exception if there's
2781 not enough space left on the stack */
2782 alloca(PYOS_STACK_MARGIN * sizeof(void*));
2783 return 0;
2784 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2785 EXCEPTION_EXECUTE_HANDLER :
2786 EXCEPTION_CONTINUE_SEARCH) {
2787 int errcode = _resetstkoflw();
2788 if (errcode == 0)
2789 {
2790 Py_FatalError("Could not reset the stack!");
2791 }
2792 }
2793 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002794}
2795
2796#endif /* WIN32 && _MSC_VER */
2797
2798/* Alternate implementations can be added here... */
2799
2800#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002801
2802
2803/* Wrappers around sigaction() or signal(). */
2804
2805PyOS_sighandler_t
2806PyOS_getsig(int sig)
2807{
2808#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002809 struct sigaction context;
2810 if (sigaction(sig, NULL, &context) == -1)
2811 return SIG_ERR;
2812 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002813#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002814 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002815/* Special signal handling for the secure CRT in Visual Studio 2005 */
2816#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002817 switch (sig) {
2818 /* Only these signals are valid */
2819 case SIGINT:
2820 case SIGILL:
2821 case SIGFPE:
2822 case SIGSEGV:
2823 case SIGTERM:
2824 case SIGBREAK:
2825 case SIGABRT:
2826 break;
2827 /* Don't call signal() with other values or it will assert */
2828 default:
2829 return SIG_ERR;
2830 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002831#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002832 handler = signal(sig, SIG_IGN);
2833 if (handler != SIG_ERR)
2834 signal(sig, handler);
2835 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002836#endif
2837}
2838
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002839/*
2840 * All of the code in this function must only use async-signal-safe functions,
2841 * listed at `man 7 signal` or
2842 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2843 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002844PyOS_sighandler_t
2845PyOS_setsig(int sig, PyOS_sighandler_t handler)
2846{
2847#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002848 /* Some code in Modules/signalmodule.c depends on sigaction() being
2849 * used here if HAVE_SIGACTION is defined. Fix that if this code
2850 * changes to invalidate that assumption.
2851 */
2852 struct sigaction context, ocontext;
2853 context.sa_handler = handler;
2854 sigemptyset(&context.sa_mask);
2855 context.sa_flags = 0;
2856 if (sigaction(sig, &context, &ocontext) == -1)
2857 return SIG_ERR;
2858 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002859#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002860 PyOS_sighandler_t oldhandler;
2861 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002862#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002863 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002864#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002865 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002866#endif
2867}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002868
2869/* Deprecated C API functions still provided for binary compatiblity */
2870
2871#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002872PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002873PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2874{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002875 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002876}
2877
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002878#undef PyParser_SimpleParseString
2879PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002880PyParser_SimpleParseString(const char *str, int start)
2881{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002882 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002883}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002884
2885#undef PyRun_AnyFile
2886PyAPI_FUNC(int)
2887PyRun_AnyFile(FILE *fp, const char *name)
2888{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002889 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002890}
2891
2892#undef PyRun_AnyFileEx
2893PyAPI_FUNC(int)
2894PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2895{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002896 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002897}
2898
2899#undef PyRun_AnyFileFlags
2900PyAPI_FUNC(int)
2901PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2902{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002903 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002904}
2905
2906#undef PyRun_File
2907PyAPI_FUNC(PyObject *)
2908PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2909{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002910 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002911}
2912
2913#undef PyRun_FileEx
2914PyAPI_FUNC(PyObject *)
2915PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2916{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002917 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002918}
2919
2920#undef PyRun_FileFlags
2921PyAPI_FUNC(PyObject *)
2922PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002923 PyCompilerFlags *flags)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002924{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002925 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002926}
2927
2928#undef PyRun_SimpleFile
2929PyAPI_FUNC(int)
2930PyRun_SimpleFile(FILE *f, const char *p)
2931{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002932 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002933}
2934
2935#undef PyRun_SimpleFileEx
2936PyAPI_FUNC(int)
2937PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2938{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002939 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002940}
2941
2942
2943#undef PyRun_String
2944PyAPI_FUNC(PyObject *)
2945PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2946{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002947 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002948}
2949
2950#undef PyRun_SimpleString
2951PyAPI_FUNC(int)
2952PyRun_SimpleString(const char *s)
2953{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002954 return PyRun_SimpleStringFlags(s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002955}
2956
2957#undef Py_CompileString
2958PyAPI_FUNC(PyObject *)
2959Py_CompileString(const char *str, const char *p, int s)
2960{
Georg Brandl8334fd92010-12-04 10:26:46 +00002961 return Py_CompileStringExFlags(str, p, s, NULL, -1);
2962}
2963
2964#undef Py_CompileStringFlags
2965PyAPI_FUNC(PyObject *)
2966Py_CompileStringFlags(const char *str, const char *p, int s,
2967 PyCompilerFlags *flags)
2968{
2969 return Py_CompileStringExFlags(str, p, s, flags, -1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002970}
2971
2972#undef PyRun_InteractiveOne
2973PyAPI_FUNC(int)
2974PyRun_InteractiveOne(FILE *f, const char *p)
2975{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002976 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002977}
2978
2979#undef PyRun_InteractiveLoop
2980PyAPI_FUNC(int)
2981PyRun_InteractiveLoop(FILE *f, const char *p)
2982{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002983 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002984}
2985
2986#ifdef __cplusplus
2987}
2988#endif