blob: f00e3eb0de803f86c90101c36b57be44b0ee8fb3 [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
Victor Stinner94faa072021-03-23 20:47:40 +010013#include "pycore_ast.h" // PyAST_mod2obj
Victor Stinnera81fca62021-03-24 00:51:50 +010014#include "pycore_compile.h" // _PyAST_Compile()
Victor Stinnere5014be2020-04-14 17:52:15 +020015#include "pycore_interp.h" // PyInterpreterState.importlib
Victor Stinner4f98f462020-04-15 04:01:58 +020016#include "pycore_object.h" // _PyDebug_PrintTotalRefs()
Victor Stinner57364ce2021-03-24 01:29:09 +010017#include "pycore_parser.h" // _PyParser_ASTFromString()
Pablo Galindo37494b42021-04-14 02:36:07 +010018#include "pycore_pyerrors.h" // _PyErr_Fetch, _Py_Offer_Suggestions
Victor Stinner4f98f462020-04-15 04:01:58 +020019#include "pycore_pylifecycle.h" // _Py_UnhandledKeyboardInterrupt
Victor Stinnere5014be2020-04-14 17:52:15 +020020#include "pycore_pystate.h" // _PyInterpreterState_GET()
Victor Stinner4f98f462020-04-15 04:01:58 +020021#include "pycore_sysmodule.h" // _PySys_Audit()
Guido van Rossum1984f1e1992-08-04 12:41:02 +000022
Victor Stinner4f98f462020-04-15 04:01:58 +020023#include "token.h" // INDENT
Victor Stinner4f98f462020-04-15 04:01:58 +020024#include "errcode.h" // E_EOF
25#include "code.h" // PyCodeObject
Victor Stinner4f98f462020-04-15 04:01:58 +020026#include "marshal.h" // PyMarshal_ReadLongFromFile()
27
28#ifdef MS_WINDOWS
29# include "malloc.h" // alloca()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000030#endif
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000031
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000032#ifdef MS_WINDOWS
Victor Stinner4f98f462020-04-15 04:01:58 +020033# undef BYTE
34# include "windows.h"
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000035#endif
Martin v. Löwis5c88d812009-01-02 20:47:48 +000036
Guido van Rossuma44823b1995-03-14 15:01:17 +000037
Victor Stinnerbd303c12013-11-07 23:07:29 +010038_Py_IDENTIFIER(builtins);
Victor Stinner09054372013-11-06 22:41:44 +010039_Py_IDENTIFIER(excepthook);
Victor Stinner3f36a572013-11-12 21:39:02 +010040_Py_IDENTIFIER(flush);
Victor Stinnerbd303c12013-11-07 23:07:29 +010041_Py_IDENTIFIER(last_traceback);
Victor Stinner09054372013-11-06 22:41:44 +010042_Py_IDENTIFIER(last_type);
43_Py_IDENTIFIER(last_value);
Victor Stinnerbd303c12013-11-07 23:07:29 +010044_Py_IDENTIFIER(ps1);
45_Py_IDENTIFIER(ps2);
46_Py_IDENTIFIER(stdin);
47_Py_IDENTIFIER(stdout);
48_Py_IDENTIFIER(stderr);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +010049_Py_static_string(PyId_string, "<string>");
Victor Stinner09054372013-11-06 22:41:44 +010050
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000051#ifdef __cplusplus
52extern "C" {
Neal Norwitz4281cef2006-03-04 19:58:13 +000053#endif
54
Guido van Rossumb73cc041993-11-01 16:28:59 +000055/* Forward */
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +000056static void flush_io(void);
Victor Stinner95701bd2013-11-06 18:41:07 +010057static PyObject *run_mod(mod_ty, PyObject *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000058 PyCompilerFlags *, PyArena *);
Victor Stinnerb6d98c12020-12-08 14:38:08 +010059static PyObject *run_pyc_file(FILE *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000060 PyCompilerFlags *);
xdegayee0582a32017-11-12 16:50:48 +010061static int PyRun_InteractiveOneObjectEx(FILE *, PyObject *, PyCompilerFlags *);
Victor Stinnerb6d98c12020-12-08 14:38:08 +010062static PyObject* pyrun_file(FILE *fp, PyObject *filename, int start,
63 PyObject *globals, PyObject *locals, int closeit,
64 PyCompilerFlags *flags);
65
Guido van Rossumce3a72a2007-10-19 23:16:50 +000066
Victor Stinnera82f63f2020-12-09 22:37:27 +010067int
68_PyRun_AnyFileObject(FILE *fp, PyObject *filename, int closeit,
69 PyCompilerFlags *flags)
70{
71 int decref_filename = 0;
72 if (filename == NULL) {
73 filename = PyUnicode_FromString("???");
74 if (filename == NULL) {
75 PyErr_Print();
76 return -1;
77 }
78 decref_filename = 1;
79 }
80
81 int res;
82 if (_Py_FdIsInteractive(fp, filename)) {
83 res = _PyRun_InteractiveLoopObject(fp, filename, flags);
84 if (closeit) {
85 fclose(fp);
86 }
87 }
88 else {
89 res = _PyRun_SimpleFileObject(fp, filename, closeit, flags);
90 }
91
92 if (decref_filename) {
93 Py_DECREF(filename);
94 }
95 return res;
96}
97
98
Guido van Rossum1984f1e1992-08-04 12:41:02 +000099/* Parse input from a file and execute it */
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000100int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000101PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000102 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000103{
Victor Stinnera82f63f2020-12-09 22:37:27 +0100104 PyObject *filename_obj;
105 if (filename != NULL) {
106 filename_obj = PyUnicode_DecodeFSDefault(filename);
107 if (filename_obj == NULL) {
108 PyErr_Print();
109 return -1;
110 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000111 }
Victor Stinnera82f63f2020-12-09 22:37:27 +0100112 else {
113 filename_obj = NULL;
114 }
115 int res = _PyRun_AnyFileObject(fp, filename_obj, closeit, flags);
116 Py_XDECREF(filename_obj);
117 return res;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000118}
119
Victor Stinnera82f63f2020-12-09 22:37:27 +0100120
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000121int
Victor Stinnera82f63f2020-12-09 22:37:27 +0100122_PyRun_InteractiveLoopObject(FILE *fp, PyObject *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000123{
Victor Stinner37d66d72019-06-13 02:16:41 +0200124 PyCompilerFlags local_flags = _PyCompilerFlags_INIT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000125 if (flags == NULL) {
126 flags = &local_flags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000127 }
Victor Stinnera82f63f2020-12-09 22:37:27 +0100128
129 PyObject *v = _PySys_GetObjectId(&PyId_ps1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000130 if (v == NULL) {
Victor Stinner09054372013-11-06 22:41:44 +0100131 _PySys_SetObjectId(&PyId_ps1, v = PyUnicode_FromString(">>> "));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 Py_XDECREF(v);
133 }
Victor Stinner09054372013-11-06 22:41:44 +0100134 v = _PySys_GetObjectId(&PyId_ps2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 if (v == NULL) {
Victor Stinner09054372013-11-06 22:41:44 +0100136 _PySys_SetObjectId(&PyId_ps2, v = PyUnicode_FromString("... "));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000137 Py_XDECREF(v);
138 }
Victor Stinnera82f63f2020-12-09 22:37:27 +0100139
140#ifdef Py_REF_DEBUG
141 int show_ref_count = _Py_GetConfig()->show_ref_count;
142#endif
143 int err = 0;
144 int ret;
145 int nomem_count = 0;
xdegayee0582a32017-11-12 16:50:48 +0100146 do {
147 ret = PyRun_InteractiveOneObjectEx(fp, filename, flags);
148 if (ret == -1 && PyErr_Occurred()) {
149 /* Prevent an endless loop after multiple consecutive MemoryErrors
150 * while still allowing an interactive command to fail with a
151 * MemoryError. */
152 if (PyErr_ExceptionMatches(PyExc_MemoryError)) {
153 if (++nomem_count > 16) {
154 PyErr_Clear();
155 err = -1;
156 break;
157 }
158 } else {
159 nomem_count = 0;
160 }
161 PyErr_Print();
162 flush_io();
163 } else {
164 nomem_count = 0;
165 }
Eric Snowdae02762017-09-14 00:35:58 -0700166#ifdef Py_REF_DEBUG
Victor Stinner25420fe2017-11-20 18:12:22 -0800167 if (show_ref_count) {
Eric Snowdae02762017-09-14 00:35:58 -0700168 _PyDebug_PrintTotalRefs();
Victor Stinner25420fe2017-11-20 18:12:22 -0800169 }
Eric Snowdae02762017-09-14 00:35:58 -0700170#endif
xdegayee0582a32017-11-12 16:50:48 +0100171 } while (ret != E_EOF);
Victor Stinner95701bd2013-11-06 18:41:07 +0100172 return err;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000173}
174
Victor Stinnera82f63f2020-12-09 22:37:27 +0100175
176int
177PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
178{
179 PyObject *filename_obj = PyUnicode_DecodeFSDefault(filename);
180 if (filename_obj == NULL) {
181 PyErr_Print();
182 return -1;
183 }
184
185 int err = _PyRun_InteractiveLoopObject(fp, filename_obj, flags);
186 Py_DECREF(filename_obj);
187 return err;
188
189}
190
191
xdegayee0582a32017-11-12 16:50:48 +0100192/* A PyRun_InteractiveOneObject() auxiliary function that does not print the
193 * error on failure. */
194static int
195PyRun_InteractiveOneObjectEx(FILE *fp, PyObject *filename,
196 PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000197{
Victor Stinner95701bd2013-11-06 18:41:07 +0100198 PyObject *m, *d, *v, *w, *oenc = NULL, *mod_name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199 mod_ty mod;
200 PyArena *arena;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200201 const char *ps1 = "", *ps2 = "", *enc = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000202 int errcode = 0;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200203 _Py_IDENTIFIER(encoding);
Victor Stinner95701bd2013-11-06 18:41:07 +0100204 _Py_IDENTIFIER(__main__);
205
206 mod_name = _PyUnicode_FromId(&PyId___main__); /* borrowed */
207 if (mod_name == NULL) {
Victor Stinner95701bd2013-11-06 18:41:07 +0100208 return -1;
209 }
Tim Petersfe2127d2001-07-16 05:37:24 +0000210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000211 if (fp == stdin) {
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -0400212 /* Fetch encoding from sys.stdin if possible. */
Victor Stinnerbd303c12013-11-07 23:07:29 +0100213 v = _PySys_GetObjectId(&PyId_stdin);
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -0400214 if (v && v != Py_None) {
215 oenc = _PyObject_GetAttrId(v, &PyId_encoding);
216 if (oenc)
Serhiy Storchaka06515832016-11-20 09:13:07 +0200217 enc = PyUnicode_AsUTF8(oenc);
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -0400218 if (!enc)
219 PyErr_Clear();
220 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000221 }
Victor Stinner09054372013-11-06 22:41:44 +0100222 v = _PySys_GetObjectId(&PyId_ps1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000223 if (v != NULL) {
224 v = PyObject_Str(v);
225 if (v == NULL)
226 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +0000227 else if (PyUnicode_Check(v)) {
Serhiy Storchaka06515832016-11-20 09:13:07 +0200228 ps1 = PyUnicode_AsUTF8(v);
Victor Stinner386fe712010-05-19 00:34:15 +0000229 if (ps1 == NULL) {
230 PyErr_Clear();
231 ps1 = "";
232 }
233 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 }
Victor Stinner09054372013-11-06 22:41:44 +0100235 w = _PySys_GetObjectId(&PyId_ps2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000236 if (w != NULL) {
237 w = PyObject_Str(w);
238 if (w == NULL)
239 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +0000240 else if (PyUnicode_Check(w)) {
Serhiy Storchaka06515832016-11-20 09:13:07 +0200241 ps2 = PyUnicode_AsUTF8(w);
Victor Stinner386fe712010-05-19 00:34:15 +0000242 if (ps2 == NULL) {
243 PyErr_Clear();
244 ps2 = "";
245 }
246 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247 }
Victor Stinner8370e072021-03-24 02:23:01 +0100248 arena = _PyArena_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 if (arena == NULL) {
250 Py_XDECREF(v);
251 Py_XDECREF(w);
252 Py_XDECREF(oenc);
253 return -1;
254 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100255
Victor Stinner57364ce2021-03-24 01:29:09 +0100256 mod = _PyParser_ASTFromFile(fp, filename, enc, Py_single_input,
257 ps1, ps2, flags, &errcode, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000259 Py_XDECREF(v);
260 Py_XDECREF(w);
261 Py_XDECREF(oenc);
262 if (mod == NULL) {
Victor Stinner8370e072021-03-24 02:23:01 +0100263 _PyArena_Free(arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000264 if (errcode == E_EOF) {
265 PyErr_Clear();
266 return E_EOF;
267 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000268 return -1;
269 }
Victor Stinner95701bd2013-11-06 18:41:07 +0100270 m = PyImport_AddModuleObject(mod_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000271 if (m == NULL) {
Victor Stinner8370e072021-03-24 02:23:01 +0100272 _PyArena_Free(arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000273 return -1;
274 }
275 d = PyModule_GetDict(m);
276 v = run_mod(mod, filename, d, d, flags, arena);
Victor Stinner8370e072021-03-24 02:23:01 +0100277 _PyArena_Free(arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000278 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000279 return -1;
280 }
281 Py_DECREF(v);
Antoine Pitrou9845c7e2014-05-11 13:42:17 +0200282 flush_io();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000284}
285
Victor Stinner95701bd2013-11-06 18:41:07 +0100286int
xdegayee0582a32017-11-12 16:50:48 +0100287PyRun_InteractiveOneObject(FILE *fp, PyObject *filename, PyCompilerFlags *flags)
288{
289 int res;
290
291 res = PyRun_InteractiveOneObjectEx(fp, filename, flags);
292 if (res == -1) {
293 PyErr_Print();
294 flush_io();
295 }
296 return res;
297}
298
299int
Victor Stinner95701bd2013-11-06 18:41:07 +0100300PyRun_InteractiveOneFlags(FILE *fp, const char *filename_str, PyCompilerFlags *flags)
301{
302 PyObject *filename;
303 int res;
304
305 filename = PyUnicode_DecodeFSDefault(filename_str);
306 if (filename == NULL) {
307 PyErr_Print();
308 return -1;
309 }
310 res = PyRun_InteractiveOneObject(fp, filename, flags);
311 Py_DECREF(filename);
312 return res;
313}
314
315
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000316/* Check whether a file maybe a pyc file: Look at the extension,
317 the file type, and, if we may close it, at the first few bytes. */
318
319static int
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100320maybe_pyc_file(FILE *fp, PyObject *filename, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000321{
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100322 PyObject *ext = PyUnicode_FromString(".pyc");
323 if (ext == NULL) {
324 return -1;
325 }
326 Py_ssize_t endswith = PyUnicode_Tailmatch(filename, ext, 0, PY_SSIZE_T_MAX, +1);
327 Py_DECREF(ext);
328 if (endswith) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000329 return 1;
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100330 }
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332 /* Only look into the file if we are allowed to close it, since
333 it then should also be seekable. */
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100334 if (!closeit) {
335 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336 }
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100337
338 /* Read only two bytes of the magic. If the file was opened in
339 text mode, the bytes 3 and 4 of the magic (\r\n) might not
340 be read as they are on disk. */
341 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
342 unsigned char buf[2];
343 /* Mess: In case of -x, the stream is NOT at its start now,
344 and ungetc() was used to push back the first newline,
345 which makes the current stream position formally undefined,
346 and a x-platform nightmare.
347 Unfortunately, we have no direct way to know whether -x
348 was specified. So we use a terrible hack: if the current
349 stream position is not 0, we assume -x was specified, and
350 give up. Bug 132850 on SourceForge spells out the
351 hopelessness of trying anything else (fseek and ftell
352 don't work predictably x-platform for text-mode files).
353 */
354 int ispyc = 0;
355 if (ftell(fp) == 0) {
356 if (fread(buf, 1, 2, fp) == 2 &&
357 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
358 ispyc = 1;
359 rewind(fp);
360 }
361 return ispyc;
Tim Petersd08e3822003-04-17 15:24:21 +0000362}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000363
Andrew Svetlov90c0eb22012-11-01 14:51:14 +0200364
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100365static int
366set_main_loader(PyObject *d, PyObject *filename, const char *loader_name)
367{
Victor Stinner81a7be32020-04-14 15:14:01 +0200368 PyInterpreterState *interp = _PyInterpreterState_GET();
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100369 PyObject *bootstrap = PyObject_GetAttrString(interp->importlib,
370 "_bootstrap_external");
371 if (bootstrap == NULL) {
Nick Coghlan3f94cbf2012-07-15 19:10:39 +1000372 return -1;
373 }
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100374
375 PyObject *loader_type = PyObject_GetAttrString(bootstrap, loader_name);
376 Py_DECREF(bootstrap);
377 if (loader_type == NULL) {
378 return -1;
379 }
380
381 PyObject *loader = PyObject_CallFunction(loader_type,
382 "sO", "__main__", filename);
Nick Coghlanb7a58942012-07-15 23:21:08 +1000383 Py_DECREF(loader_type);
384 if (loader == NULL) {
Nick Coghlan85e729e2012-07-15 18:09:52 +1000385 return -1;
386 }
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100387
Nick Coghlanb7a58942012-07-15 23:21:08 +1000388 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100389 Py_DECREF(loader);
390 return -1;
Nick Coghlanb7a58942012-07-15 23:21:08 +1000391 }
Nick Coghlan85e729e2012-07-15 18:09:52 +1000392 Py_DECREF(loader);
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100393 return 0;
Nick Coghlan85e729e2012-07-15 18:09:52 +1000394}
395
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100396
Victor Stinner550e4672020-12-09 00:32:54 +0100397int
398_PyRun_SimpleFileObject(FILE *fp, PyObject *filename, int closeit,
399 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000400{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 PyObject *m, *d, *v;
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +0100402 int set_file_name = 0, ret = -1;
Guido van Rossumfdef2711994-09-14 13:31:04 +0000403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404 m = PyImport_AddModule("__main__");
405 if (m == NULL)
406 return -1;
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +0100407 Py_INCREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 d = PyModule_GetDict(m);
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +0200409 if (_PyDict_GetItemStringWithError(d, "__file__") == NULL) {
410 if (PyErr_Occurred()) {
411 goto done;
412 }
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100413 if (PyDict_SetItemString(d, "__file__", filename) < 0) {
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +0100414 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415 }
Barry Warsaw916048d2011-09-20 14:45:44 -0400416 if (PyDict_SetItemString(d, "__cached__", Py_None) < 0) {
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +0100417 goto done;
Barry Warsaw916048d2011-09-20 14:45:44 -0400418 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 set_file_name = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 }
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100421
422 int pyc = maybe_pyc_file(fp, filename, closeit);
423 if (pyc < 0) {
424 goto done;
425 }
426
427 if (pyc) {
Christian Heimes04ac4c12012-09-11 15:47:28 +0200428 FILE *pyc_fp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 /* Try to run a pyc file. First, re-open in binary */
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100430 if (closeit) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 fclose(fp);
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100432 }
433
434 pyc_fp = _Py_fopen_obj(filename, "rb");
435 if (pyc_fp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000436 fprintf(stderr, "python: Can't reopen .pyc file\n");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000437 goto done;
438 }
Nick Coghlan85e729e2012-07-15 18:09:52 +1000439
440 if (set_main_loader(d, filename, "SourcelessFileLoader") < 0) {
441 fprintf(stderr, "python: failed to set __main__.__loader__\n");
442 ret = -1;
Christian Heimes04ac4c12012-09-11 15:47:28 +0200443 fclose(pyc_fp);
Nick Coghlan85e729e2012-07-15 18:09:52 +1000444 goto done;
445 }
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100446 v = run_pyc_file(pyc_fp, d, d, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447 } else {
Nick Coghlan85e729e2012-07-15 18:09:52 +1000448 /* When running from stdin, leave __main__.__loader__ alone */
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100449 if (PyUnicode_CompareWithASCIIString(filename, "<stdin>") != 0 &&
Nick Coghlan85e729e2012-07-15 18:09:52 +1000450 set_main_loader(d, filename, "SourceFileLoader") < 0) {
451 fprintf(stderr, "python: failed to set __main__.__loader__\n");
452 ret = -1;
453 goto done;
454 }
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100455 v = pyrun_file(fp, filename, Py_file_input, d, d,
456 closeit, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 }
458 flush_io();
459 if (v == NULL) {
Zackery Spytzd8cba5d2018-07-03 13:47:22 -0600460 Py_CLEAR(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 PyErr_Print();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 goto done;
463 }
464 Py_DECREF(v);
465 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +0000466 done:
INADA Naoki82daa602018-11-29 20:01:27 +0900467 if (set_file_name) {
468 if (PyDict_DelItemString(d, "__file__")) {
469 PyErr_Clear();
470 }
471 if (PyDict_DelItemString(d, "__cached__")) {
472 PyErr_Clear();
473 }
474 }
Zackery Spytzd8cba5d2018-07-03 13:47:22 -0600475 Py_XDECREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000477}
478
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100479
480int
481PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
482 PyCompilerFlags *flags)
483{
484 PyObject *filename_obj = PyUnicode_DecodeFSDefault(filename);
485 if (filename_obj == NULL) {
486 return -1;
487 }
Victor Stinner550e4672020-12-09 00:32:54 +0100488 int res = _PyRun_SimpleFileObject(fp, filename_obj, closeit, flags);
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100489 Py_DECREF(filename_obj);
490 return res;
491}
492
493
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000494int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000495PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +0000496{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 PyObject *m, *d, *v;
498 m = PyImport_AddModule("__main__");
499 if (m == NULL)
500 return -1;
501 d = PyModule_GetDict(m);
502 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
503 if (v == NULL) {
504 PyErr_Print();
505 return -1;
506 }
507 Py_DECREF(v);
508 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000509}
510
Barry Warsaw035574d1997-08-29 22:07:17 +0000511static int
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100512parse_syntax_error(PyObject *err, PyObject **message, PyObject **filename,
Pablo Galindoa77aac42021-04-23 14:27:05 +0100513 Py_ssize_t *lineno, Py_ssize_t *offset,
514 Py_ssize_t* end_lineno, Py_ssize_t* end_offset,
515 PyObject **text)
Barry Warsaw035574d1997-08-29 22:07:17 +0000516{
Ammar Askar90d29702020-06-02 08:17:24 +0000517 Py_ssize_t hold;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 PyObject *v;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200519 _Py_IDENTIFIER(msg);
520 _Py_IDENTIFIER(filename);
521 _Py_IDENTIFIER(lineno);
522 _Py_IDENTIFIER(offset);
Pablo Galindoa77aac42021-04-23 14:27:05 +0100523 _Py_IDENTIFIER(end_lineno);
524 _Py_IDENTIFIER(end_offset);
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200525 _Py_IDENTIFIER(text);
Barry Warsaw035574d1997-08-29 22:07:17 +0000526
Benjamin Peterson80d50422012-04-03 00:30:38 -0400527 *message = NULL;
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100528 *filename = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 /* new style errors. `err' is an instance */
Benjamin Peterson0a9a6362012-04-03 00:35:36 -0400531 *message = _PyObject_GetAttrId(err, &PyId_msg);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400532 if (!*message)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +0000534
Benjamin Peterson0a9a6362012-04-03 00:35:36 -0400535 v = _PyObject_GetAttrId(err, &PyId_filename);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400536 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400538 if (v == Py_None) {
539 Py_DECREF(v);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100540 *filename = _PyUnicode_FromId(&PyId_string);
541 if (*filename == NULL)
542 goto finally;
543 Py_INCREF(*filename);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400544 }
545 else {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100546 *filename = v;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400547 }
Barry Warsaw035574d1997-08-29 22:07:17 +0000548
Benjamin Peterson0a9a6362012-04-03 00:35:36 -0400549 v = _PyObject_GetAttrId(err, &PyId_lineno);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400550 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 goto finally;
Ammar Askar90d29702020-06-02 08:17:24 +0000552 hold = PyLong_AsSsize_t(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 if (hold < 0 && PyErr_Occurred())
555 goto finally;
Serhiy Storchaka56f6e762015-09-06 21:25:30 +0300556 *lineno = hold;
Barry Warsaw035574d1997-08-29 22:07:17 +0000557
Benjamin Peterson0a9a6362012-04-03 00:35:36 -0400558 v = _PyObject_GetAttrId(err, &PyId_offset);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400559 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 goto finally;
561 if (v == Py_None) {
562 *offset = -1;
563 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564 } else {
Ammar Askar90d29702020-06-02 08:17:24 +0000565 hold = PyLong_AsSsize_t(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 if (hold < 0 && PyErr_Occurred())
568 goto finally;
Serhiy Storchaka56f6e762015-09-06 21:25:30 +0300569 *offset = hold;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 }
Barry Warsaw035574d1997-08-29 22:07:17 +0000571
Pablo Galindoa77aac42021-04-23 14:27:05 +0100572 if (Py_TYPE(err) == (PyTypeObject*)PyExc_SyntaxError) {
573 v = _PyObject_GetAttrId(err, &PyId_end_lineno);
574 if (!v) {
575 PyErr_Clear();
576 *end_lineno = *lineno;
577 }
578 else if (v == Py_None) {
579 *end_lineno = *lineno;
580 Py_DECREF(v);
581 } else {
582 hold = PyLong_AsSsize_t(v);
583 Py_DECREF(v);
584 if (hold < 0 && PyErr_Occurred())
585 goto finally;
586 *end_lineno = hold;
587 }
588
589 v = _PyObject_GetAttrId(err, &PyId_end_offset);
590 if (!v) {
591 PyErr_Clear();
592 *end_offset = -1;
593 }
594 else if (v == Py_None) {
595 *end_offset = -1;
596 Py_DECREF(v);
597 } else {
598 hold = PyLong_AsSsize_t(v);
599 Py_DECREF(v);
600 if (hold < 0 && PyErr_Occurred())
601 goto finally;
602 *end_offset = hold;
603 }
604 } else {
605 // SyntaxError subclasses
606 *end_lineno = *lineno;
607 *end_offset = -1;
608 }
609
Benjamin Peterson0a9a6362012-04-03 00:35:36 -0400610 v = _PyObject_GetAttrId(err, &PyId_text);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400611 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400613 if (v == Py_None) {
614 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 *text = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400616 }
617 else {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100618 *text = v;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400619 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +0000621
622finally:
Benjamin Peterson80d50422012-04-03 00:30:38 -0400623 Py_XDECREF(*message);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100624 Py_XDECREF(*filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +0000626}
627
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000628static void
Pablo Galindoa77aac42021-04-23 14:27:05 +0100629print_error_text(PyObject *f, Py_ssize_t offset, Py_ssize_t end_offset, PyObject *text_obj)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000630{
Pablo Galindoa77aac42021-04-23 14:27:05 +0100631 size_t caret_repetitions = (end_offset > 0 && end_offset > offset) ? end_offset - offset : 1;
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700632 /* Convert text to a char pointer; return if error */
633 const char *text = PyUnicode_AsUTF8(text_obj);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100634 if (text == NULL)
635 return;
636
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700637 /* Convert offset from 1-based to 0-based */
638 offset--;
639
640 /* Strip leading whitespace from text, adjusting offset as we go */
641 while (*text == ' ' || *text == '\t' || *text == '\f') {
642 text++;
643 offset--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 }
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700645
646 /* Calculate text length excluding trailing newline */
647 Py_ssize_t len = strlen(text);
648 if (len > 0 && text[len-1] == '\n') {
649 len--;
650 }
651
652 /* Clip offset to at most len */
653 if (offset > len) {
654 offset = len;
655 }
656
657 /* Skip past newlines embedded in text */
658 for (;;) {
659 const char *nl = strchr(text, '\n');
660 if (nl == NULL) {
661 break;
662 }
663 Py_ssize_t inl = nl - text;
Ammar Askar90d29702020-06-02 08:17:24 +0000664 if (inl >= offset) {
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700665 break;
666 }
667 inl += 1;
668 text += inl;
669 len -= inl;
670 offset -= (int)inl;
671 }
672
673 /* Print text */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 PyFile_WriteString(" ", f);
675 PyFile_WriteString(text, f);
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700676
677 /* Make sure there's a newline at the end */
678 if (text[len] != '\n') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 PyFile_WriteString("\n", f);
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700680 }
681
682 /* Don't print caret if it points to the left of the text */
683 if (offset < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 return;
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700685
686 /* Write caret line */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000687 PyFile_WriteString(" ", f);
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700688 while (--offset >= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000689 PyFile_WriteString(" ", f);
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700690 }
Pablo Galindoa77aac42021-04-23 14:27:05 +0100691 for (size_t caret_iter=0; caret_iter < caret_repetitions ; caret_iter++) {
692 PyFile_WriteString("^", f);
693 }
694 PyFile_WriteString("\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000695}
696
Tim Peterscf615b52003-04-19 18:47:02 +0000697
Victor Stinner12083282019-05-17 23:05:29 +0200698int
699_Py_HandleSystemExit(int *exitcode_p)
700{
Victor Stinnerda7933e2020-04-13 03:04:28 +0200701 int inspect = _Py_GetConfig()->inspect;
Victor Stinnerc96be812019-05-14 17:34:56 +0200702 if (inspect) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000703 /* Don't exit if -i flag was given. This flag is set to 0
704 * when entering interactive mode for inspecting. */
Victor Stinner12083282019-05-17 23:05:29 +0200705 return 0;
Victor Stinnerc96be812019-05-14 17:34:56 +0200706 }
Guido van Rossumd8faa362007-04-27 19:54:29 +0000707
Victor Stinner12083282019-05-17 23:05:29 +0200708 if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
709 return 0;
710 }
711
712 PyObject *exception, *value, *tb;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 PyErr_Fetch(&exception, &value, &tb);
Victor Stinner12083282019-05-17 23:05:29 +0200714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 fflush(stdout);
Victor Stinner12083282019-05-17 23:05:29 +0200716
717 int exitcode = 0;
718 if (value == NULL || value == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000719 goto done;
Victor Stinner12083282019-05-17 23:05:29 +0200720 }
721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722 if (PyExceptionInstance_Check(value)) {
723 /* The error code should be in the `code' attribute. */
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200724 _Py_IDENTIFIER(code);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200725 PyObject *code = _PyObject_GetAttrId(value, &PyId_code);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 if (code) {
727 Py_DECREF(value);
728 value = code;
729 if (value == Py_None)
730 goto done;
731 }
732 /* If we failed to dig out the 'code' attribute,
733 just let the else clause below print the error. */
734 }
Victor Stinner12083282019-05-17 23:05:29 +0200735
736 if (PyLong_Check(value)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 exitcode = (int)PyLong_AsLong(value);
Victor Stinner12083282019-05-17 23:05:29 +0200738 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 else {
Victor Stinnerbd303c12013-11-07 23:07:29 +0100740 PyObject *sys_stderr = _PySys_GetObjectId(&PyId_stderr);
Nick Coghland979e432014-02-09 10:43:21 +1000741 /* We clear the exception here to avoid triggering the assertion
742 * in PyObject_Str that ensures it won't silently lose exception
743 * details.
744 */
745 PyErr_Clear();
Victor Stinner7126dbc2010-05-21 23:45:42 +0000746 if (sys_stderr != NULL && sys_stderr != Py_None) {
747 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
748 } else {
749 PyObject_Print(value, stderr, Py_PRINT_RAW);
750 fflush(stderr);
751 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000752 PySys_WriteStderr("\n");
753 exitcode = 1;
754 }
Victor Stinner12083282019-05-17 23:05:29 +0200755
Tim Peterscf615b52003-04-19 18:47:02 +0000756 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000757 /* Restore and clear the exception info, in order to properly decref
758 * the exception, value, and traceback. If we just exit instead,
759 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
760 * some finalizers from running.
761 */
762 PyErr_Restore(exception, value, tb);
763 PyErr_Clear();
Victor Stinner12083282019-05-17 23:05:29 +0200764 *exitcode_p = exitcode;
765 return 1;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000766}
767
Victor Stinner12083282019-05-17 23:05:29 +0200768
769static void
770handle_system_exit(void)
771{
772 int exitcode;
773 if (_Py_HandleSystemExit(&exitcode)) {
774 Py_Exit(exitcode);
775 }
776}
777
778
Victor Stinner438a12d2019-05-24 17:01:38 +0200779static void
780_PyErr_PrintEx(PyThreadState *tstate, int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000781{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +0000783
Victor Stinner12083282019-05-17 23:05:29 +0200784 handle_system_exit();
785
Victor Stinner438a12d2019-05-24 17:01:38 +0200786 _PyErr_Fetch(tstate, &exception, &v, &tb);
787 if (exception == NULL) {
788 goto done;
789 }
790
791 _PyErr_NormalizeException(tstate, &exception, &v, &tb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 if (tb == NULL) {
793 tb = Py_None;
794 Py_INCREF(tb);
795 }
796 PyException_SetTraceback(v, tb);
Victor Stinner438a12d2019-05-24 17:01:38 +0200797 if (exception == NULL) {
798 goto done;
799 }
800
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000801 /* Now we know v != NULL too */
802 if (set_sys_last_vars) {
xdegaye66caacf2017-10-23 18:08:41 +0200803 if (_PySys_SetObjectId(&PyId_last_type, exception) < 0) {
Victor Stinner438a12d2019-05-24 17:01:38 +0200804 _PyErr_Clear(tstate);
xdegaye66caacf2017-10-23 18:08:41 +0200805 }
806 if (_PySys_SetObjectId(&PyId_last_value, v) < 0) {
Victor Stinner438a12d2019-05-24 17:01:38 +0200807 _PyErr_Clear(tstate);
xdegaye66caacf2017-10-23 18:08:41 +0200808 }
809 if (_PySys_SetObjectId(&PyId_last_traceback, tb) < 0) {
Victor Stinner438a12d2019-05-24 17:01:38 +0200810 _PyErr_Clear(tstate);
xdegaye66caacf2017-10-23 18:08:41 +0200811 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 }
Victor Stinner09054372013-11-06 22:41:44 +0100813 hook = _PySys_GetObjectId(&PyId_excepthook);
Victor Stinner1c1e68c2020-03-27 15:11:45 +0100814 if (_PySys_Audit(tstate, "sys.excepthook", "OOOO", hook ? hook : Py_None,
815 exception, v, tb) < 0) {
Steve Dowerbea33f52019-11-28 08:46:11 -0800816 if (PyErr_ExceptionMatches(PyExc_RuntimeError)) {
817 PyErr_Clear();
818 goto done;
819 }
820 _PyErr_WriteUnraisableMsg("in audit hook", NULL);
821 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000822 if (hook) {
Victor Stinner71cb64a2016-08-20 00:57:43 +0200823 PyObject* stack[3];
824 PyObject *result;
825
826 stack[0] = exception;
827 stack[1] = v;
828 stack[2] = tb;
Victor Stinner559bb6a2016-08-22 22:48:54 +0200829 result = _PyObject_FastCall(hook, stack, 3);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 if (result == NULL) {
Victor Stinner12083282019-05-17 23:05:29 +0200831 handle_system_exit();
832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 PyObject *exception2, *v2, *tb2;
Victor Stinner438a12d2019-05-24 17:01:38 +0200834 _PyErr_Fetch(tstate, &exception2, &v2, &tb2);
835 _PyErr_NormalizeException(tstate, &exception2, &v2, &tb2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 /* It should not be possible for exception2 or v2
837 to be NULL. However PyErr_Display() can't
838 tolerate NULLs, so just be safe. */
839 if (exception2 == NULL) {
840 exception2 = Py_None;
841 Py_INCREF(exception2);
842 }
843 if (v2 == NULL) {
844 v2 = Py_None;
845 Py_INCREF(v2);
846 }
847 fflush(stdout);
848 PySys_WriteStderr("Error in sys.excepthook:\n");
849 PyErr_Display(exception2, v2, tb2);
850 PySys_WriteStderr("\nOriginal exception was:\n");
851 PyErr_Display(exception, v, tb);
852 Py_DECREF(exception2);
853 Py_DECREF(v2);
854 Py_XDECREF(tb2);
855 }
856 Py_XDECREF(result);
Victor Stinner438a12d2019-05-24 17:01:38 +0200857 }
858 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 PySys_WriteStderr("sys.excepthook is missing\n");
860 PyErr_Display(exception, v, tb);
861 }
Victor Stinner438a12d2019-05-24 17:01:38 +0200862
863done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 Py_XDECREF(exception);
865 Py_XDECREF(v);
866 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000867}
868
Victor Stinner438a12d2019-05-24 17:01:38 +0200869void
870_PyErr_Print(PyThreadState *tstate)
871{
872 _PyErr_PrintEx(tstate, 1);
873}
874
875void
876PyErr_PrintEx(int set_sys_last_vars)
877{
878 PyThreadState *tstate = _PyThreadState_GET();
879 _PyErr_PrintEx(tstate, set_sys_last_vars);
880}
881
882void
883PyErr_Print(void)
884{
885 PyErr_PrintEx(1);
886}
887
Benjamin Petersone6528212008-07-15 15:32:09 +0000888static void
889print_exception(PyObject *f, PyObject *value)
890{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 int err = 0;
Serhiy Storchaka98c44332020-10-10 22:23:42 +0300892 PyObject *type, *tb, *tmp;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200893 _Py_IDENTIFIER(print_file_and_line);
Benjamin Petersone6528212008-07-15 15:32:09 +0000894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000895 if (!PyExceptionInstance_Check(value)) {
Victor Stinner52ce3b02013-12-09 02:10:08 +0100896 err = PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
897 err += PyFile_WriteString(Py_TYPE(value)->tp_name, f);
898 err += PyFile_WriteString(" found\n", f);
899 if (err)
900 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000901 return;
902 }
Benjamin Peterson26582602008-08-23 20:08:07 +0000903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 Py_INCREF(value);
905 fflush(stdout);
906 type = (PyObject *) Py_TYPE(value);
907 tb = PyException_GetTraceback(value);
908 if (tb && tb != Py_None)
909 err = PyTraceBack_Print(tb, f);
910 if (err == 0 &&
Serhiy Storchaka98c44332020-10-10 22:23:42 +0300911 (err = _PyObject_LookupAttrId(value, &PyId_print_file_and_line, &tmp)) > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100913 PyObject *message, *filename, *text;
Pablo Galindoa77aac42021-04-23 14:27:05 +0100914 Py_ssize_t lineno, offset, end_lineno, end_offset;
Serhiy Storchaka98c44332020-10-10 22:23:42 +0300915 err = 0;
916 Py_DECREF(tmp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 if (!parse_syntax_error(value, &message, &filename,
Pablo Galindoa77aac42021-04-23 14:27:05 +0100918 &lineno, &offset,
919 &end_lineno, &end_offset, &text))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 PyErr_Clear();
921 else {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100922 PyObject *line;
923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 Py_DECREF(value);
925 value = message;
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100926
Ammar Askar90d29702020-06-02 08:17:24 +0000927 line = PyUnicode_FromFormat(" File \"%S\", line %zd\n",
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100928 filename, lineno);
929 Py_DECREF(filename);
930 if (line != NULL) {
931 PyFile_WriteObject(line, f, Py_PRINT_RAW);
932 Py_DECREF(line);
933 }
934
935 if (text != NULL) {
Pablo Galindoa77aac42021-04-23 14:27:05 +0100936 Py_ssize_t line_size;
937 const char* error_line = PyUnicode_AsUTF8AndSize(text, &line_size);
938 // If the location of the error spawn multiple lines, we want
939 // to just print the first one and highlight everything until
940 // the end of that one since we don't support multi-line error
941 // messages.
942 if (end_lineno > lineno) {
943 end_offset = (error_line != NULL) ? line_size : -1;
944 }
945 // Limit the ammount of '^' that we can display to
946 // the size of the text in the source line.
947 if (error_line != NULL && end_offset > line_size + 1) {
948 end_offset = line_size + 1;
949 }
950 print_error_text(f, offset, end_offset, text);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100951 Py_DECREF(text);
952 }
953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 /* Can't be bothered to check all those
955 PyFile_WriteString() calls */
956 if (PyErr_Occurred())
957 err = -1;
958 }
959 }
960 if (err) {
961 /* Don't do anything else */
962 }
963 else {
964 PyObject* moduleName;
Serhiy Storchakaceeef102018-06-15 11:09:43 +0300965 const char *className;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200966 _Py_IDENTIFIER(__module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000967 assert(PyExceptionClass_Check(type));
968 className = PyExceptionClass_Name(type);
969 if (className != NULL) {
Serhiy Storchakaceeef102018-06-15 11:09:43 +0300970 const char *dot = strrchr(className, '.');
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 if (dot != NULL)
972 className = dot+1;
973 }
Benjamin Petersone6528212008-07-15 15:32:09 +0000974
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200975 moduleName = _PyObject_GetAttrId(type, &PyId___module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 if (moduleName == NULL || !PyUnicode_Check(moduleName))
977 {
Victor Stinner13b21bd2011-05-26 14:25:13 +0200978 Py_XDECREF(moduleName);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 err = PyFile_WriteString("<unknown>", f);
980 }
981 else {
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +0200982 if (!_PyUnicode_EqualToASCIIId(moduleName, &PyId_builtins))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 {
Victor Stinner937114f2013-11-07 00:12:30 +0100984 err = PyFile_WriteObject(moduleName, f, Py_PRINT_RAW);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 err += PyFile_WriteString(".", f);
986 }
987 Py_DECREF(moduleName);
988 }
989 if (err == 0) {
990 if (className == NULL)
991 err = PyFile_WriteString("<unknown>", f);
992 else
993 err = PyFile_WriteString(className, f);
994 }
995 }
996 if (err == 0 && (value != Py_None)) {
997 PyObject *s = PyObject_Str(value);
998 /* only print colon if the str() of the
999 object is not the empty string
1000 */
Martin Panter3263f682016-02-28 03:16:11 +00001001 if (s == NULL) {
1002 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 err = -1;
Martin Panter3263f682016-02-28 03:16:11 +00001004 PyFile_WriteString(": <exception str() failed>", f);
1005 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 else if (!PyUnicode_Check(s) ||
Victor Stinnere251d6d2011-11-20 19:20:00 +01001007 PyUnicode_GetLength(s) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 err = PyFile_WriteString(": ", f);
1009 if (err == 0)
1010 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1011 Py_XDECREF(s);
1012 }
1013 /* try to write a newline in any case */
Martin Panter3263f682016-02-28 03:16:11 +00001014 if (err < 0) {
1015 PyErr_Clear();
1016 }
Pablo Galindo37494b42021-04-14 02:36:07 +01001017 PyObject* suggestions = _Py_Offer_Suggestions(value);
1018 if (suggestions) {
1019 // Add a trailer ". Did you mean: (...)?"
Pablo Galindo7a041162021-04-19 23:35:53 +01001020 err = PyFile_WriteString(". Did you mean: '", f);
Pablo Galindo37494b42021-04-14 02:36:07 +01001021 if (err == 0) {
1022 err = PyFile_WriteObject(suggestions, f, Py_PRINT_RAW);
Pablo Galindo7a041162021-04-19 23:35:53 +01001023 err += PyFile_WriteString("'?", f);
Pablo Galindo37494b42021-04-14 02:36:07 +01001024 }
1025 Py_DECREF(suggestions);
Pablo Galindoe07f4ab2021-04-14 18:58:28 +01001026 } else if (PyErr_Occurred()) {
1027 PyErr_Clear();
Pablo Galindo37494b42021-04-14 02:36:07 +01001028 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 err += PyFile_WriteString("\n", f);
1030 Py_XDECREF(tb);
1031 Py_DECREF(value);
1032 /* If an error happened here, don't show it.
1033 XXX This is wrong, but too many callers rely on this behavior. */
1034 if (err != 0)
1035 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001036}
1037
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02001038static const char cause_message[] =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 "\nThe above exception was the direct cause "
1040 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001041
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02001042static const char context_message[] =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 "\nDuring handling of the above exception, "
1044 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001045
1046static void
1047print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1048{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 int err = 0, res;
1050 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00001051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 if (seen != NULL) {
1053 /* Exception chaining */
Zane Bitterde860732017-10-17 17:29:39 -04001054 PyObject *value_id = PyLong_FromVoidPtr(value);
1055 if (value_id == NULL || PySet_Add(seen, value_id) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 PyErr_Clear();
1057 else if (PyExceptionInstance_Check(value)) {
Zane Bitterde860732017-10-17 17:29:39 -04001058 PyObject *check_id = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 cause = PyException_GetCause(value);
1060 context = PyException_GetContext(value);
Benjamin Petersond5a1c442012-05-14 22:09:31 -07001061 if (cause) {
Zane Bitterde860732017-10-17 17:29:39 -04001062 check_id = PyLong_FromVoidPtr(cause);
1063 if (check_id == NULL) {
1064 res = -1;
1065 } else {
1066 res = PySet_Contains(seen, check_id);
1067 Py_DECREF(check_id);
1068 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 if (res == -1)
1070 PyErr_Clear();
1071 if (res == 0) {
1072 print_exception_recursive(
1073 f, cause, seen);
1074 err |= PyFile_WriteString(
1075 cause_message, f);
1076 }
1077 }
Benjamin Petersond5a1c442012-05-14 22:09:31 -07001078 else if (context &&
1079 !((PyBaseExceptionObject *)value)->suppress_context) {
Zane Bitterde860732017-10-17 17:29:39 -04001080 check_id = PyLong_FromVoidPtr(context);
1081 if (check_id == NULL) {
1082 res = -1;
1083 } else {
1084 res = PySet_Contains(seen, check_id);
1085 Py_DECREF(check_id);
1086 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 if (res == -1)
1088 PyErr_Clear();
1089 if (res == 0) {
1090 print_exception_recursive(
1091 f, context, seen);
1092 err |= PyFile_WriteString(
1093 context_message, f);
1094 }
1095 }
1096 Py_XDECREF(context);
1097 Py_XDECREF(cause);
1098 }
Zane Bitterde860732017-10-17 17:29:39 -04001099 Py_XDECREF(value_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001100 }
1101 print_exception(f, value);
1102 if (err != 0)
1103 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001104}
1105
Thomas Wouters477c8d52006-05-27 19:21:47 +00001106void
Victor Stinnercd590a72019-05-28 00:39:52 +02001107_PyErr_Display(PyObject *file, PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001108{
Victor Stinnercd590a72019-05-28 00:39:52 +02001109 assert(file != NULL && file != Py_None);
1110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 PyObject *seen;
Antoine Pitrou24201d42013-10-13 21:53:13 +02001112 if (PyExceptionInstance_Check(value)
1113 && tb != NULL && PyTraceBack_Check(tb)) {
1114 /* Put the traceback on the exception, otherwise it won't get
1115 displayed. See issue #18776. */
1116 PyObject *cur_tb = PyException_GetTraceback(value);
1117 if (cur_tb == NULL)
1118 PyException_SetTraceback(value, tb);
1119 else
1120 Py_DECREF(cur_tb);
1121 }
Victor Stinnercd590a72019-05-28 00:39:52 +02001122
1123 /* We choose to ignore seen being possibly NULL, and report
1124 at least the main exception (it could be a MemoryError).
1125 */
1126 seen = PySet_New(NULL);
1127 if (seen == NULL) {
1128 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001129 }
Victor Stinnercd590a72019-05-28 00:39:52 +02001130 print_exception_recursive(file, value, seen);
1131 Py_XDECREF(seen);
Victor Stinnera85a1d32019-05-28 16:01:17 +02001132
1133 /* Call file.flush() */
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001134 PyObject *res = _PyObject_CallMethodIdNoArgs(file, &PyId_flush);
Victor Stinnera85a1d32019-05-28 16:01:17 +02001135 if (!res) {
1136 /* Silently ignore file.flush() error */
1137 PyErr_Clear();
1138 }
1139 else {
1140 Py_DECREF(res);
1141 }
Victor Stinnercd590a72019-05-28 00:39:52 +02001142}
1143
1144void
1145PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
1146{
1147 PyObject *file = _PySys_GetObjectId(&PyId_stderr);
1148 if (file == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 _PyObject_Dump(value);
1150 fprintf(stderr, "lost sys.stderr\n");
Victor Stinnercd590a72019-05-28 00:39:52 +02001151 return;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001152 }
Victor Stinnercd590a72019-05-28 00:39:52 +02001153 if (file == Py_None) {
1154 return;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 }
Pablo Galindo09b90a02021-03-29 23:38:51 +01001156 Py_INCREF(file);
Victor Stinnercd590a72019-05-28 00:39:52 +02001157 _PyErr_Display(file, exception, value, tb);
Pablo Galindo09b90a02021-03-29 23:38:51 +01001158 Py_DECREF(file);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001159}
1160
Guido van Rossum82598051997-03-05 00:20:32 +00001161PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001162PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001164{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001165 PyObject *ret = NULL;
1166 mod_ty mod;
Victor Stinner95701bd2013-11-06 18:41:07 +01001167 PyArena *arena;
Victor Stinner95701bd2013-11-06 18:41:07 +01001168 PyObject *filename;
1169
1170 filename = _PyUnicode_FromId(&PyId_string); /* borrowed */
1171 if (filename == NULL)
1172 return NULL;
1173
Victor Stinner8370e072021-03-24 02:23:01 +01001174 arena = _PyArena_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 if (arena == NULL)
1176 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001177
Victor Stinner57364ce2021-03-24 01:29:09 +01001178 mod = _PyParser_ASTFromString(str, filename, start, flags, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001180 if (mod != NULL)
Victor Stinner95701bd2013-11-06 18:41:07 +01001181 ret = run_mod(mod, filename, globals, locals, flags, arena);
Victor Stinner8370e072021-03-24 02:23:01 +01001182 _PyArena_Free(arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001184}
1185
Victor Stinnerb6d98c12020-12-08 14:38:08 +01001186
1187static PyObject *
1188pyrun_file(FILE *fp, PyObject *filename, int start, PyObject *globals,
1189 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001190{
Victor Stinner8370e072021-03-24 02:23:01 +01001191 PyArena *arena = _PyArena_New();
Victor Stinnerb6d98c12020-12-08 14:38:08 +01001192 if (arena == NULL) {
1193 return NULL;
1194 }
1195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 mod_ty mod;
Victor Stinner57364ce2021-03-24 01:29:09 +01001197 mod = _PyParser_ASTFromFile(fp, filename, NULL, start, NULL, NULL,
1198 flags, NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001199
Victor Stinnerb6d98c12020-12-08 14:38:08 +01001200 if (closeit) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 fclose(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 }
Victor Stinner95701bd2013-11-06 18:41:07 +01001203
Victor Stinnerb6d98c12020-12-08 14:38:08 +01001204 PyObject *ret;
1205 if (mod != NULL) {
1206 ret = run_mod(mod, filename, globals, locals, flags, arena);
1207 }
1208 else {
1209 ret = NULL;
1210 }
Victor Stinner8370e072021-03-24 02:23:01 +01001211 _PyArena_Free(arena);
Victor Stinnerb6d98c12020-12-08 14:38:08 +01001212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001214}
1215
Victor Stinnerb6d98c12020-12-08 14:38:08 +01001216
1217PyObject *
1218PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
1219 PyObject *locals, int closeit, PyCompilerFlags *flags)
1220{
1221 PyObject *filename_obj = PyUnicode_DecodeFSDefault(filename);
1222 if (filename_obj == NULL) {
1223 return NULL;
1224 }
1225
1226 PyObject *res = pyrun_file(fp, filename_obj, start, globals,
1227 locals, closeit, flags);
1228 Py_DECREF(filename_obj);
1229 return res;
1230
1231}
1232
1233
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001234static void
1235flush_io(void)
1236{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 PyObject *f, *r;
1238 PyObject *type, *value, *traceback;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001240 /* Save the current exception */
1241 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001242
Victor Stinnerbd303c12013-11-07 23:07:29 +01001243 f = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 if (f != NULL) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001245 r = _PyObject_CallMethodIdNoArgs(f, &PyId_flush);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001246 if (r)
1247 Py_DECREF(r);
1248 else
1249 PyErr_Clear();
1250 }
Victor Stinnerbd303c12013-11-07 23:07:29 +01001251 f = _PySys_GetObjectId(&PyId_stdout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001252 if (f != NULL) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001253 r = _PyObject_CallMethodIdNoArgs(f, &PyId_flush);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 if (r)
1255 Py_DECREF(r);
1256 else
1257 PyErr_Clear();
1258 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001261}
1262
Guido van Rossum82598051997-03-05 00:20:32 +00001263static PyObject *
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001264run_eval_code_obj(PyThreadState *tstate, PyCodeObject *co, PyObject *globals, PyObject *locals)
Gregory P. Smith38f11cc2019-02-16 12:57:40 -08001265{
1266 PyObject *v;
Gregory P. Smithd9bc5432019-02-20 17:35:54 -08001267 /*
1268 * We explicitly re-initialize _Py_UnhandledKeyboardInterrupt every eval
1269 * _just in case_ someone is calling into an embedded Python where they
1270 * don't care about an uncaught KeyboardInterrupt exception (why didn't they
1271 * leave config.install_signal_handlers set to 0?!?) but then later call
1272 * Py_Main() itself (which _checks_ this flag and dies with a signal after
1273 * its interpreter exits). We don't want a previous embedded interpreter's
1274 * uncaught exception to trigger an unexplained signal exit from a future
1275 * Py_Main() based one.
1276 */
1277 _Py_UnhandledKeyboardInterrupt = 0;
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001278
1279 /* Set globals['__builtins__'] if it doesn't exist */
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02001280 if (globals != NULL && _PyDict_GetItemStringWithError(globals, "__builtins__") == NULL) {
1281 if (PyErr_Occurred() ||
1282 PyDict_SetItemString(globals, "__builtins__",
1283 tstate->interp->builtins) < 0)
1284 {
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001285 return NULL;
1286 }
1287 }
1288
Gregory P. Smith38f11cc2019-02-16 12:57:40 -08001289 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001290 if (!v && _PyErr_Occurred(tstate) == PyExc_KeyboardInterrupt) {
Gregory P. Smith38f11cc2019-02-16 12:57:40 -08001291 _Py_UnhandledKeyboardInterrupt = 1;
1292 }
1293 return v;
1294}
1295
1296static PyObject *
Victor Stinner95701bd2013-11-06 18:41:07 +01001297run_mod(mod_ty mod, PyObject *filename, PyObject *globals, PyObject *locals,
1298 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001299{
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001300 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinnera81fca62021-03-24 00:51:50 +01001301 PyCodeObject *co = _PyAST_Compile(mod, filename, flags, -1, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001302 if (co == NULL)
1303 return NULL;
Steve Dowerb82e17e2019-05-23 08:45:22 -07001304
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001305 if (_PySys_Audit(tstate, "exec", "O", co) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07001306 Py_DECREF(co);
1307 return NULL;
1308 }
1309
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001310 PyObject *v = run_eval_code_obj(tstate, co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001311 Py_DECREF(co);
1312 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001313}
1314
Guido van Rossum82598051997-03-05 00:20:32 +00001315static PyObject *
Victor Stinnerb6d98c12020-12-08 14:38:08 +01001316run_pyc_file(FILE *fp, PyObject *globals, PyObject *locals,
1317 PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001318{
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001319 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 PyCodeObject *co;
1321 PyObject *v;
1322 long magic;
1323 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 magic = PyMarshal_ReadLongFromFile(fp);
1326 if (magic != PyImport_GetMagicNumber()) {
Victor Stinner5200f552015-03-18 13:56:25 +01001327 if (!PyErr_Occurred())
1328 PyErr_SetString(PyExc_RuntimeError,
1329 "Bad magic number in .pyc file");
Zackery Spytzea737752018-06-23 21:15:24 -06001330 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001331 }
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08001332 /* Skip the rest of the header. */
1333 (void) PyMarshal_ReadLongFromFile(fp);
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001334 (void) PyMarshal_ReadLongFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 (void) PyMarshal_ReadLongFromFile(fp);
Zackery Spytzea737752018-06-23 21:15:24 -06001336 if (PyErr_Occurred()) {
1337 goto error;
1338 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 v = PyMarshal_ReadLastObjectFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001340 if (v == NULL || !PyCode_Check(v)) {
1341 Py_XDECREF(v);
1342 PyErr_SetString(PyExc_RuntimeError,
1343 "Bad code object in .pyc file");
Zackery Spytzea737752018-06-23 21:15:24 -06001344 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001345 }
Zackery Spytzea737752018-06-23 21:15:24 -06001346 fclose(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 co = (PyCodeObject *)v;
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001348 v = run_eval_code_obj(tstate, co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001349 if (v && flags)
1350 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1351 Py_DECREF(co);
1352 return v;
Zackery Spytzea737752018-06-23 21:15:24 -06001353error:
1354 fclose(fp);
1355 return NULL;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001356}
1357
Guido van Rossum82598051997-03-05 00:20:32 +00001358PyObject *
Victor Stinner14e461d2013-08-26 22:28:21 +02001359Py_CompileStringObject(const char *str, PyObject *filename, int start,
1360 PyCompilerFlags *flags, int optimize)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001361{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 PyCodeObject *co;
1363 mod_ty mod;
Victor Stinner8370e072021-03-24 02:23:01 +01001364 PyArena *arena = _PyArena_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001365 if (arena == NULL)
1366 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001367
Victor Stinner57364ce2021-03-24 01:29:09 +01001368 mod = _PyParser_ASTFromString(str, filename, start, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001369 if (mod == NULL) {
Victor Stinner8370e072021-03-24 02:23:01 +01001370 _PyArena_Free(arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001371 return NULL;
1372 }
1373 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
1374 PyObject *result = PyAST_mod2obj(mod);
Victor Stinner8370e072021-03-24 02:23:01 +01001375 _PyArena_Free(arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001376 return result;
1377 }
Victor Stinnera81fca62021-03-24 00:51:50 +01001378 co = _PyAST_Compile(mod, filename, flags, optimize, arena);
Victor Stinner8370e072021-03-24 02:23:01 +01001379 _PyArena_Free(arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001380 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001381}
1382
Victor Stinner14e461d2013-08-26 22:28:21 +02001383PyObject *
1384Py_CompileStringExFlags(const char *str, const char *filename_str, int start,
1385 PyCompilerFlags *flags, int optimize)
1386{
1387 PyObject *filename, *co;
1388 filename = PyUnicode_DecodeFSDefault(filename_str);
1389 if (filename == NULL)
1390 return NULL;
1391 co = Py_CompileStringObject(str, filename, start, flags, optimize);
1392 Py_DECREF(filename);
1393 return co;
1394}
1395
Dino Viehland41540692019-05-28 16:21:17 -07001396const char *
1397_Py_SourceAsString(PyObject *cmd, const char *funcname, const char *what, PyCompilerFlags *cf, PyObject **cmd_copy)
1398{
1399 const char *str;
1400 Py_ssize_t size;
1401 Py_buffer view;
1402
1403 *cmd_copy = NULL;
1404 if (PyUnicode_Check(cmd)) {
1405 cf->cf_flags |= PyCF_IGNORE_COOKIE;
1406 str = PyUnicode_AsUTF8AndSize(cmd, &size);
1407 if (str == NULL)
1408 return NULL;
1409 }
1410 else if (PyBytes_Check(cmd)) {
1411 str = PyBytes_AS_STRING(cmd);
1412 size = PyBytes_GET_SIZE(cmd);
1413 }
1414 else if (PyByteArray_Check(cmd)) {
1415 str = PyByteArray_AS_STRING(cmd);
1416 size = PyByteArray_GET_SIZE(cmd);
1417 }
1418 else if (PyObject_GetBuffer(cmd, &view, PyBUF_SIMPLE) == 0) {
1419 /* Copy to NUL-terminated buffer. */
1420 *cmd_copy = PyBytes_FromStringAndSize(
1421 (const char *)view.buf, view.len);
1422 PyBuffer_Release(&view);
1423 if (*cmd_copy == NULL) {
1424 return NULL;
1425 }
1426 str = PyBytes_AS_STRING(*cmd_copy);
1427 size = PyBytes_GET_SIZE(*cmd_copy);
1428 }
1429 else {
1430 PyErr_Format(PyExc_TypeError,
1431 "%s() arg 1 must be a %s object",
1432 funcname, what);
1433 return NULL;
1434 }
1435
1436 if (strlen(str) != (size_t)size) {
1437 PyErr_SetString(PyExc_ValueError,
1438 "source code string cannot contain null bytes");
1439 Py_CLEAR(*cmd_copy);
1440 return NULL;
1441 }
1442 return str;
1443}
1444
Zachary Warec4821d62014-11-21 23:35:12 -06001445#if defined(USE_STACKCHECK)
1446#if defined(WIN32) && defined(_MSC_VER)
1447
1448/* Stack checking for Microsoft C */
1449
1450#include <malloc.h>
1451#include <excpt.h>
1452
1453/*
1454 * Return non-zero when we run out of memory on the stack; zero otherwise.
1455 */
1456int
1457PyOS_CheckStack(void)
1458{
1459 __try {
1460 /* alloca throws a stack overflow exception if there's
1461 not enough space left on the stack */
1462 alloca(PYOS_STACK_MARGIN * sizeof(void*));
1463 return 0;
1464 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
1465 EXCEPTION_EXECUTE_HANDLER :
1466 EXCEPTION_CONTINUE_SEARCH) {
1467 int errcode = _resetstkoflw();
1468 if (errcode == 0)
1469 {
1470 Py_FatalError("Could not reset the stack!");
1471 }
1472 }
1473 return 1;
1474}
1475
1476#endif /* WIN32 && _MSC_VER */
1477
1478/* Alternate implementations can be added here... */
1479
1480#endif /* USE_STACKCHECK */
1481
Pablo Galindo46bd5ed2020-12-02 05:16:31 +00001482/* Deprecated C API functions still provided for binary compatibility */
1483
1484#undef PyRun_AnyFile
1485PyAPI_FUNC(int)
1486PyRun_AnyFile(FILE *fp, const char *name)
1487{
1488 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
1489}
1490
1491#undef PyRun_AnyFileEx
1492PyAPI_FUNC(int)
1493PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
1494{
1495 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
1496}
1497
1498#undef PyRun_AnyFileFlags
1499PyAPI_FUNC(int)
1500PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
1501{
1502 return PyRun_AnyFileExFlags(fp, name, 0, flags);
1503}
1504
1505#undef PyRun_File
1506PyAPI_FUNC(PyObject *)
1507PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
1508{
1509 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
1510}
1511
1512#undef PyRun_FileEx
1513PyAPI_FUNC(PyObject *)
1514PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
1515{
1516 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
1517}
1518
1519#undef PyRun_FileFlags
1520PyAPI_FUNC(PyObject *)
1521PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
1522 PyCompilerFlags *flags)
1523{
1524 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
1525}
1526
1527#undef PyRun_SimpleFile
1528PyAPI_FUNC(int)
1529PyRun_SimpleFile(FILE *f, const char *p)
1530{
1531 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
1532}
1533
1534#undef PyRun_SimpleFileEx
1535PyAPI_FUNC(int)
1536PyRun_SimpleFileEx(FILE *f, const char *p, int c)
1537{
1538 return PyRun_SimpleFileExFlags(f, p, c, NULL);
1539}
1540
1541
1542#undef PyRun_String
1543PyAPI_FUNC(PyObject *)
1544PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
1545{
1546 return PyRun_StringFlags(str, s, g, l, NULL);
1547}
1548
1549#undef PyRun_SimpleString
1550PyAPI_FUNC(int)
1551PyRun_SimpleString(const char *s)
1552{
1553 return PyRun_SimpleStringFlags(s, NULL);
1554}
1555
1556#undef Py_CompileString
1557PyAPI_FUNC(PyObject *)
1558Py_CompileString(const char *str, const char *p, int s)
1559{
1560 return Py_CompileStringExFlags(str, p, s, NULL, -1);
1561}
1562
1563#undef Py_CompileStringFlags
1564PyAPI_FUNC(PyObject *)
1565Py_CompileStringFlags(const char *str, const char *p, int s,
1566 PyCompilerFlags *flags)
1567{
1568 return Py_CompileStringExFlags(str, p, s, flags, -1);
1569}
1570
1571#undef PyRun_InteractiveOne
1572PyAPI_FUNC(int)
1573PyRun_InteractiveOne(FILE *f, const char *p)
1574{
1575 return PyRun_InteractiveOneFlags(f, p, NULL);
1576}
1577
1578#undef PyRun_InteractiveLoop
1579PyAPI_FUNC(int)
1580PyRun_InteractiveLoop(FILE *f, const char *p)
1581{
1582 return PyRun_InteractiveLoopFlags(f, p, NULL);
1583}
1584
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001585#ifdef __cplusplus
1586}
1587#endif