blob: cbd62aa056fd2ff3ec9e7edfc107779240aefe42 [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
Ezio Melotti1f8898a2013-03-26 01:59:56 +020038#ifdef Py_REF_DEBUG
Antoine Pitrou208ac5c2013-04-24 20:17:53 +020039static
40void _print_total_refs(void) {
Ezio Melotti1f8898a2013-03-26 01:59:56 +020041 PyObject *xoptions, *key, *value;
42 xoptions = PySys_GetXOptions();
43 if (xoptions == NULL)
44 return;
45 key = PyUnicode_FromString("showrefcount");
46 if (key == NULL)
47 return;
48 value = PyDict_GetItem(xoptions, key);
49 Py_DECREF(key);
50 if (value == Py_True)
51 fprintf(stderr,
52 "[%" PY_FORMAT_SIZE_T "d refs, "
53 "%" PY_FORMAT_SIZE_T "d blocks]\n",
54 _Py_GetRefTotal(), _Py_GetAllocatedBlocks());
55}
56#endif
57
Neal Norwitz4281cef2006-03-04 19:58:13 +000058#ifndef Py_REF_DEBUG
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000059#define PRINT_TOTAL_REFS()
Neal Norwitz4281cef2006-03-04 19:58:13 +000060#else /* Py_REF_DEBUG */
Ezio Melotti1f8898a2013-03-26 01:59:56 +020061#define PRINT_TOTAL_REFS() _print_total_refs()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000062#endif
63
64#ifdef __cplusplus
65extern "C" {
Neal Norwitz4281cef2006-03-04 19:58:13 +000066#endif
67
Martin v. Löwis790465f2008-04-05 20:41:37 +000068extern wchar_t *Py_GetPath(void);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000069
Guido van Rossum82598051997-03-05 00:20:32 +000070extern grammar _PyParser_Grammar; /* From graminit.c */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000071
Guido van Rossumb73cc041993-11-01 16:28:59 +000072/* Forward */
Nick Coghlan85e729e2012-07-15 18:09:52 +100073static void initmain(PyInterpreterState *interp);
Victor Stinner793b5312011-04-27 00:24:21 +020074static int initfsencoding(PyInterpreterState *interp);
Tim Petersdbd9ba62000-07-09 03:09:57 +000075static void initsite(void);
Guido van Rossumce3a72a2007-10-19 23:16:50 +000076static int initstdio(void);
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +000077static void flush_io(void);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000078static PyObject *run_mod(mod_ty, const char *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000079 PyCompilerFlags *, PyArena *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000080static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000081 PyCompilerFlags *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000082static void err_input(perrdetail *);
Victor Stinner7f2fee32011-04-05 00:39:01 +020083static void err_free(perrdetail *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000084static void initsigs(void);
Collin Winter670e6922007-03-21 02:57:17 +000085static void call_py_exitfuncs(void);
Antoine Pitrou011bd622009-10-20 21:52:47 +000086static void wait_for_thread_shutdown(void);
Tim Petersdbd9ba62000-07-09 03:09:57 +000087static void call_ll_exitfuncs(void);
Victor Stinner3a50e702011-10-18 21:21:00 +020088extern int _PyUnicode_Init(void);
Victor Stinner26f91992013-07-17 01:22:45 +020089extern int _PyStructSequence_Init(void);
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000090extern void _PyUnicode_Fini(void);
Guido van Rossumddefaf32007-01-14 03:31:43 +000091extern int _PyLong_Init(void);
92extern void PyLong_Fini(void);
Victor Stinner024e37a2011-03-31 01:31:06 +020093extern int _PyFaulthandler_Init(void);
94extern void _PyFaulthandler_Fini(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +000095
Mark Hammond8d98d2c2003-04-19 15:41:53 +000096#ifdef WITH_THREAD
97extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
98extern void _PyGILState_Fini(void);
99#endif /* WITH_THREAD */
100
Guido van Rossum82598051997-03-05 00:20:32 +0000101int Py_DebugFlag; /* Needed by parser.c */
102int Py_VerboseFlag; /* Needed by import.c */
Georg Brandl8aa7e992010-12-28 18:30:18 +0000103int Py_QuietFlag; /* Needed by sysmodule.c */
Guido van Rossum7433b121997-02-14 19:45:36 +0000104int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Georg Brandl0b2489e2011-05-15 08:49:12 +0200105int Py_InspectFlag; /* Needed to determine whether to exit at SystemExit */
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000106int Py_NoSiteFlag; /* Suppress 'import site' */
Guido van Rossum98297ee2007-11-06 21:34:58 +0000107int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
Christian Heimes790c8232008-01-07 21:14:23 +0000108int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.py[co]) */
Barry Warsaw3ce09642000-05-02 19:18:59 +0000109int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +0000110int Py_FrozenFlag; /* Needed by getpath.c */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000111int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Christian Heimes8dc226f2008-05-06 23:45:46 +0000112int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
Antoine Pitrou05608432009-01-09 18:53:14 +0000113int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100114int Py_HashRandomizationFlag = 0; /* for -R and PYTHONHASHSEED */
Christian Heimesad73a9c2013-08-10 16:36:18 +0200115int Py_IsolatedFlag = 0; /* for -I, isolate from user's env */
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000116
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200117PyThreadState *_Py_Finalizing = NULL;
118
Christian Heimes33fe8092008-04-13 13:53:33 +0000119/* PyModule_GetWarningsModule is no longer necessary as of 2.6
120since _warnings is builtin. This API should not be used. */
121PyObject *
122PyModule_GetWarningsModule(void)
Mark Hammondedd07732003-07-15 23:03:55 +0000123{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000124 return PyImport_ImportModule("warnings");
Mark Hammondedd07732003-07-15 23:03:55 +0000125}
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000126
Guido van Rossum25ce5661997-08-02 03:10:38 +0000127static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000128
Thomas Wouters7e474022000-07-16 12:04:32 +0000129/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000130
131int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000132Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000133{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000134 return initialized;
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000135}
136
Guido van Rossum25ce5661997-08-02 03:10:38 +0000137/* Global initializations. Can be undone by Py_Finalize(). Don't
138 call this twice without an intervening Py_Finalize() call. When
139 initializations fail, a fatal error is issued and the function does
140 not return. On return, the first thread and interpreter state have
141 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000142
Guido van Rossum25ce5661997-08-02 03:10:38 +0000143 Locking: you must hold the interpreter lock while calling this.
144 (If the lock has not yet been initialized, that's equivalent to
145 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000146
Guido van Rossum25ce5661997-08-02 03:10:38 +0000147*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000148
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000149static int
150add_flag(int flag, const char *envs)
151{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000152 int env = atoi(envs);
153 if (flag < env)
154 flag = env;
155 if (flag < 1)
156 flag = 1;
157 return flag;
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000158}
159
Christian Heimes5833a2f2008-10-30 21:40:04 +0000160static char*
Victor Stinner94908bb2010-08-18 21:23:25 +0000161get_codec_name(const char *encoding)
Christian Heimes5833a2f2008-10-30 21:40:04 +0000162{
Victor Stinner94908bb2010-08-18 21:23:25 +0000163 char *name_utf8, *name_str;
Victor Stinner386fe712010-05-19 00:34:15 +0000164 PyObject *codec, *name = NULL;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200165 _Py_IDENTIFIER(name);
Christian Heimes5833a2f2008-10-30 21:40:04 +0000166
Victor Stinner94908bb2010-08-18 21:23:25 +0000167 codec = _PyCodec_Lookup(encoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000168 if (!codec)
169 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000170
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200171 name = _PyObject_GetAttrId(codec, &PyId_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000172 Py_CLEAR(codec);
173 if (!name)
174 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000175
Victor Stinner94908bb2010-08-18 21:23:25 +0000176 name_utf8 = _PyUnicode_AsString(name);
Victor Stinner4ca28092011-03-20 23:09:03 +0100177 if (name_utf8 == NULL)
Victor Stinner386fe712010-05-19 00:34:15 +0000178 goto error;
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200179 name_str = _PyMem_RawStrdup(name_utf8);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000180 Py_DECREF(name);
Victor Stinner94908bb2010-08-18 21:23:25 +0000181 if (name_str == NULL) {
182 PyErr_NoMemory();
183 return NULL;
184 }
185 return name_str;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000186
187error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 Py_XDECREF(codec);
Victor Stinner386fe712010-05-19 00:34:15 +0000189 Py_XDECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000190 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000191}
Victor Stinner94908bb2010-08-18 21:23:25 +0000192
Victor Stinner94908bb2010-08-18 21:23:25 +0000193static char*
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200194get_locale_encoding(void)
Victor Stinner94908bb2010-08-18 21:23:25 +0000195{
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200196#ifdef MS_WINDOWS
197 char codepage[100];
198 PyOS_snprintf(codepage, sizeof(codepage), "cp%d", GetACP());
199 return get_codec_name(codepage);
200#elif defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94908bb2010-08-18 21:23:25 +0000201 char* codeset = nl_langinfo(CODESET);
202 if (!codeset || codeset[0] == '\0') {
203 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
204 return NULL;
205 }
206 return get_codec_name(codeset);
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200207#else
208 PyErr_SetNone(PyExc_NotImplementedError);
209 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000210#endif
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200211}
Christian Heimes5833a2f2008-10-30 21:40:04 +0000212
Brett Cannonfd074152012-04-14 14:10:13 -0400213static void
214import_init(PyInterpreterState *interp, PyObject *sysmod)
215{
216 PyObject *importlib;
217 PyObject *impmod;
218 PyObject *sys_modules;
219 PyObject *value;
220
221 /* Import _importlib through its frozen version, _frozen_importlib. */
Brett Cannonfd074152012-04-14 14:10:13 -0400222 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
223 Py_FatalError("Py_Initialize: can't import _frozen_importlib");
224 }
225 else if (Py_VerboseFlag) {
226 PySys_FormatStderr("import _frozen_importlib # frozen\n");
227 }
228 importlib = PyImport_AddModule("_frozen_importlib");
229 if (importlib == NULL) {
230 Py_FatalError("Py_Initialize: couldn't get _frozen_importlib from "
231 "sys.modules");
232 }
233 interp->importlib = importlib;
234 Py_INCREF(interp->importlib);
235
236 /* Install _importlib as __import__ */
237 impmod = PyInit_imp();
238 if (impmod == NULL) {
239 Py_FatalError("Py_Initialize: can't import imp");
240 }
241 else if (Py_VerboseFlag) {
242 PySys_FormatStderr("import imp # builtin\n");
243 }
244 sys_modules = PyImport_GetModuleDict();
245 if (Py_VerboseFlag) {
246 PySys_FormatStderr("import sys # builtin\n");
247 }
Brett Cannon6f44d662012-04-15 16:08:47 -0400248 if (PyDict_SetItemString(sys_modules, "_imp", impmod) < 0) {
249 Py_FatalError("Py_Initialize: can't save _imp to sys.modules");
Brett Cannonfd074152012-04-14 14:10:13 -0400250 }
251
Brett Cannone0d88a12012-04-25 20:54:04 -0400252 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
Brett Cannonfd074152012-04-14 14:10:13 -0400253 if (value == NULL) {
254 PyErr_Print();
255 Py_FatalError("Py_Initialize: importlib install failed");
256 }
257 Py_DECREF(value);
Brett Cannonfc9ca272012-04-15 01:35:05 -0400258 Py_DECREF(impmod);
Brett Cannonfd074152012-04-14 14:10:13 -0400259
260 _PyImportZip_Init();
261}
262
263
Guido van Rossuma027efa1997-05-05 20:56:21 +0000264void
Antoine Pitroue67f48c2012-06-19 22:29:35 +0200265_Py_InitializeEx_Private(int install_sigs, int install_importlib)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000266{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000267 PyInterpreterState *interp;
268 PyThreadState *tstate;
269 PyObject *bimod, *sysmod, *pstderr;
270 char *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000271 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000273 if (initialized)
274 return;
275 initialized = 1;
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200276 _Py_Finalizing = NULL;
Tim Petersd08e3822003-04-17 15:24:21 +0000277
Andrew M. Kuchlingb2ceb3a2010-02-22 23:26:10 +0000278#if defined(HAVE_LANGINFO_H) && defined(HAVE_SETLOCALE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000279 /* Set up the LC_CTYPE locale, so we can obtain
280 the locale's charset without having to switch
281 locales. */
282 setlocale(LC_CTYPE, "");
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +0000283#endif
284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000285 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
286 Py_DebugFlag = add_flag(Py_DebugFlag, p);
287 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
288 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
289 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
290 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
291 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
292 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100293 /* The variable is only tested for existence here; _PyRandom_Init will
294 check its value further. */
295 if ((p = Py_GETENV("PYTHONHASHSEED")) && *p != '\0')
296 Py_HashRandomizationFlag = add_flag(Py_HashRandomizationFlag, p);
297
298 _PyRandom_Init();
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000300 interp = PyInterpreterState_New();
301 if (interp == NULL)
302 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000304 tstate = PyThreadState_New(interp);
305 if (tstate == NULL)
306 Py_FatalError("Py_Initialize: can't make first thread");
307 (void) PyThreadState_Swap(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000308
Victor Stinner6961bd62010-08-17 22:26:51 +0000309#ifdef WITH_THREAD
Antoine Pitroub0b384b2010-09-20 20:13:48 +0000310 /* We can't call _PyEval_FiniThreads() in Py_Finalize because
311 destroying the GIL might fail when it is being referenced from
312 another running thread (see issue #9901).
313 Instead we destroy the previously created GIL here, which ensures
314 that we can call Py_Initialize / Py_Finalize multiple times. */
315 _PyEval_FiniThreads();
316
317 /* Auto-thread-state API */
Victor Stinner6961bd62010-08-17 22:26:51 +0000318 _PyGILState_Init(interp, tstate);
319#endif /* WITH_THREAD */
320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 if (!_PyFrame_Init())
324 Py_FatalError("Py_Initialize: can't init frames");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000326 if (!_PyLong_Init())
327 Py_FatalError("Py_Initialize: can't init longs");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000329 if (!PyByteArray_Init())
330 Py_FatalError("Py_Initialize: can't init bytearray");
Neal Norwitz6968b052007-02-27 19:02:19 +0000331
Victor Stinner1c8f0592013-07-22 22:24:54 +0200332 if (!_PyFloat_Init())
333 Py_FatalError("Py_Initialize: can't init float");
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000335 interp->modules = PyDict_New();
336 if (interp->modules == NULL)
337 Py_FatalError("Py_Initialize: can't make modules dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 /* Init Unicode implementation; relies on the codec registry */
Victor Stinner3a50e702011-10-18 21:21:00 +0200340 if (_PyUnicode_Init() < 0)
341 Py_FatalError("Py_Initialize: can't initialize unicode");
Victor Stinner26f91992013-07-17 01:22:45 +0200342 if (_PyStructSequence_Init() < 0)
343 Py_FatalError("Py_Initialize: can't initialize structseq");
Guido van Rossumc94044c2000-03-10 23:03:54 +0000344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000345 bimod = _PyBuiltin_Init();
346 if (bimod == NULL)
347 Py_FatalError("Py_Initialize: can't initialize builtins modules");
Victor Stinner49d3f252010-10-17 01:24:53 +0000348 _PyImport_FixupBuiltin(bimod, "builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 interp->builtins = PyModule_GetDict(bimod);
350 if (interp->builtins == NULL)
351 Py_FatalError("Py_Initialize: can't initialize builtins dict");
352 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000354 /* initialize builtin exceptions */
Brett Cannonfd074152012-04-14 14:10:13 -0400355 _PyExc_Init(bimod);
Christian Heimes9a68f8c2007-11-14 00:16:07 +0000356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000357 sysmod = _PySys_Init();
358 if (sysmod == NULL)
359 Py_FatalError("Py_Initialize: can't initialize sys");
360 interp->sysdict = PyModule_GetDict(sysmod);
361 if (interp->sysdict == NULL)
362 Py_FatalError("Py_Initialize: can't initialize sys dict");
363 Py_INCREF(interp->sysdict);
Victor Stinner49d3f252010-10-17 01:24:53 +0000364 _PyImport_FixupBuiltin(sysmod, "sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000365 PySys_SetPath(Py_GetPath());
366 PyDict_SetItemString(interp->sysdict, "modules",
367 interp->modules);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000369 /* Set up a preliminary stderr printer until we have enough
370 infrastructure for the io module in place. */
371 pstderr = PyFile_NewStdPrinter(fileno(stderr));
372 if (pstderr == NULL)
373 Py_FatalError("Py_Initialize: can't set preliminary stderr");
374 PySys_SetObject("stderr", pstderr);
375 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000376 Py_DECREF(pstderr);
Guido van Rossum826d8972007-10-30 18:34:07 +0000377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000378 _PyImport_Init();
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 _PyImportHooks_Init();
Just van Rossum52e14d62002-12-30 22:08:05 +0000381
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000382 /* Initialize _warnings. */
383 _PyWarnings_Init();
384
Antoine Pitroue67f48c2012-06-19 22:29:35 +0200385 if (!install_importlib)
386 return;
387
Brett Cannonfd074152012-04-14 14:10:13 -0400388 import_init(interp, sysmod);
389
Victor Stinnerd5698cb2012-07-31 02:55:49 +0200390 /* initialize the faulthandler module */
391 if (_PyFaulthandler_Init())
392 Py_FatalError("Py_Initialize: can't initialize faulthandler");
393
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +0000394 _PyTime_Init();
395
Victor Stinner793b5312011-04-27 00:24:21 +0200396 if (initfsencoding(interp) < 0)
397 Py_FatalError("Py_Initialize: unable to load the file system codec");
Martin v. Löwis011e8422009-05-05 04:43:17 +0000398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399 if (install_sigs)
400 initsigs(); /* Signal handling stuff, including initintr() */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000401
Nick Coghlan85e729e2012-07-15 18:09:52 +1000402 initmain(interp); /* Module __main__ */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 if (initstdio() < 0)
404 Py_FatalError(
405 "Py_Initialize: can't initialize sys standard streams");
406
Antoine Pitroucf9f9802010-11-10 13:55:25 +0000407 /* Initialize warnings. */
408 if (PySys_HasWarnOptions()) {
409 PyObject *warnings_module = PyImport_ImportModule("warnings");
410 if (warnings_module == NULL) {
411 fprintf(stderr, "'import warnings' failed; traceback:\n");
412 PyErr_Print();
413 }
414 Py_XDECREF(warnings_module);
415 }
416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 if (!Py_NoSiteFlag)
418 initsite(); /* Module site */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000419}
420
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000421void
Antoine Pitroue67f48c2012-06-19 22:29:35 +0200422Py_InitializeEx(int install_sigs)
423{
424 _Py_InitializeEx_Private(install_sigs, 1);
425}
426
427void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000428Py_Initialize(void)
429{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000430 Py_InitializeEx(1);
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000431}
432
433
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000434#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000435extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000436#endif
437
Guido van Rossume8432ac2007-07-09 15:04:50 +0000438/* Flush stdout and stderr */
439
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100440static int
441file_is_closed(PyObject *fobj)
442{
443 int r;
444 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
445 if (tmp == NULL) {
446 PyErr_Clear();
447 return 0;
448 }
449 r = PyObject_IsTrue(tmp);
450 Py_DECREF(tmp);
451 if (r < 0)
452 PyErr_Clear();
453 return r > 0;
454}
455
Neal Norwitz2bad9702007-08-27 06:19:22 +0000456static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000457flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000458{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 PyObject *fout = PySys_GetObject("stdout");
460 PyObject *ferr = PySys_GetObject("stderr");
461 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200462 _Py_IDENTIFIER(flush);
Guido van Rossume8432ac2007-07-09 15:04:50 +0000463
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100464 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200465 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 if (tmp == NULL)
Antoine Pitroubddc9fe2010-08-08 20:46:42 +0000467 PyErr_WriteUnraisable(fout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 else
469 Py_DECREF(tmp);
470 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000471
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100472 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200473 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 if (tmp == NULL)
475 PyErr_Clear();
476 else
477 Py_DECREF(tmp);
478 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000479}
480
Guido van Rossum25ce5661997-08-02 03:10:38 +0000481/* Undo the effect of Py_Initialize().
482
483 Beware: if multiple interpreter and/or thread states exist, these
484 are not wiped out; only the current thread and interpreter state
485 are deleted. But since everything else is deleted, those other
486 interpreter and thread states should no longer be used.
487
488 (XXX We should do better, e.g. wipe out all interpreters and
489 threads.)
490
491 Locking: as above.
492
493*/
494
495void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000496Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000497{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 PyInterpreterState *interp;
499 PyThreadState *tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 if (!initialized)
502 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 wait_for_thread_shutdown();
Antoine Pitrou011bd622009-10-20 21:52:47 +0000505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 /* The interpreter is still entirely intact at this point, and the
507 * exit funcs may be relying on that. In particular, if some thread
508 * or exit func is still waiting to do an import, the import machinery
509 * expects Py_IsInitialized() to return true. So don't say the
510 * interpreter is uninitialized until after the exit funcs have run.
511 * Note that Threading.py uses an exit func to do a join on all the
512 * threads created thru it, so this also protects pending imports in
513 * the threads created via Threading.
514 */
515 call_py_exitfuncs();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 /* Get current thread state and interpreter pointer */
518 tstate = PyThreadState_GET();
519 interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000520
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200521 /* Remaining threads (e.g. daemon threads) will automatically exit
522 after taking the GIL (in PyEval_RestoreThread()). */
523 _Py_Finalizing = tstate;
524 initialized = 0;
525
526 /* Flush stdout+stderr */
527 flush_std_files();
528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000529 /* Disable signal handling */
530 PyOS_FiniInterrupts();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 /* Collect garbage. This may call finalizers; it's nice to call these
533 * before all modules are destroyed.
534 * XXX If a __del__ or weakref callback is triggered here, and tries to
535 * XXX import a module, bad things can happen, because Python no
536 * XXX longer believes it's initialized.
537 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
538 * XXX is easy to provoke that way. I've also seen, e.g.,
539 * XXX Exception exceptions.ImportError: 'No module named sha'
540 * XXX in <function callback at 0x008F5718> ignored
541 * XXX but I'm unclear on exactly how that one happens. In any case,
542 * XXX I haven't seen a real-life report of either of these.
543 */
544 PyGC_Collect();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000545#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 /* With COUNT_ALLOCS, it helps to run GC multiple times:
547 each collection might release some types from the type
548 list, so they become garbage. */
549 while (PyGC_Collect() > 0)
550 /* nothing */;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000551#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 /* Destroy all modules */
553 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 /* Flush stdout+stderr (again, in case more was printed) */
556 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000558 /* Collect final garbage. This disposes of cycles created by
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100559 * class definitions, for example.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 * XXX This is disabled because it caused too many problems. If
561 * XXX a __del__ or weakref callback triggers here, Python code has
562 * XXX a hard time running, because even the sys module has been
563 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
564 * XXX One symptom is a sequence of information-free messages
565 * XXX coming from threads (if a __del__ or callback is invoked,
566 * XXX other threads can execute too, and any exception they encounter
567 * XXX triggers a comedy of errors as subsystem after subsystem
568 * XXX fails to find what it *expects* to find in sys to help report
569 * XXX the exception and consequent unexpected failures). I've also
570 * XXX seen segfaults then, after adding print statements to the
571 * XXX Python code getting called.
572 */
Tim Peters1d7323e2003-12-01 21:35:27 +0000573#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000575#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
578 _PyImport_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000579
Antoine Pitroufd417cc2013-05-05 08:12:42 +0200580 /* Cleanup typeobject.c's internal caches. */
581 _PyType_Fini();
582
Victor Stinner024e37a2011-03-31 01:31:06 +0200583 /* unload faulthandler module */
584 _PyFaulthandler_Fini();
585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 /* Debugging stuff */
Guido van Rossum1707aad1997-12-08 23:43:45 +0000587#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000588 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000589#endif
590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000591 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000592
Tim Peters9cf25ce2003-04-17 15:21:01 +0000593#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 /* Display all objects still alive -- this can invoke arbitrary
595 * __repr__ overrides, so requires a mostly-intact interpreter.
596 * Alas, a lot of stuff may still be alive now that will be cleaned
597 * up later.
598 */
599 if (Py_GETENV("PYTHONDUMPREFS"))
600 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000601#endif /* Py_TRACE_REFS */
602
Antoine Pitroufd417cc2013-05-05 08:12:42 +0200603 /* Clear interpreter state and all thread states. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000604 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 /* Now we decref the exception classes. After this point nothing
607 can raise an exception. That's okay, because each Fini() method
608 below has been checked to make sure no exceptions are ever
609 raised.
610 */
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 _PyExc_Fini();
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 /* Sundry finalizers */
615 PyMethod_Fini();
616 PyFrame_Fini();
617 PyCFunction_Fini();
618 PyTuple_Fini();
619 PyList_Fini();
620 PySet_Fini();
621 PyBytes_Fini();
622 PyByteArray_Fini();
623 PyLong_Fini();
624 PyFloat_Fini();
625 PyDict_Fini();
Antoine Pitrouf34a0cd2011-11-18 20:14:34 +0100626 PySlice_Fini();
Antoine Pitrou5f454a02013-05-06 21:15:57 +0200627 _PyGC_Fini();
Antoine Pitrou4879a962013-08-31 00:26:02 +0200628 _PyRandom_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 /* Cleanup Unicode implementation */
631 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000633 /* reset file system default encoding */
Victor Stinnerb744ba12010-05-15 12:27:16 +0000634 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200635 PyMem_RawFree((char*)Py_FileSystemDefaultEncoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 Py_FileSystemDefaultEncoding = NULL;
637 }
Christian Heimesc8967002007-11-30 10:18:26 +0000638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 /* XXX Still allocated:
640 - various static ad-hoc pointers to interned strings
641 - int and float free list blocks
642 - whatever various modules and libraries allocate
643 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000646
Victor Stinner51fa4582013-07-07 15:50:49 +0200647 /* Cleanup auto-thread-state */
648#ifdef WITH_THREAD
649 _PyGILState_Fini();
650#endif /* WITH_THREAD */
651
652 /* Delete current thread. After this, many C API calls become crashy. */
653 PyThreadState_Swap(NULL);
654 PyInterpreterState_Delete(interp);
655
Tim Peters269b2a62003-04-17 19:52:29 +0000656#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 /* Display addresses (& refcnts) of all objects still alive.
658 * An address can be used to find the repr of the object, printed
659 * above by _Py_PrintReferences.
660 */
661 if (Py_GETENV("PYTHONDUMPREFS"))
662 _Py_PrintReferenceAddresses(stderr);
Tim Peters269b2a62003-04-17 19:52:29 +0000663#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000664#ifdef PYMALLOC_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 if (Py_GETENV("PYTHONMALLOCSTATS"))
David Malcolm49526f42012-06-22 14:55:41 -0400666 _PyObject_DebugMallocStats(stderr);
Tim Peters0e871182002-04-13 08:29:14 +0000667#endif
668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000669 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000670}
671
672/* Create and initialize a new interpreter and thread, and return the
673 new thread. This requires that Py_Initialize() has been called
674 first.
675
676 Unsuccessful initialization yields a NULL pointer. Note that *no*
677 exception information is available even in this case -- the
678 exception information is held in the thread, and there is no
679 thread.
680
681 Locking: as above.
682
683*/
684
685PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000686Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000687{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000688 PyInterpreterState *interp;
689 PyThreadState *tstate, *save_tstate;
690 PyObject *bimod, *sysmod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 if (!initialized)
693 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000694
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000695 interp = PyInterpreterState_New();
696 if (interp == NULL)
697 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 tstate = PyThreadState_New(interp);
700 if (tstate == NULL) {
701 PyInterpreterState_Delete(interp);
702 return NULL;
703 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 save_tstate = PyThreadState_Swap(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 /* XXX The following is lax in error checking */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 interp->modules = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000710
Victor Stinner49d3f252010-10-17 01:24:53 +0000711 bimod = _PyImport_FindBuiltin("builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 if (bimod != NULL) {
713 interp->builtins = PyModule_GetDict(bimod);
714 if (interp->builtins == NULL)
715 goto handle_error;
716 Py_INCREF(interp->builtins);
717 }
Christian Heimes6a27efa2008-10-30 21:48:26 +0000718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000719 /* initialize builtin exceptions */
Brett Cannonfd074152012-04-14 14:10:13 -0400720 _PyExc_Init(bimod);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000721
Victor Stinner49d3f252010-10-17 01:24:53 +0000722 sysmod = _PyImport_FindBuiltin("sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000723 if (bimod != NULL && sysmod != NULL) {
724 PyObject *pstderr;
Brett Cannonfd074152012-04-14 14:10:13 -0400725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 interp->sysdict = PyModule_GetDict(sysmod);
727 if (interp->sysdict == NULL)
728 goto handle_error;
729 Py_INCREF(interp->sysdict);
730 PySys_SetPath(Py_GetPath());
731 PyDict_SetItemString(interp->sysdict, "modules",
732 interp->modules);
733 /* Set up a preliminary stderr printer until we have enough
734 infrastructure for the io module in place. */
735 pstderr = PyFile_NewStdPrinter(fileno(stderr));
736 if (pstderr == NULL)
737 Py_FatalError("Py_Initialize: can't set preliminary stderr");
738 PySys_SetObject("stderr", pstderr);
739 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000740 Py_DECREF(pstderr);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000742 _PyImportHooks_Init();
Victor Stinner793b5312011-04-27 00:24:21 +0200743
Brett Cannonfd074152012-04-14 14:10:13 -0400744 import_init(interp, sysmod);
745
Victor Stinner793b5312011-04-27 00:24:21 +0200746 if (initfsencoding(interp) < 0)
747 goto handle_error;
748
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000749 if (initstdio() < 0)
750 Py_FatalError(
751 "Py_Initialize: can't initialize sys standard streams");
Nick Coghlan85e729e2012-07-15 18:09:52 +1000752 initmain(interp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000753 if (!Py_NoSiteFlag)
754 initsite();
755 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000757 if (!PyErr_Occurred())
758 return tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000759
Thomas Wouters89f507f2006-12-13 04:49:30 +0000760handle_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 /* Oops, it didn't work. Undo it all. */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000762
Victor Stinnerc40a3502011-04-27 00:20:27 +0200763 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 PyThreadState_Clear(tstate);
765 PyThreadState_Swap(save_tstate);
766 PyThreadState_Delete(tstate);
767 PyInterpreterState_Delete(interp);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000770}
771
772/* Delete an interpreter and its last thread. This requires that the
773 given thread state is current, that the thread has no remaining
774 frames, and that it is its interpreter's only remaining thread.
775 It is a fatal error to violate these constraints.
776
777 (Py_Finalize() doesn't have these constraints -- it zaps
778 everything, regardless.)
779
780 Locking: as above.
781
782*/
783
784void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000785Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000786{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 PyInterpreterState *interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 if (tstate != PyThreadState_GET())
790 Py_FatalError("Py_EndInterpreter: thread is not current");
791 if (tstate->frame != NULL)
792 Py_FatalError("Py_EndInterpreter: thread still has a frame");
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200793
794 wait_for_thread_shutdown();
795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 if (tstate != interp->tstate_head || tstate->next != NULL)
797 Py_FatalError("Py_EndInterpreter: not the last thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 PyImport_Cleanup();
800 PyInterpreterState_Clear(interp);
801 PyThreadState_Swap(NULL);
802 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000803}
804
Antoine Pitrou01cca5e2012-07-05 20:56:30 +0200805#ifdef MS_WINDOWS
Martin v. Löwis790465f2008-04-05 20:41:37 +0000806static wchar_t *progname = L"python";
Antoine Pitrou01cca5e2012-07-05 20:56:30 +0200807#else
808static wchar_t *progname = L"python3";
809#endif
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000810
811void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000812Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000813{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 if (pn && *pn)
815 progname = pn;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000816}
817
Martin v. Löwis790465f2008-04-05 20:41:37 +0000818wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000819Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000820{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000822}
823
Martin v. Löwis790465f2008-04-05 20:41:37 +0000824static wchar_t *default_home = NULL;
Victor Stinner55a12202013-08-28 01:47:46 +0200825static wchar_t env_home[MAXPATHLEN+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000826
827void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000828Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000829{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 default_home = home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000831}
832
Martin v. Löwis790465f2008-04-05 20:41:37 +0000833wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000834Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000835{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 wchar_t *home = default_home;
837 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
838 char* chome = Py_GETENV("PYTHONHOME");
839 if (chome) {
840 size_t r = mbstowcs(env_home, chome, PATH_MAX+1);
841 if (r != (size_t)-1 && r <= PATH_MAX)
842 home = env_home;
843 }
Martin v. Löwis790465f2008-04-05 20:41:37 +0000844
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 }
846 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000847}
848
Guido van Rossum6135a871995-01-09 17:53:26 +0000849/* Create __main__ module */
850
851static void
Nick Coghlan85e729e2012-07-15 18:09:52 +1000852initmain(PyInterpreterState *interp)
Guido van Rossum6135a871995-01-09 17:53:26 +0000853{
Brett Cannon13853a62013-05-04 17:37:09 -0400854 PyObject *m, *d, *loader;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 m = PyImport_AddModule("__main__");
856 if (m == NULL)
857 Py_FatalError("can't create __main__ module");
858 d = PyModule_GetDict(m);
859 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
860 PyObject *bimod = PyImport_ImportModule("builtins");
Nick Coghlan85e729e2012-07-15 18:09:52 +1000861 if (bimod == NULL) {
862 Py_FatalError("Failed to retrieve builtins module");
863 }
864 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
865 Py_FatalError("Failed to initialize __main__.__builtins__");
866 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 Py_DECREF(bimod);
868 }
Nick Coghlan85e729e2012-07-15 18:09:52 +1000869 /* Main is a little special - imp.is_builtin("__main__") will return
870 * False, but BuiltinImporter is still the most appropriate initial
871 * setting for its __loader__ attribute. A more suitable value will
872 * be set if __main__ gets further initialized later in the startup
873 * process.
874 */
Brett Cannon13853a62013-05-04 17:37:09 -0400875 loader = PyDict_GetItemString(d, "__loader__");
Brett Cannon4c14b5d2013-05-04 13:56:58 -0400876 if (loader == NULL || loader == Py_None) {
Nick Coghlan85e729e2012-07-15 18:09:52 +1000877 PyObject *loader = PyObject_GetAttrString(interp->importlib,
878 "BuiltinImporter");
879 if (loader == NULL) {
880 Py_FatalError("Failed to retrieve BuiltinImporter");
881 }
882 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
883 Py_FatalError("Failed to initialize __main__.__loader__");
884 }
885 Py_DECREF(loader);
886 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000887}
888
Victor Stinner793b5312011-04-27 00:24:21 +0200889static int
890initfsencoding(PyInterpreterState *interp)
Victor Stinnerb744ba12010-05-15 12:27:16 +0000891{
892 PyObject *codec;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000893
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200894 if (Py_FileSystemDefaultEncoding == NULL)
895 {
896 Py_FileSystemDefaultEncoding = get_locale_encoding();
897 if (Py_FileSystemDefaultEncoding == NULL)
Victor Stinnere4743092010-10-19 00:05:51 +0000898 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
Victor Stinnerb744ba12010-05-15 12:27:16 +0000899
Victor Stinnere4743092010-10-19 00:05:51 +0000900 Py_HasFileSystemDefaultEncoding = 0;
Victor Stinner793b5312011-04-27 00:24:21 +0200901 interp->fscodec_initialized = 1;
902 return 0;
Victor Stinner7f84ab52010-06-11 00:36:33 +0000903 }
Victor Stinnerb744ba12010-05-15 12:27:16 +0000904
905 /* the encoding is mbcs, utf-8 or ascii */
906 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
907 if (!codec) {
908 /* Such error can only occurs in critical situations: no more
909 * memory, import a module of the standard library failed,
910 * etc. */
Victor Stinner793b5312011-04-27 00:24:21 +0200911 return -1;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000912 }
Victor Stinner793b5312011-04-27 00:24:21 +0200913 Py_DECREF(codec);
914 interp->fscodec_initialized = 1;
915 return 0;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000916}
917
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000918/* Import the site module (not into __main__ though) */
919
920static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000921initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000922{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 PyObject *m;
924 m = PyImport_ImportModule("site");
925 if (m == NULL) {
Victor Stinner62ce62a2013-07-22 22:53:28 +0200926 fprintf(stderr, "Failed to import the site module\n");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 PyErr_Print();
928 Py_Finalize();
929 exit(1);
930 }
931 else {
932 Py_DECREF(m);
933 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000934}
935
Antoine Pitrou05608432009-01-09 18:53:14 +0000936static PyObject*
937create_stdio(PyObject* io,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 int fd, int write_mode, char* name,
939 char* encoding, char* errors)
Antoine Pitrou05608432009-01-09 18:53:14 +0000940{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
942 const char* mode;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +0000943 const char* newline;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 PyObject *line_buffering;
945 int buffering, isatty;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200946 _Py_IDENTIFIER(open);
947 _Py_IDENTIFIER(isatty);
948 _Py_IDENTIFIER(TextIOWrapper);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200949 _Py_IDENTIFIER(name);
950 _Py_IDENTIFIER(mode);
Antoine Pitrou05608432009-01-09 18:53:14 +0000951
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 /* stdin is always opened in buffered mode, first because it shouldn't
953 make a difference in common use cases, second because TextIOWrapper
954 depends on the presence of a read1() method which only exists on
955 buffered streams.
956 */
957 if (Py_UnbufferedStdioFlag && write_mode)
958 buffering = 0;
959 else
960 buffering = -1;
961 if (write_mode)
962 mode = "wb";
963 else
964 mode = "rb";
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200965 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
966 fd, mode, buffering,
967 Py_None, Py_None, Py_None, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 if (buf == NULL)
969 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 if (buffering) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200972 _Py_IDENTIFIER(raw);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200973 raw = _PyObject_GetAttrId(buf, &PyId_raw);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 if (raw == NULL)
975 goto error;
976 }
977 else {
978 raw = buf;
979 Py_INCREF(raw);
980 }
Antoine Pitrou05608432009-01-09 18:53:14 +0000981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 text = PyUnicode_FromString(name);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200983 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 goto error;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200985 res = _PyObject_CallMethodId(raw, &PyId_isatty, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 if (res == NULL)
987 goto error;
988 isatty = PyObject_IsTrue(res);
989 Py_DECREF(res);
990 if (isatty == -1)
991 goto error;
992 if (isatty || Py_UnbufferedStdioFlag)
993 line_buffering = Py_True;
994 else
995 line_buffering = Py_False;
Antoine Pitrou91696412009-01-09 22:12:30 +0000996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 Py_CLEAR(raw);
998 Py_CLEAR(text);
Antoine Pitrou91696412009-01-09 22:12:30 +0000999
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001000#ifdef MS_WINDOWS
Victor Stinner7b3f0fa2012-08-04 01:28:00 +02001001 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1002 newlines to "\n".
1003 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1004 newline = NULL;
1005#else
1006 /* sys.stdin: split lines at "\n".
1007 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1008 newline = "\n";
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001009#endif
1010
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001011 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssO",
1012 buf, encoding, errors,
1013 newline, line_buffering);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 Py_CLEAR(buf);
1015 if (stream == NULL)
1016 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +00001017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 if (write_mode)
1019 mode = "w";
1020 else
1021 mode = "r";
1022 text = PyUnicode_FromString(mode);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001023 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 goto error;
1025 Py_CLEAR(text);
1026 return stream;
Antoine Pitrou05608432009-01-09 18:53:14 +00001027
1028error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 Py_XDECREF(buf);
1030 Py_XDECREF(stream);
1031 Py_XDECREF(text);
1032 Py_XDECREF(raw);
1033 return NULL;
Antoine Pitrou05608432009-01-09 18:53:14 +00001034}
1035
Antoine Pitrou11942a52011-11-28 19:08:36 +01001036static int
1037is_valid_fd(int fd)
1038{
1039 int dummy_fd;
1040 if (fd < 0 || !_PyVerify_fd(fd))
1041 return 0;
1042 dummy_fd = dup(fd);
1043 if (dummy_fd < 0)
1044 return 0;
1045 close(dummy_fd);
1046 return 1;
1047}
1048
Georg Brandl1a3284e2007-12-02 09:40:06 +00001049/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001050static int
1051initstdio(void)
1052{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 PyObject *iomod = NULL, *wrapper;
1054 PyObject *bimod = NULL;
1055 PyObject *m;
1056 PyObject *std = NULL;
1057 int status = 0, fd;
1058 PyObject * encoding_attr;
1059 char *encoding = NULL, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001061 /* Hack to avoid a nasty recursion issue when Python is invoked
1062 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1063 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1064 goto error;
1065 }
1066 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001068 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1069 goto error;
1070 }
1071 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 if (!(bimod = PyImport_ImportModule("builtins"))) {
1074 goto error;
1075 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001076
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 if (!(iomod = PyImport_ImportModule("io"))) {
1078 goto error;
1079 }
1080 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1081 goto error;
1082 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 /* Set builtins.open */
1085 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
Antoine Pitrou5a96b522010-11-20 19:50:57 +00001086 Py_DECREF(wrapper);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 goto error;
1088 }
Antoine Pitrou5a96b522010-11-20 19:50:57 +00001089 Py_DECREF(wrapper);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 encoding = Py_GETENV("PYTHONIOENCODING");
1092 errors = NULL;
1093 if (encoding) {
Victor Stinner49fc8ec2013-07-07 23:30:24 +02001094 encoding = _PyMem_Strdup(encoding);
1095 if (encoding == NULL) {
1096 PyErr_NoMemory();
1097 goto error;
1098 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099 errors = strchr(encoding, ':');
1100 if (errors) {
1101 *errors = '\0';
1102 errors++;
1103 }
1104 }
Martin v. Löwis0f599892008-06-02 11:13:03 +00001105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 /* Set sys.stdin */
1107 fd = fileno(stdin);
1108 /* Under some conditions stdin, stdout and stderr may not be connected
1109 * and fileno() may point to an invalid file descriptor. For example
1110 * GUI apps don't have valid standard streams by default.
1111 */
Antoine Pitrou11942a52011-11-28 19:08:36 +01001112 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 std = Py_None;
1114 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 }
1116 else {
1117 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1118 if (std == NULL)
1119 goto error;
1120 } /* if (fd < 0) */
1121 PySys_SetObject("__stdin__", std);
1122 PySys_SetObject("stdin", std);
1123 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 /* Set sys.stdout */
1126 fd = fileno(stdout);
Antoine Pitrou11942a52011-11-28 19:08:36 +01001127 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001128 std = Py_None;
1129 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 }
1131 else {
1132 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1133 if (std == NULL)
1134 goto error;
1135 } /* if (fd < 0) */
1136 PySys_SetObject("__stdout__", std);
1137 PySys_SetObject("stdout", std);
1138 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001139
Guido van Rossum98297ee2007-11-06 21:34:58 +00001140#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001141 /* Set sys.stderr, replaces the preliminary stderr */
1142 fd = fileno(stderr);
Antoine Pitrou11942a52011-11-28 19:08:36 +01001143 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001144 std = Py_None;
1145 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 }
1147 else {
1148 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1149 if (std == NULL)
1150 goto error;
1151 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +00001152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 /* Same as hack above, pre-import stderr's codec to avoid recursion
1154 when import.c tries to write to stderr in verbose mode. */
1155 encoding_attr = PyObject_GetAttrString(std, "encoding");
1156 if (encoding_attr != NULL) {
Victor Stinner49fc8ec2013-07-07 23:30:24 +02001157 const char * std_encoding;
1158 std_encoding = _PyUnicode_AsString(encoding_attr);
1159 if (std_encoding != NULL) {
1160 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
Antoine Pitrou2fabfac2012-01-18 15:14:46 +01001161 Py_XDECREF(codec_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 }
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +00001163 Py_DECREF(encoding_attr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 }
1165 PyErr_Clear(); /* Not a fatal error if codec isn't available */
Trent Nelson39e307e2008-03-19 06:45:48 +00001166
Victor Stinnerba308832013-07-22 23:55:19 +02001167 if (PySys_SetObject("__stderr__", std) < 0) {
1168 Py_DECREF(std);
1169 goto error;
1170 }
1171 if (PySys_SetObject("stderr", std) < 0) {
1172 Py_DECREF(std);
1173 goto error;
1174 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001176#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001179 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001180 status = -1;
1181 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001182
Victor Stinner49fc8ec2013-07-07 23:30:24 +02001183 PyMem_Free(encoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001184 Py_XDECREF(bimod);
1185 Py_XDECREF(iomod);
1186 return status;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001187}
1188
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001189/* Parse input from a file and execute it */
1190
1191int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001192PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001193 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001194{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 if (filename == NULL)
1196 filename = "???";
1197 if (Py_FdIsInteractive(fp, filename)) {
1198 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
1199 if (closeit)
1200 fclose(fp);
1201 return err;
1202 }
1203 else
1204 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001205}
1206
1207int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001208PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001209{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 PyObject *v;
1211 int ret;
1212 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214 if (flags == NULL) {
1215 flags = &local_flags;
1216 local_flags.cf_flags = 0;
1217 }
1218 v = PySys_GetObject("ps1");
1219 if (v == NULL) {
1220 PySys_SetObject("ps1", v = PyUnicode_FromString(">>> "));
1221 Py_XDECREF(v);
1222 }
1223 v = PySys_GetObject("ps2");
1224 if (v == NULL) {
1225 PySys_SetObject("ps2", v = PyUnicode_FromString("... "));
1226 Py_XDECREF(v);
1227 }
1228 for (;;) {
1229 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
1230 PRINT_TOTAL_REFS();
1231 if (ret == E_EOF)
1232 return 0;
1233 /*
1234 if (ret == E_NOMEM)
1235 return -1;
1236 */
1237 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001238}
1239
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001240/* compute parser flags based on compiler flags */
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001241static int PARSER_FLAGS(PyCompilerFlags *flags)
1242{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001243 int parser_flags = 0;
1244 if (!flags)
1245 return 0;
1246 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
1247 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1248 if (flags->cf_flags & PyCF_IGNORE_COOKIE)
1249 parser_flags |= PyPARSE_IGNORE_COOKIE;
1250 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
1251 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1252 return parser_flags;
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001253}
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001254
Thomas Wouters89f507f2006-12-13 04:49:30 +00001255#if 0
1256/* Keep an example of flags with future keyword support. */
1257#define PARSER_FLAGS(flags) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1259 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1260 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1261 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001262#endif
1263
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001264int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001265PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001266{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001267 PyObject *m, *d, *v, *w, *oenc = NULL;
1268 mod_ty mod;
1269 PyArena *arena;
1270 char *ps1 = "", *ps2 = "", *enc = NULL;
1271 int errcode = 0;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001272 _Py_IDENTIFIER(encoding);
Tim Petersfe2127d2001-07-16 05:37:24 +00001273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001274 if (fp == stdin) {
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -04001275 /* Fetch encoding from sys.stdin if possible. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001276 v = PySys_GetObject("stdin");
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -04001277 if (v && v != Py_None) {
1278 oenc = _PyObject_GetAttrId(v, &PyId_encoding);
1279 if (oenc)
1280 enc = _PyUnicode_AsString(oenc);
1281 if (!enc)
1282 PyErr_Clear();
1283 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 }
1285 v = PySys_GetObject("ps1");
1286 if (v != NULL) {
1287 v = PyObject_Str(v);
1288 if (v == NULL)
1289 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001290 else if (PyUnicode_Check(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001291 ps1 = _PyUnicode_AsString(v);
Victor Stinner386fe712010-05-19 00:34:15 +00001292 if (ps1 == NULL) {
1293 PyErr_Clear();
1294 ps1 = "";
1295 }
1296 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001297 }
1298 w = PySys_GetObject("ps2");
1299 if (w != NULL) {
1300 w = PyObject_Str(w);
1301 if (w == NULL)
1302 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001303 else if (PyUnicode_Check(w)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001304 ps2 = _PyUnicode_AsString(w);
Victor Stinner386fe712010-05-19 00:34:15 +00001305 if (ps2 == NULL) {
1306 PyErr_Clear();
1307 ps2 = "";
1308 }
1309 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 }
1311 arena = PyArena_New();
1312 if (arena == NULL) {
1313 Py_XDECREF(v);
1314 Py_XDECREF(w);
1315 Py_XDECREF(oenc);
1316 return -1;
1317 }
1318 mod = PyParser_ASTFromFile(fp, filename, enc,
1319 Py_single_input, ps1, ps2,
1320 flags, &errcode, arena);
1321 Py_XDECREF(v);
1322 Py_XDECREF(w);
1323 Py_XDECREF(oenc);
1324 if (mod == NULL) {
1325 PyArena_Free(arena);
1326 if (errcode == E_EOF) {
1327 PyErr_Clear();
1328 return E_EOF;
1329 }
1330 PyErr_Print();
1331 return -1;
1332 }
1333 m = PyImport_AddModule("__main__");
1334 if (m == NULL) {
1335 PyArena_Free(arena);
1336 return -1;
1337 }
1338 d = PyModule_GetDict(m);
1339 v = run_mod(mod, filename, d, d, flags, arena);
1340 PyArena_Free(arena);
1341 flush_io();
1342 if (v == NULL) {
1343 PyErr_Print();
1344 return -1;
1345 }
1346 Py_DECREF(v);
1347 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001348}
1349
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001350/* Check whether a file maybe a pyc file: Look at the extension,
1351 the file type, and, if we may close it, at the first few bytes. */
1352
1353static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001354maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001355{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001356 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1357 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 /* Only look into the file if we are allowed to close it, since
1360 it then should also be seekable. */
1361 if (closeit) {
1362 /* Read only two bytes of the magic. If the file was opened in
1363 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1364 be read as they are on disk. */
1365 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1366 unsigned char buf[2];
1367 /* Mess: In case of -x, the stream is NOT at its start now,
1368 and ungetc() was used to push back the first newline,
1369 which makes the current stream position formally undefined,
1370 and a x-platform nightmare.
1371 Unfortunately, we have no direct way to know whether -x
1372 was specified. So we use a terrible hack: if the current
1373 stream position is not 0, we assume -x was specified, and
1374 give up. Bug 132850 on SourceForge spells out the
1375 hopelessness of trying anything else (fseek and ftell
1376 don't work predictably x-platform for text-mode files).
1377 */
1378 int ispyc = 0;
1379 if (ftell(fp) == 0) {
1380 if (fread(buf, 1, 2, fp) == 2 &&
1381 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
1382 ispyc = 1;
1383 rewind(fp);
1384 }
1385 return ispyc;
1386 }
1387 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001388}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001389
Antoine Pitrou32d483c2013-07-30 21:01:23 +02001390static int
1391set_main_loader(PyObject *d, const char *filename, const char *loader_name)
Nick Coghlan85e729e2012-07-15 18:09:52 +10001392{
1393 PyInterpreterState *interp;
1394 PyThreadState *tstate;
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001395 PyObject *filename_obj, *loader_type, *loader;
Nick Coghlanb7a58942012-07-15 23:21:08 +10001396 int result = 0;
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001397
1398 filename_obj = PyUnicode_DecodeFSDefault(filename);
1399 if (filename_obj == NULL)
1400 return -1;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001401 /* Get current thread state and interpreter pointer */
1402 tstate = PyThreadState_GET();
1403 interp = tstate->interp;
Nick Coghlan3f94cbf2012-07-15 19:10:39 +10001404 loader_type = PyObject_GetAttrString(interp->importlib, loader_name);
1405 if (loader_type == NULL) {
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001406 Py_DECREF(filename_obj);
Nick Coghlan3f94cbf2012-07-15 19:10:39 +10001407 return -1;
1408 }
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001409 loader = PyObject_CallFunction(loader_type, "sN", "__main__", filename_obj);
Nick Coghlanb7a58942012-07-15 23:21:08 +10001410 Py_DECREF(loader_type);
1411 if (loader == NULL) {
Nick Coghlan85e729e2012-07-15 18:09:52 +10001412 return -1;
1413 }
Nick Coghlanb7a58942012-07-15 23:21:08 +10001414 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
1415 result = -1;
1416 }
Nick Coghlan85e729e2012-07-15 18:09:52 +10001417 Py_DECREF(loader);
Nick Coghlanb7a58942012-07-15 23:21:08 +10001418 return result;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001419}
1420
1421int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001422PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001423 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001424{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 PyObject *m, *d, *v;
1426 const char *ext;
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001427 int set_file_name = 0, ret = -1;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00001428 size_t len;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001430 m = PyImport_AddModule("__main__");
1431 if (m == NULL)
1432 return -1;
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001433 Py_INCREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001434 d = PyModule_GetDict(m);
1435 if (PyDict_GetItemString(d, "__file__") == NULL) {
1436 PyObject *f;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00001437 f = PyUnicode_DecodeFSDefault(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 if (f == NULL)
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001439 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001440 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1441 Py_DECREF(f);
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001442 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001443 }
Barry Warsaw916048d2011-09-20 14:45:44 -04001444 if (PyDict_SetItemString(d, "__cached__", Py_None) < 0) {
1445 Py_DECREF(f);
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001446 goto done;
Barry Warsaw916048d2011-09-20 14:45:44 -04001447 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 set_file_name = 1;
1449 Py_DECREF(f);
1450 }
1451 len = strlen(filename);
1452 ext = filename + len - (len > 4 ? 4 : 0);
1453 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Christian Heimes04ac4c12012-09-11 15:47:28 +02001454 FILE *pyc_fp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001455 /* Try to run a pyc file. First, re-open in binary */
1456 if (closeit)
1457 fclose(fp);
Victor Stinnerdaf45552013-08-28 00:53:59 +02001458 if ((pyc_fp = _Py_fopen(filename, "rb")) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001459 fprintf(stderr, "python: Can't reopen .pyc file\n");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001460 goto done;
1461 }
1462 /* Turn on optimization if a .pyo file is given */
1463 if (strcmp(ext, ".pyo") == 0)
1464 Py_OptimizeFlag = 1;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001465
1466 if (set_main_loader(d, filename, "SourcelessFileLoader") < 0) {
1467 fprintf(stderr, "python: failed to set __main__.__loader__\n");
1468 ret = -1;
Christian Heimes04ac4c12012-09-11 15:47:28 +02001469 fclose(pyc_fp);
Nick Coghlan85e729e2012-07-15 18:09:52 +10001470 goto done;
1471 }
Christian Heimes04ac4c12012-09-11 15:47:28 +02001472 v = run_pyc_file(pyc_fp, filename, d, d, flags);
1473 fclose(pyc_fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001474 } else {
Nick Coghlan85e729e2012-07-15 18:09:52 +10001475 /* When running from stdin, leave __main__.__loader__ alone */
1476 if (strcmp(filename, "<stdin>") != 0 &&
1477 set_main_loader(d, filename, "SourceFileLoader") < 0) {
1478 fprintf(stderr, "python: failed to set __main__.__loader__\n");
1479 ret = -1;
1480 goto done;
1481 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001482 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
1483 closeit, flags);
1484 }
1485 flush_io();
1486 if (v == NULL) {
1487 PyErr_Print();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001488 goto done;
1489 }
1490 Py_DECREF(v);
1491 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001492 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001493 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1494 PyErr_Clear();
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001495 Py_DECREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001496 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001497}
1498
1499int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001500PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001501{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001502 PyObject *m, *d, *v;
1503 m = PyImport_AddModule("__main__");
1504 if (m == NULL)
1505 return -1;
1506 d = PyModule_GetDict(m);
1507 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
1508 if (v == NULL) {
1509 PyErr_Print();
1510 return -1;
1511 }
1512 Py_DECREF(v);
1513 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001514}
1515
Barry Warsaw035574d1997-08-29 22:07:17 +00001516static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001517parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001518 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001519{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001520 long hold;
1521 PyObject *v;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001522 _Py_IDENTIFIER(msg);
1523 _Py_IDENTIFIER(filename);
1524 _Py_IDENTIFIER(lineno);
1525 _Py_IDENTIFIER(offset);
1526 _Py_IDENTIFIER(text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001527
Benjamin Peterson80d50422012-04-03 00:30:38 -04001528 *message = NULL;
1529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001530 /* new style errors. `err' is an instance */
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001531 *message = _PyObject_GetAttrId(err, &PyId_msg);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001532 if (!*message)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001533 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001534
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001535 v = _PyObject_GetAttrId(err, &PyId_filename);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001536 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001537 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001538 if (v == Py_None) {
1539 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001540 *filename = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001541 }
1542 else {
1543 *filename = _PyUnicode_AsString(v);
1544 Py_DECREF(v);
1545 if (!*filename)
1546 goto finally;
1547 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001548
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001549 v = _PyObject_GetAttrId(err, &PyId_lineno);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001550 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001551 goto finally;
1552 hold = PyLong_AsLong(v);
1553 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001554 if (hold < 0 && PyErr_Occurred())
1555 goto finally;
1556 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001557
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001558 v = _PyObject_GetAttrId(err, &PyId_offset);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001559 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 goto finally;
1561 if (v == Py_None) {
1562 *offset = -1;
1563 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001564 } else {
1565 hold = PyLong_AsLong(v);
1566 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001567 if (hold < 0 && PyErr_Occurred())
1568 goto finally;
1569 *offset = (int)hold;
1570 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001571
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001572 v = _PyObject_GetAttrId(err, &PyId_text);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001573 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001574 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001575 if (v == Py_None) {
1576 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001577 *text = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001578 }
1579 else {
1580 *text = _PyUnicode_AsString(v);
1581 Py_DECREF(v);
1582 if (!*text)
1583 goto finally;
1584 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001586
1587finally:
Benjamin Peterson80d50422012-04-03 00:30:38 -04001588 Py_XDECREF(*message);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001589 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001590}
1591
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001592void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001593PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001594{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001596}
1597
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001598static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001599print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001600{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 char *nl;
1602 if (offset >= 0) {
Benjamin Petersona95e9772010-10-29 03:28:14 +00001603 if (offset > 0 && offset == strlen(text) && text[offset - 1] == '\n')
1604 offset--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 for (;;) {
1606 nl = strchr(text, '\n');
1607 if (nl == NULL || nl-text >= offset)
1608 break;
1609 offset -= (int)(nl+1-text);
1610 text = nl+1;
1611 }
1612 while (*text == ' ' || *text == '\t') {
1613 text++;
1614 offset--;
1615 }
1616 }
1617 PyFile_WriteString(" ", f);
1618 PyFile_WriteString(text, f);
1619 if (*text == '\0' || text[strlen(text)-1] != '\n')
1620 PyFile_WriteString("\n", f);
1621 if (offset == -1)
1622 return;
1623 PyFile_WriteString(" ", f);
Benjamin Petersona95e9772010-10-29 03:28:14 +00001624 while (--offset > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001625 PyFile_WriteString(" ", f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001626 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001627}
1628
Guido van Rossum66e8e862001-03-23 17:54:43 +00001629static void
1630handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001631{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001632 PyObject *exception, *value, *tb;
1633 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001635 if (Py_InspectFlag)
1636 /* Don't exit if -i flag was given. This flag is set to 0
1637 * when entering interactive mode for inspecting. */
1638 return;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001640 PyErr_Fetch(&exception, &value, &tb);
1641 fflush(stdout);
1642 if (value == NULL || value == Py_None)
1643 goto done;
1644 if (PyExceptionInstance_Check(value)) {
1645 /* The error code should be in the `code' attribute. */
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001646 _Py_IDENTIFIER(code);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001647 PyObject *code = _PyObject_GetAttrId(value, &PyId_code);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001648 if (code) {
1649 Py_DECREF(value);
1650 value = code;
1651 if (value == Py_None)
1652 goto done;
1653 }
1654 /* If we failed to dig out the 'code' attribute,
1655 just let the else clause below print the error. */
1656 }
1657 if (PyLong_Check(value))
1658 exitcode = (int)PyLong_AsLong(value);
1659 else {
Victor Stinnere9fb3192010-05-17 08:58:51 +00001660 PyObject *sys_stderr = PySys_GetObject("stderr");
Victor Stinner7126dbc2010-05-21 23:45:42 +00001661 if (sys_stderr != NULL && sys_stderr != Py_None) {
1662 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
1663 } else {
1664 PyObject_Print(value, stderr, Py_PRINT_RAW);
1665 fflush(stderr);
1666 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001667 PySys_WriteStderr("\n");
1668 exitcode = 1;
1669 }
Tim Peterscf615b52003-04-19 18:47:02 +00001670 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001671 /* Restore and clear the exception info, in order to properly decref
1672 * the exception, value, and traceback. If we just exit instead,
1673 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1674 * some finalizers from running.
1675 */
1676 PyErr_Restore(exception, value, tb);
1677 PyErr_Clear();
1678 Py_Exit(exitcode);
1679 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001680}
1681
1682void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001683PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001684{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001686
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001687 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1688 handle_system_exit();
1689 }
1690 PyErr_Fetch(&exception, &v, &tb);
1691 if (exception == NULL)
1692 return;
1693 PyErr_NormalizeException(&exception, &v, &tb);
1694 if (tb == NULL) {
1695 tb = Py_None;
1696 Py_INCREF(tb);
1697 }
1698 PyException_SetTraceback(v, tb);
1699 if (exception == NULL)
1700 return;
1701 /* Now we know v != NULL too */
1702 if (set_sys_last_vars) {
1703 PySys_SetObject("last_type", exception);
1704 PySys_SetObject("last_value", v);
1705 PySys_SetObject("last_traceback", tb);
1706 }
1707 hook = PySys_GetObject("excepthook");
1708 if (hook) {
1709 PyObject *args = PyTuple_Pack(3, exception, v, tb);
1710 PyObject *result = PyEval_CallObject(hook, args);
1711 if (result == NULL) {
1712 PyObject *exception2, *v2, *tb2;
1713 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1714 handle_system_exit();
1715 }
1716 PyErr_Fetch(&exception2, &v2, &tb2);
1717 PyErr_NormalizeException(&exception2, &v2, &tb2);
1718 /* It should not be possible for exception2 or v2
1719 to be NULL. However PyErr_Display() can't
1720 tolerate NULLs, so just be safe. */
1721 if (exception2 == NULL) {
1722 exception2 = Py_None;
1723 Py_INCREF(exception2);
1724 }
1725 if (v2 == NULL) {
1726 v2 = Py_None;
1727 Py_INCREF(v2);
1728 }
1729 fflush(stdout);
1730 PySys_WriteStderr("Error in sys.excepthook:\n");
1731 PyErr_Display(exception2, v2, tb2);
1732 PySys_WriteStderr("\nOriginal exception was:\n");
1733 PyErr_Display(exception, v, tb);
1734 Py_DECREF(exception2);
1735 Py_DECREF(v2);
1736 Py_XDECREF(tb2);
1737 }
1738 Py_XDECREF(result);
1739 Py_XDECREF(args);
1740 } else {
1741 PySys_WriteStderr("sys.excepthook is missing\n");
1742 PyErr_Display(exception, v, tb);
1743 }
1744 Py_XDECREF(exception);
1745 Py_XDECREF(v);
1746 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001747}
1748
Benjamin Petersone6528212008-07-15 15:32:09 +00001749static void
1750print_exception(PyObject *f, PyObject *value)
1751{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001752 int err = 0;
1753 PyObject *type, *tb;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001754 _Py_IDENTIFIER(print_file_and_line);
Benjamin Petersone6528212008-07-15 15:32:09 +00001755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001756 if (!PyExceptionInstance_Check(value)) {
1757 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1758 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1759 PyFile_WriteString(" found\n", f);
1760 return;
1761 }
Benjamin Peterson26582602008-08-23 20:08:07 +00001762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001763 Py_INCREF(value);
1764 fflush(stdout);
1765 type = (PyObject *) Py_TYPE(value);
1766 tb = PyException_GetTraceback(value);
1767 if (tb && tb != Py_None)
1768 err = PyTraceBack_Print(tb, f);
1769 if (err == 0 &&
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001770 _PyObject_HasAttrId(value, &PyId_print_file_and_line))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001771 {
1772 PyObject *message;
1773 const char *filename, *text;
1774 int lineno, offset;
1775 if (!parse_syntax_error(value, &message, &filename,
1776 &lineno, &offset, &text))
1777 PyErr_Clear();
1778 else {
1779 char buf[10];
1780 PyFile_WriteString(" File \"", f);
1781 if (filename == NULL)
1782 PyFile_WriteString("<string>", f);
1783 else
1784 PyFile_WriteString(filename, f);
1785 PyFile_WriteString("\", line ", f);
1786 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1787 PyFile_WriteString(buf, f);
1788 PyFile_WriteString("\n", f);
1789 if (text != NULL)
1790 print_error_text(f, offset, text);
1791 Py_DECREF(value);
1792 value = message;
1793 /* Can't be bothered to check all those
1794 PyFile_WriteString() calls */
1795 if (PyErr_Occurred())
1796 err = -1;
1797 }
1798 }
1799 if (err) {
1800 /* Don't do anything else */
1801 }
1802 else {
1803 PyObject* moduleName;
1804 char* className;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001805 _Py_IDENTIFIER(__module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001806 assert(PyExceptionClass_Check(type));
1807 className = PyExceptionClass_Name(type);
1808 if (className != NULL) {
1809 char *dot = strrchr(className, '.');
1810 if (dot != NULL)
1811 className = dot+1;
1812 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001813
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001814 moduleName = _PyObject_GetAttrId(type, &PyId___module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001815 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1816 {
Victor Stinner13b21bd2011-05-26 14:25:13 +02001817 Py_XDECREF(moduleName);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001818 err = PyFile_WriteString("<unknown>", f);
1819 }
1820 else {
1821 char* modstr = _PyUnicode_AsString(moduleName);
1822 if (modstr && strcmp(modstr, "builtins"))
1823 {
1824 err = PyFile_WriteString(modstr, f);
1825 err += PyFile_WriteString(".", f);
1826 }
1827 Py_DECREF(moduleName);
1828 }
1829 if (err == 0) {
1830 if (className == NULL)
1831 err = PyFile_WriteString("<unknown>", f);
1832 else
1833 err = PyFile_WriteString(className, f);
1834 }
1835 }
1836 if (err == 0 && (value != Py_None)) {
1837 PyObject *s = PyObject_Str(value);
1838 /* only print colon if the str() of the
1839 object is not the empty string
1840 */
1841 if (s == NULL)
1842 err = -1;
1843 else if (!PyUnicode_Check(s) ||
Victor Stinnere251d6d2011-11-20 19:20:00 +01001844 PyUnicode_GetLength(s) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001845 err = PyFile_WriteString(": ", f);
1846 if (err == 0)
1847 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1848 Py_XDECREF(s);
1849 }
1850 /* try to write a newline in any case */
1851 err += PyFile_WriteString("\n", f);
1852 Py_XDECREF(tb);
1853 Py_DECREF(value);
1854 /* If an error happened here, don't show it.
1855 XXX This is wrong, but too many callers rely on this behavior. */
1856 if (err != 0)
1857 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001858}
1859
1860static const char *cause_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861 "\nThe above exception was the direct cause "
1862 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001863
1864static const char *context_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 "\nDuring handling of the above exception, "
1866 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001867
1868static void
1869print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1870{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001871 int err = 0, res;
1872 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00001873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001874 if (seen != NULL) {
1875 /* Exception chaining */
1876 if (PySet_Add(seen, value) == -1)
1877 PyErr_Clear();
1878 else if (PyExceptionInstance_Check(value)) {
1879 cause = PyException_GetCause(value);
1880 context = PyException_GetContext(value);
Benjamin Petersond5a1c442012-05-14 22:09:31 -07001881 if (cause) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001882 res = PySet_Contains(seen, cause);
1883 if (res == -1)
1884 PyErr_Clear();
1885 if (res == 0) {
1886 print_exception_recursive(
1887 f, cause, seen);
1888 err |= PyFile_WriteString(
1889 cause_message, f);
1890 }
1891 }
Benjamin Petersond5a1c442012-05-14 22:09:31 -07001892 else if (context &&
1893 !((PyBaseExceptionObject *)value)->suppress_context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001894 res = PySet_Contains(seen, context);
1895 if (res == -1)
1896 PyErr_Clear();
1897 if (res == 0) {
1898 print_exception_recursive(
1899 f, context, seen);
1900 err |= PyFile_WriteString(
1901 context_message, f);
1902 }
1903 }
1904 Py_XDECREF(context);
1905 Py_XDECREF(cause);
1906 }
1907 }
1908 print_exception(f, value);
1909 if (err != 0)
1910 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001911}
1912
Thomas Wouters477c8d52006-05-27 19:21:47 +00001913void
1914PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001915{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001916 PyObject *seen;
1917 PyObject *f = PySys_GetObject("stderr");
1918 if (f == Py_None) {
1919 /* pass */
1920 }
1921 else if (f == NULL) {
1922 _PyObject_Dump(value);
1923 fprintf(stderr, "lost sys.stderr\n");
1924 }
1925 else {
1926 /* We choose to ignore seen being possibly NULL, and report
1927 at least the main exception (it could be a MemoryError).
1928 */
1929 seen = PySet_New(NULL);
1930 if (seen == NULL)
1931 PyErr_Clear();
1932 print_exception_recursive(f, value, seen);
1933 Py_XDECREF(seen);
1934 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001935}
1936
Guido van Rossum82598051997-03-05 00:20:32 +00001937PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001938PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001939 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001940{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001941 PyObject *ret = NULL;
1942 mod_ty mod;
1943 PyArena *arena = PyArena_New();
1944 if (arena == NULL)
1945 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001947 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
1948 if (mod != NULL)
1949 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
1950 PyArena_Free(arena);
1951 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001952}
1953
1954PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001955PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001956 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001957{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001958 PyObject *ret;
1959 mod_ty mod;
1960 PyArena *arena = PyArena_New();
1961 if (arena == NULL)
1962 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001964 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
1965 flags, NULL, arena);
1966 if (closeit)
1967 fclose(fp);
1968 if (mod == NULL) {
1969 PyArena_Free(arena);
1970 return NULL;
1971 }
1972 ret = run_mod(mod, filename, globals, locals, flags, arena);
1973 PyArena_Free(arena);
1974 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001975}
1976
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001977static void
1978flush_io(void)
1979{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001980 PyObject *f, *r;
1981 PyObject *type, *value, *traceback;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001982 _Py_IDENTIFIER(flush);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001983
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001984 /* Save the current exception */
1985 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001987 f = PySys_GetObject("stderr");
1988 if (f != NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001989 r = _PyObject_CallMethodId(f, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001990 if (r)
1991 Py_DECREF(r);
1992 else
1993 PyErr_Clear();
1994 }
1995 f = PySys_GetObject("stdout");
1996 if (f != NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001997 r = _PyObject_CallMethodId(f, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 if (r)
1999 Py_DECREF(r);
2000 else
2001 PyErr_Clear();
2002 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00002003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00002005}
2006
Guido van Rossum82598051997-03-05 00:20:32 +00002007static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002008run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002009 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002010{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002011 PyCodeObject *co;
2012 PyObject *v;
2013 co = PyAST_Compile(mod, filename, flags, arena);
2014 if (co == NULL)
2015 return NULL;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002016 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002017 Py_DECREF(co);
2018 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002019}
2020
Guido van Rossum82598051997-03-05 00:20:32 +00002021static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002022run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002023 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00002024{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002025 PyCodeObject *co;
2026 PyObject *v;
2027 long magic;
2028 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00002029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 magic = PyMarshal_ReadLongFromFile(fp);
2031 if (magic != PyImport_GetMagicNumber()) {
2032 PyErr_SetString(PyExc_RuntimeError,
2033 "Bad magic number in .pyc file");
2034 return NULL;
2035 }
Antoine Pitrou5136ac02012-01-13 18:52:16 +01002036 /* Skip mtime and size */
2037 (void) PyMarshal_ReadLongFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002038 (void) PyMarshal_ReadLongFromFile(fp);
2039 v = PyMarshal_ReadLastObjectFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002040 if (v == NULL || !PyCode_Check(v)) {
2041 Py_XDECREF(v);
2042 PyErr_SetString(PyExc_RuntimeError,
2043 "Bad code object in .pyc file");
2044 return NULL;
2045 }
2046 co = (PyCodeObject *)v;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002047 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002048 if (v && flags)
2049 flags->cf_flags |= (co->co_flags & PyCF_MASK);
2050 Py_DECREF(co);
2051 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00002052}
2053
Guido van Rossum82598051997-03-05 00:20:32 +00002054PyObject *
Victor Stinner14e461d2013-08-26 22:28:21 +02002055Py_CompileStringObject(const char *str, PyObject *filename, int start,
2056 PyCompilerFlags *flags, int optimize)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002057{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002058 PyCodeObject *co;
2059 mod_ty mod;
2060 PyArena *arena = PyArena_New();
2061 if (arena == NULL)
2062 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002063
Victor Stinner14e461d2013-08-26 22:28:21 +02002064 mod = PyParser_ASTFromStringObject(str, filename, start, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002065 if (mod == NULL) {
2066 PyArena_Free(arena);
2067 return NULL;
2068 }
2069 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
2070 PyObject *result = PyAST_mod2obj(mod);
2071 PyArena_Free(arena);
2072 return result;
2073 }
Victor Stinner14e461d2013-08-26 22:28:21 +02002074 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002075 PyArena_Free(arena);
2076 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00002077}
2078
Victor Stinner14e461d2013-08-26 22:28:21 +02002079PyObject *
2080Py_CompileStringExFlags(const char *str, const char *filename_str, int start,
2081 PyCompilerFlags *flags, int optimize)
2082{
2083 PyObject *filename, *co;
2084 filename = PyUnicode_DecodeFSDefault(filename_str);
2085 if (filename == NULL)
2086 return NULL;
2087 co = Py_CompileStringObject(str, filename, start, flags, optimize);
2088 Py_DECREF(filename);
2089 return co;
2090}
2091
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002092/* For use in Py_LIMITED_API */
2093#undef Py_CompileString
2094PyObject *
2095PyCompileString(const char *str, const char *filename, int start)
2096{
2097 return Py_CompileStringFlags(str, filename, start, NULL);
2098}
2099
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002100struct symtable *
Victor Stinner14e461d2013-08-26 22:28:21 +02002101Py_SymtableStringObject(const char *str, PyObject *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002102{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002103 struct symtable *st;
2104 mod_ty mod;
2105 PyCompilerFlags flags;
Victor Stinner14e461d2013-08-26 22:28:21 +02002106 PyArena *arena;
2107
2108 arena = PyArena_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002109 if (arena == NULL)
2110 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002112 flags.cf_flags = 0;
Victor Stinner14e461d2013-08-26 22:28:21 +02002113 mod = PyParser_ASTFromStringObject(str, filename, start, &flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002114 if (mod == NULL) {
2115 PyArena_Free(arena);
2116 return NULL;
2117 }
Victor Stinner14e461d2013-08-26 22:28:21 +02002118 st = PySymtable_BuildObject(mod, filename, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 PyArena_Free(arena);
2120 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002121}
2122
Victor Stinner14e461d2013-08-26 22:28:21 +02002123struct symtable *
2124Py_SymtableString(const char *str, const char *filename_str, int start)
2125{
2126 PyObject *filename;
2127 struct symtable *st;
2128
2129 filename = PyUnicode_DecodeFSDefault(filename_str);
2130 if (filename == NULL)
2131 return NULL;
2132 st = Py_SymtableStringObject(str, filename, start);
2133 Py_DECREF(filename);
2134 return st;
2135}
2136
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002137/* Preferred access to parser is through AST. */
2138mod_ty
Victor Stinner14e461d2013-08-26 22:28:21 +02002139PyParser_ASTFromStringObject(const char *s, PyObject *filename, int start,
2140 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002141{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002142 mod_ty mod;
2143 PyCompilerFlags localflags;
2144 perrdetail err;
2145 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00002146
Victor Stinner14e461d2013-08-26 22:28:21 +02002147 node *n = PyParser_ParseStringObject(s, filename,
2148 &_PyParser_Grammar, start, &err,
2149 &iflags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002150 if (flags == NULL) {
2151 localflags.cf_flags = 0;
2152 flags = &localflags;
2153 }
2154 if (n) {
2155 flags->cf_flags |= iflags & PyCF_MASK;
Victor Stinner14e461d2013-08-26 22:28:21 +02002156 mod = PyAST_FromNodeObject(n, flags, filename, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002157 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002158 }
2159 else {
2160 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002161 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002162 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002163 err_free(&err);
2164 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002165}
2166
2167mod_ty
Victor Stinner14e461d2013-08-26 22:28:21 +02002168PyParser_ASTFromString(const char *s, const char *filename_str, int start,
2169 PyCompilerFlags *flags, PyArena *arena)
2170{
2171 PyObject *filename;
2172 mod_ty mod;
2173 filename = PyUnicode_DecodeFSDefault(filename_str);
2174 if (filename == NULL)
2175 return NULL;
2176 mod = PyParser_ASTFromStringObject(s, filename, start, flags, arena);
2177 Py_DECREF(filename);
2178 return mod;
2179}
2180
2181mod_ty
2182PyParser_ASTFromFileObject(FILE *fp, PyObject *filename, const char* enc,
2183 int start, char *ps1,
2184 char *ps2, PyCompilerFlags *flags, int *errcode,
2185 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002186{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002187 mod_ty mod;
2188 PyCompilerFlags localflags;
2189 perrdetail err;
2190 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00002191
Victor Stinner14e461d2013-08-26 22:28:21 +02002192 node *n = PyParser_ParseFileObject(fp, filename, enc,
2193 &_PyParser_Grammar,
2194 start, ps1, ps2, &err, &iflags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002195 if (flags == NULL) {
2196 localflags.cf_flags = 0;
2197 flags = &localflags;
2198 }
2199 if (n) {
2200 flags->cf_flags |= iflags & PyCF_MASK;
Victor Stinner14e461d2013-08-26 22:28:21 +02002201 mod = PyAST_FromNodeObject(n, flags, filename, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002202 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002203 }
2204 else {
2205 err_input(&err);
2206 if (errcode)
2207 *errcode = err.error;
Victor Stinner7f2fee32011-04-05 00:39:01 +02002208 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002209 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002210 err_free(&err);
2211 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002212}
2213
Victor Stinner14e461d2013-08-26 22:28:21 +02002214mod_ty
2215PyParser_ASTFromFile(FILE *fp, const char *filename_str, const char* enc,
2216 int start, char *ps1,
2217 char *ps2, PyCompilerFlags *flags, int *errcode,
2218 PyArena *arena)
2219{
2220 mod_ty mod;
2221 PyObject *filename;
2222 filename = PyUnicode_DecodeFSDefault(filename_str);
2223 if (filename == NULL)
2224 return NULL;
2225 mod = PyParser_ASTFromFileObject(fp, filename, enc, start, ps1, ps2,
2226 flags, errcode, arena);
2227 Py_DECREF(filename);
2228 return mod;
2229}
2230
Guido van Rossuma110aa61994-08-29 12:50:44 +00002231/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002232
Guido van Rossuma110aa61994-08-29 12:50:44 +00002233node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002234PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002235{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 perrdetail err;
2237 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
2238 &_PyParser_Grammar,
2239 start, NULL, NULL, &err, flags);
2240 if (n == NULL)
2241 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002242 err_free(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002244 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002245}
2246
Guido van Rossuma110aa61994-08-29 12:50:44 +00002247/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002248
Guido van Rossuma110aa61994-08-29 12:50:44 +00002249node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002250PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00002251{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002252 perrdetail err;
2253 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
2254 start, &err, flags);
2255 if (n == NULL)
2256 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002257 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002258 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00002259}
2260
2261node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002262PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002263 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00002264{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 perrdetail err;
2266 node *n = PyParser_ParseStringFlagsFilename(str, filename,
2267 &_PyParser_Grammar, start, &err, flags);
2268 if (n == NULL)
2269 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002270 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002271 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00002272}
2273
2274node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002275PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00002276{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002277 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00002278}
2279
Guido van Rossum66ebd912003-04-17 16:02:26 +00002280/* May want to move a more generalized form of this to parsetok.c or
2281 even parser modules. */
2282
2283void
Victor Stinner7f2fee32011-04-05 00:39:01 +02002284PyParser_ClearError(perrdetail *err)
2285{
2286 err_free(err);
2287}
2288
2289void
Guido van Rossum66ebd912003-04-17 16:02:26 +00002290PyParser_SetError(perrdetail *err)
2291{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002292 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00002293}
2294
Victor Stinner7f2fee32011-04-05 00:39:01 +02002295static void
2296err_free(perrdetail *err)
2297{
2298 Py_CLEAR(err->filename);
2299}
2300
Guido van Rossuma110aa61994-08-29 12:50:44 +00002301/* Set the error appropriate to the given input error code (see errcode.h) */
2302
2303static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002304err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00002305{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002306 PyObject *v, *w, *errtype, *errtext;
2307 PyObject *msg_obj = NULL;
2308 char *msg = NULL;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00002309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002310 errtype = PyExc_SyntaxError;
2311 switch (err->error) {
2312 case E_ERROR:
2313 return;
2314 case E_SYNTAX:
2315 errtype = PyExc_IndentationError;
2316 if (err->expected == INDENT)
2317 msg = "expected an indented block";
2318 else if (err->token == INDENT)
2319 msg = "unexpected indent";
2320 else if (err->token == DEDENT)
2321 msg = "unexpected unindent";
2322 else {
2323 errtype = PyExc_SyntaxError;
2324 msg = "invalid syntax";
2325 }
2326 break;
2327 case E_TOKEN:
2328 msg = "invalid token";
2329 break;
2330 case E_EOFS:
2331 msg = "EOF while scanning triple-quoted string literal";
2332 break;
2333 case E_EOLS:
2334 msg = "EOL while scanning string literal";
2335 break;
2336 case E_INTR:
2337 if (!PyErr_Occurred())
2338 PyErr_SetNone(PyExc_KeyboardInterrupt);
2339 goto cleanup;
2340 case E_NOMEM:
2341 PyErr_NoMemory();
2342 goto cleanup;
2343 case E_EOF:
2344 msg = "unexpected EOF while parsing";
2345 break;
2346 case E_TABSPACE:
2347 errtype = PyExc_TabError;
2348 msg = "inconsistent use of tabs and spaces in indentation";
2349 break;
2350 case E_OVERFLOW:
2351 msg = "expression too long";
2352 break;
2353 case E_DEDENT:
2354 errtype = PyExc_IndentationError;
2355 msg = "unindent does not match any outer indentation level";
2356 break;
2357 case E_TOODEEP:
2358 errtype = PyExc_IndentationError;
2359 msg = "too many levels of indentation";
2360 break;
2361 case E_DECODE: {
2362 PyObject *type, *value, *tb;
2363 PyErr_Fetch(&type, &value, &tb);
2364 msg = "unknown decode error";
2365 if (value != NULL)
2366 msg_obj = PyObject_Str(value);
2367 Py_XDECREF(type);
2368 Py_XDECREF(value);
2369 Py_XDECREF(tb);
2370 break;
2371 }
2372 case E_LINECONT:
2373 msg = "unexpected character after line continuation character";
2374 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00002375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002376 case E_IDENTIFIER:
2377 msg = "invalid character in identifier";
2378 break;
Meador Ingefa21bf02012-01-19 01:08:41 -06002379 case E_BADSINGLE:
2380 msg = "multiple statements found while compiling a single statement";
2381 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002382 default:
2383 fprintf(stderr, "error=%d\n", err->error);
2384 msg = "unknown parsing error";
2385 break;
2386 }
2387 /* err->text may not be UTF-8 in case of decoding errors.
2388 Explicitly convert to an object. */
2389 if (!err->text) {
2390 errtext = Py_None;
2391 Py_INCREF(Py_None);
2392 } else {
2393 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
2394 "replace");
2395 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002396 v = Py_BuildValue("(OiiN)", err->filename,
2397 err->lineno, err->offset, errtext);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002398 if (v != NULL) {
2399 if (msg_obj)
2400 w = Py_BuildValue("(OO)", msg_obj, v);
2401 else
2402 w = Py_BuildValue("(sO)", msg, v);
2403 } else
2404 w = NULL;
2405 Py_XDECREF(v);
2406 PyErr_SetObject(errtype, w);
2407 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00002408cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002409 Py_XDECREF(msg_obj);
2410 if (err->text != NULL) {
2411 PyObject_FREE(err->text);
2412 err->text = NULL;
2413 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002414}
2415
2416/* Print fatal error message and abort */
2417
2418void
Tim Peters7c321a82002-07-09 02:57:01 +00002419Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002420{
Victor Stinner024e37a2011-03-31 01:31:06 +02002421 const int fd = fileno(stderr);
2422 PyThreadState *tstate;
2423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002424 fprintf(stderr, "Fatal Python error: %s\n", msg);
2425 fflush(stderr); /* it helps in Windows debug build */
2426 if (PyErr_Occurred()) {
Victor Stinner55a5c782010-06-08 21:00:13 +00002427 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002428 }
Victor Stinner024e37a2011-03-31 01:31:06 +02002429 else {
2430 tstate = _Py_atomic_load_relaxed(&_PyThreadState_Current);
2431 if (tstate != NULL) {
2432 fputc('\n', stderr);
2433 fflush(stderr);
Victor Stinner7bba62f2011-05-07 12:43:00 +02002434 _Py_DumpTracebackThreads(fd, tstate->interp, tstate);
Victor Stinner024e37a2011-03-31 01:31:06 +02002435 }
Victor Stinnerd727e232011-04-01 12:13:55 +02002436 _PyFaulthandler_Fini();
Victor Stinner024e37a2011-03-31 01:31:06 +02002437 }
2438
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002439#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002440 {
2441 size_t len = strlen(msg);
2442 WCHAR* buffer;
2443 size_t i;
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002445 /* Convert the message to wchar_t. This uses a simple one-to-one
2446 conversion, assuming that the this error message actually uses ASCII
2447 only. If this ceases to be true, we will have to convert. */
2448 buffer = alloca( (len+1) * (sizeof *buffer));
2449 for( i=0; i<=len; ++i)
2450 buffer[i] = msg[i];
2451 OutputDebugStringW(L"Fatal Python error: ");
2452 OutputDebugStringW(buffer);
2453 OutputDebugStringW(L"\n");
2454 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002455#ifdef _DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002456 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002457#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002458#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002459 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002460}
2461
2462/* Clean up and exit */
2463
Guido van Rossuma110aa61994-08-29 12:50:44 +00002464#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002465#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002466#endif
2467
Collin Winter670e6922007-03-21 02:57:17 +00002468static void (*pyexitfunc)(void) = NULL;
2469/* For the atexit module. */
2470void _Py_PyAtExit(void (*func)(void))
2471{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002472 pyexitfunc = func;
Collin Winter670e6922007-03-21 02:57:17 +00002473}
2474
2475static void
2476call_py_exitfuncs(void)
2477{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002478 if (pyexitfunc == NULL)
2479 return;
Collin Winter670e6922007-03-21 02:57:17 +00002480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002481 (*pyexitfunc)();
2482 PyErr_Clear();
Collin Winter670e6922007-03-21 02:57:17 +00002483}
2484
Antoine Pitrou011bd622009-10-20 21:52:47 +00002485/* Wait until threading._shutdown completes, provided
2486 the threading module was imported in the first place.
2487 The shutdown routine will wait until all non-daemon
2488 "threading" threads have completed. */
2489static void
2490wait_for_thread_shutdown(void)
2491{
2492#ifdef WITH_THREAD
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002493 _Py_IDENTIFIER(_shutdown);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002494 PyObject *result;
2495 PyThreadState *tstate = PyThreadState_GET();
2496 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2497 "threading");
2498 if (threading == NULL) {
2499 /* threading not imported */
2500 PyErr_Clear();
2501 return;
2502 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002503 result = _PyObject_CallMethodId(threading, &PyId__shutdown, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002504 if (result == NULL) {
2505 PyErr_WriteUnraisable(threading);
2506 }
2507 else {
2508 Py_DECREF(result);
2509 }
2510 Py_DECREF(threading);
Antoine Pitrou011bd622009-10-20 21:52:47 +00002511#endif
2512}
2513
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002514#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002515static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002516static int nexitfuncs = 0;
2517
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002518int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002519{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002520 if (nexitfuncs >= NEXITFUNCS)
2521 return -1;
2522 exitfuncs[nexitfuncs++] = func;
2523 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00002524}
2525
Guido van Rossumcc283f51997-08-05 02:22:03 +00002526static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002527call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002528{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002529 while (nexitfuncs > 0)
2530 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002532 fflush(stdout);
2533 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002534}
2535
2536void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002537Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002538{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002539 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002541 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002542}
2543
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002544static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002545initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002546{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002547#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002548 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002549#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002550#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002551 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002552#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002553#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002554 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002555#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002556 PyOS_InitInterrupts(); /* May imply initsignal() */
Victor Stinnerd786ad52013-07-21 13:25:51 +02002557 if (PyErr_Occurred()) {
2558 Py_FatalError("Py_Initialize: can't import signal");
2559 }
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002560}
2561
Guido van Rossum7433b121997-02-14 19:45:36 +00002562
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002563/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2564 *
2565 * All of the code in this function must only use async-signal-safe functions,
2566 * listed at `man 7 signal` or
2567 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2568 */
2569void
2570_Py_RestoreSignals(void)
2571{
2572#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002573 PyOS_setsig(SIGPIPE, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002574#endif
2575#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002576 PyOS_setsig(SIGXFZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002577#endif
2578#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002579 PyOS_setsig(SIGXFSZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002580#endif
2581}
2582
2583
Guido van Rossum7433b121997-02-14 19:45:36 +00002584/*
2585 * The file descriptor fd is considered ``interactive'' if either
2586 * a) isatty(fd) is TRUE, or
2587 * b) the -i flag was given, and the filename associated with
2588 * the descriptor is NULL or "<stdin>" or "???".
2589 */
2590int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002591Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002592{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002593 if (isatty((int)fileno(fp)))
2594 return 1;
2595 if (!Py_InteractiveFlag)
2596 return 0;
2597 return (filename == NULL) ||
2598 (strcmp(filename, "<stdin>") == 0) ||
2599 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00002600}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002601
2602
Tim Petersd08e3822003-04-17 15:24:21 +00002603#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002604#if defined(WIN32) && defined(_MSC_VER)
2605
2606/* Stack checking for Microsoft C */
2607
2608#include <malloc.h>
2609#include <excpt.h>
2610
Fred Drakee8de31c2000-08-31 05:38:39 +00002611/*
2612 * Return non-zero when we run out of memory on the stack; zero otherwise.
2613 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002614int
Fred Drake399739f2000-08-31 05:52:44 +00002615PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002616{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002617 __try {
2618 /* alloca throws a stack overflow exception if there's
2619 not enough space left on the stack */
2620 alloca(PYOS_STACK_MARGIN * sizeof(void*));
2621 return 0;
2622 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2623 EXCEPTION_EXECUTE_HANDLER :
2624 EXCEPTION_CONTINUE_SEARCH) {
2625 int errcode = _resetstkoflw();
2626 if (errcode == 0)
2627 {
2628 Py_FatalError("Could not reset the stack!");
2629 }
2630 }
2631 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002632}
2633
2634#endif /* WIN32 && _MSC_VER */
2635
2636/* Alternate implementations can be added here... */
2637
2638#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002639
2640
2641/* Wrappers around sigaction() or signal(). */
2642
2643PyOS_sighandler_t
2644PyOS_getsig(int sig)
2645{
2646#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002647 struct sigaction context;
2648 if (sigaction(sig, NULL, &context) == -1)
2649 return SIG_ERR;
2650 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002651#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002652 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002653/* Special signal handling for the secure CRT in Visual Studio 2005 */
2654#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002655 switch (sig) {
2656 /* Only these signals are valid */
2657 case SIGINT:
2658 case SIGILL:
2659 case SIGFPE:
2660 case SIGSEGV:
2661 case SIGTERM:
2662 case SIGBREAK:
2663 case SIGABRT:
2664 break;
2665 /* Don't call signal() with other values or it will assert */
2666 default:
2667 return SIG_ERR;
2668 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002669#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002670 handler = signal(sig, SIG_IGN);
2671 if (handler != SIG_ERR)
2672 signal(sig, handler);
2673 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002674#endif
2675}
2676
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002677/*
2678 * All of the code in this function must only use async-signal-safe functions,
2679 * listed at `man 7 signal` or
2680 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2681 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002682PyOS_sighandler_t
2683PyOS_setsig(int sig, PyOS_sighandler_t handler)
2684{
2685#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002686 /* Some code in Modules/signalmodule.c depends on sigaction() being
2687 * used here if HAVE_SIGACTION is defined. Fix that if this code
2688 * changes to invalidate that assumption.
2689 */
2690 struct sigaction context, ocontext;
2691 context.sa_handler = handler;
2692 sigemptyset(&context.sa_mask);
2693 context.sa_flags = 0;
2694 if (sigaction(sig, &context, &ocontext) == -1)
2695 return SIG_ERR;
2696 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002697#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002698 PyOS_sighandler_t oldhandler;
2699 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002700#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002701 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002702#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002703 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002704#endif
2705}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002706
2707/* Deprecated C API functions still provided for binary compatiblity */
2708
2709#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002710PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002711PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2712{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002713 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002714}
2715
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002716#undef PyParser_SimpleParseString
2717PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002718PyParser_SimpleParseString(const char *str, int start)
2719{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002720 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002721}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002722
2723#undef PyRun_AnyFile
2724PyAPI_FUNC(int)
2725PyRun_AnyFile(FILE *fp, const char *name)
2726{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002727 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002728}
2729
2730#undef PyRun_AnyFileEx
2731PyAPI_FUNC(int)
2732PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2733{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002734 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002735}
2736
2737#undef PyRun_AnyFileFlags
2738PyAPI_FUNC(int)
2739PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2740{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002741 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002742}
2743
2744#undef PyRun_File
2745PyAPI_FUNC(PyObject *)
2746PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2747{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002748 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002749}
2750
2751#undef PyRun_FileEx
2752PyAPI_FUNC(PyObject *)
2753PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2754{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002755 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002756}
2757
2758#undef PyRun_FileFlags
2759PyAPI_FUNC(PyObject *)
2760PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002761 PyCompilerFlags *flags)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002762{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002763 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002764}
2765
2766#undef PyRun_SimpleFile
2767PyAPI_FUNC(int)
2768PyRun_SimpleFile(FILE *f, const char *p)
2769{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002770 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002771}
2772
2773#undef PyRun_SimpleFileEx
2774PyAPI_FUNC(int)
2775PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2776{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002777 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002778}
2779
2780
2781#undef PyRun_String
2782PyAPI_FUNC(PyObject *)
2783PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2784{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002785 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002786}
2787
2788#undef PyRun_SimpleString
2789PyAPI_FUNC(int)
2790PyRun_SimpleString(const char *s)
2791{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002792 return PyRun_SimpleStringFlags(s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002793}
2794
2795#undef Py_CompileString
2796PyAPI_FUNC(PyObject *)
2797Py_CompileString(const char *str, const char *p, int s)
2798{
Georg Brandl8334fd92010-12-04 10:26:46 +00002799 return Py_CompileStringExFlags(str, p, s, NULL, -1);
2800}
2801
2802#undef Py_CompileStringFlags
2803PyAPI_FUNC(PyObject *)
2804Py_CompileStringFlags(const char *str, const char *p, int s,
2805 PyCompilerFlags *flags)
2806{
2807 return Py_CompileStringExFlags(str, p, s, flags, -1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002808}
2809
2810#undef PyRun_InteractiveOne
2811PyAPI_FUNC(int)
2812PyRun_InteractiveOne(FILE *f, const char *p)
2813{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002814 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002815}
2816
2817#undef PyRun_InteractiveLoop
2818PyAPI_FUNC(int)
2819PyRun_InteractiveLoop(FILE *f, const char *p)
2820{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002821 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002822}
2823
2824#ifdef __cplusplus
2825}
2826#endif