blob: 0f1794acec73ae980096b748afbd61528ec4ffaa [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
Christian Claussccd82a02021-10-07 17:30:08 +02005 * shutdown code, the phases are split across separate modules (bootstrap,
Eric Snowc7ec9982017-05-23 23:00:52 -07006 * 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
Miss Islington (bot)6b996d62021-09-08 09:32:19 -070016#include "pycore_object.h" // _PyDebug_PrintTotalRefs(),
17 // _PyType_GetQualName()
Victor Stinner57364ce2021-03-24 01:29:09 +010018#include "pycore_parser.h" // _PyParser_ASTFromString()
Pablo Galindo37494b42021-04-14 02:36:07 +010019#include "pycore_pyerrors.h" // _PyErr_Fetch, _Py_Offer_Suggestions
Victor Stinner4f98f462020-04-15 04:01:58 +020020#include "pycore_pylifecycle.h" // _Py_UnhandledKeyboardInterrupt
Victor Stinnere5014be2020-04-14 17:52:15 +020021#include "pycore_pystate.h" // _PyInterpreterState_GET()
Victor Stinner4f98f462020-04-15 04:01:58 +020022#include "pycore_sysmodule.h" // _PySys_Audit()
Guido van Rossum1984f1e1992-08-04 12:41:02 +000023
Victor Stinner4f98f462020-04-15 04:01:58 +020024#include "token.h" // INDENT
Victor Stinner4f98f462020-04-15 04:01:58 +020025#include "errcode.h" // E_EOF
26#include "code.h" // PyCodeObject
Victor Stinner4f98f462020-04-15 04:01:58 +020027#include "marshal.h" // PyMarshal_ReadLongFromFile()
28
29#ifdef MS_WINDOWS
30# include "malloc.h" // alloca()
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
Victor Stinner4f98f462020-04-15 04:01:58 +020034# undef BYTE
35# include "windows.h"
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000036#endif
Martin v. Löwis5c88d812009-01-02 20:47:48 +000037
Guido van Rossuma44823b1995-03-14 15:01:17 +000038
Victor Stinnerbd303c12013-11-07 23:07:29 +010039_Py_IDENTIFIER(builtins);
Victor Stinner09054372013-11-06 22:41:44 +010040_Py_IDENTIFIER(excepthook);
Victor Stinner3f36a572013-11-12 21:39:02 +010041_Py_IDENTIFIER(flush);
Victor Stinnerbd303c12013-11-07 23:07:29 +010042_Py_IDENTIFIER(last_traceback);
Victor Stinner09054372013-11-06 22:41:44 +010043_Py_IDENTIFIER(last_type);
44_Py_IDENTIFIER(last_value);
Victor Stinnerbd303c12013-11-07 23:07:29 +010045_Py_IDENTIFIER(ps1);
46_Py_IDENTIFIER(ps2);
47_Py_IDENTIFIER(stdin);
48_Py_IDENTIFIER(stdout);
49_Py_IDENTIFIER(stderr);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +010050_Py_static_string(PyId_string, "<string>");
Victor Stinner09054372013-11-06 22:41:44 +010051
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000052#ifdef __cplusplus
53extern "C" {
Neal Norwitz4281cef2006-03-04 19:58:13 +000054#endif
55
Guido van Rossumb73cc041993-11-01 16:28:59 +000056/* Forward */
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +000057static void flush_io(void);
Victor Stinner95701bd2013-11-06 18:41:07 +010058static PyObject *run_mod(mod_ty, PyObject *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000059 PyCompilerFlags *, PyArena *);
Victor Stinnerb6d98c12020-12-08 14:38:08 +010060static PyObject *run_pyc_file(FILE *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000061 PyCompilerFlags *);
xdegayee0582a32017-11-12 16:50:48 +010062static int PyRun_InteractiveOneObjectEx(FILE *, PyObject *, PyCompilerFlags *);
Victor Stinnerb6d98c12020-12-08 14:38:08 +010063static PyObject* pyrun_file(FILE *fp, PyObject *filename, int start,
64 PyObject *globals, PyObject *locals, int closeit,
65 PyCompilerFlags *flags);
66
Guido van Rossumce3a72a2007-10-19 23:16:50 +000067
Victor Stinnera82f63f2020-12-09 22:37:27 +010068int
69_PyRun_AnyFileObject(FILE *fp, PyObject *filename, int closeit,
70 PyCompilerFlags *flags)
71{
72 int decref_filename = 0;
73 if (filename == NULL) {
74 filename = PyUnicode_FromString("???");
75 if (filename == NULL) {
76 PyErr_Print();
77 return -1;
78 }
79 decref_filename = 1;
80 }
81
82 int res;
83 if (_Py_FdIsInteractive(fp, filename)) {
84 res = _PyRun_InteractiveLoopObject(fp, filename, flags);
85 if (closeit) {
86 fclose(fp);
87 }
88 }
89 else {
90 res = _PyRun_SimpleFileObject(fp, filename, closeit, flags);
91 }
92
93 if (decref_filename) {
94 Py_DECREF(filename);
95 }
96 return res;
97}
98
99
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000100/* Parse input from a file and execute it */
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000101int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000102PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000103 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000104{
Victor Stinnera82f63f2020-12-09 22:37:27 +0100105 PyObject *filename_obj;
106 if (filename != NULL) {
107 filename_obj = PyUnicode_DecodeFSDefault(filename);
108 if (filename_obj == NULL) {
109 PyErr_Print();
110 return -1;
111 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000112 }
Victor Stinnera82f63f2020-12-09 22:37:27 +0100113 else {
114 filename_obj = NULL;
115 }
116 int res = _PyRun_AnyFileObject(fp, filename_obj, closeit, flags);
117 Py_XDECREF(filename_obj);
118 return res;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000119}
120
Victor Stinnera82f63f2020-12-09 22:37:27 +0100121
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000122int
Victor Stinnera82f63f2020-12-09 22:37:27 +0100123_PyRun_InteractiveLoopObject(FILE *fp, PyObject *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000124{
Victor Stinner37d66d72019-06-13 02:16:41 +0200125 PyCompilerFlags local_flags = _PyCompilerFlags_INIT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000126 if (flags == NULL) {
127 flags = &local_flags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 }
Victor Stinnera82f63f2020-12-09 22:37:27 +0100129
130 PyObject *v = _PySys_GetObjectId(&PyId_ps1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000131 if (v == NULL) {
Victor Stinner09054372013-11-06 22:41:44 +0100132 _PySys_SetObjectId(&PyId_ps1, v = PyUnicode_FromString(">>> "));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000133 Py_XDECREF(v);
134 }
Victor Stinner09054372013-11-06 22:41:44 +0100135 v = _PySys_GetObjectId(&PyId_ps2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000136 if (v == NULL) {
Victor Stinner09054372013-11-06 22:41:44 +0100137 _PySys_SetObjectId(&PyId_ps2, v = PyUnicode_FromString("... "));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000138 Py_XDECREF(v);
139 }
Victor Stinnera82f63f2020-12-09 22:37:27 +0100140
141#ifdef Py_REF_DEBUG
142 int show_ref_count = _Py_GetConfig()->show_ref_count;
143#endif
144 int err = 0;
145 int ret;
146 int nomem_count = 0;
xdegayee0582a32017-11-12 16:50:48 +0100147 do {
148 ret = PyRun_InteractiveOneObjectEx(fp, filename, flags);
149 if (ret == -1 && PyErr_Occurred()) {
150 /* Prevent an endless loop after multiple consecutive MemoryErrors
151 * while still allowing an interactive command to fail with a
152 * MemoryError. */
153 if (PyErr_ExceptionMatches(PyExc_MemoryError)) {
154 if (++nomem_count > 16) {
155 PyErr_Clear();
156 err = -1;
157 break;
158 }
159 } else {
160 nomem_count = 0;
161 }
162 PyErr_Print();
163 flush_io();
164 } else {
165 nomem_count = 0;
166 }
Eric Snowdae02762017-09-14 00:35:58 -0700167#ifdef Py_REF_DEBUG
Victor Stinner25420fe2017-11-20 18:12:22 -0800168 if (show_ref_count) {
Eric Snowdae02762017-09-14 00:35:58 -0700169 _PyDebug_PrintTotalRefs();
Victor Stinner25420fe2017-11-20 18:12:22 -0800170 }
Eric Snowdae02762017-09-14 00:35:58 -0700171#endif
xdegayee0582a32017-11-12 16:50:48 +0100172 } while (ret != E_EOF);
Victor Stinner95701bd2013-11-06 18:41:07 +0100173 return err;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000174}
175
Victor Stinnera82f63f2020-12-09 22:37:27 +0100176
177int
178PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
179{
180 PyObject *filename_obj = PyUnicode_DecodeFSDefault(filename);
181 if (filename_obj == NULL) {
182 PyErr_Print();
183 return -1;
184 }
185
186 int err = _PyRun_InteractiveLoopObject(fp, filename_obj, flags);
187 Py_DECREF(filename_obj);
188 return err;
189
190}
191
192
xdegayee0582a32017-11-12 16:50:48 +0100193/* A PyRun_InteractiveOneObject() auxiliary function that does not print the
194 * error on failure. */
195static int
196PyRun_InteractiveOneObjectEx(FILE *fp, PyObject *filename,
197 PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000198{
Victor Stinner95701bd2013-11-06 18:41:07 +0100199 PyObject *m, *d, *v, *w, *oenc = NULL, *mod_name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000200 mod_ty mod;
201 PyArena *arena;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200202 const char *ps1 = "", *ps2 = "", *enc = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000203 int errcode = 0;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200204 _Py_IDENTIFIER(encoding);
Victor Stinner95701bd2013-11-06 18:41:07 +0100205 _Py_IDENTIFIER(__main__);
206
207 mod_name = _PyUnicode_FromId(&PyId___main__); /* borrowed */
208 if (mod_name == NULL) {
Victor Stinner95701bd2013-11-06 18:41:07 +0100209 return -1;
210 }
Tim Petersfe2127d2001-07-16 05:37:24 +0000211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000212 if (fp == stdin) {
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -0400213 /* Fetch encoding from sys.stdin if possible. */
Victor Stinnerbd303c12013-11-07 23:07:29 +0100214 v = _PySys_GetObjectId(&PyId_stdin);
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -0400215 if (v && v != Py_None) {
216 oenc = _PyObject_GetAttrId(v, &PyId_encoding);
217 if (oenc)
Serhiy Storchaka06515832016-11-20 09:13:07 +0200218 enc = PyUnicode_AsUTF8(oenc);
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -0400219 if (!enc)
220 PyErr_Clear();
221 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000222 }
Victor Stinner09054372013-11-06 22:41:44 +0100223 v = _PySys_GetObjectId(&PyId_ps1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000224 if (v != NULL) {
225 v = PyObject_Str(v);
226 if (v == NULL)
227 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +0000228 else if (PyUnicode_Check(v)) {
Serhiy Storchaka06515832016-11-20 09:13:07 +0200229 ps1 = PyUnicode_AsUTF8(v);
Victor Stinner386fe712010-05-19 00:34:15 +0000230 if (ps1 == NULL) {
231 PyErr_Clear();
232 ps1 = "";
233 }
234 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 }
Victor Stinner09054372013-11-06 22:41:44 +0100236 w = _PySys_GetObjectId(&PyId_ps2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 if (w != NULL) {
238 w = PyObject_Str(w);
239 if (w == NULL)
240 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +0000241 else if (PyUnicode_Check(w)) {
Serhiy Storchaka06515832016-11-20 09:13:07 +0200242 ps2 = PyUnicode_AsUTF8(w);
Victor Stinner386fe712010-05-19 00:34:15 +0000243 if (ps2 == NULL) {
244 PyErr_Clear();
245 ps2 = "";
246 }
247 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 }
Victor Stinner8370e072021-03-24 02:23:01 +0100249 arena = _PyArena_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000250 if (arena == NULL) {
251 Py_XDECREF(v);
252 Py_XDECREF(w);
253 Py_XDECREF(oenc);
254 return -1;
255 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100256
Victor Stinner57364ce2021-03-24 01:29:09 +0100257 mod = _PyParser_ASTFromFile(fp, filename, enc, Py_single_input,
258 ps1, ps2, flags, &errcode, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000260 Py_XDECREF(v);
261 Py_XDECREF(w);
262 Py_XDECREF(oenc);
263 if (mod == NULL) {
Victor Stinner8370e072021-03-24 02:23:01 +0100264 _PyArena_Free(arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000265 if (errcode == E_EOF) {
266 PyErr_Clear();
267 return E_EOF;
268 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 return -1;
270 }
Victor Stinner95701bd2013-11-06 18:41:07 +0100271 m = PyImport_AddModuleObject(mod_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 if (m == NULL) {
Victor Stinner8370e072021-03-24 02:23:01 +0100273 _PyArena_Free(arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000274 return -1;
275 }
276 d = PyModule_GetDict(m);
277 v = run_mod(mod, filename, d, d, flags, arena);
Victor Stinner8370e072021-03-24 02:23:01 +0100278 _PyArena_Free(arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000279 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 return -1;
281 }
282 Py_DECREF(v);
Antoine Pitrou9845c7e2014-05-11 13:42:17 +0200283 flush_io();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000284 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000285}
286
Victor Stinner95701bd2013-11-06 18:41:07 +0100287int
xdegayee0582a32017-11-12 16:50:48 +0100288PyRun_InteractiveOneObject(FILE *fp, PyObject *filename, PyCompilerFlags *flags)
289{
290 int res;
291
292 res = PyRun_InteractiveOneObjectEx(fp, filename, flags);
293 if (res == -1) {
294 PyErr_Print();
295 flush_io();
296 }
297 return res;
298}
299
300int
Victor Stinner95701bd2013-11-06 18:41:07 +0100301PyRun_InteractiveOneFlags(FILE *fp, const char *filename_str, PyCompilerFlags *flags)
302{
303 PyObject *filename;
304 int res;
305
306 filename = PyUnicode_DecodeFSDefault(filename_str);
307 if (filename == NULL) {
308 PyErr_Print();
309 return -1;
310 }
311 res = PyRun_InteractiveOneObject(fp, filename, flags);
312 Py_DECREF(filename);
313 return res;
314}
315
316
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000317/* Check whether a file maybe a pyc file: Look at the extension,
318 the file type, and, if we may close it, at the first few bytes. */
319
320static int
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100321maybe_pyc_file(FILE *fp, PyObject *filename, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000322{
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100323 PyObject *ext = PyUnicode_FromString(".pyc");
324 if (ext == NULL) {
325 return -1;
326 }
327 Py_ssize_t endswith = PyUnicode_Tailmatch(filename, ext, 0, PY_SSIZE_T_MAX, +1);
328 Py_DECREF(ext);
329 if (endswith) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 return 1;
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100331 }
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 /* Only look into the file if we are allowed to close it, since
334 it then should also be seekable. */
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100335 if (!closeit) {
336 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000337 }
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100338
339 /* Read only two bytes of the magic. If the file was opened in
340 text mode, the bytes 3 and 4 of the magic (\r\n) might not
341 be read as they are on disk. */
342 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
343 unsigned char buf[2];
344 /* Mess: In case of -x, the stream is NOT at its start now,
345 and ungetc() was used to push back the first newline,
346 which makes the current stream position formally undefined,
347 and a x-platform nightmare.
348 Unfortunately, we have no direct way to know whether -x
349 was specified. So we use a terrible hack: if the current
350 stream position is not 0, we assume -x was specified, and
351 give up. Bug 132850 on SourceForge spells out the
352 hopelessness of trying anything else (fseek and ftell
353 don't work predictably x-platform for text-mode files).
354 */
355 int ispyc = 0;
356 if (ftell(fp) == 0) {
357 if (fread(buf, 1, 2, fp) == 2 &&
358 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
359 ispyc = 1;
360 rewind(fp);
361 }
362 return ispyc;
Tim Petersd08e3822003-04-17 15:24:21 +0000363}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000364
Andrew Svetlov90c0eb22012-11-01 14:51:14 +0200365
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100366static int
367set_main_loader(PyObject *d, PyObject *filename, const char *loader_name)
368{
Victor Stinner81a7be32020-04-14 15:14:01 +0200369 PyInterpreterState *interp = _PyInterpreterState_GET();
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100370 PyObject *bootstrap = PyObject_GetAttrString(interp->importlib,
371 "_bootstrap_external");
372 if (bootstrap == NULL) {
Nick Coghlan3f94cbf2012-07-15 19:10:39 +1000373 return -1;
374 }
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100375
376 PyObject *loader_type = PyObject_GetAttrString(bootstrap, loader_name);
377 Py_DECREF(bootstrap);
378 if (loader_type == NULL) {
379 return -1;
380 }
381
382 PyObject *loader = PyObject_CallFunction(loader_type,
383 "sO", "__main__", filename);
Nick Coghlanb7a58942012-07-15 23:21:08 +1000384 Py_DECREF(loader_type);
385 if (loader == NULL) {
Nick Coghlan85e729e2012-07-15 18:09:52 +1000386 return -1;
387 }
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100388
Nick Coghlanb7a58942012-07-15 23:21:08 +1000389 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100390 Py_DECREF(loader);
391 return -1;
Nick Coghlanb7a58942012-07-15 23:21:08 +1000392 }
Nick Coghlan85e729e2012-07-15 18:09:52 +1000393 Py_DECREF(loader);
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100394 return 0;
Nick Coghlan85e729e2012-07-15 18:09:52 +1000395}
396
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100397
Victor Stinner550e4672020-12-09 00:32:54 +0100398int
399_PyRun_SimpleFileObject(FILE *fp, PyObject *filename, int closeit,
400 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000401{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 PyObject *m, *d, *v;
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +0100403 int set_file_name = 0, ret = -1;
Guido van Rossumfdef2711994-09-14 13:31:04 +0000404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000405 m = PyImport_AddModule("__main__");
406 if (m == NULL)
407 return -1;
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +0100408 Py_INCREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000409 d = PyModule_GetDict(m);
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +0200410 if (_PyDict_GetItemStringWithError(d, "__file__") == NULL) {
411 if (PyErr_Occurred()) {
412 goto done;
413 }
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100414 if (PyDict_SetItemString(d, "__file__", filename) < 0) {
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +0100415 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000416 }
Barry Warsaw916048d2011-09-20 14:45:44 -0400417 if (PyDict_SetItemString(d, "__cached__", Py_None) < 0) {
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +0100418 goto done;
Barry Warsaw916048d2011-09-20 14:45:44 -0400419 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 set_file_name = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 }
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100422
423 int pyc = maybe_pyc_file(fp, filename, closeit);
424 if (pyc < 0) {
425 goto done;
426 }
427
428 if (pyc) {
Christian Heimes04ac4c12012-09-11 15:47:28 +0200429 FILE *pyc_fp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000430 /* Try to run a pyc file. First, re-open in binary */
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100431 if (closeit) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000432 fclose(fp);
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100433 }
434
435 pyc_fp = _Py_fopen_obj(filename, "rb");
436 if (pyc_fp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000437 fprintf(stderr, "python: Can't reopen .pyc file\n");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000438 goto done;
439 }
Nick Coghlan85e729e2012-07-15 18:09:52 +1000440
441 if (set_main_loader(d, filename, "SourcelessFileLoader") < 0) {
442 fprintf(stderr, "python: failed to set __main__.__loader__\n");
443 ret = -1;
Christian Heimes04ac4c12012-09-11 15:47:28 +0200444 fclose(pyc_fp);
Nick Coghlan85e729e2012-07-15 18:09:52 +1000445 goto done;
446 }
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100447 v = run_pyc_file(pyc_fp, d, d, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 } else {
Nick Coghlan85e729e2012-07-15 18:09:52 +1000449 /* When running from stdin, leave __main__.__loader__ alone */
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100450 if (PyUnicode_CompareWithASCIIString(filename, "<stdin>") != 0 &&
Nick Coghlan85e729e2012-07-15 18:09:52 +1000451 set_main_loader(d, filename, "SourceFileLoader") < 0) {
452 fprintf(stderr, "python: failed to set __main__.__loader__\n");
453 ret = -1;
454 goto done;
455 }
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100456 v = pyrun_file(fp, filename, Py_file_input, d, d,
457 closeit, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 }
459 flush_io();
460 if (v == NULL) {
Zackery Spytzd8cba5d2018-07-03 13:47:22 -0600461 Py_CLEAR(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 PyErr_Print();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 goto done;
464 }
465 Py_DECREF(v);
466 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +0000467 done:
INADA Naoki82daa602018-11-29 20:01:27 +0900468 if (set_file_name) {
469 if (PyDict_DelItemString(d, "__file__")) {
470 PyErr_Clear();
471 }
472 if (PyDict_DelItemString(d, "__cached__")) {
473 PyErr_Clear();
474 }
475 }
Zackery Spytzd8cba5d2018-07-03 13:47:22 -0600476 Py_XDECREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000478}
479
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100480
481int
482PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
483 PyCompilerFlags *flags)
484{
485 PyObject *filename_obj = PyUnicode_DecodeFSDefault(filename);
486 if (filename_obj == NULL) {
487 return -1;
488 }
Victor Stinner550e4672020-12-09 00:32:54 +0100489 int res = _PyRun_SimpleFileObject(fp, filename_obj, closeit, flags);
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100490 Py_DECREF(filename_obj);
491 return res;
492}
493
494
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000495int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000496PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +0000497{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 PyObject *m, *d, *v;
499 m = PyImport_AddModule("__main__");
500 if (m == NULL)
501 return -1;
502 d = PyModule_GetDict(m);
503 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
504 if (v == NULL) {
505 PyErr_Print();
506 return -1;
507 }
508 Py_DECREF(v);
509 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000510}
511
Barry Warsaw035574d1997-08-29 22:07:17 +0000512static int
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100513parse_syntax_error(PyObject *err, PyObject **message, PyObject **filename,
Pablo Galindoa77aac42021-04-23 14:27:05 +0100514 Py_ssize_t *lineno, Py_ssize_t *offset,
515 Py_ssize_t* end_lineno, Py_ssize_t* end_offset,
516 PyObject **text)
Barry Warsaw035574d1997-08-29 22:07:17 +0000517{
Ammar Askar90d29702020-06-02 08:17:24 +0000518 Py_ssize_t hold;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 PyObject *v;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200520 _Py_IDENTIFIER(msg);
521 _Py_IDENTIFIER(filename);
522 _Py_IDENTIFIER(lineno);
523 _Py_IDENTIFIER(offset);
Pablo Galindoa77aac42021-04-23 14:27:05 +0100524 _Py_IDENTIFIER(end_lineno);
525 _Py_IDENTIFIER(end_offset);
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200526 _Py_IDENTIFIER(text);
Barry Warsaw035574d1997-08-29 22:07:17 +0000527
Benjamin Peterson80d50422012-04-03 00:30:38 -0400528 *message = NULL;
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100529 *filename = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 /* new style errors. `err' is an instance */
Benjamin Peterson0a9a6362012-04-03 00:35:36 -0400532 *message = _PyObject_GetAttrId(err, &PyId_msg);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400533 if (!*message)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +0000535
Benjamin Peterson0a9a6362012-04-03 00:35:36 -0400536 v = _PyObject_GetAttrId(err, &PyId_filename);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400537 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400539 if (v == Py_None) {
540 Py_DECREF(v);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100541 *filename = _PyUnicode_FromId(&PyId_string);
542 if (*filename == NULL)
543 goto finally;
544 Py_INCREF(*filename);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400545 }
546 else {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100547 *filename = v;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400548 }
Barry Warsaw035574d1997-08-29 22:07:17 +0000549
Benjamin Peterson0a9a6362012-04-03 00:35:36 -0400550 v = _PyObject_GetAttrId(err, &PyId_lineno);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400551 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 goto finally;
Ammar Askar90d29702020-06-02 08:17:24 +0000553 hold = PyLong_AsSsize_t(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 if (hold < 0 && PyErr_Occurred())
556 goto finally;
Serhiy Storchaka56f6e762015-09-06 21:25:30 +0300557 *lineno = hold;
Barry Warsaw035574d1997-08-29 22:07:17 +0000558
Benjamin Peterson0a9a6362012-04-03 00:35:36 -0400559 v = _PyObject_GetAttrId(err, &PyId_offset);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400560 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 goto finally;
562 if (v == Py_None) {
563 *offset = -1;
564 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 } else {
Ammar Askar90d29702020-06-02 08:17:24 +0000566 hold = PyLong_AsSsize_t(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 if (hold < 0 && PyErr_Occurred())
569 goto finally;
Serhiy Storchaka56f6e762015-09-06 21:25:30 +0300570 *offset = hold;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000571 }
Barry Warsaw035574d1997-08-29 22:07:17 +0000572
Pablo Galindoa77aac42021-04-23 14:27:05 +0100573 if (Py_TYPE(err) == (PyTypeObject*)PyExc_SyntaxError) {
574 v = _PyObject_GetAttrId(err, &PyId_end_lineno);
575 if (!v) {
576 PyErr_Clear();
577 *end_lineno = *lineno;
578 }
579 else if (v == Py_None) {
580 *end_lineno = *lineno;
581 Py_DECREF(v);
582 } else {
583 hold = PyLong_AsSsize_t(v);
584 Py_DECREF(v);
585 if (hold < 0 && PyErr_Occurred())
586 goto finally;
587 *end_lineno = hold;
588 }
589
590 v = _PyObject_GetAttrId(err, &PyId_end_offset);
591 if (!v) {
592 PyErr_Clear();
593 *end_offset = -1;
594 }
595 else if (v == Py_None) {
596 *end_offset = -1;
597 Py_DECREF(v);
598 } else {
599 hold = PyLong_AsSsize_t(v);
600 Py_DECREF(v);
601 if (hold < 0 && PyErr_Occurred())
602 goto finally;
603 *end_offset = hold;
604 }
605 } else {
606 // SyntaxError subclasses
607 *end_lineno = *lineno;
608 *end_offset = -1;
609 }
610
Benjamin Peterson0a9a6362012-04-03 00:35:36 -0400611 v = _PyObject_GetAttrId(err, &PyId_text);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400612 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400614 if (v == Py_None) {
615 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 *text = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400617 }
618 else {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100619 *text = v;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400620 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +0000622
623finally:
Benjamin Peterson80d50422012-04-03 00:30:38 -0400624 Py_XDECREF(*message);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100625 Py_XDECREF(*filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000626 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +0000627}
628
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000629static void
Pablo Galindoa77aac42021-04-23 14:27:05 +0100630print_error_text(PyObject *f, Py_ssize_t offset, Py_ssize_t end_offset, PyObject *text_obj)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000631{
Pablo Galindoa77aac42021-04-23 14:27:05 +0100632 size_t caret_repetitions = (end_offset > 0 && end_offset > offset) ? end_offset - offset : 1;
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700633 /* Convert text to a char pointer; return if error */
634 const char *text = PyUnicode_AsUTF8(text_obj);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100635 if (text == NULL)
636 return;
637
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700638 /* Convert offset from 1-based to 0-based */
639 offset--;
640
641 /* Strip leading whitespace from text, adjusting offset as we go */
642 while (*text == ' ' || *text == '\t' || *text == '\f') {
643 text++;
644 offset--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 }
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700646
647 /* Calculate text length excluding trailing newline */
648 Py_ssize_t len = strlen(text);
649 if (len > 0 && text[len-1] == '\n') {
650 len--;
651 }
652
653 /* Clip offset to at most len */
654 if (offset > len) {
655 offset = len;
656 }
657
658 /* Skip past newlines embedded in text */
659 for (;;) {
660 const char *nl = strchr(text, '\n');
661 if (nl == NULL) {
662 break;
663 }
664 Py_ssize_t inl = nl - text;
Ammar Askar90d29702020-06-02 08:17:24 +0000665 if (inl >= offset) {
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700666 break;
667 }
668 inl += 1;
669 text += inl;
670 len -= inl;
671 offset -= (int)inl;
672 }
673
674 /* Print text */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 PyFile_WriteString(" ", f);
676 PyFile_WriteString(text, f);
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700677
678 /* Make sure there's a newline at the end */
679 if (text[len] != '\n') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000680 PyFile_WriteString("\n", f);
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700681 }
682
683 /* Don't print caret if it points to the left of the text */
684 if (offset < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 return;
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700686
687 /* Write caret line */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000688 PyFile_WriteString(" ", f);
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700689 while (--offset >= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 PyFile_WriteString(" ", f);
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700691 }
Pablo Galindoa77aac42021-04-23 14:27:05 +0100692 for (size_t caret_iter=0; caret_iter < caret_repetitions ; caret_iter++) {
693 PyFile_WriteString("^", f);
694 }
695 PyFile_WriteString("\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000696}
697
Tim Peterscf615b52003-04-19 18:47:02 +0000698
Victor Stinner12083282019-05-17 23:05:29 +0200699int
700_Py_HandleSystemExit(int *exitcode_p)
701{
Victor Stinnerda7933e2020-04-13 03:04:28 +0200702 int inspect = _Py_GetConfig()->inspect;
Victor Stinnerc96be812019-05-14 17:34:56 +0200703 if (inspect) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 /* Don't exit if -i flag was given. This flag is set to 0
705 * when entering interactive mode for inspecting. */
Victor Stinner12083282019-05-17 23:05:29 +0200706 return 0;
Victor Stinnerc96be812019-05-14 17:34:56 +0200707 }
Guido van Rossumd8faa362007-04-27 19:54:29 +0000708
Victor Stinner12083282019-05-17 23:05:29 +0200709 if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
710 return 0;
711 }
712
713 PyObject *exception, *value, *tb;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 PyErr_Fetch(&exception, &value, &tb);
Victor Stinner12083282019-05-17 23:05:29 +0200715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000716 fflush(stdout);
Victor Stinner12083282019-05-17 23:05:29 +0200717
718 int exitcode = 0;
719 if (value == NULL || value == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 goto done;
Victor Stinner12083282019-05-17 23:05:29 +0200721 }
722
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000723 if (PyExceptionInstance_Check(value)) {
724 /* The error code should be in the `code' attribute. */
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200725 _Py_IDENTIFIER(code);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200726 PyObject *code = _PyObject_GetAttrId(value, &PyId_code);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000727 if (code) {
728 Py_DECREF(value);
729 value = code;
730 if (value == Py_None)
731 goto done;
732 }
733 /* If we failed to dig out the 'code' attribute,
734 just let the else clause below print the error. */
735 }
Victor Stinner12083282019-05-17 23:05:29 +0200736
737 if (PyLong_Check(value)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000738 exitcode = (int)PyLong_AsLong(value);
Victor Stinner12083282019-05-17 23:05:29 +0200739 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 else {
Victor Stinnerbd303c12013-11-07 23:07:29 +0100741 PyObject *sys_stderr = _PySys_GetObjectId(&PyId_stderr);
Nick Coghland979e432014-02-09 10:43:21 +1000742 /* We clear the exception here to avoid triggering the assertion
743 * in PyObject_Str that ensures it won't silently lose exception
744 * details.
745 */
746 PyErr_Clear();
Victor Stinner7126dbc2010-05-21 23:45:42 +0000747 if (sys_stderr != NULL && sys_stderr != Py_None) {
748 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
749 } else {
750 PyObject_Print(value, stderr, Py_PRINT_RAW);
751 fflush(stderr);
752 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000753 PySys_WriteStderr("\n");
754 exitcode = 1;
755 }
Victor Stinner12083282019-05-17 23:05:29 +0200756
Tim Peterscf615b52003-04-19 18:47:02 +0000757 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 /* Restore and clear the exception info, in order to properly decref
759 * the exception, value, and traceback. If we just exit instead,
760 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
761 * some finalizers from running.
762 */
763 PyErr_Restore(exception, value, tb);
764 PyErr_Clear();
Victor Stinner12083282019-05-17 23:05:29 +0200765 *exitcode_p = exitcode;
766 return 1;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000767}
768
Victor Stinner12083282019-05-17 23:05:29 +0200769
770static void
771handle_system_exit(void)
772{
773 int exitcode;
774 if (_Py_HandleSystemExit(&exitcode)) {
775 Py_Exit(exitcode);
776 }
777}
778
779
Victor Stinner438a12d2019-05-24 17:01:38 +0200780static void
781_PyErr_PrintEx(PyThreadState *tstate, int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000782{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +0000784
Victor Stinner12083282019-05-17 23:05:29 +0200785 handle_system_exit();
786
Victor Stinner438a12d2019-05-24 17:01:38 +0200787 _PyErr_Fetch(tstate, &exception, &v, &tb);
788 if (exception == NULL) {
789 goto done;
790 }
791
792 _PyErr_NormalizeException(tstate, &exception, &v, &tb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 if (tb == NULL) {
794 tb = Py_None;
795 Py_INCREF(tb);
796 }
797 PyException_SetTraceback(v, tb);
Victor Stinner438a12d2019-05-24 17:01:38 +0200798 if (exception == NULL) {
799 goto done;
800 }
801
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 /* Now we know v != NULL too */
803 if (set_sys_last_vars) {
xdegaye66caacf2017-10-23 18:08:41 +0200804 if (_PySys_SetObjectId(&PyId_last_type, exception) < 0) {
Victor Stinner438a12d2019-05-24 17:01:38 +0200805 _PyErr_Clear(tstate);
xdegaye66caacf2017-10-23 18:08:41 +0200806 }
807 if (_PySys_SetObjectId(&PyId_last_value, v) < 0) {
Victor Stinner438a12d2019-05-24 17:01:38 +0200808 _PyErr_Clear(tstate);
xdegaye66caacf2017-10-23 18:08:41 +0200809 }
810 if (_PySys_SetObjectId(&PyId_last_traceback, tb) < 0) {
Victor Stinner438a12d2019-05-24 17:01:38 +0200811 _PyErr_Clear(tstate);
xdegaye66caacf2017-10-23 18:08:41 +0200812 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 }
Victor Stinner09054372013-11-06 22:41:44 +0100814 hook = _PySys_GetObjectId(&PyId_excepthook);
Victor Stinner1c1e68c2020-03-27 15:11:45 +0100815 if (_PySys_Audit(tstate, "sys.excepthook", "OOOO", hook ? hook : Py_None,
816 exception, v, tb) < 0) {
Steve Dowerbea33f52019-11-28 08:46:11 -0800817 if (PyErr_ExceptionMatches(PyExc_RuntimeError)) {
818 PyErr_Clear();
819 goto done;
820 }
821 _PyErr_WriteUnraisableMsg("in audit hook", NULL);
822 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 if (hook) {
Victor Stinner71cb64a2016-08-20 00:57:43 +0200824 PyObject* stack[3];
825 PyObject *result;
826
827 stack[0] = exception;
828 stack[1] = v;
829 stack[2] = tb;
Victor Stinner559bb6a2016-08-22 22:48:54 +0200830 result = _PyObject_FastCall(hook, stack, 3);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 if (result == NULL) {
Victor Stinner12083282019-05-17 23:05:29 +0200832 handle_system_exit();
833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 PyObject *exception2, *v2, *tb2;
Victor Stinner438a12d2019-05-24 17:01:38 +0200835 _PyErr_Fetch(tstate, &exception2, &v2, &tb2);
836 _PyErr_NormalizeException(tstate, &exception2, &v2, &tb2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837 /* It should not be possible for exception2 or v2
838 to be NULL. However PyErr_Display() can't
839 tolerate NULLs, so just be safe. */
840 if (exception2 == NULL) {
841 exception2 = Py_None;
842 Py_INCREF(exception2);
843 }
844 if (v2 == NULL) {
845 v2 = Py_None;
846 Py_INCREF(v2);
847 }
848 fflush(stdout);
849 PySys_WriteStderr("Error in sys.excepthook:\n");
850 PyErr_Display(exception2, v2, tb2);
851 PySys_WriteStderr("\nOriginal exception was:\n");
852 PyErr_Display(exception, v, tb);
853 Py_DECREF(exception2);
854 Py_DECREF(v2);
855 Py_XDECREF(tb2);
856 }
857 Py_XDECREF(result);
Victor Stinner438a12d2019-05-24 17:01:38 +0200858 }
859 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 PySys_WriteStderr("sys.excepthook is missing\n");
861 PyErr_Display(exception, v, tb);
862 }
Victor Stinner438a12d2019-05-24 17:01:38 +0200863
864done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000865 Py_XDECREF(exception);
866 Py_XDECREF(v);
867 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000868}
869
Victor Stinner438a12d2019-05-24 17:01:38 +0200870void
871_PyErr_Print(PyThreadState *tstate)
872{
873 _PyErr_PrintEx(tstate, 1);
874}
875
876void
877PyErr_PrintEx(int set_sys_last_vars)
878{
879 PyThreadState *tstate = _PyThreadState_GET();
880 _PyErr_PrintEx(tstate, set_sys_last_vars);
881}
882
883void
884PyErr_Print(void)
885{
886 PyErr_PrintEx(1);
887}
888
Benjamin Petersone6528212008-07-15 15:32:09 +0000889static void
890print_exception(PyObject *f, PyObject *value)
891{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 int err = 0;
Serhiy Storchaka98c44332020-10-10 22:23:42 +0300893 PyObject *type, *tb, *tmp;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200894 _Py_IDENTIFIER(print_file_and_line);
Benjamin Petersone6528212008-07-15 15:32:09 +0000895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 if (!PyExceptionInstance_Check(value)) {
Victor Stinner52ce3b02013-12-09 02:10:08 +0100897 err = PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
898 err += PyFile_WriteString(Py_TYPE(value)->tp_name, f);
899 err += PyFile_WriteString(" found\n", f);
900 if (err)
901 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 return;
903 }
Benjamin Peterson26582602008-08-23 20:08:07 +0000904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 Py_INCREF(value);
906 fflush(stdout);
907 type = (PyObject *) Py_TYPE(value);
908 tb = PyException_GetTraceback(value);
909 if (tb && tb != Py_None)
910 err = PyTraceBack_Print(tb, f);
911 if (err == 0 &&
Serhiy Storchaka98c44332020-10-10 22:23:42 +0300912 (err = _PyObject_LookupAttrId(value, &PyId_print_file_and_line, &tmp)) > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100914 PyObject *message, *filename, *text;
Pablo Galindoa77aac42021-04-23 14:27:05 +0100915 Py_ssize_t lineno, offset, end_lineno, end_offset;
Serhiy Storchaka98c44332020-10-10 22:23:42 +0300916 err = 0;
917 Py_DECREF(tmp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 if (!parse_syntax_error(value, &message, &filename,
Pablo Galindoa77aac42021-04-23 14:27:05 +0100919 &lineno, &offset,
920 &end_lineno, &end_offset, &text))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 PyErr_Clear();
922 else {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100923 PyObject *line;
924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 Py_DECREF(value);
926 value = message;
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100927
Ammar Askar90d29702020-06-02 08:17:24 +0000928 line = PyUnicode_FromFormat(" File \"%S\", line %zd\n",
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100929 filename, lineno);
930 Py_DECREF(filename);
931 if (line != NULL) {
932 PyFile_WriteObject(line, f, Py_PRINT_RAW);
933 Py_DECREF(line);
934 }
935
936 if (text != NULL) {
Pablo Galindoa77aac42021-04-23 14:27:05 +0100937 Py_ssize_t line_size;
938 const char* error_line = PyUnicode_AsUTF8AndSize(text, &line_size);
939 // If the location of the error spawn multiple lines, we want
940 // to just print the first one and highlight everything until
941 // the end of that one since we don't support multi-line error
942 // messages.
943 if (end_lineno > lineno) {
944 end_offset = (error_line != NULL) ? line_size : -1;
945 }
Christian Claussccd82a02021-10-07 17:30:08 +0200946 // Limit the amount of '^' that we can display to
Pablo Galindoa77aac42021-04-23 14:27:05 +0100947 // the size of the text in the source line.
948 if (error_line != NULL && end_offset > line_size + 1) {
949 end_offset = line_size + 1;
950 }
951 print_error_text(f, offset, end_offset, text);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100952 Py_DECREF(text);
953 }
954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 /* Can't be bothered to check all those
956 PyFile_WriteString() calls */
957 if (PyErr_Occurred())
958 err = -1;
959 }
960 }
961 if (err) {
962 /* Don't do anything else */
963 }
964 else {
Miss Islington (bot)6b996d62021-09-08 09:32:19 -0700965 PyObject* modulename;
966
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200967 _Py_IDENTIFIER(__module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 assert(PyExceptionClass_Check(type));
Benjamin Petersone6528212008-07-15 15:32:09 +0000969
Miss Islington (bot)6b996d62021-09-08 09:32:19 -0700970 modulename = _PyObject_GetAttrId(type, &PyId___module__);
971 if (modulename == NULL || !PyUnicode_Check(modulename))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 {
Miss Islington (bot)6b996d62021-09-08 09:32:19 -0700973 Py_XDECREF(modulename);
974 PyErr_Clear();
Irit Katriel4d2cc3e2021-11-29 10:07:24 +0000975 err = PyFile_WriteString("<unknown>.", f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 }
977 else {
Miss Islington (bot)6b996d62021-09-08 09:32:19 -0700978 if (!_PyUnicode_EqualToASCIIId(modulename, &PyId_builtins))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 {
Miss Islington (bot)6b996d62021-09-08 09:32:19 -0700980 err = PyFile_WriteObject(modulename, f, Py_PRINT_RAW);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 err += PyFile_WriteString(".", f);
982 }
Miss Islington (bot)6b996d62021-09-08 09:32:19 -0700983 Py_DECREF(modulename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 }
985 if (err == 0) {
Miss Islington (bot)6b996d62021-09-08 09:32:19 -0700986 PyObject* qualname = _PyType_GetQualName((PyTypeObject *)type);
987 if (qualname == NULL || !PyUnicode_Check(qualname)) {
988 Py_XDECREF(qualname);
989 PyErr_Clear();
990 err = PyFile_WriteString("<unknown>", f);
991 }
992 else {
993 err = PyFile_WriteObject(qualname, f, Py_PRINT_RAW);
994 Py_DECREF(qualname);
995 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 }
997 }
998 if (err == 0 && (value != Py_None)) {
999 PyObject *s = PyObject_Str(value);
1000 /* only print colon if the str() of the
1001 object is not the empty string
1002 */
Martin Panter3263f682016-02-28 03:16:11 +00001003 if (s == NULL) {
1004 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 err = -1;
Martin Panter3263f682016-02-28 03:16:11 +00001006 PyFile_WriteString(": <exception str() failed>", f);
1007 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 else if (!PyUnicode_Check(s) ||
Victor Stinnere251d6d2011-11-20 19:20:00 +01001009 PyUnicode_GetLength(s) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 err = PyFile_WriteString(": ", f);
1011 if (err == 0)
1012 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1013 Py_XDECREF(s);
1014 }
1015 /* try to write a newline in any case */
Martin Panter3263f682016-02-28 03:16:11 +00001016 if (err < 0) {
1017 PyErr_Clear();
1018 }
Pablo Galindo37494b42021-04-14 02:36:07 +01001019 PyObject* suggestions = _Py_Offer_Suggestions(value);
1020 if (suggestions) {
1021 // Add a trailer ". Did you mean: (...)?"
Pablo Galindo7a041162021-04-19 23:35:53 +01001022 err = PyFile_WriteString(". Did you mean: '", f);
Pablo Galindo37494b42021-04-14 02:36:07 +01001023 if (err == 0) {
1024 err = PyFile_WriteObject(suggestions, f, Py_PRINT_RAW);
Pablo Galindo7a041162021-04-19 23:35:53 +01001025 err += PyFile_WriteString("'?", f);
Pablo Galindo37494b42021-04-14 02:36:07 +01001026 }
1027 Py_DECREF(suggestions);
Pablo Galindoe07f4ab2021-04-14 18:58:28 +01001028 } else if (PyErr_Occurred()) {
1029 PyErr_Clear();
Pablo Galindo37494b42021-04-14 02:36:07 +01001030 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 err += PyFile_WriteString("\n", f);
1032 Py_XDECREF(tb);
1033 Py_DECREF(value);
1034 /* If an error happened here, don't show it.
1035 XXX This is wrong, but too many callers rely on this behavior. */
1036 if (err != 0)
1037 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001038}
1039
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02001040static const char cause_message[] =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 "\nThe above exception was the direct cause "
1042 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001043
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02001044static const char context_message[] =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 "\nDuring handling of the above exception, "
1046 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001047
1048static void
1049print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1050{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 int err = 0, res;
1052 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00001053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 if (seen != NULL) {
1055 /* Exception chaining */
Zane Bitterde860732017-10-17 17:29:39 -04001056 PyObject *value_id = PyLong_FromVoidPtr(value);
1057 if (value_id == NULL || PySet_Add(seen, value_id) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 PyErr_Clear();
1059 else if (PyExceptionInstance_Check(value)) {
Zane Bitterde860732017-10-17 17:29:39 -04001060 PyObject *check_id = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001061 cause = PyException_GetCause(value);
1062 context = PyException_GetContext(value);
Benjamin Petersond5a1c442012-05-14 22:09:31 -07001063 if (cause) {
Zane Bitterde860732017-10-17 17:29:39 -04001064 check_id = PyLong_FromVoidPtr(cause);
1065 if (check_id == NULL) {
1066 res = -1;
1067 } else {
1068 res = PySet_Contains(seen, check_id);
1069 Py_DECREF(check_id);
1070 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 if (res == -1)
1072 PyErr_Clear();
1073 if (res == 0) {
1074 print_exception_recursive(
1075 f, cause, seen);
1076 err |= PyFile_WriteString(
1077 cause_message, f);
1078 }
1079 }
Benjamin Petersond5a1c442012-05-14 22:09:31 -07001080 else if (context &&
1081 !((PyBaseExceptionObject *)value)->suppress_context) {
Zane Bitterde860732017-10-17 17:29:39 -04001082 check_id = PyLong_FromVoidPtr(context);
1083 if (check_id == NULL) {
1084 res = -1;
1085 } else {
1086 res = PySet_Contains(seen, check_id);
1087 Py_DECREF(check_id);
1088 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 if (res == -1)
1090 PyErr_Clear();
1091 if (res == 0) {
1092 print_exception_recursive(
1093 f, context, seen);
1094 err |= PyFile_WriteString(
1095 context_message, f);
1096 }
1097 }
1098 Py_XDECREF(context);
1099 Py_XDECREF(cause);
1100 }
Zane Bitterde860732017-10-17 17:29:39 -04001101 Py_XDECREF(value_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 }
1103 print_exception(f, value);
1104 if (err != 0)
1105 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001106}
1107
Thomas Wouters477c8d52006-05-27 19:21:47 +00001108void
Victor Stinnercd590a72019-05-28 00:39:52 +02001109_PyErr_Display(PyObject *file, PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001110{
Victor Stinnercd590a72019-05-28 00:39:52 +02001111 assert(file != NULL && file != Py_None);
1112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 PyObject *seen;
Antoine Pitrou24201d42013-10-13 21:53:13 +02001114 if (PyExceptionInstance_Check(value)
1115 && tb != NULL && PyTraceBack_Check(tb)) {
1116 /* Put the traceback on the exception, otherwise it won't get
1117 displayed. See issue #18776. */
1118 PyObject *cur_tb = PyException_GetTraceback(value);
1119 if (cur_tb == NULL)
1120 PyException_SetTraceback(value, tb);
1121 else
1122 Py_DECREF(cur_tb);
1123 }
Victor Stinnercd590a72019-05-28 00:39:52 +02001124
1125 /* We choose to ignore seen being possibly NULL, and report
1126 at least the main exception (it could be a MemoryError).
1127 */
1128 seen = PySet_New(NULL);
1129 if (seen == NULL) {
1130 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 }
Victor Stinnercd590a72019-05-28 00:39:52 +02001132 print_exception_recursive(file, value, seen);
1133 Py_XDECREF(seen);
Victor Stinnera85a1d32019-05-28 16:01:17 +02001134
1135 /* Call file.flush() */
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001136 PyObject *res = _PyObject_CallMethodIdNoArgs(file, &PyId_flush);
Victor Stinnera85a1d32019-05-28 16:01:17 +02001137 if (!res) {
1138 /* Silently ignore file.flush() error */
1139 PyErr_Clear();
1140 }
1141 else {
1142 Py_DECREF(res);
1143 }
Victor Stinnercd590a72019-05-28 00:39:52 +02001144}
1145
1146void
1147PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
1148{
1149 PyObject *file = _PySys_GetObjectId(&PyId_stderr);
1150 if (file == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 _PyObject_Dump(value);
1152 fprintf(stderr, "lost sys.stderr\n");
Victor Stinnercd590a72019-05-28 00:39:52 +02001153 return;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 }
Victor Stinnercd590a72019-05-28 00:39:52 +02001155 if (file == Py_None) {
1156 return;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001157 }
Pablo Galindo09b90a02021-03-29 23:38:51 +01001158 Py_INCREF(file);
Victor Stinnercd590a72019-05-28 00:39:52 +02001159 _PyErr_Display(file, exception, value, tb);
Pablo Galindo09b90a02021-03-29 23:38:51 +01001160 Py_DECREF(file);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001161}
1162
Guido van Rossum82598051997-03-05 00:20:32 +00001163PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001164PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001165 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001166{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001167 PyObject *ret = NULL;
1168 mod_ty mod;
Victor Stinner95701bd2013-11-06 18:41:07 +01001169 PyArena *arena;
Victor Stinner95701bd2013-11-06 18:41:07 +01001170 PyObject *filename;
1171
1172 filename = _PyUnicode_FromId(&PyId_string); /* borrowed */
1173 if (filename == NULL)
1174 return NULL;
1175
Victor Stinner8370e072021-03-24 02:23:01 +01001176 arena = _PyArena_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001177 if (arena == NULL)
1178 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001179
Victor Stinner57364ce2021-03-24 01:29:09 +01001180 mod = _PyParser_ASTFromString(str, filename, start, flags, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 if (mod != NULL)
Victor Stinner95701bd2013-11-06 18:41:07 +01001183 ret = run_mod(mod, filename, globals, locals, flags, arena);
Victor Stinner8370e072021-03-24 02:23:01 +01001184 _PyArena_Free(arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001185 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001186}
1187
Victor Stinnerb6d98c12020-12-08 14:38:08 +01001188
1189static PyObject *
1190pyrun_file(FILE *fp, PyObject *filename, int start, PyObject *globals,
1191 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001192{
Victor Stinner8370e072021-03-24 02:23:01 +01001193 PyArena *arena = _PyArena_New();
Victor Stinnerb6d98c12020-12-08 14:38:08 +01001194 if (arena == NULL) {
1195 return NULL;
1196 }
1197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 mod_ty mod;
Victor Stinner57364ce2021-03-24 01:29:09 +01001199 mod = _PyParser_ASTFromFile(fp, filename, NULL, start, NULL, NULL,
1200 flags, NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001201
Victor Stinnerb6d98c12020-12-08 14:38:08 +01001202 if (closeit) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001203 fclose(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 }
Victor Stinner95701bd2013-11-06 18:41:07 +01001205
Victor Stinnerb6d98c12020-12-08 14:38:08 +01001206 PyObject *ret;
1207 if (mod != NULL) {
1208 ret = run_mod(mod, filename, globals, locals, flags, arena);
1209 }
1210 else {
1211 ret = NULL;
1212 }
Victor Stinner8370e072021-03-24 02:23:01 +01001213 _PyArena_Free(arena);
Victor Stinnerb6d98c12020-12-08 14:38:08 +01001214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001216}
1217
Victor Stinnerb6d98c12020-12-08 14:38:08 +01001218
1219PyObject *
1220PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
1221 PyObject *locals, int closeit, PyCompilerFlags *flags)
1222{
1223 PyObject *filename_obj = PyUnicode_DecodeFSDefault(filename);
1224 if (filename_obj == NULL) {
1225 return NULL;
1226 }
1227
1228 PyObject *res = pyrun_file(fp, filename_obj, start, globals,
1229 locals, closeit, flags);
1230 Py_DECREF(filename_obj);
1231 return res;
1232
1233}
1234
1235
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001236static void
1237flush_io(void)
1238{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 PyObject *f, *r;
1240 PyObject *type, *value, *traceback;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001242 /* Save the current exception */
1243 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001244
Victor Stinnerbd303c12013-11-07 23:07:29 +01001245 f = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001246 if (f != NULL) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001247 r = _PyObject_CallMethodIdNoArgs(f, &PyId_flush);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 if (r)
1249 Py_DECREF(r);
1250 else
1251 PyErr_Clear();
1252 }
Victor Stinnerbd303c12013-11-07 23:07:29 +01001253 f = _PySys_GetObjectId(&PyId_stdout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 if (f != NULL) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001255 r = _PyObject_CallMethodIdNoArgs(f, &PyId_flush);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001256 if (r)
1257 Py_DECREF(r);
1258 else
1259 PyErr_Clear();
1260 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001262 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001263}
1264
Guido van Rossum82598051997-03-05 00:20:32 +00001265static PyObject *
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001266run_eval_code_obj(PyThreadState *tstate, PyCodeObject *co, PyObject *globals, PyObject *locals)
Gregory P. Smith38f11cc2019-02-16 12:57:40 -08001267{
1268 PyObject *v;
Gregory P. Smithd9bc5432019-02-20 17:35:54 -08001269 /*
1270 * We explicitly re-initialize _Py_UnhandledKeyboardInterrupt every eval
1271 * _just in case_ someone is calling into an embedded Python where they
1272 * don't care about an uncaught KeyboardInterrupt exception (why didn't they
1273 * leave config.install_signal_handlers set to 0?!?) but then later call
1274 * Py_Main() itself (which _checks_ this flag and dies with a signal after
1275 * its interpreter exits). We don't want a previous embedded interpreter's
1276 * uncaught exception to trigger an unexplained signal exit from a future
1277 * Py_Main() based one.
1278 */
1279 _Py_UnhandledKeyboardInterrupt = 0;
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001280
1281 /* Set globals['__builtins__'] if it doesn't exist */
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02001282 if (globals != NULL && _PyDict_GetItemStringWithError(globals, "__builtins__") == NULL) {
1283 if (PyErr_Occurred() ||
1284 PyDict_SetItemString(globals, "__builtins__",
1285 tstate->interp->builtins) < 0)
1286 {
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001287 return NULL;
1288 }
1289 }
1290
Gregory P. Smith38f11cc2019-02-16 12:57:40 -08001291 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001292 if (!v && _PyErr_Occurred(tstate) == PyExc_KeyboardInterrupt) {
Gregory P. Smith38f11cc2019-02-16 12:57:40 -08001293 _Py_UnhandledKeyboardInterrupt = 1;
1294 }
1295 return v;
1296}
1297
1298static PyObject *
Victor Stinner95701bd2013-11-06 18:41:07 +01001299run_mod(mod_ty mod, PyObject *filename, PyObject *globals, PyObject *locals,
1300 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001301{
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001302 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinnera81fca62021-03-24 00:51:50 +01001303 PyCodeObject *co = _PyAST_Compile(mod, filename, flags, -1, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001304 if (co == NULL)
1305 return NULL;
Steve Dowerb82e17e2019-05-23 08:45:22 -07001306
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001307 if (_PySys_Audit(tstate, "exec", "O", co) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07001308 Py_DECREF(co);
1309 return NULL;
1310 }
1311
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001312 PyObject *v = run_eval_code_obj(tstate, co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 Py_DECREF(co);
1314 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001315}
1316
Guido van Rossum82598051997-03-05 00:20:32 +00001317static PyObject *
Victor Stinnerb6d98c12020-12-08 14:38:08 +01001318run_pyc_file(FILE *fp, PyObject *globals, PyObject *locals,
1319 PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001320{
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001321 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001322 PyCodeObject *co;
1323 PyObject *v;
1324 long magic;
1325 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001327 magic = PyMarshal_ReadLongFromFile(fp);
1328 if (magic != PyImport_GetMagicNumber()) {
Victor Stinner5200f552015-03-18 13:56:25 +01001329 if (!PyErr_Occurred())
1330 PyErr_SetString(PyExc_RuntimeError,
1331 "Bad magic number in .pyc file");
Zackery Spytzea737752018-06-23 21:15:24 -06001332 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 }
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08001334 /* Skip the rest of the header. */
1335 (void) PyMarshal_ReadLongFromFile(fp);
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001336 (void) PyMarshal_ReadLongFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 (void) PyMarshal_ReadLongFromFile(fp);
Zackery Spytzea737752018-06-23 21:15:24 -06001338 if (PyErr_Occurred()) {
1339 goto error;
1340 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001341 v = PyMarshal_ReadLastObjectFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 if (v == NULL || !PyCode_Check(v)) {
1343 Py_XDECREF(v);
1344 PyErr_SetString(PyExc_RuntimeError,
1345 "Bad code object in .pyc file");
Zackery Spytzea737752018-06-23 21:15:24 -06001346 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 }
Zackery Spytzea737752018-06-23 21:15:24 -06001348 fclose(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001349 co = (PyCodeObject *)v;
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001350 v = run_eval_code_obj(tstate, co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 if (v && flags)
1352 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1353 Py_DECREF(co);
1354 return v;
Zackery Spytzea737752018-06-23 21:15:24 -06001355error:
1356 fclose(fp);
1357 return NULL;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001358}
1359
Guido van Rossum82598051997-03-05 00:20:32 +00001360PyObject *
Victor Stinner14e461d2013-08-26 22:28:21 +02001361Py_CompileStringObject(const char *str, PyObject *filename, int start,
1362 PyCompilerFlags *flags, int optimize)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001363{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001364 PyCodeObject *co;
1365 mod_ty mod;
Victor Stinner8370e072021-03-24 02:23:01 +01001366 PyArena *arena = _PyArena_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001367 if (arena == NULL)
1368 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001369
Victor Stinner57364ce2021-03-24 01:29:09 +01001370 mod = _PyParser_ASTFromString(str, filename, start, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001371 if (mod == NULL) {
Victor Stinner8370e072021-03-24 02:23:01 +01001372 _PyArena_Free(arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001373 return NULL;
1374 }
1375 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
1376 PyObject *result = PyAST_mod2obj(mod);
Victor Stinner8370e072021-03-24 02:23:01 +01001377 _PyArena_Free(arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001378 return result;
1379 }
Victor Stinnera81fca62021-03-24 00:51:50 +01001380 co = _PyAST_Compile(mod, filename, flags, optimize, arena);
Victor Stinner8370e072021-03-24 02:23:01 +01001381 _PyArena_Free(arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001382 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001383}
1384
Victor Stinner14e461d2013-08-26 22:28:21 +02001385PyObject *
1386Py_CompileStringExFlags(const char *str, const char *filename_str, int start,
1387 PyCompilerFlags *flags, int optimize)
1388{
1389 PyObject *filename, *co;
1390 filename = PyUnicode_DecodeFSDefault(filename_str);
1391 if (filename == NULL)
1392 return NULL;
1393 co = Py_CompileStringObject(str, filename, start, flags, optimize);
1394 Py_DECREF(filename);
1395 return co;
1396}
1397
Dino Viehland41540692019-05-28 16:21:17 -07001398const char *
1399_Py_SourceAsString(PyObject *cmd, const char *funcname, const char *what, PyCompilerFlags *cf, PyObject **cmd_copy)
1400{
1401 const char *str;
1402 Py_ssize_t size;
1403 Py_buffer view;
1404
1405 *cmd_copy = NULL;
1406 if (PyUnicode_Check(cmd)) {
1407 cf->cf_flags |= PyCF_IGNORE_COOKIE;
1408 str = PyUnicode_AsUTF8AndSize(cmd, &size);
1409 if (str == NULL)
1410 return NULL;
1411 }
1412 else if (PyBytes_Check(cmd)) {
1413 str = PyBytes_AS_STRING(cmd);
1414 size = PyBytes_GET_SIZE(cmd);
1415 }
1416 else if (PyByteArray_Check(cmd)) {
1417 str = PyByteArray_AS_STRING(cmd);
1418 size = PyByteArray_GET_SIZE(cmd);
1419 }
1420 else if (PyObject_GetBuffer(cmd, &view, PyBUF_SIMPLE) == 0) {
1421 /* Copy to NUL-terminated buffer. */
1422 *cmd_copy = PyBytes_FromStringAndSize(
1423 (const char *)view.buf, view.len);
1424 PyBuffer_Release(&view);
1425 if (*cmd_copy == NULL) {
1426 return NULL;
1427 }
1428 str = PyBytes_AS_STRING(*cmd_copy);
1429 size = PyBytes_GET_SIZE(*cmd_copy);
1430 }
1431 else {
1432 PyErr_Format(PyExc_TypeError,
1433 "%s() arg 1 must be a %s object",
1434 funcname, what);
1435 return NULL;
1436 }
1437
1438 if (strlen(str) != (size_t)size) {
1439 PyErr_SetString(PyExc_ValueError,
1440 "source code string cannot contain null bytes");
1441 Py_CLEAR(*cmd_copy);
1442 return NULL;
1443 }
1444 return str;
1445}
1446
Zachary Warec4821d62014-11-21 23:35:12 -06001447#if defined(USE_STACKCHECK)
1448#if defined(WIN32) && defined(_MSC_VER)
1449
1450/* Stack checking for Microsoft C */
1451
1452#include <malloc.h>
1453#include <excpt.h>
1454
1455/*
1456 * Return non-zero when we run out of memory on the stack; zero otherwise.
1457 */
1458int
1459PyOS_CheckStack(void)
1460{
1461 __try {
1462 /* alloca throws a stack overflow exception if there's
1463 not enough space left on the stack */
1464 alloca(PYOS_STACK_MARGIN * sizeof(void*));
1465 return 0;
1466 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
1467 EXCEPTION_EXECUTE_HANDLER :
1468 EXCEPTION_CONTINUE_SEARCH) {
1469 int errcode = _resetstkoflw();
1470 if (errcode == 0)
1471 {
1472 Py_FatalError("Could not reset the stack!");
1473 }
1474 }
1475 return 1;
1476}
1477
1478#endif /* WIN32 && _MSC_VER */
1479
1480/* Alternate implementations can be added here... */
1481
1482#endif /* USE_STACKCHECK */
1483
Pablo Galindo46bd5ed2020-12-02 05:16:31 +00001484/* Deprecated C API functions still provided for binary compatibility */
1485
1486#undef PyRun_AnyFile
1487PyAPI_FUNC(int)
1488PyRun_AnyFile(FILE *fp, const char *name)
1489{
1490 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
1491}
1492
1493#undef PyRun_AnyFileEx
1494PyAPI_FUNC(int)
1495PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
1496{
1497 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
1498}
1499
1500#undef PyRun_AnyFileFlags
1501PyAPI_FUNC(int)
1502PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
1503{
1504 return PyRun_AnyFileExFlags(fp, name, 0, flags);
1505}
1506
1507#undef PyRun_File
1508PyAPI_FUNC(PyObject *)
1509PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
1510{
1511 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
1512}
1513
1514#undef PyRun_FileEx
1515PyAPI_FUNC(PyObject *)
1516PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
1517{
1518 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
1519}
1520
1521#undef PyRun_FileFlags
1522PyAPI_FUNC(PyObject *)
1523PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
1524 PyCompilerFlags *flags)
1525{
1526 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
1527}
1528
1529#undef PyRun_SimpleFile
1530PyAPI_FUNC(int)
1531PyRun_SimpleFile(FILE *f, const char *p)
1532{
1533 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
1534}
1535
1536#undef PyRun_SimpleFileEx
1537PyAPI_FUNC(int)
1538PyRun_SimpleFileEx(FILE *f, const char *p, int c)
1539{
1540 return PyRun_SimpleFileExFlags(f, p, c, NULL);
1541}
1542
1543
1544#undef PyRun_String
1545PyAPI_FUNC(PyObject *)
1546PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
1547{
1548 return PyRun_StringFlags(str, s, g, l, NULL);
1549}
1550
1551#undef PyRun_SimpleString
1552PyAPI_FUNC(int)
1553PyRun_SimpleString(const char *s)
1554{
1555 return PyRun_SimpleStringFlags(s, NULL);
1556}
1557
1558#undef Py_CompileString
1559PyAPI_FUNC(PyObject *)
1560Py_CompileString(const char *str, const char *p, int s)
1561{
1562 return Py_CompileStringExFlags(str, p, s, NULL, -1);
1563}
1564
1565#undef Py_CompileStringFlags
1566PyAPI_FUNC(PyObject *)
1567Py_CompileStringFlags(const char *str, const char *p, int s,
1568 PyCompilerFlags *flags)
1569{
1570 return Py_CompileStringExFlags(str, p, s, flags, -1);
1571}
1572
1573#undef PyRun_InteractiveOne
1574PyAPI_FUNC(int)
1575PyRun_InteractiveOne(FILE *f, const char *p)
1576{
1577 return PyRun_InteractiveOneFlags(f, p, NULL);
1578}
1579
1580#undef PyRun_InteractiveLoop
1581PyAPI_FUNC(int)
1582PyRun_InteractiveLoop(FILE *f, const char *p)
1583{
1584 return PyRun_InteractiveLoopFlags(f, p, NULL);
1585}
1586
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001587#ifdef __cplusplus
1588}
1589#endif