blob: 906877a0a853ca92a7dc4cd0325fd78db8b2d98a [file] [log] [blame]
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001
Eric Snowc7ec9982017-05-23 23:00:52 -07002/* Top level execution of Python code (including in __main__) */
3
4/* To help control the interfaces between the startup, execution and
5 * shutdown code, the phases are split across separate modules (boostrap,
6 * pythonrun, shutdown)
7 */
8
9/* TODO: Cull includes following phase split */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000010
Guido van Rossum82598051997-03-05 00:20:32 +000011#include "Python.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000012
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013#include "Python-ast.h"
Victor Stinner3bb183d2018-11-22 18:38:38 +010014#undef Yield /* undefine macro conflicting with <winbase.h> */
Gregory P. Smith38f11cc2019-02-16 12:57:40 -080015#include "pycore_pylifecycle.h"
Victor Stinner621cebe2018-11-12 16:53:38 +010016#include "pycore_pystate.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000017#include "grammar.h"
18#include "node.h"
Fred Drake85f36392000-07-11 17:53:00 +000019#include "token.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000020#include "parsetok.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000021#include "errcode.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000022#include "code.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000023#include "symtable.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000024#include "ast.h"
Guido van Rossumfdef2711994-09-14 13:31:04 +000025#include "marshal.h"
Martin v. Löwis790465f2008-04-05 20:41:37 +000026#include "osdefs.h"
Victor Stinner518e6102014-03-18 02:06:38 +010027#include <locale.h>
Guido van Rossum1984f1e1992-08-04 12:41:02 +000028
Thomas Wouters0e3f5912006-08-11 14:57:12 +000029#ifdef HAVE_SIGNAL_H
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000030#include <signal.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000031#endif
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000032
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000033#ifdef MS_WINDOWS
Martin v. Löwis5c88d812009-01-02 20:47:48 +000034#include "malloc.h" /* for alloca */
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000035#endif
Martin v. Löwis5c88d812009-01-02 20:47:48 +000036
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000037#ifdef MS_WINDOWS
Guido van Rossuma44823b1995-03-14 15:01:17 +000038#undef BYTE
39#include "windows.h"
40#endif
41
Victor Stinnerbd303c12013-11-07 23:07:29 +010042_Py_IDENTIFIER(builtins);
Victor Stinner09054372013-11-06 22:41:44 +010043_Py_IDENTIFIER(excepthook);
Victor Stinner3f36a572013-11-12 21:39:02 +010044_Py_IDENTIFIER(flush);
Victor Stinnerbd303c12013-11-07 23:07:29 +010045_Py_IDENTIFIER(last_traceback);
Victor Stinner09054372013-11-06 22:41:44 +010046_Py_IDENTIFIER(last_type);
47_Py_IDENTIFIER(last_value);
Victor Stinnerbd303c12013-11-07 23:07:29 +010048_Py_IDENTIFIER(ps1);
49_Py_IDENTIFIER(ps2);
50_Py_IDENTIFIER(stdin);
51_Py_IDENTIFIER(stdout);
52_Py_IDENTIFIER(stderr);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +010053_Py_static_string(PyId_string, "<string>");
Victor Stinner09054372013-11-06 22:41:44 +010054
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000055#ifdef __cplusplus
56extern "C" {
Neal Norwitz4281cef2006-03-04 19:58:13 +000057#endif
58
Guido van Rossum82598051997-03-05 00:20:32 +000059extern grammar _PyParser_Grammar; /* From graminit.c */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000060
Guido van Rossumb73cc041993-11-01 16:28:59 +000061/* Forward */
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +000062static void flush_io(void);
Victor Stinner95701bd2013-11-06 18:41:07 +010063static PyObject *run_mod(mod_ty, PyObject *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000064 PyCompilerFlags *, PyArena *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000065static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000066 PyCompilerFlags *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000067static void err_input(perrdetail *);
Victor Stinner7f2fee32011-04-05 00:39:01 +020068static void err_free(perrdetail *);
xdegayee0582a32017-11-12 16:50:48 +010069static int PyRun_InteractiveOneObjectEx(FILE *, PyObject *, PyCompilerFlags *);
Guido van Rossumce3a72a2007-10-19 23:16:50 +000070
Guido van Rossum1984f1e1992-08-04 12:41:02 +000071/* Parse input from a file and execute it */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000072int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000073PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000074 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +000075{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000076 if (filename == NULL)
77 filename = "???";
78 if (Py_FdIsInteractive(fp, filename)) {
79 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
80 if (closeit)
81 fclose(fp);
82 return err;
83 }
84 else
85 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000086}
87
88int
Victor Stinner95701bd2013-11-06 18:41:07 +010089PyRun_InteractiveLoopFlags(FILE *fp, const char *filename_str, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +000090{
Victor Stinner95701bd2013-11-06 18:41:07 +010091 PyObject *filename, *v;
92 int ret, err;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000093 PyCompilerFlags local_flags;
xdegayee0582a32017-11-12 16:50:48 +010094 int nomem_count = 0;
Victor Stinner25420fe2017-11-20 18:12:22 -080095#ifdef Py_REF_DEBUG
Victor Stinnercaba55b2018-08-03 15:33:52 +020096 int show_ref_count = _PyInterpreterState_Get()->core_config.show_ref_count;
Victor Stinner25420fe2017-11-20 18:12:22 -080097#endif
Jeremy Hylton9f324e92001-03-01 22:59:14 +000098
Victor Stinner95701bd2013-11-06 18:41:07 +010099 filename = PyUnicode_DecodeFSDefault(filename_str);
100 if (filename == NULL) {
101 PyErr_Print();
102 return -1;
103 }
104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000105 if (flags == NULL) {
106 flags = &local_flags;
107 local_flags.cf_flags = 0;
108 }
Victor Stinner09054372013-11-06 22:41:44 +0100109 v = _PySys_GetObjectId(&PyId_ps1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000110 if (v == NULL) {
Victor Stinner09054372013-11-06 22:41:44 +0100111 _PySys_SetObjectId(&PyId_ps1, v = PyUnicode_FromString(">>> "));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000112 Py_XDECREF(v);
113 }
Victor Stinner09054372013-11-06 22:41:44 +0100114 v = _PySys_GetObjectId(&PyId_ps2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000115 if (v == NULL) {
Victor Stinner09054372013-11-06 22:41:44 +0100116 _PySys_SetObjectId(&PyId_ps2, v = PyUnicode_FromString("... "));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000117 Py_XDECREF(v);
118 }
xdegayee0582a32017-11-12 16:50:48 +0100119 err = 0;
120 do {
121 ret = PyRun_InteractiveOneObjectEx(fp, filename, flags);
122 if (ret == -1 && PyErr_Occurred()) {
123 /* Prevent an endless loop after multiple consecutive MemoryErrors
124 * while still allowing an interactive command to fail with a
125 * MemoryError. */
126 if (PyErr_ExceptionMatches(PyExc_MemoryError)) {
127 if (++nomem_count > 16) {
128 PyErr_Clear();
129 err = -1;
130 break;
131 }
132 } else {
133 nomem_count = 0;
134 }
135 PyErr_Print();
136 flush_io();
137 } else {
138 nomem_count = 0;
139 }
Eric Snowdae02762017-09-14 00:35:58 -0700140#ifdef Py_REF_DEBUG
Victor Stinner25420fe2017-11-20 18:12:22 -0800141 if (show_ref_count) {
Eric Snowdae02762017-09-14 00:35:58 -0700142 _PyDebug_PrintTotalRefs();
Victor Stinner25420fe2017-11-20 18:12:22 -0800143 }
Eric Snowdae02762017-09-14 00:35:58 -0700144#endif
xdegayee0582a32017-11-12 16:50:48 +0100145 } while (ret != E_EOF);
Victor Stinner95701bd2013-11-06 18:41:07 +0100146 Py_DECREF(filename);
147 return err;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000148}
149
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000150/* compute parser flags based on compiler flags */
Benjamin Petersonf5b52242009-03-02 23:31:26 +0000151static int PARSER_FLAGS(PyCompilerFlags *flags)
152{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000153 int parser_flags = 0;
154 if (!flags)
155 return 0;
156 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
157 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
158 if (flags->cf_flags & PyCF_IGNORE_COOKIE)
159 parser_flags |= PyPARSE_IGNORE_COOKIE;
160 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
161 parser_flags |= PyPARSE_BARRY_AS_BDFL;
Guido van Rossumdcfcd142019-01-31 03:40:27 -0800162 if (flags->cf_flags & PyCF_TYPE_COMMENTS)
163 parser_flags |= PyPARSE_TYPE_COMMENTS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000164 return parser_flags;
Benjamin Petersonf5b52242009-03-02 23:31:26 +0000165}
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000166
Thomas Wouters89f507f2006-12-13 04:49:30 +0000167#if 0
168/* Keep an example of flags with future keyword support. */
169#define PARSER_FLAGS(flags) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000170 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
171 PyPARSE_DONT_IMPLY_DEDENT : 0) \
172 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
173 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000174#endif
175
xdegayee0582a32017-11-12 16:50:48 +0100176/* A PyRun_InteractiveOneObject() auxiliary function that does not print the
177 * error on failure. */
178static int
179PyRun_InteractiveOneObjectEx(FILE *fp, PyObject *filename,
180 PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000181{
Victor Stinner95701bd2013-11-06 18:41:07 +0100182 PyObject *m, *d, *v, *w, *oenc = NULL, *mod_name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000183 mod_ty mod;
184 PyArena *arena;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200185 const char *ps1 = "", *ps2 = "", *enc = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 int errcode = 0;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200187 _Py_IDENTIFIER(encoding);
Victor Stinner95701bd2013-11-06 18:41:07 +0100188 _Py_IDENTIFIER(__main__);
189
190 mod_name = _PyUnicode_FromId(&PyId___main__); /* borrowed */
191 if (mod_name == NULL) {
Victor Stinner95701bd2013-11-06 18:41:07 +0100192 return -1;
193 }
Tim Petersfe2127d2001-07-16 05:37:24 +0000194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 if (fp == stdin) {
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -0400196 /* Fetch encoding from sys.stdin if possible. */
Victor Stinnerbd303c12013-11-07 23:07:29 +0100197 v = _PySys_GetObjectId(&PyId_stdin);
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -0400198 if (v && v != Py_None) {
199 oenc = _PyObject_GetAttrId(v, &PyId_encoding);
200 if (oenc)
Serhiy Storchaka06515832016-11-20 09:13:07 +0200201 enc = PyUnicode_AsUTF8(oenc);
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -0400202 if (!enc)
203 PyErr_Clear();
204 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000205 }
Victor Stinner09054372013-11-06 22:41:44 +0100206 v = _PySys_GetObjectId(&PyId_ps1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000207 if (v != NULL) {
208 v = PyObject_Str(v);
209 if (v == NULL)
210 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +0000211 else if (PyUnicode_Check(v)) {
Serhiy Storchaka06515832016-11-20 09:13:07 +0200212 ps1 = PyUnicode_AsUTF8(v);
Victor Stinner386fe712010-05-19 00:34:15 +0000213 if (ps1 == NULL) {
214 PyErr_Clear();
215 ps1 = "";
216 }
217 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000218 }
Victor Stinner09054372013-11-06 22:41:44 +0100219 w = _PySys_GetObjectId(&PyId_ps2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000220 if (w != NULL) {
221 w = PyObject_Str(w);
222 if (w == NULL)
223 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +0000224 else if (PyUnicode_Check(w)) {
Serhiy Storchaka06515832016-11-20 09:13:07 +0200225 ps2 = PyUnicode_AsUTF8(w);
Victor Stinner386fe712010-05-19 00:34:15 +0000226 if (ps2 == NULL) {
227 PyErr_Clear();
228 ps2 = "";
229 }
230 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 }
232 arena = PyArena_New();
233 if (arena == NULL) {
234 Py_XDECREF(v);
235 Py_XDECREF(w);
236 Py_XDECREF(oenc);
237 return -1;
238 }
Victor Stinner95701bd2013-11-06 18:41:07 +0100239 mod = PyParser_ASTFromFileObject(fp, filename, enc,
240 Py_single_input, ps1, ps2,
241 flags, &errcode, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000242 Py_XDECREF(v);
243 Py_XDECREF(w);
244 Py_XDECREF(oenc);
245 if (mod == NULL) {
246 PyArena_Free(arena);
247 if (errcode == E_EOF) {
248 PyErr_Clear();
249 return E_EOF;
250 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 return -1;
252 }
Victor Stinner95701bd2013-11-06 18:41:07 +0100253 m = PyImport_AddModuleObject(mod_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000254 if (m == NULL) {
255 PyArena_Free(arena);
256 return -1;
257 }
258 d = PyModule_GetDict(m);
259 v = run_mod(mod, filename, d, d, flags, arena);
260 PyArena_Free(arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 return -1;
263 }
264 Py_DECREF(v);
Antoine Pitrou9845c7e2014-05-11 13:42:17 +0200265 flush_io();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000266 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000267}
268
Victor Stinner95701bd2013-11-06 18:41:07 +0100269int
xdegayee0582a32017-11-12 16:50:48 +0100270PyRun_InteractiveOneObject(FILE *fp, PyObject *filename, PyCompilerFlags *flags)
271{
272 int res;
273
274 res = PyRun_InteractiveOneObjectEx(fp, filename, flags);
275 if (res == -1) {
276 PyErr_Print();
277 flush_io();
278 }
279 return res;
280}
281
282int
Victor Stinner95701bd2013-11-06 18:41:07 +0100283PyRun_InteractiveOneFlags(FILE *fp, const char *filename_str, PyCompilerFlags *flags)
284{
285 PyObject *filename;
286 int res;
287
288 filename = PyUnicode_DecodeFSDefault(filename_str);
289 if (filename == NULL) {
290 PyErr_Print();
291 return -1;
292 }
293 res = PyRun_InteractiveOneObject(fp, filename, flags);
294 Py_DECREF(filename);
295 return res;
296}
297
298
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000299/* Check whether a file maybe a pyc file: Look at the extension,
300 the file type, and, if we may close it, at the first few bytes. */
301
302static int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000303maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000304{
Brett Cannonf299abd2015-04-13 14:21:02 -0400305 if (strcmp(ext, ".pyc") == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000306 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000308 /* Only look into the file if we are allowed to close it, since
309 it then should also be seekable. */
310 if (closeit) {
311 /* Read only two bytes of the magic. If the file was opened in
312 text mode, the bytes 3 and 4 of the magic (\r\n) might not
313 be read as they are on disk. */
314 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
315 unsigned char buf[2];
316 /* Mess: In case of -x, the stream is NOT at its start now,
317 and ungetc() was used to push back the first newline,
318 which makes the current stream position formally undefined,
319 and a x-platform nightmare.
320 Unfortunately, we have no direct way to know whether -x
321 was specified. So we use a terrible hack: if the current
322 stream position is not 0, we assume -x was specified, and
323 give up. Bug 132850 on SourceForge spells out the
324 hopelessness of trying anything else (fseek and ftell
325 don't work predictably x-platform for text-mode files).
326 */
327 int ispyc = 0;
328 if (ftell(fp) == 0) {
329 if (fread(buf, 1, 2, fp) == 2 &&
330 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
331 ispyc = 1;
332 rewind(fp);
333 }
334 return ispyc;
335 }
336 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +0000337}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000338
Antoine Pitrou32d483c2013-07-30 21:01:23 +0200339static int
340set_main_loader(PyObject *d, const char *filename, const char *loader_name)
Nick Coghlan85e729e2012-07-15 18:09:52 +1000341{
Eric Snow32439d62015-05-02 19:15:18 -0600342 PyObject *filename_obj, *bootstrap, *loader_type = NULL, *loader;
Nick Coghlanb7a58942012-07-15 23:21:08 +1000343 int result = 0;
Andrew Svetlov90c0eb22012-11-01 14:51:14 +0200344
345 filename_obj = PyUnicode_DecodeFSDefault(filename);
346 if (filename_obj == NULL)
347 return -1;
Victor Stinnercaba55b2018-08-03 15:33:52 +0200348 PyInterpreterState *interp = _PyInterpreterState_Get();
Eric Snow32439d62015-05-02 19:15:18 -0600349 bootstrap = PyObject_GetAttrString(interp->importlib,
350 "_bootstrap_external");
351 if (bootstrap != NULL) {
352 loader_type = PyObject_GetAttrString(bootstrap, loader_name);
353 Py_DECREF(bootstrap);
354 }
Nick Coghlan3f94cbf2012-07-15 19:10:39 +1000355 if (loader_type == NULL) {
Andrew Svetlov90c0eb22012-11-01 14:51:14 +0200356 Py_DECREF(filename_obj);
Nick Coghlan3f94cbf2012-07-15 19:10:39 +1000357 return -1;
358 }
Andrew Svetlov90c0eb22012-11-01 14:51:14 +0200359 loader = PyObject_CallFunction(loader_type, "sN", "__main__", filename_obj);
Nick Coghlanb7a58942012-07-15 23:21:08 +1000360 Py_DECREF(loader_type);
361 if (loader == NULL) {
Nick Coghlan85e729e2012-07-15 18:09:52 +1000362 return -1;
363 }
Nick Coghlanb7a58942012-07-15 23:21:08 +1000364 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
365 result = -1;
366 }
Nick Coghlan85e729e2012-07-15 18:09:52 +1000367 Py_DECREF(loader);
Nick Coghlanb7a58942012-07-15 23:21:08 +1000368 return result;
Nick Coghlan85e729e2012-07-15 18:09:52 +1000369}
370
371int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000372PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000373 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000374{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 PyObject *m, *d, *v;
376 const char *ext;
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +0100377 int set_file_name = 0, ret = -1;
Victor Stinner0fcab4a2011-01-04 12:59:15 +0000378 size_t len;
Guido van Rossumfdef2711994-09-14 13:31:04 +0000379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 m = PyImport_AddModule("__main__");
381 if (m == NULL)
382 return -1;
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +0100383 Py_INCREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 d = PyModule_GetDict(m);
385 if (PyDict_GetItemString(d, "__file__") == NULL) {
386 PyObject *f;
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000387 f = PyUnicode_DecodeFSDefault(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000388 if (f == NULL)
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +0100389 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000390 if (PyDict_SetItemString(d, "__file__", f) < 0) {
391 Py_DECREF(f);
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +0100392 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 }
Barry Warsaw916048d2011-09-20 14:45:44 -0400394 if (PyDict_SetItemString(d, "__cached__", Py_None) < 0) {
395 Py_DECREF(f);
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +0100396 goto done;
Barry Warsaw916048d2011-09-20 14:45:44 -0400397 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000398 set_file_name = 1;
399 Py_DECREF(f);
400 }
401 len = strlen(filename);
402 ext = filename + len - (len > 4 ? 4 : 0);
403 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Christian Heimes04ac4c12012-09-11 15:47:28 +0200404 FILE *pyc_fp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000405 /* Try to run a pyc file. First, re-open in binary */
406 if (closeit)
407 fclose(fp);
Victor Stinnerdaf45552013-08-28 00:53:59 +0200408 if ((pyc_fp = _Py_fopen(filename, "rb")) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000409 fprintf(stderr, "python: Can't reopen .pyc file\n");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000410 goto done;
411 }
Nick Coghlan85e729e2012-07-15 18:09:52 +1000412
413 if (set_main_loader(d, filename, "SourcelessFileLoader") < 0) {
414 fprintf(stderr, "python: failed to set __main__.__loader__\n");
415 ret = -1;
Christian Heimes04ac4c12012-09-11 15:47:28 +0200416 fclose(pyc_fp);
Nick Coghlan85e729e2012-07-15 18:09:52 +1000417 goto done;
418 }
Christian Heimes04ac4c12012-09-11 15:47:28 +0200419 v = run_pyc_file(pyc_fp, filename, d, d, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 } else {
Nick Coghlan85e729e2012-07-15 18:09:52 +1000421 /* When running from stdin, leave __main__.__loader__ alone */
422 if (strcmp(filename, "<stdin>") != 0 &&
423 set_main_loader(d, filename, "SourceFileLoader") < 0) {
424 fprintf(stderr, "python: failed to set __main__.__loader__\n");
425 ret = -1;
426 goto done;
427 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000428 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
429 closeit, flags);
430 }
431 flush_io();
432 if (v == NULL) {
Zackery Spytzd8cba5d2018-07-03 13:47:22 -0600433 Py_CLEAR(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 PyErr_Print();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 goto done;
436 }
437 Py_DECREF(v);
438 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +0000439 done:
INADA Naoki82daa602018-11-29 20:01:27 +0900440 if (set_file_name) {
441 if (PyDict_DelItemString(d, "__file__")) {
442 PyErr_Clear();
443 }
444 if (PyDict_DelItemString(d, "__cached__")) {
445 PyErr_Clear();
446 }
447 }
Zackery Spytzd8cba5d2018-07-03 13:47:22 -0600448 Py_XDECREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000449 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000450}
451
452int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000453PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +0000454{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 PyObject *m, *d, *v;
456 m = PyImport_AddModule("__main__");
457 if (m == NULL)
458 return -1;
459 d = PyModule_GetDict(m);
460 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
461 if (v == NULL) {
462 PyErr_Print();
463 return -1;
464 }
465 Py_DECREF(v);
466 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000467}
468
Barry Warsaw035574d1997-08-29 22:07:17 +0000469static int
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100470parse_syntax_error(PyObject *err, PyObject **message, PyObject **filename,
471 int *lineno, int *offset, PyObject **text)
Barry Warsaw035574d1997-08-29 22:07:17 +0000472{
Serhiy Storchaka56f6e762015-09-06 21:25:30 +0300473 int hold;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 PyObject *v;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200475 _Py_IDENTIFIER(msg);
476 _Py_IDENTIFIER(filename);
477 _Py_IDENTIFIER(lineno);
478 _Py_IDENTIFIER(offset);
479 _Py_IDENTIFIER(text);
Barry Warsaw035574d1997-08-29 22:07:17 +0000480
Benjamin Peterson80d50422012-04-03 00:30:38 -0400481 *message = NULL;
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100482 *filename = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 /* new style errors. `err' is an instance */
Benjamin Peterson0a9a6362012-04-03 00:35:36 -0400485 *message = _PyObject_GetAttrId(err, &PyId_msg);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400486 if (!*message)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +0000488
Benjamin Peterson0a9a6362012-04-03 00:35:36 -0400489 v = _PyObject_GetAttrId(err, &PyId_filename);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400490 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400492 if (v == Py_None) {
493 Py_DECREF(v);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100494 *filename = _PyUnicode_FromId(&PyId_string);
495 if (*filename == NULL)
496 goto finally;
497 Py_INCREF(*filename);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400498 }
499 else {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100500 *filename = v;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400501 }
Barry Warsaw035574d1997-08-29 22:07:17 +0000502
Benjamin Peterson0a9a6362012-04-03 00:35:36 -0400503 v = _PyObject_GetAttrId(err, &PyId_lineno);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400504 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 goto finally;
Serhiy Storchaka56f6e762015-09-06 21:25:30 +0300506 hold = _PyLong_AsInt(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 if (hold < 0 && PyErr_Occurred())
509 goto finally;
Serhiy Storchaka56f6e762015-09-06 21:25:30 +0300510 *lineno = hold;
Barry Warsaw035574d1997-08-29 22:07:17 +0000511
Benjamin Peterson0a9a6362012-04-03 00:35:36 -0400512 v = _PyObject_GetAttrId(err, &PyId_offset);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400513 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 goto finally;
515 if (v == Py_None) {
516 *offset = -1;
517 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 } else {
Serhiy Storchaka56f6e762015-09-06 21:25:30 +0300519 hold = _PyLong_AsInt(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 if (hold < 0 && PyErr_Occurred())
522 goto finally;
Serhiy Storchaka56f6e762015-09-06 21:25:30 +0300523 *offset = hold;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000524 }
Barry Warsaw035574d1997-08-29 22:07:17 +0000525
Benjamin Peterson0a9a6362012-04-03 00:35:36 -0400526 v = _PyObject_GetAttrId(err, &PyId_text);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400527 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400529 if (v == Py_None) {
530 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 *text = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400532 }
533 else {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100534 *text = v;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400535 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000536 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +0000537
538finally:
Benjamin Peterson80d50422012-04-03 00:30:38 -0400539 Py_XDECREF(*message);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100540 Py_XDECREF(*filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +0000542}
543
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000544void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000545PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000546{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000547 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +0000548}
549
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000550static void
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100551print_error_text(PyObject *f, int offset, PyObject *text_obj)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000552{
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200553 const char *text;
554 const char *nl;
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100555
Serhiy Storchaka06515832016-11-20 09:13:07 +0200556 text = PyUnicode_AsUTF8(text_obj);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100557 if (text == NULL)
558 return;
559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 if (offset >= 0) {
Victor Stinner98ea54c2014-08-15 23:30:40 +0200561 if (offset > 0 && (size_t)offset == strlen(text) && text[offset - 1] == '\n')
Benjamin Petersona95e9772010-10-29 03:28:14 +0000562 offset--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 for (;;) {
564 nl = strchr(text, '\n');
565 if (nl == NULL || nl-text >= offset)
566 break;
567 offset -= (int)(nl+1-text);
568 text = nl+1;
569 }
Martin Panterca3263c2016-12-11 00:18:36 +0000570 while (*text == ' ' || *text == '\t' || *text == '\f') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000571 text++;
572 offset--;
573 }
574 }
575 PyFile_WriteString(" ", f);
576 PyFile_WriteString(text, f);
577 if (*text == '\0' || text[strlen(text)-1] != '\n')
578 PyFile_WriteString("\n", f);
579 if (offset == -1)
580 return;
581 PyFile_WriteString(" ", f);
Benjamin Petersona95e9772010-10-29 03:28:14 +0000582 while (--offset > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 PyFile_WriteString(" ", f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000585}
586
Guido van Rossum66e8e862001-03-23 17:54:43 +0000587static void
588handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000589{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 PyObject *exception, *value, *tb;
591 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +0000592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 if (Py_InspectFlag)
594 /* Don't exit if -i flag was given. This flag is set to 0
595 * when entering interactive mode for inspecting. */
596 return;
Guido van Rossumd8faa362007-04-27 19:54:29 +0000597
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 PyErr_Fetch(&exception, &value, &tb);
599 fflush(stdout);
600 if (value == NULL || value == Py_None)
601 goto done;
602 if (PyExceptionInstance_Check(value)) {
603 /* The error code should be in the `code' attribute. */
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200604 _Py_IDENTIFIER(code);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200605 PyObject *code = _PyObject_GetAttrId(value, &PyId_code);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 if (code) {
607 Py_DECREF(value);
608 value = code;
609 if (value == Py_None)
610 goto done;
611 }
612 /* If we failed to dig out the 'code' attribute,
613 just let the else clause below print the error. */
614 }
615 if (PyLong_Check(value))
616 exitcode = (int)PyLong_AsLong(value);
617 else {
Victor Stinnerbd303c12013-11-07 23:07:29 +0100618 PyObject *sys_stderr = _PySys_GetObjectId(&PyId_stderr);
Nick Coghland979e432014-02-09 10:43:21 +1000619 /* We clear the exception here to avoid triggering the assertion
620 * in PyObject_Str that ensures it won't silently lose exception
621 * details.
622 */
623 PyErr_Clear();
Victor Stinner7126dbc2010-05-21 23:45:42 +0000624 if (sys_stderr != NULL && sys_stderr != Py_None) {
625 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
626 } else {
627 PyObject_Print(value, stderr, Py_PRINT_RAW);
628 fflush(stderr);
629 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 PySys_WriteStderr("\n");
631 exitcode = 1;
632 }
Tim Peterscf615b52003-04-19 18:47:02 +0000633 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 /* Restore and clear the exception info, in order to properly decref
635 * the exception, value, and traceback. If we just exit instead,
636 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
637 * some finalizers from running.
638 */
639 PyErr_Restore(exception, value, tb);
640 PyErr_Clear();
641 Py_Exit(exitcode);
642 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000643}
644
645void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000646PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000647{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +0000649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
651 handle_system_exit();
652 }
653 PyErr_Fetch(&exception, &v, &tb);
654 if (exception == NULL)
655 return;
656 PyErr_NormalizeException(&exception, &v, &tb);
657 if (tb == NULL) {
658 tb = Py_None;
659 Py_INCREF(tb);
660 }
661 PyException_SetTraceback(v, tb);
662 if (exception == NULL)
663 return;
664 /* Now we know v != NULL too */
665 if (set_sys_last_vars) {
xdegaye66caacf2017-10-23 18:08:41 +0200666 if (_PySys_SetObjectId(&PyId_last_type, exception) < 0) {
667 PyErr_Clear();
668 }
669 if (_PySys_SetObjectId(&PyId_last_value, v) < 0) {
670 PyErr_Clear();
671 }
672 if (_PySys_SetObjectId(&PyId_last_traceback, tb) < 0) {
673 PyErr_Clear();
674 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 }
Victor Stinner09054372013-11-06 22:41:44 +0100676 hook = _PySys_GetObjectId(&PyId_excepthook);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 if (hook) {
Victor Stinner71cb64a2016-08-20 00:57:43 +0200678 PyObject* stack[3];
679 PyObject *result;
680
681 stack[0] = exception;
682 stack[1] = v;
683 stack[2] = tb;
Victor Stinner559bb6a2016-08-22 22:48:54 +0200684 result = _PyObject_FastCall(hook, stack, 3);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 if (result == NULL) {
686 PyObject *exception2, *v2, *tb2;
687 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
688 handle_system_exit();
689 }
690 PyErr_Fetch(&exception2, &v2, &tb2);
691 PyErr_NormalizeException(&exception2, &v2, &tb2);
692 /* It should not be possible for exception2 or v2
693 to be NULL. However PyErr_Display() can't
694 tolerate NULLs, so just be safe. */
695 if (exception2 == NULL) {
696 exception2 = Py_None;
697 Py_INCREF(exception2);
698 }
699 if (v2 == NULL) {
700 v2 = Py_None;
701 Py_INCREF(v2);
702 }
703 fflush(stdout);
704 PySys_WriteStderr("Error in sys.excepthook:\n");
705 PyErr_Display(exception2, v2, tb2);
706 PySys_WriteStderr("\nOriginal exception was:\n");
707 PyErr_Display(exception, v, tb);
708 Py_DECREF(exception2);
709 Py_DECREF(v2);
710 Py_XDECREF(tb2);
711 }
712 Py_XDECREF(result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 } else {
714 PySys_WriteStderr("sys.excepthook is missing\n");
715 PyErr_Display(exception, v, tb);
716 }
717 Py_XDECREF(exception);
718 Py_XDECREF(v);
719 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000720}
721
Benjamin Petersone6528212008-07-15 15:32:09 +0000722static void
723print_exception(PyObject *f, PyObject *value)
724{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725 int err = 0;
726 PyObject *type, *tb;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200727 _Py_IDENTIFIER(print_file_and_line);
Benjamin Petersone6528212008-07-15 15:32:09 +0000728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000729 if (!PyExceptionInstance_Check(value)) {
Victor Stinner52ce3b02013-12-09 02:10:08 +0100730 err = PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
731 err += PyFile_WriteString(Py_TYPE(value)->tp_name, f);
732 err += PyFile_WriteString(" found\n", f);
733 if (err)
734 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000735 return;
736 }
Benjamin Peterson26582602008-08-23 20:08:07 +0000737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000738 Py_INCREF(value);
739 fflush(stdout);
740 type = (PyObject *) Py_TYPE(value);
741 tb = PyException_GetTraceback(value);
742 if (tb && tb != Py_None)
743 err = PyTraceBack_Print(tb, f);
744 if (err == 0 &&
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200745 _PyObject_HasAttrId(value, &PyId_print_file_and_line))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100747 PyObject *message, *filename, *text;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 int lineno, offset;
749 if (!parse_syntax_error(value, &message, &filename,
750 &lineno, &offset, &text))
751 PyErr_Clear();
752 else {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100753 PyObject *line;
754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000755 Py_DECREF(value);
756 value = message;
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100757
758 line = PyUnicode_FromFormat(" File \"%U\", line %d\n",
759 filename, lineno);
760 Py_DECREF(filename);
761 if (line != NULL) {
762 PyFile_WriteObject(line, f, Py_PRINT_RAW);
763 Py_DECREF(line);
764 }
765
766 if (text != NULL) {
767 print_error_text(f, offset, text);
768 Py_DECREF(text);
769 }
770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000771 /* Can't be bothered to check all those
772 PyFile_WriteString() calls */
773 if (PyErr_Occurred())
774 err = -1;
775 }
776 }
777 if (err) {
778 /* Don't do anything else */
779 }
780 else {
781 PyObject* moduleName;
Serhiy Storchakaceeef102018-06-15 11:09:43 +0300782 const char *className;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200783 _Py_IDENTIFIER(__module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 assert(PyExceptionClass_Check(type));
785 className = PyExceptionClass_Name(type);
786 if (className != NULL) {
Serhiy Storchakaceeef102018-06-15 11:09:43 +0300787 const char *dot = strrchr(className, '.');
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000788 if (dot != NULL)
789 className = dot+1;
790 }
Benjamin Petersone6528212008-07-15 15:32:09 +0000791
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200792 moduleName = _PyObject_GetAttrId(type, &PyId___module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 if (moduleName == NULL || !PyUnicode_Check(moduleName))
794 {
Victor Stinner13b21bd2011-05-26 14:25:13 +0200795 Py_XDECREF(moduleName);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 err = PyFile_WriteString("<unknown>", f);
797 }
798 else {
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +0200799 if (!_PyUnicode_EqualToASCIIId(moduleName, &PyId_builtins))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000800 {
Victor Stinner937114f2013-11-07 00:12:30 +0100801 err = PyFile_WriteObject(moduleName, f, Py_PRINT_RAW);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 err += PyFile_WriteString(".", f);
803 }
804 Py_DECREF(moduleName);
805 }
806 if (err == 0) {
807 if (className == NULL)
808 err = PyFile_WriteString("<unknown>", f);
809 else
810 err = PyFile_WriteString(className, f);
811 }
812 }
813 if (err == 0 && (value != Py_None)) {
814 PyObject *s = PyObject_Str(value);
815 /* only print colon if the str() of the
816 object is not the empty string
817 */
Martin Panter3263f682016-02-28 03:16:11 +0000818 if (s == NULL) {
819 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 err = -1;
Martin Panter3263f682016-02-28 03:16:11 +0000821 PyFile_WriteString(": <exception str() failed>", f);
822 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 else if (!PyUnicode_Check(s) ||
Victor Stinnere251d6d2011-11-20 19:20:00 +0100824 PyUnicode_GetLength(s) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000825 err = PyFile_WriteString(": ", f);
826 if (err == 0)
827 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
828 Py_XDECREF(s);
829 }
830 /* try to write a newline in any case */
Martin Panter3263f682016-02-28 03:16:11 +0000831 if (err < 0) {
832 PyErr_Clear();
833 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 err += PyFile_WriteString("\n", f);
835 Py_XDECREF(tb);
836 Py_DECREF(value);
837 /* If an error happened here, don't show it.
838 XXX This is wrong, but too many callers rely on this behavior. */
839 if (err != 0)
840 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +0000841}
842
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200843static const char cause_message[] =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 "\nThe above exception was the direct cause "
845 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +0000846
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200847static const char context_message[] =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 "\nDuring handling of the above exception, "
849 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +0000850
851static void
852print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
853{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000854 int err = 0, res;
855 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +0000856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000857 if (seen != NULL) {
858 /* Exception chaining */
Zane Bitterde860732017-10-17 17:29:39 -0400859 PyObject *value_id = PyLong_FromVoidPtr(value);
860 if (value_id == NULL || PySet_Add(seen, value_id) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 PyErr_Clear();
862 else if (PyExceptionInstance_Check(value)) {
Zane Bitterde860732017-10-17 17:29:39 -0400863 PyObject *check_id = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 cause = PyException_GetCause(value);
865 context = PyException_GetContext(value);
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700866 if (cause) {
Zane Bitterde860732017-10-17 17:29:39 -0400867 check_id = PyLong_FromVoidPtr(cause);
868 if (check_id == NULL) {
869 res = -1;
870 } else {
871 res = PySet_Contains(seen, check_id);
872 Py_DECREF(check_id);
873 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 if (res == -1)
875 PyErr_Clear();
876 if (res == 0) {
877 print_exception_recursive(
878 f, cause, seen);
879 err |= PyFile_WriteString(
880 cause_message, f);
881 }
882 }
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700883 else if (context &&
884 !((PyBaseExceptionObject *)value)->suppress_context) {
Zane Bitterde860732017-10-17 17:29:39 -0400885 check_id = PyLong_FromVoidPtr(context);
886 if (check_id == NULL) {
887 res = -1;
888 } else {
889 res = PySet_Contains(seen, check_id);
890 Py_DECREF(check_id);
891 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 if (res == -1)
893 PyErr_Clear();
894 if (res == 0) {
895 print_exception_recursive(
896 f, context, seen);
897 err |= PyFile_WriteString(
898 context_message, f);
899 }
900 }
901 Py_XDECREF(context);
902 Py_XDECREF(cause);
903 }
Zane Bitterde860732017-10-17 17:29:39 -0400904 Py_XDECREF(value_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 }
906 print_exception(f, value);
907 if (err != 0)
908 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +0000909}
910
Thomas Wouters477c8d52006-05-27 19:21:47 +0000911void
912PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000913{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 PyObject *seen;
Victor Stinnerbd303c12013-11-07 23:07:29 +0100915 PyObject *f = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrou24201d42013-10-13 21:53:13 +0200916 if (PyExceptionInstance_Check(value)
917 && tb != NULL && PyTraceBack_Check(tb)) {
918 /* Put the traceback on the exception, otherwise it won't get
919 displayed. See issue #18776. */
920 PyObject *cur_tb = PyException_GetTraceback(value);
921 if (cur_tb == NULL)
922 PyException_SetTraceback(value, tb);
923 else
924 Py_DECREF(cur_tb);
925 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 if (f == Py_None) {
927 /* pass */
928 }
929 else if (f == NULL) {
930 _PyObject_Dump(value);
931 fprintf(stderr, "lost sys.stderr\n");
932 }
933 else {
934 /* We choose to ignore seen being possibly NULL, and report
935 at least the main exception (it could be a MemoryError).
936 */
937 seen = PySet_New(NULL);
938 if (seen == NULL)
939 PyErr_Clear();
940 print_exception_recursive(f, value, seen);
941 Py_XDECREF(seen);
942 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000943}
944
Guido van Rossum82598051997-03-05 00:20:32 +0000945PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000946PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000948{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 PyObject *ret = NULL;
950 mod_ty mod;
Victor Stinner95701bd2013-11-06 18:41:07 +0100951 PyArena *arena;
Victor Stinner95701bd2013-11-06 18:41:07 +0100952 PyObject *filename;
953
954 filename = _PyUnicode_FromId(&PyId_string); /* borrowed */
955 if (filename == NULL)
956 return NULL;
957
958 arena = PyArena_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 if (arena == NULL)
960 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +0000961
Victor Stinner95701bd2013-11-06 18:41:07 +0100962 mod = PyParser_ASTFromStringObject(str, filename, start, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 if (mod != NULL)
Victor Stinner95701bd2013-11-06 18:41:07 +0100964 ret = run_mod(mod, filename, globals, locals, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 PyArena_Free(arena);
966 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000967}
968
969PyObject *
Victor Stinner95701bd2013-11-06 18:41:07 +0100970PyRun_FileExFlags(FILE *fp, const char *filename_str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000972{
Victor Stinner95701bd2013-11-06 18:41:07 +0100973 PyObject *ret = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 mod_ty mod;
Victor Stinner95701bd2013-11-06 18:41:07 +0100975 PyArena *arena = NULL;
976 PyObject *filename;
Guido van Rossum98297ee2007-11-06 21:34:58 +0000977
Victor Stinner95701bd2013-11-06 18:41:07 +0100978 filename = PyUnicode_DecodeFSDefault(filename_str);
979 if (filename == NULL)
980 goto exit;
981
982 arena = PyArena_New();
983 if (arena == NULL)
984 goto exit;
985
986 mod = PyParser_ASTFromFileObject(fp, filename, NULL, start, 0, 0,
987 flags, NULL, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 if (closeit)
989 fclose(fp);
990 if (mod == NULL) {
Victor Stinner95701bd2013-11-06 18:41:07 +0100991 goto exit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 }
993 ret = run_mod(mod, filename, globals, locals, flags, arena);
Victor Stinner95701bd2013-11-06 18:41:07 +0100994
995exit:
996 Py_XDECREF(filename);
997 if (arena != NULL)
998 PyArena_Free(arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001000}
1001
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001002static void
1003flush_io(void)
1004{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 PyObject *f, *r;
1006 PyObject *type, *value, *traceback;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 /* Save the current exception */
1009 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001010
Victor Stinnerbd303c12013-11-07 23:07:29 +01001011 f = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 if (f != NULL) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001013 r = _PyObject_CallMethodId(f, &PyId_flush, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 if (r)
1015 Py_DECREF(r);
1016 else
1017 PyErr_Clear();
1018 }
Victor Stinnerbd303c12013-11-07 23:07:29 +01001019 f = _PySys_GetObjectId(&PyId_stdout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 if (f != NULL) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001021 r = _PyObject_CallMethodId(f, &PyId_flush, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 if (r)
1023 Py_DECREF(r);
1024 else
1025 PyErr_Clear();
1026 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001029}
1030
Guido van Rossum82598051997-03-05 00:20:32 +00001031static PyObject *
Gregory P. Smith38f11cc2019-02-16 12:57:40 -08001032run_eval_code_obj(PyCodeObject *co, PyObject *globals, PyObject *locals)
1033{
1034 PyObject *v;
Gregory P. Smithd9bc5432019-02-20 17:35:54 -08001035 /*
1036 * We explicitly re-initialize _Py_UnhandledKeyboardInterrupt every eval
1037 * _just in case_ someone is calling into an embedded Python where they
1038 * don't care about an uncaught KeyboardInterrupt exception (why didn't they
1039 * leave config.install_signal_handlers set to 0?!?) but then later call
1040 * Py_Main() itself (which _checks_ this flag and dies with a signal after
1041 * its interpreter exits). We don't want a previous embedded interpreter's
1042 * uncaught exception to trigger an unexplained signal exit from a future
1043 * Py_Main() based one.
1044 */
1045 _Py_UnhandledKeyboardInterrupt = 0;
Gregory P. Smith38f11cc2019-02-16 12:57:40 -08001046 v = PyEval_EvalCode((PyObject*)co, globals, locals);
1047 if (!v && PyErr_Occurred() == PyExc_KeyboardInterrupt) {
1048 _Py_UnhandledKeyboardInterrupt = 1;
1049 }
1050 return v;
1051}
1052
1053static PyObject *
Victor Stinner95701bd2013-11-06 18:41:07 +01001054run_mod(mod_ty mod, PyObject *filename, PyObject *globals, PyObject *locals,
1055 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001056{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 PyCodeObject *co;
1058 PyObject *v;
Victor Stinner95701bd2013-11-06 18:41:07 +01001059 co = PyAST_CompileObject(mod, filename, flags, -1, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001060 if (co == NULL)
1061 return NULL;
Gregory P. Smith38f11cc2019-02-16 12:57:40 -08001062 v = run_eval_code_obj(co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 Py_DECREF(co);
1064 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001065}
1066
Guido van Rossum82598051997-03-05 00:20:32 +00001067static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001068run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001070{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 PyCodeObject *co;
1072 PyObject *v;
1073 long magic;
1074 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001075
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 magic = PyMarshal_ReadLongFromFile(fp);
1077 if (magic != PyImport_GetMagicNumber()) {
Victor Stinner5200f552015-03-18 13:56:25 +01001078 if (!PyErr_Occurred())
1079 PyErr_SetString(PyExc_RuntimeError,
1080 "Bad magic number in .pyc file");
Zackery Spytzea737752018-06-23 21:15:24 -06001081 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 }
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08001083 /* Skip the rest of the header. */
1084 (void) PyMarshal_ReadLongFromFile(fp);
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001085 (void) PyMarshal_ReadLongFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 (void) PyMarshal_ReadLongFromFile(fp);
Zackery Spytzea737752018-06-23 21:15:24 -06001087 if (PyErr_Occurred()) {
1088 goto error;
1089 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001090 v = PyMarshal_ReadLastObjectFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 if (v == NULL || !PyCode_Check(v)) {
1092 Py_XDECREF(v);
1093 PyErr_SetString(PyExc_RuntimeError,
1094 "Bad code object in .pyc file");
Zackery Spytzea737752018-06-23 21:15:24 -06001095 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001096 }
Zackery Spytzea737752018-06-23 21:15:24 -06001097 fclose(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 co = (PyCodeObject *)v;
Gregory P. Smith38f11cc2019-02-16 12:57:40 -08001099 v = run_eval_code_obj(co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001100 if (v && flags)
1101 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1102 Py_DECREF(co);
1103 return v;
Zackery Spytzea737752018-06-23 21:15:24 -06001104error:
1105 fclose(fp);
1106 return NULL;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001107}
1108
Guido van Rossum82598051997-03-05 00:20:32 +00001109PyObject *
Victor Stinner14e461d2013-08-26 22:28:21 +02001110Py_CompileStringObject(const char *str, PyObject *filename, int start,
1111 PyCompilerFlags *flags, int optimize)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001112{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 PyCodeObject *co;
1114 mod_ty mod;
1115 PyArena *arena = PyArena_New();
1116 if (arena == NULL)
1117 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001118
Victor Stinner14e461d2013-08-26 22:28:21 +02001119 mod = PyParser_ASTFromStringObject(str, filename, start, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001120 if (mod == NULL) {
1121 PyArena_Free(arena);
1122 return NULL;
1123 }
1124 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
1125 PyObject *result = PyAST_mod2obj(mod);
1126 PyArena_Free(arena);
1127 return result;
1128 }
Victor Stinner14e461d2013-08-26 22:28:21 +02001129 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 PyArena_Free(arena);
1131 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001132}
1133
Victor Stinner14e461d2013-08-26 22:28:21 +02001134PyObject *
1135Py_CompileStringExFlags(const char *str, const char *filename_str, int start,
1136 PyCompilerFlags *flags, int optimize)
1137{
1138 PyObject *filename, *co;
1139 filename = PyUnicode_DecodeFSDefault(filename_str);
1140 if (filename == NULL)
1141 return NULL;
1142 co = Py_CompileStringObject(str, filename, start, flags, optimize);
1143 Py_DECREF(filename);
1144 return co;
1145}
1146
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001147/* For use in Py_LIMITED_API */
1148#undef Py_CompileString
1149PyObject *
1150PyCompileString(const char *str, const char *filename, int start)
1151{
1152 return Py_CompileStringFlags(str, filename, start, NULL);
1153}
1154
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001155struct symtable *
Victor Stinner14e461d2013-08-26 22:28:21 +02001156Py_SymtableStringObject(const char *str, PyObject *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001157{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001158 struct symtable *st;
1159 mod_ty mod;
1160 PyCompilerFlags flags;
Victor Stinner14e461d2013-08-26 22:28:21 +02001161 PyArena *arena;
1162
1163 arena = PyArena_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 if (arena == NULL)
1165 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001167 flags.cf_flags = 0;
Victor Stinner14e461d2013-08-26 22:28:21 +02001168 mod = PyParser_ASTFromStringObject(str, filename, start, &flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 if (mod == NULL) {
1170 PyArena_Free(arena);
1171 return NULL;
1172 }
Victor Stinner14e461d2013-08-26 22:28:21 +02001173 st = PySymtable_BuildObject(mod, filename, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 PyArena_Free(arena);
1175 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001176}
1177
Victor Stinner14e461d2013-08-26 22:28:21 +02001178struct symtable *
1179Py_SymtableString(const char *str, const char *filename_str, int start)
1180{
1181 PyObject *filename;
1182 struct symtable *st;
1183
1184 filename = PyUnicode_DecodeFSDefault(filename_str);
1185 if (filename == NULL)
1186 return NULL;
1187 st = Py_SymtableStringObject(str, filename, start);
1188 Py_DECREF(filename);
1189 return st;
1190}
1191
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001192/* Preferred access to parser is through AST. */
1193mod_ty
Victor Stinner14e461d2013-08-26 22:28:21 +02001194PyParser_ASTFromStringObject(const char *s, PyObject *filename, int start,
1195 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001196{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 mod_ty mod;
1198 PyCompilerFlags localflags;
1199 perrdetail err;
1200 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001201
Victor Stinner14e461d2013-08-26 22:28:21 +02001202 node *n = PyParser_ParseStringObject(s, filename,
1203 &_PyParser_Grammar, start, &err,
1204 &iflags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 if (flags == NULL) {
1206 localflags.cf_flags = 0;
1207 flags = &localflags;
1208 }
1209 if (n) {
1210 flags->cf_flags |= iflags & PyCF_MASK;
Victor Stinner14e461d2013-08-26 22:28:21 +02001211 mod = PyAST_FromNodeObject(n, flags, filename, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001212 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 }
1214 else {
1215 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02001216 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02001218 err_free(&err);
1219 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001220}
1221
1222mod_ty
Victor Stinner14e461d2013-08-26 22:28:21 +02001223PyParser_ASTFromString(const char *s, const char *filename_str, int start,
1224 PyCompilerFlags *flags, PyArena *arena)
1225{
1226 PyObject *filename;
1227 mod_ty mod;
1228 filename = PyUnicode_DecodeFSDefault(filename_str);
1229 if (filename == NULL)
1230 return NULL;
1231 mod = PyParser_ASTFromStringObject(s, filename, start, flags, arena);
1232 Py_DECREF(filename);
1233 return mod;
1234}
1235
1236mod_ty
1237PyParser_ASTFromFileObject(FILE *fp, PyObject *filename, const char* enc,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001238 int start, const char *ps1,
1239 const char *ps2, PyCompilerFlags *flags, int *errcode,
Victor Stinner14e461d2013-08-26 22:28:21 +02001240 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001241{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001242 mod_ty mod;
1243 PyCompilerFlags localflags;
1244 perrdetail err;
1245 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001246
Victor Stinner14e461d2013-08-26 22:28:21 +02001247 node *n = PyParser_ParseFileObject(fp, filename, enc,
1248 &_PyParser_Grammar,
1249 start, ps1, ps2, &err, &iflags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001250 if (flags == NULL) {
1251 localflags.cf_flags = 0;
1252 flags = &localflags;
1253 }
1254 if (n) {
1255 flags->cf_flags |= iflags & PyCF_MASK;
Victor Stinner14e461d2013-08-26 22:28:21 +02001256 mod = PyAST_FromNodeObject(n, flags, filename, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001257 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 }
1259 else {
1260 err_input(&err);
1261 if (errcode)
1262 *errcode = err.error;
Victor Stinner7f2fee32011-04-05 00:39:01 +02001263 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02001265 err_free(&err);
1266 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001267}
1268
Victor Stinner14e461d2013-08-26 22:28:21 +02001269mod_ty
1270PyParser_ASTFromFile(FILE *fp, const char *filename_str, const char* enc,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001271 int start, const char *ps1,
1272 const char *ps2, PyCompilerFlags *flags, int *errcode,
Victor Stinner14e461d2013-08-26 22:28:21 +02001273 PyArena *arena)
1274{
1275 mod_ty mod;
1276 PyObject *filename;
1277 filename = PyUnicode_DecodeFSDefault(filename_str);
1278 if (filename == NULL)
1279 return NULL;
1280 mod = PyParser_ASTFromFileObject(fp, filename, enc, start, ps1, ps2,
1281 flags, errcode, arena);
1282 Py_DECREF(filename);
1283 return mod;
1284}
1285
Guido van Rossuma110aa61994-08-29 12:50:44 +00001286/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001287
Guido van Rossuma110aa61994-08-29 12:50:44 +00001288node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001289PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001290{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001291 perrdetail err;
1292 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
1293 &_PyParser_Grammar,
1294 start, NULL, NULL, &err, flags);
1295 if (n == NULL)
1296 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02001297 err_free(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001299 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001300}
1301
Guido van Rossuma110aa61994-08-29 12:50:44 +00001302/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001303
Guido van Rossuma110aa61994-08-29 12:50:44 +00001304node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001305PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001306{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 perrdetail err;
1308 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1309 start, &err, flags);
1310 if (n == NULL)
1311 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02001312 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00001314}
1315
1316node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001317PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001318 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001319{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 perrdetail err;
1321 node *n = PyParser_ParseStringFlagsFilename(str, filename,
1322 &_PyParser_Grammar, start, &err, flags);
1323 if (n == NULL)
1324 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02001325 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001326 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001327}
1328
Guido van Rossum66ebd912003-04-17 16:02:26 +00001329/* May want to move a more generalized form of this to parsetok.c or
1330 even parser modules. */
1331
1332void
Victor Stinner7f2fee32011-04-05 00:39:01 +02001333PyParser_ClearError(perrdetail *err)
1334{
1335 err_free(err);
1336}
1337
1338void
Guido van Rossum66ebd912003-04-17 16:02:26 +00001339PyParser_SetError(perrdetail *err)
1340{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001341 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00001342}
1343
Victor Stinner7f2fee32011-04-05 00:39:01 +02001344static void
1345err_free(perrdetail *err)
1346{
1347 Py_CLEAR(err->filename);
1348}
1349
Guido van Rossuma110aa61994-08-29 12:50:44 +00001350/* Set the error appropriate to the given input error code (see errcode.h) */
1351
1352static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001353err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001354{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 PyObject *v, *w, *errtype, *errtext;
1356 PyObject *msg_obj = NULL;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02001357 const char *msg = NULL;
Serhiy Storchaka65fd0592014-01-21 22:26:52 +02001358 int offset = err->offset;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00001359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 errtype = PyExc_SyntaxError;
1361 switch (err->error) {
1362 case E_ERROR:
Serhiy Storchaka993030a2018-07-12 00:17:53 +03001363 goto cleanup;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001364 case E_SYNTAX:
1365 errtype = PyExc_IndentationError;
1366 if (err->expected == INDENT)
1367 msg = "expected an indented block";
1368 else if (err->token == INDENT)
1369 msg = "unexpected indent";
1370 else if (err->token == DEDENT)
1371 msg = "unexpected unindent";
Serhiy Storchakaaba24ff2018-07-23 23:41:11 +03001372 else if (err->expected == NOTEQUAL) {
1373 errtype = PyExc_SyntaxError;
1374 msg = "with Barry as BDFL, use '<>' instead of '!='";
1375 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001376 else {
1377 errtype = PyExc_SyntaxError;
1378 msg = "invalid syntax";
1379 }
1380 break;
1381 case E_TOKEN:
1382 msg = "invalid token";
1383 break;
1384 case E_EOFS:
1385 msg = "EOF while scanning triple-quoted string literal";
1386 break;
1387 case E_EOLS:
1388 msg = "EOL while scanning string literal";
1389 break;
1390 case E_INTR:
1391 if (!PyErr_Occurred())
1392 PyErr_SetNone(PyExc_KeyboardInterrupt);
1393 goto cleanup;
1394 case E_NOMEM:
1395 PyErr_NoMemory();
1396 goto cleanup;
1397 case E_EOF:
1398 msg = "unexpected EOF while parsing";
1399 break;
1400 case E_TABSPACE:
1401 errtype = PyExc_TabError;
1402 msg = "inconsistent use of tabs and spaces in indentation";
1403 break;
1404 case E_OVERFLOW:
1405 msg = "expression too long";
1406 break;
1407 case E_DEDENT:
1408 errtype = PyExc_IndentationError;
1409 msg = "unindent does not match any outer indentation level";
1410 break;
1411 case E_TOODEEP:
1412 errtype = PyExc_IndentationError;
1413 msg = "too many levels of indentation";
1414 break;
1415 case E_DECODE: {
1416 PyObject *type, *value, *tb;
1417 PyErr_Fetch(&type, &value, &tb);
1418 msg = "unknown decode error";
1419 if (value != NULL)
1420 msg_obj = PyObject_Str(value);
1421 Py_XDECREF(type);
1422 Py_XDECREF(value);
1423 Py_XDECREF(tb);
1424 break;
1425 }
1426 case E_LINECONT:
1427 msg = "unexpected character after line continuation character";
1428 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00001429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001430 case E_IDENTIFIER:
1431 msg = "invalid character in identifier";
1432 break;
Meador Ingefa21bf02012-01-19 01:08:41 -06001433 case E_BADSINGLE:
1434 msg = "multiple statements found while compiling a single statement";
1435 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001436 default:
1437 fprintf(stderr, "error=%d\n", err->error);
1438 msg = "unknown parsing error";
1439 break;
1440 }
1441 /* err->text may not be UTF-8 in case of decoding errors.
1442 Explicitly convert to an object. */
1443 if (!err->text) {
1444 errtext = Py_None;
1445 Py_INCREF(Py_None);
1446 } else {
Serhiy Storchaka65fd0592014-01-21 22:26:52 +02001447 errtext = PyUnicode_DecodeUTF8(err->text, err->offset,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 "replace");
Serhiy Storchaka65fd0592014-01-21 22:26:52 +02001449 if (errtext != NULL) {
1450 Py_ssize_t len = strlen(err->text);
1451 offset = (int)PyUnicode_GET_LENGTH(errtext);
1452 if (len != err->offset) {
1453 Py_DECREF(errtext);
1454 errtext = PyUnicode_DecodeUTF8(err->text, len,
1455 "replace");
1456 }
1457 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001458 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02001459 v = Py_BuildValue("(OiiN)", err->filename,
Serhiy Storchaka65fd0592014-01-21 22:26:52 +02001460 err->lineno, offset, errtext);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001461 if (v != NULL) {
1462 if (msg_obj)
1463 w = Py_BuildValue("(OO)", msg_obj, v);
1464 else
1465 w = Py_BuildValue("(sO)", msg, v);
1466 } else
1467 w = NULL;
1468 Py_XDECREF(v);
1469 PyErr_SetObject(errtype, w);
1470 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00001471cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 Py_XDECREF(msg_obj);
1473 if (err->text != NULL) {
1474 PyObject_FREE(err->text);
1475 err->text = NULL;
1476 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001477}
1478
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001479
Zachary Warec4821d62014-11-21 23:35:12 -06001480#if defined(USE_STACKCHECK)
1481#if defined(WIN32) && defined(_MSC_VER)
1482
1483/* Stack checking for Microsoft C */
1484
1485#include <malloc.h>
1486#include <excpt.h>
1487
1488/*
1489 * Return non-zero when we run out of memory on the stack; zero otherwise.
1490 */
1491int
1492PyOS_CheckStack(void)
1493{
1494 __try {
1495 /* alloca throws a stack overflow exception if there's
1496 not enough space left on the stack */
1497 alloca(PYOS_STACK_MARGIN * sizeof(void*));
1498 return 0;
1499 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
1500 EXCEPTION_EXECUTE_HANDLER :
1501 EXCEPTION_CONTINUE_SEARCH) {
1502 int errcode = _resetstkoflw();
1503 if (errcode == 0)
1504 {
1505 Py_FatalError("Could not reset the stack!");
1506 }
1507 }
1508 return 1;
1509}
1510
1511#endif /* WIN32 && _MSC_VER */
1512
1513/* Alternate implementations can be added here... */
1514
1515#endif /* USE_STACKCHECK */
1516
Martin Panter46f50722016-05-26 05:35:26 +00001517/* Deprecated C API functions still provided for binary compatibility */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001518
1519#undef PyParser_SimpleParseFile
Benjamin Petersone5024512018-09-12 12:06:42 -07001520node *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001521PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
1522{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001524}
1525
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001526#undef PyParser_SimpleParseString
Benjamin Petersone5024512018-09-12 12:06:42 -07001527node *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001528PyParser_SimpleParseString(const char *str, int start)
1529{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001530 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001531}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001532
1533#undef PyRun_AnyFile
Benjamin Petersone5024512018-09-12 12:06:42 -07001534int
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001535PyRun_AnyFile(FILE *fp, const char *name)
1536{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001537 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001538}
1539
1540#undef PyRun_AnyFileEx
Benjamin Petersone5024512018-09-12 12:06:42 -07001541int
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001542PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
1543{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001544 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001545}
1546
1547#undef PyRun_AnyFileFlags
Benjamin Petersone5024512018-09-12 12:06:42 -07001548int
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001549PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
1550{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001551 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001552}
1553
1554#undef PyRun_File
Benjamin Petersone5024512018-09-12 12:06:42 -07001555PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001556PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
1557{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001559}
1560
1561#undef PyRun_FileEx
Benjamin Petersone5024512018-09-12 12:06:42 -07001562PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001563PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
1564{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001566}
1567
1568#undef PyRun_FileFlags
Benjamin Petersone5024512018-09-12 12:06:42 -07001569PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001570PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001571 PyCompilerFlags *flags)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001572{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001573 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001574}
1575
1576#undef PyRun_SimpleFile
Benjamin Petersone5024512018-09-12 12:06:42 -07001577int
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001578PyRun_SimpleFile(FILE *f, const char *p)
1579{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001580 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001581}
1582
1583#undef PyRun_SimpleFileEx
Benjamin Petersone5024512018-09-12 12:06:42 -07001584int
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001585PyRun_SimpleFileEx(FILE *f, const char *p, int c)
1586{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001587 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001588}
1589
1590
1591#undef PyRun_String
Benjamin Petersone5024512018-09-12 12:06:42 -07001592PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001593PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
1594{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001596}
1597
1598#undef PyRun_SimpleString
Benjamin Petersone5024512018-09-12 12:06:42 -07001599int
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001600PyRun_SimpleString(const char *s)
1601{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001602 return PyRun_SimpleStringFlags(s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001603}
1604
1605#undef Py_CompileString
Benjamin Petersone5024512018-09-12 12:06:42 -07001606PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001607Py_CompileString(const char *str, const char *p, int s)
1608{
Georg Brandl8334fd92010-12-04 10:26:46 +00001609 return Py_CompileStringExFlags(str, p, s, NULL, -1);
1610}
1611
1612#undef Py_CompileStringFlags
Benjamin Petersone5024512018-09-12 12:06:42 -07001613PyObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00001614Py_CompileStringFlags(const char *str, const char *p, int s,
1615 PyCompilerFlags *flags)
1616{
1617 return Py_CompileStringExFlags(str, p, s, flags, -1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001618}
1619
1620#undef PyRun_InteractiveOne
Benjamin Petersone5024512018-09-12 12:06:42 -07001621int
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001622PyRun_InteractiveOne(FILE *f, const char *p)
1623{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001624 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001625}
1626
1627#undef PyRun_InteractiveLoop
Benjamin Petersone5024512018-09-12 12:06:42 -07001628int
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001629PyRun_InteractiveLoop(FILE *f, const char *p)
1630{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001631 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001632}
1633
1634#ifdef __cplusplus
1635}
1636#endif