blob: e16835b13e817cb8e4439595f5933e5f59b5689e [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 Stinner3bb183d2018-11-22 18:38:38 +010014#undef Yield /* undefine macro conflicting with <winbase.h> */
Victor Stinner4f98f462020-04-15 04:01:58 +020015
Victor Stinnera81fca62021-03-24 00:51:50 +010016#include "pycore_compile.h" // _PyAST_Compile()
Victor Stinnere5014be2020-04-14 17:52:15 +020017#include "pycore_interp.h" // PyInterpreterState.importlib
Victor Stinner4f98f462020-04-15 04:01:58 +020018#include "pycore_object.h" // _PyDebug_PrintTotalRefs()
19#include "pycore_pyerrors.h" // _PyErr_Fetch
20#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 }
249 arena = PyArena_New();
250 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
Lysandros Nikolaou564cd182020-06-22 02:47:46 +0300257 mod = PyParser_ASTFromFileObject(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) {
264 PyArena_Free(arena);
265 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) {
273 PyArena_Free(arena);
274 return -1;
275 }
276 d = PyModule_GetDict(m);
277 v = run_mod(mod, filename, d, d, flags, arena);
278 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,
Ammar Askar90d29702020-06-02 08:17:24 +0000514 Py_ssize_t *lineno, Py_ssize_t *offset, PyObject **text)
Barry Warsaw035574d1997-08-29 22:07:17 +0000515{
Ammar Askar90d29702020-06-02 08:17:24 +0000516 Py_ssize_t hold;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 PyObject *v;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200518 _Py_IDENTIFIER(msg);
519 _Py_IDENTIFIER(filename);
520 _Py_IDENTIFIER(lineno);
521 _Py_IDENTIFIER(offset);
522 _Py_IDENTIFIER(text);
Barry Warsaw035574d1997-08-29 22:07:17 +0000523
Benjamin Peterson80d50422012-04-03 00:30:38 -0400524 *message = NULL;
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100525 *filename = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000527 /* new style errors. `err' is an instance */
Benjamin Peterson0a9a6362012-04-03 00:35:36 -0400528 *message = _PyObject_GetAttrId(err, &PyId_msg);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400529 if (!*message)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +0000531
Benjamin Peterson0a9a6362012-04-03 00:35:36 -0400532 v = _PyObject_GetAttrId(err, &PyId_filename);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400533 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400535 if (v == Py_None) {
536 Py_DECREF(v);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100537 *filename = _PyUnicode_FromId(&PyId_string);
538 if (*filename == NULL)
539 goto finally;
540 Py_INCREF(*filename);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400541 }
542 else {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100543 *filename = v;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400544 }
Barry Warsaw035574d1997-08-29 22:07:17 +0000545
Benjamin Peterson0a9a6362012-04-03 00:35:36 -0400546 v = _PyObject_GetAttrId(err, &PyId_lineno);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400547 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 goto finally;
Ammar Askar90d29702020-06-02 08:17:24 +0000549 hold = PyLong_AsSsize_t(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 if (hold < 0 && PyErr_Occurred())
552 goto finally;
Serhiy Storchaka56f6e762015-09-06 21:25:30 +0300553 *lineno = hold;
Barry Warsaw035574d1997-08-29 22:07:17 +0000554
Benjamin Peterson0a9a6362012-04-03 00:35:36 -0400555 v = _PyObject_GetAttrId(err, &PyId_offset);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400556 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 goto finally;
558 if (v == Py_None) {
559 *offset = -1;
560 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 } else {
Ammar Askar90d29702020-06-02 08:17:24 +0000562 hold = PyLong_AsSsize_t(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564 if (hold < 0 && PyErr_Occurred())
565 goto finally;
Serhiy Storchaka56f6e762015-09-06 21:25:30 +0300566 *offset = hold;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 }
Barry Warsaw035574d1997-08-29 22:07:17 +0000568
Benjamin Peterson0a9a6362012-04-03 00:35:36 -0400569 v = _PyObject_GetAttrId(err, &PyId_text);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400570 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000571 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400572 if (v == Py_None) {
573 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 *text = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400575 }
576 else {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100577 *text = v;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400578 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +0000580
581finally:
Benjamin Peterson80d50422012-04-03 00:30:38 -0400582 Py_XDECREF(*message);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100583 Py_XDECREF(*filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +0000585}
586
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000587static void
Ammar Askar90d29702020-06-02 08:17:24 +0000588print_error_text(PyObject *f, Py_ssize_t offset, PyObject *text_obj)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000589{
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700590 /* Convert text to a char pointer; return if error */
591 const char *text = PyUnicode_AsUTF8(text_obj);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100592 if (text == NULL)
593 return;
594
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700595 /* Convert offset from 1-based to 0-based */
596 offset--;
597
598 /* Strip leading whitespace from text, adjusting offset as we go */
599 while (*text == ' ' || *text == '\t' || *text == '\f') {
600 text++;
601 offset--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 }
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700603
604 /* Calculate text length excluding trailing newline */
605 Py_ssize_t len = strlen(text);
606 if (len > 0 && text[len-1] == '\n') {
607 len--;
608 }
609
610 /* Clip offset to at most len */
611 if (offset > len) {
612 offset = len;
613 }
614
615 /* Skip past newlines embedded in text */
616 for (;;) {
617 const char *nl = strchr(text, '\n');
618 if (nl == NULL) {
619 break;
620 }
621 Py_ssize_t inl = nl - text;
Ammar Askar90d29702020-06-02 08:17:24 +0000622 if (inl >= offset) {
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700623 break;
624 }
625 inl += 1;
626 text += inl;
627 len -= inl;
628 offset -= (int)inl;
629 }
630
631 /* Print text */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 PyFile_WriteString(" ", f);
633 PyFile_WriteString(text, f);
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700634
635 /* Make sure there's a newline at the end */
636 if (text[len] != '\n') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000637 PyFile_WriteString("\n", f);
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700638 }
639
640 /* Don't print caret if it points to the left of the text */
641 if (offset < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 return;
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700643
644 /* Write caret line */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 PyFile_WriteString(" ", f);
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700646 while (--offset >= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 PyFile_WriteString(" ", f);
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700648 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000650}
651
Tim Peterscf615b52003-04-19 18:47:02 +0000652
Victor Stinner12083282019-05-17 23:05:29 +0200653int
654_Py_HandleSystemExit(int *exitcode_p)
655{
Victor Stinnerda7933e2020-04-13 03:04:28 +0200656 int inspect = _Py_GetConfig()->inspect;
Victor Stinnerc96be812019-05-14 17:34:56 +0200657 if (inspect) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 /* Don't exit if -i flag was given. This flag is set to 0
659 * when entering interactive mode for inspecting. */
Victor Stinner12083282019-05-17 23:05:29 +0200660 return 0;
Victor Stinnerc96be812019-05-14 17:34:56 +0200661 }
Guido van Rossumd8faa362007-04-27 19:54:29 +0000662
Victor Stinner12083282019-05-17 23:05:29 +0200663 if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
664 return 0;
665 }
666
667 PyObject *exception, *value, *tb;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 PyErr_Fetch(&exception, &value, &tb);
Victor Stinner12083282019-05-17 23:05:29 +0200669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 fflush(stdout);
Victor Stinner12083282019-05-17 23:05:29 +0200671
672 int exitcode = 0;
673 if (value == NULL || value == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 goto done;
Victor Stinner12083282019-05-17 23:05:29 +0200675 }
676
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 if (PyExceptionInstance_Check(value)) {
678 /* The error code should be in the `code' attribute. */
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200679 _Py_IDENTIFIER(code);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200680 PyObject *code = _PyObject_GetAttrId(value, &PyId_code);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 if (code) {
682 Py_DECREF(value);
683 value = code;
684 if (value == Py_None)
685 goto done;
686 }
687 /* If we failed to dig out the 'code' attribute,
688 just let the else clause below print the error. */
689 }
Victor Stinner12083282019-05-17 23:05:29 +0200690
691 if (PyLong_Check(value)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 exitcode = (int)PyLong_AsLong(value);
Victor Stinner12083282019-05-17 23:05:29 +0200693 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 else {
Victor Stinnerbd303c12013-11-07 23:07:29 +0100695 PyObject *sys_stderr = _PySys_GetObjectId(&PyId_stderr);
Nick Coghland979e432014-02-09 10:43:21 +1000696 /* We clear the exception here to avoid triggering the assertion
697 * in PyObject_Str that ensures it won't silently lose exception
698 * details.
699 */
700 PyErr_Clear();
Victor Stinner7126dbc2010-05-21 23:45:42 +0000701 if (sys_stderr != NULL && sys_stderr != Py_None) {
702 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
703 } else {
704 PyObject_Print(value, stderr, Py_PRINT_RAW);
705 fflush(stderr);
706 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 PySys_WriteStderr("\n");
708 exitcode = 1;
709 }
Victor Stinner12083282019-05-17 23:05:29 +0200710
Tim Peterscf615b52003-04-19 18:47:02 +0000711 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 /* Restore and clear the exception info, in order to properly decref
713 * the exception, value, and traceback. If we just exit instead,
714 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
715 * some finalizers from running.
716 */
717 PyErr_Restore(exception, value, tb);
718 PyErr_Clear();
Victor Stinner12083282019-05-17 23:05:29 +0200719 *exitcode_p = exitcode;
720 return 1;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000721}
722
Victor Stinner12083282019-05-17 23:05:29 +0200723
724static void
725handle_system_exit(void)
726{
727 int exitcode;
728 if (_Py_HandleSystemExit(&exitcode)) {
729 Py_Exit(exitcode);
730 }
731}
732
733
Victor Stinner438a12d2019-05-24 17:01:38 +0200734static void
735_PyErr_PrintEx(PyThreadState *tstate, int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000736{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +0000738
Victor Stinner12083282019-05-17 23:05:29 +0200739 handle_system_exit();
740
Victor Stinner438a12d2019-05-24 17:01:38 +0200741 _PyErr_Fetch(tstate, &exception, &v, &tb);
742 if (exception == NULL) {
743 goto done;
744 }
745
746 _PyErr_NormalizeException(tstate, &exception, &v, &tb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000747 if (tb == NULL) {
748 tb = Py_None;
749 Py_INCREF(tb);
750 }
751 PyException_SetTraceback(v, tb);
Victor Stinner438a12d2019-05-24 17:01:38 +0200752 if (exception == NULL) {
753 goto done;
754 }
755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 /* Now we know v != NULL too */
757 if (set_sys_last_vars) {
xdegaye66caacf2017-10-23 18:08:41 +0200758 if (_PySys_SetObjectId(&PyId_last_type, exception) < 0) {
Victor Stinner438a12d2019-05-24 17:01:38 +0200759 _PyErr_Clear(tstate);
xdegaye66caacf2017-10-23 18:08:41 +0200760 }
761 if (_PySys_SetObjectId(&PyId_last_value, v) < 0) {
Victor Stinner438a12d2019-05-24 17:01:38 +0200762 _PyErr_Clear(tstate);
xdegaye66caacf2017-10-23 18:08:41 +0200763 }
764 if (_PySys_SetObjectId(&PyId_last_traceback, tb) < 0) {
Victor Stinner438a12d2019-05-24 17:01:38 +0200765 _PyErr_Clear(tstate);
xdegaye66caacf2017-10-23 18:08:41 +0200766 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000767 }
Victor Stinner09054372013-11-06 22:41:44 +0100768 hook = _PySys_GetObjectId(&PyId_excepthook);
Victor Stinner1c1e68c2020-03-27 15:11:45 +0100769 if (_PySys_Audit(tstate, "sys.excepthook", "OOOO", hook ? hook : Py_None,
770 exception, v, tb) < 0) {
Steve Dowerbea33f52019-11-28 08:46:11 -0800771 if (PyErr_ExceptionMatches(PyExc_RuntimeError)) {
772 PyErr_Clear();
773 goto done;
774 }
775 _PyErr_WriteUnraisableMsg("in audit hook", NULL);
776 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000777 if (hook) {
Victor Stinner71cb64a2016-08-20 00:57:43 +0200778 PyObject* stack[3];
779 PyObject *result;
780
781 stack[0] = exception;
782 stack[1] = v;
783 stack[2] = tb;
Victor Stinner559bb6a2016-08-22 22:48:54 +0200784 result = _PyObject_FastCall(hook, stack, 3);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 if (result == NULL) {
Victor Stinner12083282019-05-17 23:05:29 +0200786 handle_system_exit();
787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000788 PyObject *exception2, *v2, *tb2;
Victor Stinner438a12d2019-05-24 17:01:38 +0200789 _PyErr_Fetch(tstate, &exception2, &v2, &tb2);
790 _PyErr_NormalizeException(tstate, &exception2, &v2, &tb2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 /* It should not be possible for exception2 or v2
792 to be NULL. However PyErr_Display() can't
793 tolerate NULLs, so just be safe. */
794 if (exception2 == NULL) {
795 exception2 = Py_None;
796 Py_INCREF(exception2);
797 }
798 if (v2 == NULL) {
799 v2 = Py_None;
800 Py_INCREF(v2);
801 }
802 fflush(stdout);
803 PySys_WriteStderr("Error in sys.excepthook:\n");
804 PyErr_Display(exception2, v2, tb2);
805 PySys_WriteStderr("\nOriginal exception was:\n");
806 PyErr_Display(exception, v, tb);
807 Py_DECREF(exception2);
808 Py_DECREF(v2);
809 Py_XDECREF(tb2);
810 }
811 Py_XDECREF(result);
Victor Stinner438a12d2019-05-24 17:01:38 +0200812 }
813 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 PySys_WriteStderr("sys.excepthook is missing\n");
815 PyErr_Display(exception, v, tb);
816 }
Victor Stinner438a12d2019-05-24 17:01:38 +0200817
818done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 Py_XDECREF(exception);
820 Py_XDECREF(v);
821 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000822}
823
Victor Stinner438a12d2019-05-24 17:01:38 +0200824void
825_PyErr_Print(PyThreadState *tstate)
826{
827 _PyErr_PrintEx(tstate, 1);
828}
829
830void
831PyErr_PrintEx(int set_sys_last_vars)
832{
833 PyThreadState *tstate = _PyThreadState_GET();
834 _PyErr_PrintEx(tstate, set_sys_last_vars);
835}
836
837void
838PyErr_Print(void)
839{
840 PyErr_PrintEx(1);
841}
842
Benjamin Petersone6528212008-07-15 15:32:09 +0000843static void
844print_exception(PyObject *f, PyObject *value)
845{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 int err = 0;
Serhiy Storchaka98c44332020-10-10 22:23:42 +0300847 PyObject *type, *tb, *tmp;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200848 _Py_IDENTIFIER(print_file_and_line);
Benjamin Petersone6528212008-07-15 15:32:09 +0000849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 if (!PyExceptionInstance_Check(value)) {
Victor Stinner52ce3b02013-12-09 02:10:08 +0100851 err = PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
852 err += PyFile_WriteString(Py_TYPE(value)->tp_name, f);
853 err += PyFile_WriteString(" found\n", f);
854 if (err)
855 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856 return;
857 }
Benjamin Peterson26582602008-08-23 20:08:07 +0000858
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 Py_INCREF(value);
860 fflush(stdout);
861 type = (PyObject *) Py_TYPE(value);
862 tb = PyException_GetTraceback(value);
863 if (tb && tb != Py_None)
864 err = PyTraceBack_Print(tb, f);
865 if (err == 0 &&
Serhiy Storchaka98c44332020-10-10 22:23:42 +0300866 (err = _PyObject_LookupAttrId(value, &PyId_print_file_and_line, &tmp)) > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100868 PyObject *message, *filename, *text;
Ammar Askar90d29702020-06-02 08:17:24 +0000869 Py_ssize_t lineno, offset;
Serhiy Storchaka98c44332020-10-10 22:23:42 +0300870 err = 0;
871 Py_DECREF(tmp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 if (!parse_syntax_error(value, &message, &filename,
873 &lineno, &offset, &text))
874 PyErr_Clear();
875 else {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100876 PyObject *line;
877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 Py_DECREF(value);
879 value = message;
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100880
Ammar Askar90d29702020-06-02 08:17:24 +0000881 line = PyUnicode_FromFormat(" File \"%S\", line %zd\n",
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100882 filename, lineno);
883 Py_DECREF(filename);
884 if (line != NULL) {
885 PyFile_WriteObject(line, f, Py_PRINT_RAW);
886 Py_DECREF(line);
887 }
888
889 if (text != NULL) {
890 print_error_text(f, offset, text);
891 Py_DECREF(text);
892 }
893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 /* Can't be bothered to check all those
895 PyFile_WriteString() calls */
896 if (PyErr_Occurred())
897 err = -1;
898 }
899 }
900 if (err) {
901 /* Don't do anything else */
902 }
903 else {
904 PyObject* moduleName;
Serhiy Storchakaceeef102018-06-15 11:09:43 +0300905 const char *className;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200906 _Py_IDENTIFIER(__module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 assert(PyExceptionClass_Check(type));
908 className = PyExceptionClass_Name(type);
909 if (className != NULL) {
Serhiy Storchakaceeef102018-06-15 11:09:43 +0300910 const char *dot = strrchr(className, '.');
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911 if (dot != NULL)
912 className = dot+1;
913 }
Benjamin Petersone6528212008-07-15 15:32:09 +0000914
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200915 moduleName = _PyObject_GetAttrId(type, &PyId___module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 if (moduleName == NULL || !PyUnicode_Check(moduleName))
917 {
Victor Stinner13b21bd2011-05-26 14:25:13 +0200918 Py_XDECREF(moduleName);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 err = PyFile_WriteString("<unknown>", f);
920 }
921 else {
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +0200922 if (!_PyUnicode_EqualToASCIIId(moduleName, &PyId_builtins))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 {
Victor Stinner937114f2013-11-07 00:12:30 +0100924 err = PyFile_WriteObject(moduleName, f, Py_PRINT_RAW);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 err += PyFile_WriteString(".", f);
926 }
927 Py_DECREF(moduleName);
928 }
929 if (err == 0) {
930 if (className == NULL)
931 err = PyFile_WriteString("<unknown>", f);
932 else
933 err = PyFile_WriteString(className, f);
934 }
935 }
936 if (err == 0 && (value != Py_None)) {
937 PyObject *s = PyObject_Str(value);
938 /* only print colon if the str() of the
939 object is not the empty string
940 */
Martin Panter3263f682016-02-28 03:16:11 +0000941 if (s == NULL) {
942 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 err = -1;
Martin Panter3263f682016-02-28 03:16:11 +0000944 PyFile_WriteString(": <exception str() failed>", f);
945 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 else if (!PyUnicode_Check(s) ||
Victor Stinnere251d6d2011-11-20 19:20:00 +0100947 PyUnicode_GetLength(s) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 err = PyFile_WriteString(": ", f);
949 if (err == 0)
950 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
951 Py_XDECREF(s);
952 }
953 /* try to write a newline in any case */
Martin Panter3263f682016-02-28 03:16:11 +0000954 if (err < 0) {
955 PyErr_Clear();
956 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 err += PyFile_WriteString("\n", f);
958 Py_XDECREF(tb);
959 Py_DECREF(value);
960 /* If an error happened here, don't show it.
961 XXX This is wrong, but too many callers rely on this behavior. */
962 if (err != 0)
963 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +0000964}
965
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200966static const char cause_message[] =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000967 "\nThe above exception was the direct cause "
968 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +0000969
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200970static const char context_message[] =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 "\nDuring handling of the above exception, "
972 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +0000973
974static void
975print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
976{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 int err = 0, res;
978 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +0000979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 if (seen != NULL) {
981 /* Exception chaining */
Zane Bitterde860732017-10-17 17:29:39 -0400982 PyObject *value_id = PyLong_FromVoidPtr(value);
983 if (value_id == NULL || PySet_Add(seen, value_id) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 PyErr_Clear();
985 else if (PyExceptionInstance_Check(value)) {
Zane Bitterde860732017-10-17 17:29:39 -0400986 PyObject *check_id = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 cause = PyException_GetCause(value);
988 context = PyException_GetContext(value);
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700989 if (cause) {
Zane Bitterde860732017-10-17 17:29:39 -0400990 check_id = PyLong_FromVoidPtr(cause);
991 if (check_id == NULL) {
992 res = -1;
993 } else {
994 res = PySet_Contains(seen, check_id);
995 Py_DECREF(check_id);
996 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 if (res == -1)
998 PyErr_Clear();
999 if (res == 0) {
1000 print_exception_recursive(
1001 f, cause, seen);
1002 err |= PyFile_WriteString(
1003 cause_message, f);
1004 }
1005 }
Benjamin Petersond5a1c442012-05-14 22:09:31 -07001006 else if (context &&
1007 !((PyBaseExceptionObject *)value)->suppress_context) {
Zane Bitterde860732017-10-17 17:29:39 -04001008 check_id = PyLong_FromVoidPtr(context);
1009 if (check_id == NULL) {
1010 res = -1;
1011 } else {
1012 res = PySet_Contains(seen, check_id);
1013 Py_DECREF(check_id);
1014 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 if (res == -1)
1016 PyErr_Clear();
1017 if (res == 0) {
1018 print_exception_recursive(
1019 f, context, seen);
1020 err |= PyFile_WriteString(
1021 context_message, f);
1022 }
1023 }
1024 Py_XDECREF(context);
1025 Py_XDECREF(cause);
1026 }
Zane Bitterde860732017-10-17 17:29:39 -04001027 Py_XDECREF(value_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 }
1029 print_exception(f, value);
1030 if (err != 0)
1031 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001032}
1033
Thomas Wouters477c8d52006-05-27 19:21:47 +00001034void
Victor Stinnercd590a72019-05-28 00:39:52 +02001035_PyErr_Display(PyObject *file, PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001036{
Victor Stinnercd590a72019-05-28 00:39:52 +02001037 assert(file != NULL && file != Py_None);
1038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 PyObject *seen;
Antoine Pitrou24201d42013-10-13 21:53:13 +02001040 if (PyExceptionInstance_Check(value)
1041 && tb != NULL && PyTraceBack_Check(tb)) {
1042 /* Put the traceback on the exception, otherwise it won't get
1043 displayed. See issue #18776. */
1044 PyObject *cur_tb = PyException_GetTraceback(value);
1045 if (cur_tb == NULL)
1046 PyException_SetTraceback(value, tb);
1047 else
1048 Py_DECREF(cur_tb);
1049 }
Victor Stinnercd590a72019-05-28 00:39:52 +02001050
1051 /* We choose to ignore seen being possibly NULL, and report
1052 at least the main exception (it could be a MemoryError).
1053 */
1054 seen = PySet_New(NULL);
1055 if (seen == NULL) {
1056 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 }
Victor Stinnercd590a72019-05-28 00:39:52 +02001058 print_exception_recursive(file, value, seen);
1059 Py_XDECREF(seen);
Victor Stinnera85a1d32019-05-28 16:01:17 +02001060
1061 /* Call file.flush() */
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001062 PyObject *res = _PyObject_CallMethodIdNoArgs(file, &PyId_flush);
Victor Stinnera85a1d32019-05-28 16:01:17 +02001063 if (!res) {
1064 /* Silently ignore file.flush() error */
1065 PyErr_Clear();
1066 }
1067 else {
1068 Py_DECREF(res);
1069 }
Victor Stinnercd590a72019-05-28 00:39:52 +02001070}
1071
1072void
1073PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
1074{
1075 PyObject *file = _PySys_GetObjectId(&PyId_stderr);
1076 if (file == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 _PyObject_Dump(value);
1078 fprintf(stderr, "lost sys.stderr\n");
Victor Stinnercd590a72019-05-28 00:39:52 +02001079 return;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 }
Victor Stinnercd590a72019-05-28 00:39:52 +02001081 if (file == Py_None) {
1082 return;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 }
Victor Stinnercd590a72019-05-28 00:39:52 +02001084
1085 _PyErr_Display(file, exception, value, tb);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001086}
1087
Guido van Rossum82598051997-03-05 00:20:32 +00001088PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001089PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001090 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001091{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 PyObject *ret = NULL;
1093 mod_ty mod;
Victor Stinner95701bd2013-11-06 18:41:07 +01001094 PyArena *arena;
Victor Stinner95701bd2013-11-06 18:41:07 +01001095 PyObject *filename;
1096
1097 filename = _PyUnicode_FromId(&PyId_string); /* borrowed */
1098 if (filename == NULL)
1099 return NULL;
1100
1101 arena = PyArena_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 if (arena == NULL)
1103 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001104
Lysandros Nikolaou564cd182020-06-22 02:47:46 +03001105 mod = PyParser_ASTFromStringObject(str, filename, start, flags, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001107 if (mod != NULL)
Victor Stinner95701bd2013-11-06 18:41:07 +01001108 ret = run_mod(mod, filename, globals, locals, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 PyArena_Free(arena);
1110 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001111}
1112
Victor Stinnerb6d98c12020-12-08 14:38:08 +01001113
1114static PyObject *
1115pyrun_file(FILE *fp, PyObject *filename, int start, PyObject *globals,
1116 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001117{
Victor Stinnerb6d98c12020-12-08 14:38:08 +01001118 PyArena *arena = PyArena_New();
1119 if (arena == NULL) {
1120 return NULL;
1121 }
1122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 mod_ty mod;
Lysandros Nikolaou564cd182020-06-22 02:47:46 +03001124 mod = PyParser_ASTFromFileObject(fp, filename, NULL, start, NULL, NULL,
1125 flags, NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001126
Victor Stinnerb6d98c12020-12-08 14:38:08 +01001127 if (closeit) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001128 fclose(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001129 }
Victor Stinner95701bd2013-11-06 18:41:07 +01001130
Victor Stinnerb6d98c12020-12-08 14:38:08 +01001131 PyObject *ret;
1132 if (mod != NULL) {
1133 ret = run_mod(mod, filename, globals, locals, flags, arena);
1134 }
1135 else {
1136 ret = NULL;
1137 }
1138 PyArena_Free(arena);
1139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001140 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001141}
1142
Victor Stinnerb6d98c12020-12-08 14:38:08 +01001143
1144PyObject *
1145PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
1146 PyObject *locals, int closeit, PyCompilerFlags *flags)
1147{
1148 PyObject *filename_obj = PyUnicode_DecodeFSDefault(filename);
1149 if (filename_obj == NULL) {
1150 return NULL;
1151 }
1152
1153 PyObject *res = pyrun_file(fp, filename_obj, start, globals,
1154 locals, closeit, flags);
1155 Py_DECREF(filename_obj);
1156 return res;
1157
1158}
1159
1160
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001161static void
1162flush_io(void)
1163{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 PyObject *f, *r;
1165 PyObject *type, *value, *traceback;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001167 /* Save the current exception */
1168 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001169
Victor Stinnerbd303c12013-11-07 23:07:29 +01001170 f = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 if (f != NULL) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001172 r = _PyObject_CallMethodIdNoArgs(f, &PyId_flush);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 if (r)
1174 Py_DECREF(r);
1175 else
1176 PyErr_Clear();
1177 }
Victor Stinnerbd303c12013-11-07 23:07:29 +01001178 f = _PySys_GetObjectId(&PyId_stdout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 if (f != NULL) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001180 r = _PyObject_CallMethodIdNoArgs(f, &PyId_flush);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 if (r)
1182 Py_DECREF(r);
1183 else
1184 PyErr_Clear();
1185 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001188}
1189
Guido van Rossum82598051997-03-05 00:20:32 +00001190static PyObject *
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001191run_eval_code_obj(PyThreadState *tstate, PyCodeObject *co, PyObject *globals, PyObject *locals)
Gregory P. Smith38f11cc2019-02-16 12:57:40 -08001192{
1193 PyObject *v;
Gregory P. Smithd9bc5432019-02-20 17:35:54 -08001194 /*
1195 * We explicitly re-initialize _Py_UnhandledKeyboardInterrupt every eval
1196 * _just in case_ someone is calling into an embedded Python where they
1197 * don't care about an uncaught KeyboardInterrupt exception (why didn't they
1198 * leave config.install_signal_handlers set to 0?!?) but then later call
1199 * Py_Main() itself (which _checks_ this flag and dies with a signal after
1200 * its interpreter exits). We don't want a previous embedded interpreter's
1201 * uncaught exception to trigger an unexplained signal exit from a future
1202 * Py_Main() based one.
1203 */
1204 _Py_UnhandledKeyboardInterrupt = 0;
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001205
1206 /* Set globals['__builtins__'] if it doesn't exist */
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02001207 if (globals != NULL && _PyDict_GetItemStringWithError(globals, "__builtins__") == NULL) {
1208 if (PyErr_Occurred() ||
1209 PyDict_SetItemString(globals, "__builtins__",
1210 tstate->interp->builtins) < 0)
1211 {
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001212 return NULL;
1213 }
1214 }
1215
Gregory P. Smith38f11cc2019-02-16 12:57:40 -08001216 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001217 if (!v && _PyErr_Occurred(tstate) == PyExc_KeyboardInterrupt) {
Gregory P. Smith38f11cc2019-02-16 12:57:40 -08001218 _Py_UnhandledKeyboardInterrupt = 1;
1219 }
1220 return v;
1221}
1222
1223static PyObject *
Victor Stinner95701bd2013-11-06 18:41:07 +01001224run_mod(mod_ty mod, PyObject *filename, PyObject *globals, PyObject *locals,
1225 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001226{
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001227 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinnera81fca62021-03-24 00:51:50 +01001228 PyCodeObject *co = _PyAST_Compile(mod, filename, flags, -1, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 if (co == NULL)
1230 return NULL;
Steve Dowerb82e17e2019-05-23 08:45:22 -07001231
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001232 if (_PySys_Audit(tstate, "exec", "O", co) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07001233 Py_DECREF(co);
1234 return NULL;
1235 }
1236
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001237 PyObject *v = run_eval_code_obj(tstate, co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 Py_DECREF(co);
1239 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001240}
1241
Guido van Rossum82598051997-03-05 00:20:32 +00001242static PyObject *
Victor Stinnerb6d98c12020-12-08 14:38:08 +01001243run_pyc_file(FILE *fp, PyObject *globals, PyObject *locals,
1244 PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001245{
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001246 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 PyCodeObject *co;
1248 PyObject *v;
1249 long magic;
1250 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001252 magic = PyMarshal_ReadLongFromFile(fp);
1253 if (magic != PyImport_GetMagicNumber()) {
Victor Stinner5200f552015-03-18 13:56:25 +01001254 if (!PyErr_Occurred())
1255 PyErr_SetString(PyExc_RuntimeError,
1256 "Bad magic number in .pyc file");
Zackery Spytzea737752018-06-23 21:15:24 -06001257 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 }
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08001259 /* Skip the rest of the header. */
1260 (void) PyMarshal_ReadLongFromFile(fp);
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001261 (void) PyMarshal_ReadLongFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001262 (void) PyMarshal_ReadLongFromFile(fp);
Zackery Spytzea737752018-06-23 21:15:24 -06001263 if (PyErr_Occurred()) {
1264 goto error;
1265 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001266 v = PyMarshal_ReadLastObjectFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001267 if (v == NULL || !PyCode_Check(v)) {
1268 Py_XDECREF(v);
1269 PyErr_SetString(PyExc_RuntimeError,
1270 "Bad code object in .pyc file");
Zackery Spytzea737752018-06-23 21:15:24 -06001271 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 }
Zackery Spytzea737752018-06-23 21:15:24 -06001273 fclose(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001274 co = (PyCodeObject *)v;
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001275 v = run_eval_code_obj(tstate, co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001276 if (v && flags)
1277 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1278 Py_DECREF(co);
1279 return v;
Zackery Spytzea737752018-06-23 21:15:24 -06001280error:
1281 fclose(fp);
1282 return NULL;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001283}
1284
Guido van Rossum82598051997-03-05 00:20:32 +00001285PyObject *
Victor Stinner14e461d2013-08-26 22:28:21 +02001286Py_CompileStringObject(const char *str, PyObject *filename, int start,
1287 PyCompilerFlags *flags, int optimize)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001288{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001289 PyCodeObject *co;
1290 mod_ty mod;
1291 PyArena *arena = PyArena_New();
1292 if (arena == NULL)
1293 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001294
Lysandros Nikolaou564cd182020-06-22 02:47:46 +03001295 mod = PyParser_ASTFromStringObject(str, filename, start, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001296 if (mod == NULL) {
1297 PyArena_Free(arena);
1298 return NULL;
1299 }
1300 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
1301 PyObject *result = PyAST_mod2obj(mod);
1302 PyArena_Free(arena);
1303 return result;
1304 }
Victor Stinnera81fca62021-03-24 00:51:50 +01001305 co = _PyAST_Compile(mod, filename, flags, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001306 PyArena_Free(arena);
1307 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001308}
1309
Victor Stinner14e461d2013-08-26 22:28:21 +02001310PyObject *
1311Py_CompileStringExFlags(const char *str, const char *filename_str, int start,
1312 PyCompilerFlags *flags, int optimize)
1313{
1314 PyObject *filename, *co;
1315 filename = PyUnicode_DecodeFSDefault(filename_str);
1316 if (filename == NULL)
1317 return NULL;
1318 co = Py_CompileStringObject(str, filename, start, flags, optimize);
1319 Py_DECREF(filename);
1320 return co;
1321}
1322
Dino Viehland41540692019-05-28 16:21:17 -07001323const char *
1324_Py_SourceAsString(PyObject *cmd, const char *funcname, const char *what, PyCompilerFlags *cf, PyObject **cmd_copy)
1325{
1326 const char *str;
1327 Py_ssize_t size;
1328 Py_buffer view;
1329
1330 *cmd_copy = NULL;
1331 if (PyUnicode_Check(cmd)) {
1332 cf->cf_flags |= PyCF_IGNORE_COOKIE;
1333 str = PyUnicode_AsUTF8AndSize(cmd, &size);
1334 if (str == NULL)
1335 return NULL;
1336 }
1337 else if (PyBytes_Check(cmd)) {
1338 str = PyBytes_AS_STRING(cmd);
1339 size = PyBytes_GET_SIZE(cmd);
1340 }
1341 else if (PyByteArray_Check(cmd)) {
1342 str = PyByteArray_AS_STRING(cmd);
1343 size = PyByteArray_GET_SIZE(cmd);
1344 }
1345 else if (PyObject_GetBuffer(cmd, &view, PyBUF_SIMPLE) == 0) {
1346 /* Copy to NUL-terminated buffer. */
1347 *cmd_copy = PyBytes_FromStringAndSize(
1348 (const char *)view.buf, view.len);
1349 PyBuffer_Release(&view);
1350 if (*cmd_copy == NULL) {
1351 return NULL;
1352 }
1353 str = PyBytes_AS_STRING(*cmd_copy);
1354 size = PyBytes_GET_SIZE(*cmd_copy);
1355 }
1356 else {
1357 PyErr_Format(PyExc_TypeError,
1358 "%s() arg 1 must be a %s object",
1359 funcname, what);
1360 return NULL;
1361 }
1362
1363 if (strlen(str) != (size_t)size) {
1364 PyErr_SetString(PyExc_ValueError,
1365 "source code string cannot contain null bytes");
1366 Py_CLEAR(*cmd_copy);
1367 return NULL;
1368 }
1369 return str;
1370}
1371
Zachary Warec4821d62014-11-21 23:35:12 -06001372#if defined(USE_STACKCHECK)
1373#if defined(WIN32) && defined(_MSC_VER)
1374
1375/* Stack checking for Microsoft C */
1376
1377#include <malloc.h>
1378#include <excpt.h>
1379
1380/*
1381 * Return non-zero when we run out of memory on the stack; zero otherwise.
1382 */
1383int
1384PyOS_CheckStack(void)
1385{
1386 __try {
1387 /* alloca throws a stack overflow exception if there's
1388 not enough space left on the stack */
1389 alloca(PYOS_STACK_MARGIN * sizeof(void*));
1390 return 0;
1391 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
1392 EXCEPTION_EXECUTE_HANDLER :
1393 EXCEPTION_CONTINUE_SEARCH) {
1394 int errcode = _resetstkoflw();
1395 if (errcode == 0)
1396 {
1397 Py_FatalError("Could not reset the stack!");
1398 }
1399 }
1400 return 1;
1401}
1402
1403#endif /* WIN32 && _MSC_VER */
1404
1405/* Alternate implementations can be added here... */
1406
1407#endif /* USE_STACKCHECK */
1408
Pablo Galindo46bd5ed2020-12-02 05:16:31 +00001409/* Deprecated C API functions still provided for binary compatibility */
1410
1411#undef PyRun_AnyFile
1412PyAPI_FUNC(int)
1413PyRun_AnyFile(FILE *fp, const char *name)
1414{
1415 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
1416}
1417
1418#undef PyRun_AnyFileEx
1419PyAPI_FUNC(int)
1420PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
1421{
1422 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
1423}
1424
1425#undef PyRun_AnyFileFlags
1426PyAPI_FUNC(int)
1427PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
1428{
1429 return PyRun_AnyFileExFlags(fp, name, 0, flags);
1430}
1431
1432#undef PyRun_File
1433PyAPI_FUNC(PyObject *)
1434PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
1435{
1436 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
1437}
1438
1439#undef PyRun_FileEx
1440PyAPI_FUNC(PyObject *)
1441PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
1442{
1443 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
1444}
1445
1446#undef PyRun_FileFlags
1447PyAPI_FUNC(PyObject *)
1448PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
1449 PyCompilerFlags *flags)
1450{
1451 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
1452}
1453
1454#undef PyRun_SimpleFile
1455PyAPI_FUNC(int)
1456PyRun_SimpleFile(FILE *f, const char *p)
1457{
1458 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
1459}
1460
1461#undef PyRun_SimpleFileEx
1462PyAPI_FUNC(int)
1463PyRun_SimpleFileEx(FILE *f, const char *p, int c)
1464{
1465 return PyRun_SimpleFileExFlags(f, p, c, NULL);
1466}
1467
1468
1469#undef PyRun_String
1470PyAPI_FUNC(PyObject *)
1471PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
1472{
1473 return PyRun_StringFlags(str, s, g, l, NULL);
1474}
1475
1476#undef PyRun_SimpleString
1477PyAPI_FUNC(int)
1478PyRun_SimpleString(const char *s)
1479{
1480 return PyRun_SimpleStringFlags(s, NULL);
1481}
1482
1483#undef Py_CompileString
1484PyAPI_FUNC(PyObject *)
1485Py_CompileString(const char *str, const char *p, int s)
1486{
1487 return Py_CompileStringExFlags(str, p, s, NULL, -1);
1488}
1489
1490#undef Py_CompileStringFlags
1491PyAPI_FUNC(PyObject *)
1492Py_CompileStringFlags(const char *str, const char *p, int s,
1493 PyCompilerFlags *flags)
1494{
1495 return Py_CompileStringExFlags(str, p, s, flags, -1);
1496}
1497
1498#undef PyRun_InteractiveOne
1499PyAPI_FUNC(int)
1500PyRun_InteractiveOne(FILE *f, const char *p)
1501{
1502 return PyRun_InteractiveOneFlags(f, p, NULL);
1503}
1504
1505#undef PyRun_InteractiveLoop
1506PyAPI_FUNC(int)
1507PyRun_InteractiveLoop(FILE *f, const char *p)
1508{
1509 return PyRun_InteractiveLoopFlags(f, p, NULL);
1510}
1511
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001512#ifdef __cplusplus
1513}
1514#endif