blob: 6f84cab702e980c632d35e7b066bd2d39b96cac7 [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,
Ammar Askar90d29702020-06-02 08:17:24 +0000513 Py_ssize_t *lineno, Py_ssize_t *offset, PyObject **text)
Barry Warsaw035574d1997-08-29 22:07:17 +0000514{
Ammar Askar90d29702020-06-02 08:17:24 +0000515 Py_ssize_t hold;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 PyObject *v;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200517 _Py_IDENTIFIER(msg);
518 _Py_IDENTIFIER(filename);
519 _Py_IDENTIFIER(lineno);
520 _Py_IDENTIFIER(offset);
521 _Py_IDENTIFIER(text);
Barry Warsaw035574d1997-08-29 22:07:17 +0000522
Benjamin Peterson80d50422012-04-03 00:30:38 -0400523 *message = NULL;
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100524 *filename = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 /* new style errors. `err' is an instance */
Benjamin Peterson0a9a6362012-04-03 00:35:36 -0400527 *message = _PyObject_GetAttrId(err, &PyId_msg);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400528 if (!*message)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000529 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +0000530
Benjamin Peterson0a9a6362012-04-03 00:35:36 -0400531 v = _PyObject_GetAttrId(err, &PyId_filename);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400532 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400534 if (v == Py_None) {
535 Py_DECREF(v);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100536 *filename = _PyUnicode_FromId(&PyId_string);
537 if (*filename == NULL)
538 goto finally;
539 Py_INCREF(*filename);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400540 }
541 else {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100542 *filename = v;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400543 }
Barry Warsaw035574d1997-08-29 22:07:17 +0000544
Benjamin Peterson0a9a6362012-04-03 00:35:36 -0400545 v = _PyObject_GetAttrId(err, &PyId_lineno);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400546 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000547 goto finally;
Ammar Askar90d29702020-06-02 08:17:24 +0000548 hold = PyLong_AsSsize_t(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000549 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 if (hold < 0 && PyErr_Occurred())
551 goto finally;
Serhiy Storchaka56f6e762015-09-06 21:25:30 +0300552 *lineno = hold;
Barry Warsaw035574d1997-08-29 22:07:17 +0000553
Benjamin Peterson0a9a6362012-04-03 00:35:36 -0400554 v = _PyObject_GetAttrId(err, &PyId_offset);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400555 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 goto finally;
557 if (v == Py_None) {
558 *offset = -1;
559 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 } else {
Ammar Askar90d29702020-06-02 08:17:24 +0000561 hold = PyLong_AsSsize_t(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 if (hold < 0 && PyErr_Occurred())
564 goto finally;
Serhiy Storchaka56f6e762015-09-06 21:25:30 +0300565 *offset = hold;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 }
Barry Warsaw035574d1997-08-29 22:07:17 +0000567
Benjamin Peterson0a9a6362012-04-03 00:35:36 -0400568 v = _PyObject_GetAttrId(err, &PyId_text);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400569 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400571 if (v == Py_None) {
572 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 *text = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400574 }
575 else {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100576 *text = v;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400577 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +0000579
580finally:
Benjamin Peterson80d50422012-04-03 00:30:38 -0400581 Py_XDECREF(*message);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100582 Py_XDECREF(*filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +0000584}
585
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000586static void
Ammar Askar90d29702020-06-02 08:17:24 +0000587print_error_text(PyObject *f, Py_ssize_t offset, PyObject *text_obj)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000588{
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700589 /* Convert text to a char pointer; return if error */
590 const char *text = PyUnicode_AsUTF8(text_obj);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100591 if (text == NULL)
592 return;
593
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700594 /* Convert offset from 1-based to 0-based */
595 offset--;
596
597 /* Strip leading whitespace from text, adjusting offset as we go */
598 while (*text == ' ' || *text == '\t' || *text == '\f') {
599 text++;
600 offset--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 }
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700602
603 /* Calculate text length excluding trailing newline */
604 Py_ssize_t len = strlen(text);
605 if (len > 0 && text[len-1] == '\n') {
606 len--;
607 }
608
609 /* Clip offset to at most len */
610 if (offset > len) {
611 offset = len;
612 }
613
614 /* Skip past newlines embedded in text */
615 for (;;) {
616 const char *nl = strchr(text, '\n');
617 if (nl == NULL) {
618 break;
619 }
620 Py_ssize_t inl = nl - text;
Ammar Askar90d29702020-06-02 08:17:24 +0000621 if (inl >= offset) {
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700622 break;
623 }
624 inl += 1;
625 text += inl;
626 len -= inl;
627 offset -= (int)inl;
628 }
629
630 /* Print text */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 PyFile_WriteString(" ", f);
632 PyFile_WriteString(text, f);
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700633
634 /* Make sure there's a newline at the end */
635 if (text[len] != '\n') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 PyFile_WriteString("\n", f);
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700637 }
638
639 /* Don't print caret if it points to the left of the text */
640 if (offset < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 return;
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700642
643 /* Write caret line */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 PyFile_WriteString(" ", f);
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700645 while (--offset >= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 PyFile_WriteString(" ", f);
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700647 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000649}
650
Tim Peterscf615b52003-04-19 18:47:02 +0000651
Victor Stinner12083282019-05-17 23:05:29 +0200652int
653_Py_HandleSystemExit(int *exitcode_p)
654{
Victor Stinnerda7933e2020-04-13 03:04:28 +0200655 int inspect = _Py_GetConfig()->inspect;
Victor Stinnerc96be812019-05-14 17:34:56 +0200656 if (inspect) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 /* Don't exit if -i flag was given. This flag is set to 0
658 * when entering interactive mode for inspecting. */
Victor Stinner12083282019-05-17 23:05:29 +0200659 return 0;
Victor Stinnerc96be812019-05-14 17:34:56 +0200660 }
Guido van Rossumd8faa362007-04-27 19:54:29 +0000661
Victor Stinner12083282019-05-17 23:05:29 +0200662 if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
663 return 0;
664 }
665
666 PyObject *exception, *value, *tb;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000667 PyErr_Fetch(&exception, &value, &tb);
Victor Stinner12083282019-05-17 23:05:29 +0200668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000669 fflush(stdout);
Victor Stinner12083282019-05-17 23:05:29 +0200670
671 int exitcode = 0;
672 if (value == NULL || value == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000673 goto done;
Victor Stinner12083282019-05-17 23:05:29 +0200674 }
675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 if (PyExceptionInstance_Check(value)) {
677 /* The error code should be in the `code' attribute. */
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200678 _Py_IDENTIFIER(code);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200679 PyObject *code = _PyObject_GetAttrId(value, &PyId_code);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000680 if (code) {
681 Py_DECREF(value);
682 value = code;
683 if (value == Py_None)
684 goto done;
685 }
686 /* If we failed to dig out the 'code' attribute,
687 just let the else clause below print the error. */
688 }
Victor Stinner12083282019-05-17 23:05:29 +0200689
690 if (PyLong_Check(value)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000691 exitcode = (int)PyLong_AsLong(value);
Victor Stinner12083282019-05-17 23:05:29 +0200692 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 else {
Victor Stinnerbd303c12013-11-07 23:07:29 +0100694 PyObject *sys_stderr = _PySys_GetObjectId(&PyId_stderr);
Nick Coghland979e432014-02-09 10:43:21 +1000695 /* We clear the exception here to avoid triggering the assertion
696 * in PyObject_Str that ensures it won't silently lose exception
697 * details.
698 */
699 PyErr_Clear();
Victor Stinner7126dbc2010-05-21 23:45:42 +0000700 if (sys_stderr != NULL && sys_stderr != Py_None) {
701 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
702 } else {
703 PyObject_Print(value, stderr, Py_PRINT_RAW);
704 fflush(stderr);
705 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000706 PySys_WriteStderr("\n");
707 exitcode = 1;
708 }
Victor Stinner12083282019-05-17 23:05:29 +0200709
Tim Peterscf615b52003-04-19 18:47:02 +0000710 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000711 /* Restore and clear the exception info, in order to properly decref
712 * the exception, value, and traceback. If we just exit instead,
713 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
714 * some finalizers from running.
715 */
716 PyErr_Restore(exception, value, tb);
717 PyErr_Clear();
Victor Stinner12083282019-05-17 23:05:29 +0200718 *exitcode_p = exitcode;
719 return 1;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000720}
721
Victor Stinner12083282019-05-17 23:05:29 +0200722
723static void
724handle_system_exit(void)
725{
726 int exitcode;
727 if (_Py_HandleSystemExit(&exitcode)) {
728 Py_Exit(exitcode);
729 }
730}
731
732
Victor Stinner438a12d2019-05-24 17:01:38 +0200733static void
734_PyErr_PrintEx(PyThreadState *tstate, int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000735{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +0000737
Victor Stinner12083282019-05-17 23:05:29 +0200738 handle_system_exit();
739
Victor Stinner438a12d2019-05-24 17:01:38 +0200740 _PyErr_Fetch(tstate, &exception, &v, &tb);
741 if (exception == NULL) {
742 goto done;
743 }
744
745 _PyErr_NormalizeException(tstate, &exception, &v, &tb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 if (tb == NULL) {
747 tb = Py_None;
748 Py_INCREF(tb);
749 }
750 PyException_SetTraceback(v, tb);
Victor Stinner438a12d2019-05-24 17:01:38 +0200751 if (exception == NULL) {
752 goto done;
753 }
754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000755 /* Now we know v != NULL too */
756 if (set_sys_last_vars) {
xdegaye66caacf2017-10-23 18:08:41 +0200757 if (_PySys_SetObjectId(&PyId_last_type, exception) < 0) {
Victor Stinner438a12d2019-05-24 17:01:38 +0200758 _PyErr_Clear(tstate);
xdegaye66caacf2017-10-23 18:08:41 +0200759 }
760 if (_PySys_SetObjectId(&PyId_last_value, v) < 0) {
Victor Stinner438a12d2019-05-24 17:01:38 +0200761 _PyErr_Clear(tstate);
xdegaye66caacf2017-10-23 18:08:41 +0200762 }
763 if (_PySys_SetObjectId(&PyId_last_traceback, tb) < 0) {
Victor Stinner438a12d2019-05-24 17:01:38 +0200764 _PyErr_Clear(tstate);
xdegaye66caacf2017-10-23 18:08:41 +0200765 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 }
Victor Stinner09054372013-11-06 22:41:44 +0100767 hook = _PySys_GetObjectId(&PyId_excepthook);
Victor Stinner1c1e68c2020-03-27 15:11:45 +0100768 if (_PySys_Audit(tstate, "sys.excepthook", "OOOO", hook ? hook : Py_None,
769 exception, v, tb) < 0) {
Steve Dowerbea33f52019-11-28 08:46:11 -0800770 if (PyErr_ExceptionMatches(PyExc_RuntimeError)) {
771 PyErr_Clear();
772 goto done;
773 }
774 _PyErr_WriteUnraisableMsg("in audit hook", NULL);
775 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000776 if (hook) {
Victor Stinner71cb64a2016-08-20 00:57:43 +0200777 PyObject* stack[3];
778 PyObject *result;
779
780 stack[0] = exception;
781 stack[1] = v;
782 stack[2] = tb;
Victor Stinner559bb6a2016-08-22 22:48:54 +0200783 result = _PyObject_FastCall(hook, stack, 3);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 if (result == NULL) {
Victor Stinner12083282019-05-17 23:05:29 +0200785 handle_system_exit();
786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 PyObject *exception2, *v2, *tb2;
Victor Stinner438a12d2019-05-24 17:01:38 +0200788 _PyErr_Fetch(tstate, &exception2, &v2, &tb2);
789 _PyErr_NormalizeException(tstate, &exception2, &v2, &tb2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 /* It should not be possible for exception2 or v2
791 to be NULL. However PyErr_Display() can't
792 tolerate NULLs, so just be safe. */
793 if (exception2 == NULL) {
794 exception2 = Py_None;
795 Py_INCREF(exception2);
796 }
797 if (v2 == NULL) {
798 v2 = Py_None;
799 Py_INCREF(v2);
800 }
801 fflush(stdout);
802 PySys_WriteStderr("Error in sys.excepthook:\n");
803 PyErr_Display(exception2, v2, tb2);
804 PySys_WriteStderr("\nOriginal exception was:\n");
805 PyErr_Display(exception, v, tb);
806 Py_DECREF(exception2);
807 Py_DECREF(v2);
808 Py_XDECREF(tb2);
809 }
810 Py_XDECREF(result);
Victor Stinner438a12d2019-05-24 17:01:38 +0200811 }
812 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 PySys_WriteStderr("sys.excepthook is missing\n");
814 PyErr_Display(exception, v, tb);
815 }
Victor Stinner438a12d2019-05-24 17:01:38 +0200816
817done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000818 Py_XDECREF(exception);
819 Py_XDECREF(v);
820 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000821}
822
Victor Stinner438a12d2019-05-24 17:01:38 +0200823void
824_PyErr_Print(PyThreadState *tstate)
825{
826 _PyErr_PrintEx(tstate, 1);
827}
828
829void
830PyErr_PrintEx(int set_sys_last_vars)
831{
832 PyThreadState *tstate = _PyThreadState_GET();
833 _PyErr_PrintEx(tstate, set_sys_last_vars);
834}
835
836void
837PyErr_Print(void)
838{
839 PyErr_PrintEx(1);
840}
841
Benjamin Petersone6528212008-07-15 15:32:09 +0000842static void
843print_exception(PyObject *f, PyObject *value)
844{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 int err = 0;
Serhiy Storchaka98c44332020-10-10 22:23:42 +0300846 PyObject *type, *tb, *tmp;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200847 _Py_IDENTIFIER(print_file_and_line);
Benjamin Petersone6528212008-07-15 15:32:09 +0000848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 if (!PyExceptionInstance_Check(value)) {
Victor Stinner52ce3b02013-12-09 02:10:08 +0100850 err = PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
851 err += PyFile_WriteString(Py_TYPE(value)->tp_name, f);
852 err += PyFile_WriteString(" found\n", f);
853 if (err)
854 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 return;
856 }
Benjamin Peterson26582602008-08-23 20:08:07 +0000857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 Py_INCREF(value);
859 fflush(stdout);
860 type = (PyObject *) Py_TYPE(value);
861 tb = PyException_GetTraceback(value);
862 if (tb && tb != Py_None)
863 err = PyTraceBack_Print(tb, f);
864 if (err == 0 &&
Serhiy Storchaka98c44332020-10-10 22:23:42 +0300865 (err = _PyObject_LookupAttrId(value, &PyId_print_file_and_line, &tmp)) > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100867 PyObject *message, *filename, *text;
Ammar Askar90d29702020-06-02 08:17:24 +0000868 Py_ssize_t lineno, offset;
Serhiy Storchaka98c44332020-10-10 22:23:42 +0300869 err = 0;
870 Py_DECREF(tmp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000871 if (!parse_syntax_error(value, &message, &filename,
872 &lineno, &offset, &text))
873 PyErr_Clear();
874 else {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100875 PyObject *line;
876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 Py_DECREF(value);
878 value = message;
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100879
Ammar Askar90d29702020-06-02 08:17:24 +0000880 line = PyUnicode_FromFormat(" File \"%S\", line %zd\n",
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100881 filename, lineno);
882 Py_DECREF(filename);
883 if (line != NULL) {
884 PyFile_WriteObject(line, f, Py_PRINT_RAW);
885 Py_DECREF(line);
886 }
887
888 if (text != NULL) {
889 print_error_text(f, offset, text);
890 Py_DECREF(text);
891 }
892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 /* Can't be bothered to check all those
894 PyFile_WriteString() calls */
895 if (PyErr_Occurred())
896 err = -1;
897 }
898 }
899 if (err) {
900 /* Don't do anything else */
901 }
902 else {
903 PyObject* moduleName;
Serhiy Storchakaceeef102018-06-15 11:09:43 +0300904 const char *className;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200905 _Py_IDENTIFIER(__module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 assert(PyExceptionClass_Check(type));
907 className = PyExceptionClass_Name(type);
908 if (className != NULL) {
Serhiy Storchakaceeef102018-06-15 11:09:43 +0300909 const char *dot = strrchr(className, '.');
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 if (dot != NULL)
911 className = dot+1;
912 }
Benjamin Petersone6528212008-07-15 15:32:09 +0000913
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200914 moduleName = _PyObject_GetAttrId(type, &PyId___module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 if (moduleName == NULL || !PyUnicode_Check(moduleName))
916 {
Victor Stinner13b21bd2011-05-26 14:25:13 +0200917 Py_XDECREF(moduleName);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 err = PyFile_WriteString("<unknown>", f);
919 }
920 else {
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +0200921 if (!_PyUnicode_EqualToASCIIId(moduleName, &PyId_builtins))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 {
Victor Stinner937114f2013-11-07 00:12:30 +0100923 err = PyFile_WriteObject(moduleName, f, Py_PRINT_RAW);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 err += PyFile_WriteString(".", f);
925 }
926 Py_DECREF(moduleName);
927 }
928 if (err == 0) {
929 if (className == NULL)
930 err = PyFile_WriteString("<unknown>", f);
931 else
932 err = PyFile_WriteString(className, f);
933 }
934 }
935 if (err == 0 && (value != Py_None)) {
936 PyObject *s = PyObject_Str(value);
937 /* only print colon if the str() of the
938 object is not the empty string
939 */
Martin Panter3263f682016-02-28 03:16:11 +0000940 if (s == NULL) {
941 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 err = -1;
Martin Panter3263f682016-02-28 03:16:11 +0000943 PyFile_WriteString(": <exception str() failed>", f);
944 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 else if (!PyUnicode_Check(s) ||
Victor Stinnere251d6d2011-11-20 19:20:00 +0100946 PyUnicode_GetLength(s) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 err = PyFile_WriteString(": ", f);
948 if (err == 0)
949 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
950 Py_XDECREF(s);
951 }
952 /* try to write a newline in any case */
Martin Panter3263f682016-02-28 03:16:11 +0000953 if (err < 0) {
954 PyErr_Clear();
955 }
Pablo Galindo37494b42021-04-14 02:36:07 +0100956 PyObject* suggestions = _Py_Offer_Suggestions(value);
957 if (suggestions) {
958 // Add a trailer ". Did you mean: (...)?"
959 err = PyFile_WriteString(". Did you mean: ", f);
960 if (err == 0) {
961 err = PyFile_WriteObject(suggestions, f, Py_PRINT_RAW);
962 err += PyFile_WriteString("?", f);
963 }
964 Py_DECREF(suggestions);
Pablo Galindoe07f4ab2021-04-14 18:58:28 +0100965 } else if (PyErr_Occurred()) {
966 PyErr_Clear();
Pablo Galindo37494b42021-04-14 02:36:07 +0100967 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 err += PyFile_WriteString("\n", f);
969 Py_XDECREF(tb);
970 Py_DECREF(value);
971 /* If an error happened here, don't show it.
972 XXX This is wrong, but too many callers rely on this behavior. */
973 if (err != 0)
974 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +0000975}
976
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200977static const char cause_message[] =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 "\nThe above exception was the direct cause "
979 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +0000980
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200981static const char context_message[] =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 "\nDuring handling of the above exception, "
983 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +0000984
985static void
986print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
987{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 int err = 0, res;
989 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +0000990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 if (seen != NULL) {
992 /* Exception chaining */
Zane Bitterde860732017-10-17 17:29:39 -0400993 PyObject *value_id = PyLong_FromVoidPtr(value);
994 if (value_id == NULL || PySet_Add(seen, value_id) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 PyErr_Clear();
996 else if (PyExceptionInstance_Check(value)) {
Zane Bitterde860732017-10-17 17:29:39 -0400997 PyObject *check_id = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 cause = PyException_GetCause(value);
999 context = PyException_GetContext(value);
Benjamin Petersond5a1c442012-05-14 22:09:31 -07001000 if (cause) {
Zane Bitterde860732017-10-17 17:29:39 -04001001 check_id = PyLong_FromVoidPtr(cause);
1002 if (check_id == NULL) {
1003 res = -1;
1004 } else {
1005 res = PySet_Contains(seen, check_id);
1006 Py_DECREF(check_id);
1007 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 if (res == -1)
1009 PyErr_Clear();
1010 if (res == 0) {
1011 print_exception_recursive(
1012 f, cause, seen);
1013 err |= PyFile_WriteString(
1014 cause_message, f);
1015 }
1016 }
Benjamin Petersond5a1c442012-05-14 22:09:31 -07001017 else if (context &&
1018 !((PyBaseExceptionObject *)value)->suppress_context) {
Zane Bitterde860732017-10-17 17:29:39 -04001019 check_id = PyLong_FromVoidPtr(context);
1020 if (check_id == NULL) {
1021 res = -1;
1022 } else {
1023 res = PySet_Contains(seen, check_id);
1024 Py_DECREF(check_id);
1025 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001026 if (res == -1)
1027 PyErr_Clear();
1028 if (res == 0) {
1029 print_exception_recursive(
1030 f, context, seen);
1031 err |= PyFile_WriteString(
1032 context_message, f);
1033 }
1034 }
1035 Py_XDECREF(context);
1036 Py_XDECREF(cause);
1037 }
Zane Bitterde860732017-10-17 17:29:39 -04001038 Py_XDECREF(value_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 }
1040 print_exception(f, value);
1041 if (err != 0)
1042 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001043}
1044
Thomas Wouters477c8d52006-05-27 19:21:47 +00001045void
Victor Stinnercd590a72019-05-28 00:39:52 +02001046_PyErr_Display(PyObject *file, PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001047{
Victor Stinnercd590a72019-05-28 00:39:52 +02001048 assert(file != NULL && file != Py_None);
1049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 PyObject *seen;
Antoine Pitrou24201d42013-10-13 21:53:13 +02001051 if (PyExceptionInstance_Check(value)
1052 && tb != NULL && PyTraceBack_Check(tb)) {
1053 /* Put the traceback on the exception, otherwise it won't get
1054 displayed. See issue #18776. */
1055 PyObject *cur_tb = PyException_GetTraceback(value);
1056 if (cur_tb == NULL)
1057 PyException_SetTraceback(value, tb);
1058 else
1059 Py_DECREF(cur_tb);
1060 }
Victor Stinnercd590a72019-05-28 00:39:52 +02001061
1062 /* We choose to ignore seen being possibly NULL, and report
1063 at least the main exception (it could be a MemoryError).
1064 */
1065 seen = PySet_New(NULL);
1066 if (seen == NULL) {
1067 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001068 }
Victor Stinnercd590a72019-05-28 00:39:52 +02001069 print_exception_recursive(file, value, seen);
1070 Py_XDECREF(seen);
Victor Stinnera85a1d32019-05-28 16:01:17 +02001071
1072 /* Call file.flush() */
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001073 PyObject *res = _PyObject_CallMethodIdNoArgs(file, &PyId_flush);
Victor Stinnera85a1d32019-05-28 16:01:17 +02001074 if (!res) {
1075 /* Silently ignore file.flush() error */
1076 PyErr_Clear();
1077 }
1078 else {
1079 Py_DECREF(res);
1080 }
Victor Stinnercd590a72019-05-28 00:39:52 +02001081}
1082
1083void
1084PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
1085{
1086 PyObject *file = _PySys_GetObjectId(&PyId_stderr);
1087 if (file == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001088 _PyObject_Dump(value);
1089 fprintf(stderr, "lost sys.stderr\n");
Victor Stinnercd590a72019-05-28 00:39:52 +02001090 return;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 }
Victor Stinnercd590a72019-05-28 00:39:52 +02001092 if (file == Py_None) {
1093 return;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 }
Pablo Galindo09b90a02021-03-29 23:38:51 +01001095 Py_INCREF(file);
Victor Stinnercd590a72019-05-28 00:39:52 +02001096 _PyErr_Display(file, exception, value, tb);
Pablo Galindo09b90a02021-03-29 23:38:51 +01001097 Py_DECREF(file);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001098}
1099
Guido van Rossum82598051997-03-05 00:20:32 +00001100PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001101PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001103{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 PyObject *ret = NULL;
1105 mod_ty mod;
Victor Stinner95701bd2013-11-06 18:41:07 +01001106 PyArena *arena;
Victor Stinner95701bd2013-11-06 18:41:07 +01001107 PyObject *filename;
1108
1109 filename = _PyUnicode_FromId(&PyId_string); /* borrowed */
1110 if (filename == NULL)
1111 return NULL;
1112
Victor Stinner8370e072021-03-24 02:23:01 +01001113 arena = _PyArena_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001114 if (arena == NULL)
1115 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001116
Victor Stinner57364ce2021-03-24 01:29:09 +01001117 mod = _PyParser_ASTFromString(str, filename, start, flags, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 if (mod != NULL)
Victor Stinner95701bd2013-11-06 18:41:07 +01001120 ret = run_mod(mod, filename, globals, locals, flags, arena);
Victor Stinner8370e072021-03-24 02:23:01 +01001121 _PyArena_Free(arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001123}
1124
Victor Stinnerb6d98c12020-12-08 14:38:08 +01001125
1126static PyObject *
1127pyrun_file(FILE *fp, PyObject *filename, int start, PyObject *globals,
1128 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001129{
Victor Stinner8370e072021-03-24 02:23:01 +01001130 PyArena *arena = _PyArena_New();
Victor Stinnerb6d98c12020-12-08 14:38:08 +01001131 if (arena == NULL) {
1132 return NULL;
1133 }
1134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001135 mod_ty mod;
Victor Stinner57364ce2021-03-24 01:29:09 +01001136 mod = _PyParser_ASTFromFile(fp, filename, NULL, start, NULL, NULL,
1137 flags, NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001138
Victor Stinnerb6d98c12020-12-08 14:38:08 +01001139 if (closeit) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001140 fclose(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001141 }
Victor Stinner95701bd2013-11-06 18:41:07 +01001142
Victor Stinnerb6d98c12020-12-08 14:38:08 +01001143 PyObject *ret;
1144 if (mod != NULL) {
1145 ret = run_mod(mod, filename, globals, locals, flags, arena);
1146 }
1147 else {
1148 ret = NULL;
1149 }
Victor Stinner8370e072021-03-24 02:23:01 +01001150 _PyArena_Free(arena);
Victor Stinnerb6d98c12020-12-08 14:38:08 +01001151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001152 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001153}
1154
Victor Stinnerb6d98c12020-12-08 14:38:08 +01001155
1156PyObject *
1157PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
1158 PyObject *locals, int closeit, PyCompilerFlags *flags)
1159{
1160 PyObject *filename_obj = PyUnicode_DecodeFSDefault(filename);
1161 if (filename_obj == NULL) {
1162 return NULL;
1163 }
1164
1165 PyObject *res = pyrun_file(fp, filename_obj, start, globals,
1166 locals, closeit, flags);
1167 Py_DECREF(filename_obj);
1168 return res;
1169
1170}
1171
1172
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001173static void
1174flush_io(void)
1175{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001176 PyObject *f, *r;
1177 PyObject *type, *value, *traceback;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 /* Save the current exception */
1180 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001181
Victor Stinnerbd303c12013-11-07 23:07:29 +01001182 f = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 if (f != NULL) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001184 r = _PyObject_CallMethodIdNoArgs(f, &PyId_flush);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001185 if (r)
1186 Py_DECREF(r);
1187 else
1188 PyErr_Clear();
1189 }
Victor Stinnerbd303c12013-11-07 23:07:29 +01001190 f = _PySys_GetObjectId(&PyId_stdout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 if (f != NULL) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001192 r = _PyObject_CallMethodIdNoArgs(f, &PyId_flush);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001193 if (r)
1194 Py_DECREF(r);
1195 else
1196 PyErr_Clear();
1197 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001199 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001200}
1201
Guido van Rossum82598051997-03-05 00:20:32 +00001202static PyObject *
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001203run_eval_code_obj(PyThreadState *tstate, PyCodeObject *co, PyObject *globals, PyObject *locals)
Gregory P. Smith38f11cc2019-02-16 12:57:40 -08001204{
1205 PyObject *v;
Gregory P. Smithd9bc5432019-02-20 17:35:54 -08001206 /*
1207 * We explicitly re-initialize _Py_UnhandledKeyboardInterrupt every eval
1208 * _just in case_ someone is calling into an embedded Python where they
1209 * don't care about an uncaught KeyboardInterrupt exception (why didn't they
1210 * leave config.install_signal_handlers set to 0?!?) but then later call
1211 * Py_Main() itself (which _checks_ this flag and dies with a signal after
1212 * its interpreter exits). We don't want a previous embedded interpreter's
1213 * uncaught exception to trigger an unexplained signal exit from a future
1214 * Py_Main() based one.
1215 */
1216 _Py_UnhandledKeyboardInterrupt = 0;
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001217
1218 /* Set globals['__builtins__'] if it doesn't exist */
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02001219 if (globals != NULL && _PyDict_GetItemStringWithError(globals, "__builtins__") == NULL) {
1220 if (PyErr_Occurred() ||
1221 PyDict_SetItemString(globals, "__builtins__",
1222 tstate->interp->builtins) < 0)
1223 {
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001224 return NULL;
1225 }
1226 }
1227
Gregory P. Smith38f11cc2019-02-16 12:57:40 -08001228 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001229 if (!v && _PyErr_Occurred(tstate) == PyExc_KeyboardInterrupt) {
Gregory P. Smith38f11cc2019-02-16 12:57:40 -08001230 _Py_UnhandledKeyboardInterrupt = 1;
1231 }
1232 return v;
1233}
1234
1235static PyObject *
Victor Stinner95701bd2013-11-06 18:41:07 +01001236run_mod(mod_ty mod, PyObject *filename, PyObject *globals, PyObject *locals,
1237 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001238{
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001239 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinnera81fca62021-03-24 00:51:50 +01001240 PyCodeObject *co = _PyAST_Compile(mod, filename, flags, -1, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 if (co == NULL)
1242 return NULL;
Steve Dowerb82e17e2019-05-23 08:45:22 -07001243
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001244 if (_PySys_Audit(tstate, "exec", "O", co) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07001245 Py_DECREF(co);
1246 return NULL;
1247 }
1248
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001249 PyObject *v = run_eval_code_obj(tstate, co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001250 Py_DECREF(co);
1251 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001252}
1253
Guido van Rossum82598051997-03-05 00:20:32 +00001254static PyObject *
Victor Stinnerb6d98c12020-12-08 14:38:08 +01001255run_pyc_file(FILE *fp, PyObject *globals, PyObject *locals,
1256 PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001257{
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001258 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 PyCodeObject *co;
1260 PyObject *v;
1261 long magic;
1262 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 magic = PyMarshal_ReadLongFromFile(fp);
1265 if (magic != PyImport_GetMagicNumber()) {
Victor Stinner5200f552015-03-18 13:56:25 +01001266 if (!PyErr_Occurred())
1267 PyErr_SetString(PyExc_RuntimeError,
1268 "Bad magic number in .pyc file");
Zackery Spytzea737752018-06-23 21:15:24 -06001269 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 }
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08001271 /* Skip the rest of the header. */
1272 (void) PyMarshal_ReadLongFromFile(fp);
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001273 (void) PyMarshal_ReadLongFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001274 (void) PyMarshal_ReadLongFromFile(fp);
Zackery Spytzea737752018-06-23 21:15:24 -06001275 if (PyErr_Occurred()) {
1276 goto error;
1277 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 v = PyMarshal_ReadLastObjectFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001279 if (v == NULL || !PyCode_Check(v)) {
1280 Py_XDECREF(v);
1281 PyErr_SetString(PyExc_RuntimeError,
1282 "Bad code object in .pyc file");
Zackery Spytzea737752018-06-23 21:15:24 -06001283 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 }
Zackery Spytzea737752018-06-23 21:15:24 -06001285 fclose(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001286 co = (PyCodeObject *)v;
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001287 v = run_eval_code_obj(tstate, co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001288 if (v && flags)
1289 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1290 Py_DECREF(co);
1291 return v;
Zackery Spytzea737752018-06-23 21:15:24 -06001292error:
1293 fclose(fp);
1294 return NULL;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001295}
1296
Guido van Rossum82598051997-03-05 00:20:32 +00001297PyObject *
Victor Stinner14e461d2013-08-26 22:28:21 +02001298Py_CompileStringObject(const char *str, PyObject *filename, int start,
1299 PyCompilerFlags *flags, int optimize)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001300{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001301 PyCodeObject *co;
1302 mod_ty mod;
Victor Stinner8370e072021-03-24 02:23:01 +01001303 PyArena *arena = _PyArena_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001304 if (arena == NULL)
1305 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001306
Victor Stinner57364ce2021-03-24 01:29:09 +01001307 mod = _PyParser_ASTFromString(str, filename, start, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001308 if (mod == NULL) {
Victor Stinner8370e072021-03-24 02:23:01 +01001309 _PyArena_Free(arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 return NULL;
1311 }
1312 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
1313 PyObject *result = PyAST_mod2obj(mod);
Victor Stinner8370e072021-03-24 02:23:01 +01001314 _PyArena_Free(arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 return result;
1316 }
Victor Stinnera81fca62021-03-24 00:51:50 +01001317 co = _PyAST_Compile(mod, filename, flags, optimize, arena);
Victor Stinner8370e072021-03-24 02:23:01 +01001318 _PyArena_Free(arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001320}
1321
Victor Stinner14e461d2013-08-26 22:28:21 +02001322PyObject *
1323Py_CompileStringExFlags(const char *str, const char *filename_str, int start,
1324 PyCompilerFlags *flags, int optimize)
1325{
1326 PyObject *filename, *co;
1327 filename = PyUnicode_DecodeFSDefault(filename_str);
1328 if (filename == NULL)
1329 return NULL;
1330 co = Py_CompileStringObject(str, filename, start, flags, optimize);
1331 Py_DECREF(filename);
1332 return co;
1333}
1334
Dino Viehland41540692019-05-28 16:21:17 -07001335const char *
1336_Py_SourceAsString(PyObject *cmd, const char *funcname, const char *what, PyCompilerFlags *cf, PyObject **cmd_copy)
1337{
1338 const char *str;
1339 Py_ssize_t size;
1340 Py_buffer view;
1341
1342 *cmd_copy = NULL;
1343 if (PyUnicode_Check(cmd)) {
1344 cf->cf_flags |= PyCF_IGNORE_COOKIE;
1345 str = PyUnicode_AsUTF8AndSize(cmd, &size);
1346 if (str == NULL)
1347 return NULL;
1348 }
1349 else if (PyBytes_Check(cmd)) {
1350 str = PyBytes_AS_STRING(cmd);
1351 size = PyBytes_GET_SIZE(cmd);
1352 }
1353 else if (PyByteArray_Check(cmd)) {
1354 str = PyByteArray_AS_STRING(cmd);
1355 size = PyByteArray_GET_SIZE(cmd);
1356 }
1357 else if (PyObject_GetBuffer(cmd, &view, PyBUF_SIMPLE) == 0) {
1358 /* Copy to NUL-terminated buffer. */
1359 *cmd_copy = PyBytes_FromStringAndSize(
1360 (const char *)view.buf, view.len);
1361 PyBuffer_Release(&view);
1362 if (*cmd_copy == NULL) {
1363 return NULL;
1364 }
1365 str = PyBytes_AS_STRING(*cmd_copy);
1366 size = PyBytes_GET_SIZE(*cmd_copy);
1367 }
1368 else {
1369 PyErr_Format(PyExc_TypeError,
1370 "%s() arg 1 must be a %s object",
1371 funcname, what);
1372 return NULL;
1373 }
1374
1375 if (strlen(str) != (size_t)size) {
1376 PyErr_SetString(PyExc_ValueError,
1377 "source code string cannot contain null bytes");
1378 Py_CLEAR(*cmd_copy);
1379 return NULL;
1380 }
1381 return str;
1382}
1383
Zachary Warec4821d62014-11-21 23:35:12 -06001384#if defined(USE_STACKCHECK)
1385#if defined(WIN32) && defined(_MSC_VER)
1386
1387/* Stack checking for Microsoft C */
1388
1389#include <malloc.h>
1390#include <excpt.h>
1391
1392/*
1393 * Return non-zero when we run out of memory on the stack; zero otherwise.
1394 */
1395int
1396PyOS_CheckStack(void)
1397{
1398 __try {
1399 /* alloca throws a stack overflow exception if there's
1400 not enough space left on the stack */
1401 alloca(PYOS_STACK_MARGIN * sizeof(void*));
1402 return 0;
1403 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
1404 EXCEPTION_EXECUTE_HANDLER :
1405 EXCEPTION_CONTINUE_SEARCH) {
1406 int errcode = _resetstkoflw();
1407 if (errcode == 0)
1408 {
1409 Py_FatalError("Could not reset the stack!");
1410 }
1411 }
1412 return 1;
1413}
1414
1415#endif /* WIN32 && _MSC_VER */
1416
1417/* Alternate implementations can be added here... */
1418
1419#endif /* USE_STACKCHECK */
1420
Pablo Galindo46bd5ed2020-12-02 05:16:31 +00001421/* Deprecated C API functions still provided for binary compatibility */
1422
1423#undef PyRun_AnyFile
1424PyAPI_FUNC(int)
1425PyRun_AnyFile(FILE *fp, const char *name)
1426{
1427 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
1428}
1429
1430#undef PyRun_AnyFileEx
1431PyAPI_FUNC(int)
1432PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
1433{
1434 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
1435}
1436
1437#undef PyRun_AnyFileFlags
1438PyAPI_FUNC(int)
1439PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
1440{
1441 return PyRun_AnyFileExFlags(fp, name, 0, flags);
1442}
1443
1444#undef PyRun_File
1445PyAPI_FUNC(PyObject *)
1446PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
1447{
1448 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
1449}
1450
1451#undef PyRun_FileEx
1452PyAPI_FUNC(PyObject *)
1453PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
1454{
1455 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
1456}
1457
1458#undef PyRun_FileFlags
1459PyAPI_FUNC(PyObject *)
1460PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
1461 PyCompilerFlags *flags)
1462{
1463 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
1464}
1465
1466#undef PyRun_SimpleFile
1467PyAPI_FUNC(int)
1468PyRun_SimpleFile(FILE *f, const char *p)
1469{
1470 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
1471}
1472
1473#undef PyRun_SimpleFileEx
1474PyAPI_FUNC(int)
1475PyRun_SimpleFileEx(FILE *f, const char *p, int c)
1476{
1477 return PyRun_SimpleFileExFlags(f, p, c, NULL);
1478}
1479
1480
1481#undef PyRun_String
1482PyAPI_FUNC(PyObject *)
1483PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
1484{
1485 return PyRun_StringFlags(str, s, g, l, NULL);
1486}
1487
1488#undef PyRun_SimpleString
1489PyAPI_FUNC(int)
1490PyRun_SimpleString(const char *s)
1491{
1492 return PyRun_SimpleStringFlags(s, NULL);
1493}
1494
1495#undef Py_CompileString
1496PyAPI_FUNC(PyObject *)
1497Py_CompileString(const char *str, const char *p, int s)
1498{
1499 return Py_CompileStringExFlags(str, p, s, NULL, -1);
1500}
1501
1502#undef Py_CompileStringFlags
1503PyAPI_FUNC(PyObject *)
1504Py_CompileStringFlags(const char *str, const char *p, int s,
1505 PyCompilerFlags *flags)
1506{
1507 return Py_CompileStringExFlags(str, p, s, flags, -1);
1508}
1509
1510#undef PyRun_InteractiveOne
1511PyAPI_FUNC(int)
1512PyRun_InteractiveOne(FILE *f, const char *p)
1513{
1514 return PyRun_InteractiveOneFlags(f, p, NULL);
1515}
1516
1517#undef PyRun_InteractiveLoop
1518PyAPI_FUNC(int)
1519PyRun_InteractiveLoop(FILE *f, const char *p)
1520{
1521 return PyRun_InteractiveLoopFlags(f, p, NULL);
1522}
1523
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001524#ifdef __cplusplus
1525}
1526#endif