blob: 330b822d707c65bc9570d02cb32104838285b011 [file] [log] [blame]
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001
Eric Snowc7ec9982017-05-23 23:00:52 -07002/* Top level execution of Python code (including in __main__) */
3
4/* To help control the interfaces between the startup, execution and
5 * shutdown code, the phases are split across separate modules (boostrap,
6 * pythonrun, shutdown)
7 */
8
9/* TODO: Cull includes following phase split */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000010
Guido van Rossum82598051997-03-05 00:20:32 +000011#include "Python.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000012
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013#include "Python-ast.h"
Victor Stinner3bb183d2018-11-22 18:38:38 +010014#undef Yield /* undefine macro conflicting with <winbase.h> */
Victor Stinner4f98f462020-04-15 04:01:58 +020015
Victor Stinnere5014be2020-04-14 17:52:15 +020016#include "pycore_interp.h" // PyInterpreterState.importlib
Victor Stinner4f98f462020-04-15 04:01:58 +020017#include "pycore_object.h" // _PyDebug_PrintTotalRefs()
18#include "pycore_pyerrors.h" // _PyErr_Fetch
19#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
26#include "symtable.h" // PySymtable_BuildObject()
Victor Stinner4f98f462020-04-15 04:01:58 +020027#include "marshal.h" // PyMarshal_ReadLongFromFile()
28
Lysandros Nikolaou564cd182020-06-22 02:47:46 +030029#include "parser_interface.h" // PyParser_ASTFrom*
Pablo Galindoc5fc1562020-04-22 23:29:27 +010030
Victor Stinner4f98f462020-04-15 04:01:58 +020031#ifdef MS_WINDOWS
32# include "malloc.h" // alloca()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000033#endif
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000034
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000035#ifdef MS_WINDOWS
Victor Stinner4f98f462020-04-15 04:01:58 +020036# undef BYTE
37# include "windows.h"
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000038#endif
Martin v. Löwis5c88d812009-01-02 20:47:48 +000039
Guido van Rossuma44823b1995-03-14 15:01:17 +000040
Victor Stinnerbd303c12013-11-07 23:07:29 +010041_Py_IDENTIFIER(builtins);
Victor Stinner09054372013-11-06 22:41:44 +010042_Py_IDENTIFIER(excepthook);
Victor Stinner3f36a572013-11-12 21:39:02 +010043_Py_IDENTIFIER(flush);
Victor Stinnerbd303c12013-11-07 23:07:29 +010044_Py_IDENTIFIER(last_traceback);
Victor Stinner09054372013-11-06 22:41:44 +010045_Py_IDENTIFIER(last_type);
46_Py_IDENTIFIER(last_value);
Victor Stinnerbd303c12013-11-07 23:07:29 +010047_Py_IDENTIFIER(ps1);
48_Py_IDENTIFIER(ps2);
49_Py_IDENTIFIER(stdin);
50_Py_IDENTIFIER(stdout);
51_Py_IDENTIFIER(stderr);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +010052_Py_static_string(PyId_string, "<string>");
Victor Stinner09054372013-11-06 22:41:44 +010053
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000054#ifdef __cplusplus
55extern "C" {
Neal Norwitz4281cef2006-03-04 19:58:13 +000056#endif
57
Guido van Rossumb73cc041993-11-01 16:28:59 +000058/* Forward */
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +000059static void flush_io(void);
Victor Stinner95701bd2013-11-06 18:41:07 +010060static PyObject *run_mod(mod_ty, PyObject *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000061 PyCompilerFlags *, PyArena *);
Victor Stinnerb6d98c12020-12-08 14:38:08 +010062static PyObject *run_pyc_file(FILE *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000063 PyCompilerFlags *);
xdegayee0582a32017-11-12 16:50:48 +010064static int PyRun_InteractiveOneObjectEx(FILE *, PyObject *, PyCompilerFlags *);
Victor Stinnerb6d98c12020-12-08 14:38:08 +010065static PyObject* pyrun_file(FILE *fp, PyObject *filename, int start,
66 PyObject *globals, PyObject *locals, int closeit,
67 PyCompilerFlags *flags);
68
Guido van Rossumce3a72a2007-10-19 23:16:50 +000069
Guido van Rossum1984f1e1992-08-04 12:41:02 +000070/* Parse input from a file and execute it */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000071int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000072PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000073 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +000074{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000075 if (filename == NULL)
76 filename = "???";
77 if (Py_FdIsInteractive(fp, filename)) {
78 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
79 if (closeit)
80 fclose(fp);
81 return err;
82 }
83 else
84 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000085}
86
87int
Victor Stinner95701bd2013-11-06 18:41:07 +010088PyRun_InteractiveLoopFlags(FILE *fp, const char *filename_str, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +000089{
Victor Stinner95701bd2013-11-06 18:41:07 +010090 PyObject *filename, *v;
91 int ret, err;
Victor Stinner37d66d72019-06-13 02:16:41 +020092 PyCompilerFlags local_flags = _PyCompilerFlags_INIT;
xdegayee0582a32017-11-12 16:50:48 +010093 int nomem_count = 0;
Victor Stinner25420fe2017-11-20 18:12:22 -080094#ifdef Py_REF_DEBUG
Victor Stinnerda7933e2020-04-13 03:04:28 +020095 int show_ref_count = _Py_GetConfig()->show_ref_count;
Victor Stinner25420fe2017-11-20 18:12:22 -080096#endif
Jeremy Hylton9f324e92001-03-01 22:59:14 +000097
Victor Stinner95701bd2013-11-06 18:41:07 +010098 filename = PyUnicode_DecodeFSDefault(filename_str);
99 if (filename == NULL) {
100 PyErr_Print();
101 return -1;
102 }
103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000104 if (flags == NULL) {
105 flags = &local_flags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000106 }
Victor Stinner09054372013-11-06 22:41:44 +0100107 v = _PySys_GetObjectId(&PyId_ps1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000108 if (v == NULL) {
Victor Stinner09054372013-11-06 22:41:44 +0100109 _PySys_SetObjectId(&PyId_ps1, v = PyUnicode_FromString(">>> "));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000110 Py_XDECREF(v);
111 }
Victor Stinner09054372013-11-06 22:41:44 +0100112 v = _PySys_GetObjectId(&PyId_ps2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000113 if (v == NULL) {
Victor Stinner09054372013-11-06 22:41:44 +0100114 _PySys_SetObjectId(&PyId_ps2, v = PyUnicode_FromString("... "));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000115 Py_XDECREF(v);
116 }
xdegayee0582a32017-11-12 16:50:48 +0100117 err = 0;
118 do {
119 ret = PyRun_InteractiveOneObjectEx(fp, filename, flags);
120 if (ret == -1 && PyErr_Occurred()) {
121 /* Prevent an endless loop after multiple consecutive MemoryErrors
122 * while still allowing an interactive command to fail with a
123 * MemoryError. */
124 if (PyErr_ExceptionMatches(PyExc_MemoryError)) {
125 if (++nomem_count > 16) {
126 PyErr_Clear();
127 err = -1;
128 break;
129 }
130 } else {
131 nomem_count = 0;
132 }
133 PyErr_Print();
134 flush_io();
135 } else {
136 nomem_count = 0;
137 }
Eric Snowdae02762017-09-14 00:35:58 -0700138#ifdef Py_REF_DEBUG
Victor Stinner25420fe2017-11-20 18:12:22 -0800139 if (show_ref_count) {
Eric Snowdae02762017-09-14 00:35:58 -0700140 _PyDebug_PrintTotalRefs();
Victor Stinner25420fe2017-11-20 18:12:22 -0800141 }
Eric Snowdae02762017-09-14 00:35:58 -0700142#endif
xdegayee0582a32017-11-12 16:50:48 +0100143 } while (ret != E_EOF);
Victor Stinner95701bd2013-11-06 18:41:07 +0100144 Py_DECREF(filename);
145 return err;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000146}
147
xdegayee0582a32017-11-12 16:50:48 +0100148/* A PyRun_InteractiveOneObject() auxiliary function that does not print the
149 * error on failure. */
150static int
151PyRun_InteractiveOneObjectEx(FILE *fp, PyObject *filename,
152 PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000153{
Victor Stinner95701bd2013-11-06 18:41:07 +0100154 PyObject *m, *d, *v, *w, *oenc = NULL, *mod_name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000155 mod_ty mod;
156 PyArena *arena;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200157 const char *ps1 = "", *ps2 = "", *enc = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 int errcode = 0;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200159 _Py_IDENTIFIER(encoding);
Victor Stinner95701bd2013-11-06 18:41:07 +0100160 _Py_IDENTIFIER(__main__);
161
162 mod_name = _PyUnicode_FromId(&PyId___main__); /* borrowed */
163 if (mod_name == NULL) {
Victor Stinner95701bd2013-11-06 18:41:07 +0100164 return -1;
165 }
Tim Petersfe2127d2001-07-16 05:37:24 +0000166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000167 if (fp == stdin) {
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -0400168 /* Fetch encoding from sys.stdin if possible. */
Victor Stinnerbd303c12013-11-07 23:07:29 +0100169 v = _PySys_GetObjectId(&PyId_stdin);
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -0400170 if (v && v != Py_None) {
171 oenc = _PyObject_GetAttrId(v, &PyId_encoding);
172 if (oenc)
Serhiy Storchaka06515832016-11-20 09:13:07 +0200173 enc = PyUnicode_AsUTF8(oenc);
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -0400174 if (!enc)
175 PyErr_Clear();
176 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000177 }
Victor Stinner09054372013-11-06 22:41:44 +0100178 v = _PySys_GetObjectId(&PyId_ps1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000179 if (v != NULL) {
180 v = PyObject_Str(v);
181 if (v == NULL)
182 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +0000183 else if (PyUnicode_Check(v)) {
Serhiy Storchaka06515832016-11-20 09:13:07 +0200184 ps1 = PyUnicode_AsUTF8(v);
Victor Stinner386fe712010-05-19 00:34:15 +0000185 if (ps1 == NULL) {
186 PyErr_Clear();
187 ps1 = "";
188 }
189 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000190 }
Victor Stinner09054372013-11-06 22:41:44 +0100191 w = _PySys_GetObjectId(&PyId_ps2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000192 if (w != NULL) {
193 w = PyObject_Str(w);
194 if (w == NULL)
195 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +0000196 else if (PyUnicode_Check(w)) {
Serhiy Storchaka06515832016-11-20 09:13:07 +0200197 ps2 = PyUnicode_AsUTF8(w);
Victor Stinner386fe712010-05-19 00:34:15 +0000198 if (ps2 == NULL) {
199 PyErr_Clear();
200 ps2 = "";
201 }
202 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000203 }
204 arena = PyArena_New();
205 if (arena == NULL) {
206 Py_XDECREF(v);
207 Py_XDECREF(w);
208 Py_XDECREF(oenc);
209 return -1;
210 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100211
Lysandros Nikolaou564cd182020-06-22 02:47:46 +0300212 mod = PyParser_ASTFromFileObject(fp, filename, enc, Py_single_input,
213 ps1, ps2, flags, &errcode, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000215 Py_XDECREF(v);
216 Py_XDECREF(w);
217 Py_XDECREF(oenc);
218 if (mod == NULL) {
219 PyArena_Free(arena);
220 if (errcode == E_EOF) {
221 PyErr_Clear();
222 return E_EOF;
223 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000224 return -1;
225 }
Victor Stinner95701bd2013-11-06 18:41:07 +0100226 m = PyImport_AddModuleObject(mod_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 if (m == NULL) {
228 PyArena_Free(arena);
229 return -1;
230 }
231 d = PyModule_GetDict(m);
232 v = run_mod(mod, filename, d, d, flags, arena);
233 PyArena_Free(arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 return -1;
236 }
237 Py_DECREF(v);
Antoine Pitrou9845c7e2014-05-11 13:42:17 +0200238 flush_io();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000240}
241
Victor Stinner95701bd2013-11-06 18:41:07 +0100242int
xdegayee0582a32017-11-12 16:50:48 +0100243PyRun_InteractiveOneObject(FILE *fp, PyObject *filename, PyCompilerFlags *flags)
244{
245 int res;
246
247 res = PyRun_InteractiveOneObjectEx(fp, filename, flags);
248 if (res == -1) {
249 PyErr_Print();
250 flush_io();
251 }
252 return res;
253}
254
255int
Victor Stinner95701bd2013-11-06 18:41:07 +0100256PyRun_InteractiveOneFlags(FILE *fp, const char *filename_str, PyCompilerFlags *flags)
257{
258 PyObject *filename;
259 int res;
260
261 filename = PyUnicode_DecodeFSDefault(filename_str);
262 if (filename == NULL) {
263 PyErr_Print();
264 return -1;
265 }
266 res = PyRun_InteractiveOneObject(fp, filename, flags);
267 Py_DECREF(filename);
268 return res;
269}
270
271
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000272/* Check whether a file maybe a pyc file: Look at the extension,
273 the file type, and, if we may close it, at the first few bytes. */
274
275static int
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100276maybe_pyc_file(FILE *fp, PyObject *filename, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000277{
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100278 PyObject *ext = PyUnicode_FromString(".pyc");
279 if (ext == NULL) {
280 return -1;
281 }
282 Py_ssize_t endswith = PyUnicode_Tailmatch(filename, ext, 0, PY_SSIZE_T_MAX, +1);
283 Py_DECREF(ext);
284 if (endswith) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000285 return 1;
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100286 }
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 /* Only look into the file if we are allowed to close it, since
289 it then should also be seekable. */
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100290 if (!closeit) {
291 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000292 }
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100293
294 /* Read only two bytes of the magic. If the file was opened in
295 text mode, the bytes 3 and 4 of the magic (\r\n) might not
296 be read as they are on disk. */
297 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
298 unsigned char buf[2];
299 /* Mess: In case of -x, the stream is NOT at its start now,
300 and ungetc() was used to push back the first newline,
301 which makes the current stream position formally undefined,
302 and a x-platform nightmare.
303 Unfortunately, we have no direct way to know whether -x
304 was specified. So we use a terrible hack: if the current
305 stream position is not 0, we assume -x was specified, and
306 give up. Bug 132850 on SourceForge spells out the
307 hopelessness of trying anything else (fseek and ftell
308 don't work predictably x-platform for text-mode files).
309 */
310 int ispyc = 0;
311 if (ftell(fp) == 0) {
312 if (fread(buf, 1, 2, fp) == 2 &&
313 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
314 ispyc = 1;
315 rewind(fp);
316 }
317 return ispyc;
Tim Petersd08e3822003-04-17 15:24:21 +0000318}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000319
Andrew Svetlov90c0eb22012-11-01 14:51:14 +0200320
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100321static int
322set_main_loader(PyObject *d, PyObject *filename, const char *loader_name)
323{
Victor Stinner81a7be32020-04-14 15:14:01 +0200324 PyInterpreterState *interp = _PyInterpreterState_GET();
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100325 PyObject *bootstrap = PyObject_GetAttrString(interp->importlib,
326 "_bootstrap_external");
327 if (bootstrap == NULL) {
Nick Coghlan3f94cbf2012-07-15 19:10:39 +1000328 return -1;
329 }
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100330
331 PyObject *loader_type = PyObject_GetAttrString(bootstrap, loader_name);
332 Py_DECREF(bootstrap);
333 if (loader_type == NULL) {
334 return -1;
335 }
336
337 PyObject *loader = PyObject_CallFunction(loader_type,
338 "sO", "__main__", filename);
Nick Coghlanb7a58942012-07-15 23:21:08 +1000339 Py_DECREF(loader_type);
340 if (loader == NULL) {
Nick Coghlan85e729e2012-07-15 18:09:52 +1000341 return -1;
342 }
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100343
Nick Coghlanb7a58942012-07-15 23:21:08 +1000344 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100345 Py_DECREF(loader);
346 return -1;
Nick Coghlanb7a58942012-07-15 23:21:08 +1000347 }
Nick Coghlan85e729e2012-07-15 18:09:52 +1000348 Py_DECREF(loader);
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100349 return 0;
Nick Coghlan85e729e2012-07-15 18:09:52 +1000350}
351
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100352
353static int
354pyrun_simple_file(FILE *fp, PyObject *filename, int closeit,
355 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000356{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000357 PyObject *m, *d, *v;
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +0100358 int set_file_name = 0, ret = -1;
Guido van Rossumfdef2711994-09-14 13:31:04 +0000359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000360 m = PyImport_AddModule("__main__");
361 if (m == NULL)
362 return -1;
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +0100363 Py_INCREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364 d = PyModule_GetDict(m);
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +0200365 if (_PyDict_GetItemStringWithError(d, "__file__") == NULL) {
366 if (PyErr_Occurred()) {
367 goto done;
368 }
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100369 if (PyDict_SetItemString(d, "__file__", filename) < 0) {
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +0100370 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 }
Barry Warsaw916048d2011-09-20 14:45:44 -0400372 if (PyDict_SetItemString(d, "__cached__", Py_None) < 0) {
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +0100373 goto done;
Barry Warsaw916048d2011-09-20 14:45:44 -0400374 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 set_file_name = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 }
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100377
378 int pyc = maybe_pyc_file(fp, filename, closeit);
379 if (pyc < 0) {
380 goto done;
381 }
382
383 if (pyc) {
Christian Heimes04ac4c12012-09-11 15:47:28 +0200384 FILE *pyc_fp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000385 /* Try to run a pyc file. First, re-open in binary */
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100386 if (closeit) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000387 fclose(fp);
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100388 }
389
390 pyc_fp = _Py_fopen_obj(filename, "rb");
391 if (pyc_fp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 fprintf(stderr, "python: Can't reopen .pyc file\n");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 goto done;
394 }
Nick Coghlan85e729e2012-07-15 18:09:52 +1000395
396 if (set_main_loader(d, filename, "SourcelessFileLoader") < 0) {
397 fprintf(stderr, "python: failed to set __main__.__loader__\n");
398 ret = -1;
Christian Heimes04ac4c12012-09-11 15:47:28 +0200399 fclose(pyc_fp);
Nick Coghlan85e729e2012-07-15 18:09:52 +1000400 goto done;
401 }
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100402 v = run_pyc_file(pyc_fp, d, d, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 } else {
Nick Coghlan85e729e2012-07-15 18:09:52 +1000404 /* When running from stdin, leave __main__.__loader__ alone */
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100405 if (PyUnicode_CompareWithASCIIString(filename, "<stdin>") != 0 &&
Nick Coghlan85e729e2012-07-15 18:09:52 +1000406 set_main_loader(d, filename, "SourceFileLoader") < 0) {
407 fprintf(stderr, "python: failed to set __main__.__loader__\n");
408 ret = -1;
409 goto done;
410 }
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100411 v = pyrun_file(fp, filename, Py_file_input, d, d,
412 closeit, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 }
414 flush_io();
415 if (v == NULL) {
Zackery Spytzd8cba5d2018-07-03 13:47:22 -0600416 Py_CLEAR(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 PyErr_Print();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 goto done;
419 }
420 Py_DECREF(v);
421 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +0000422 done:
INADA Naoki82daa602018-11-29 20:01:27 +0900423 if (set_file_name) {
424 if (PyDict_DelItemString(d, "__file__")) {
425 PyErr_Clear();
426 }
427 if (PyDict_DelItemString(d, "__cached__")) {
428 PyErr_Clear();
429 }
430 }
Zackery Spytzd8cba5d2018-07-03 13:47:22 -0600431 Py_XDECREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000432 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000433}
434
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100435
436int
437PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
438 PyCompilerFlags *flags)
439{
440 PyObject *filename_obj = PyUnicode_DecodeFSDefault(filename);
441 if (filename_obj == NULL) {
442 return -1;
443 }
444 int res = pyrun_simple_file(fp, filename_obj, closeit, flags);
445 Py_DECREF(filename_obj);
446 return res;
447}
448
449
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000450int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000451PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +0000452{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 PyObject *m, *d, *v;
454 m = PyImport_AddModule("__main__");
455 if (m == NULL)
456 return -1;
457 d = PyModule_GetDict(m);
458 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
459 if (v == NULL) {
460 PyErr_Print();
461 return -1;
462 }
463 Py_DECREF(v);
464 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000465}
466
Barry Warsaw035574d1997-08-29 22:07:17 +0000467static int
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100468parse_syntax_error(PyObject *err, PyObject **message, PyObject **filename,
Ammar Askar90d29702020-06-02 08:17:24 +0000469 Py_ssize_t *lineno, Py_ssize_t *offset, PyObject **text)
Barry Warsaw035574d1997-08-29 22:07:17 +0000470{
Ammar Askar90d29702020-06-02 08:17:24 +0000471 Py_ssize_t hold;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 PyObject *v;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200473 _Py_IDENTIFIER(msg);
474 _Py_IDENTIFIER(filename);
475 _Py_IDENTIFIER(lineno);
476 _Py_IDENTIFIER(offset);
477 _Py_IDENTIFIER(text);
Barry Warsaw035574d1997-08-29 22:07:17 +0000478
Benjamin Peterson80d50422012-04-03 00:30:38 -0400479 *message = NULL;
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100480 *filename = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 /* new style errors. `err' is an instance */
Benjamin Peterson0a9a6362012-04-03 00:35:36 -0400483 *message = _PyObject_GetAttrId(err, &PyId_msg);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400484 if (!*message)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +0000486
Benjamin Peterson0a9a6362012-04-03 00:35:36 -0400487 v = _PyObject_GetAttrId(err, &PyId_filename);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400488 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400490 if (v == Py_None) {
491 Py_DECREF(v);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100492 *filename = _PyUnicode_FromId(&PyId_string);
493 if (*filename == NULL)
494 goto finally;
495 Py_INCREF(*filename);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400496 }
497 else {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100498 *filename = v;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400499 }
Barry Warsaw035574d1997-08-29 22:07:17 +0000500
Benjamin Peterson0a9a6362012-04-03 00:35:36 -0400501 v = _PyObject_GetAttrId(err, &PyId_lineno);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400502 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 goto finally;
Ammar Askar90d29702020-06-02 08:17:24 +0000504 hold = PyLong_AsSsize_t(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 if (hold < 0 && PyErr_Occurred())
507 goto finally;
Serhiy Storchaka56f6e762015-09-06 21:25:30 +0300508 *lineno = hold;
Barry Warsaw035574d1997-08-29 22:07:17 +0000509
Benjamin Peterson0a9a6362012-04-03 00:35:36 -0400510 v = _PyObject_GetAttrId(err, &PyId_offset);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400511 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 goto finally;
513 if (v == Py_None) {
514 *offset = -1;
515 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 } else {
Ammar Askar90d29702020-06-02 08:17:24 +0000517 hold = PyLong_AsSsize_t(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 if (hold < 0 && PyErr_Occurred())
520 goto finally;
Serhiy Storchaka56f6e762015-09-06 21:25:30 +0300521 *offset = hold;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 }
Barry Warsaw035574d1997-08-29 22:07:17 +0000523
Benjamin Peterson0a9a6362012-04-03 00:35:36 -0400524 v = _PyObject_GetAttrId(err, &PyId_text);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400525 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400527 if (v == Py_None) {
528 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000529 *text = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400530 }
531 else {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100532 *text = v;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400533 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +0000535
536finally:
Benjamin Peterson80d50422012-04-03 00:30:38 -0400537 Py_XDECREF(*message);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100538 Py_XDECREF(*filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000539 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +0000540}
541
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000542static void
Ammar Askar90d29702020-06-02 08:17:24 +0000543print_error_text(PyObject *f, Py_ssize_t offset, PyObject *text_obj)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000544{
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700545 /* Convert text to a char pointer; return if error */
546 const char *text = PyUnicode_AsUTF8(text_obj);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100547 if (text == NULL)
548 return;
549
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700550 /* Convert offset from 1-based to 0-based */
551 offset--;
552
553 /* Strip leading whitespace from text, adjusting offset as we go */
554 while (*text == ' ' || *text == '\t' || *text == '\f') {
555 text++;
556 offset--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 }
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700558
559 /* Calculate text length excluding trailing newline */
560 Py_ssize_t len = strlen(text);
561 if (len > 0 && text[len-1] == '\n') {
562 len--;
563 }
564
565 /* Clip offset to at most len */
566 if (offset > len) {
567 offset = len;
568 }
569
570 /* Skip past newlines embedded in text */
571 for (;;) {
572 const char *nl = strchr(text, '\n');
573 if (nl == NULL) {
574 break;
575 }
576 Py_ssize_t inl = nl - text;
Ammar Askar90d29702020-06-02 08:17:24 +0000577 if (inl >= offset) {
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700578 break;
579 }
580 inl += 1;
581 text += inl;
582 len -= inl;
583 offset -= (int)inl;
584 }
585
586 /* Print text */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000587 PyFile_WriteString(" ", f);
588 PyFile_WriteString(text, f);
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700589
590 /* Make sure there's a newline at the end */
591 if (text[len] != '\n') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 PyFile_WriteString("\n", f);
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700593 }
594
595 /* Don't print caret if it points to the left of the text */
596 if (offset < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000597 return;
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700598
599 /* Write caret line */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000600 PyFile_WriteString(" ", f);
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700601 while (--offset >= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 PyFile_WriteString(" ", f);
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700603 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000604 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000605}
606
Tim Peterscf615b52003-04-19 18:47:02 +0000607
Victor Stinner12083282019-05-17 23:05:29 +0200608int
609_Py_HandleSystemExit(int *exitcode_p)
610{
Victor Stinnerda7933e2020-04-13 03:04:28 +0200611 int inspect = _Py_GetConfig()->inspect;
Victor Stinnerc96be812019-05-14 17:34:56 +0200612 if (inspect) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 /* Don't exit if -i flag was given. This flag is set to 0
614 * when entering interactive mode for inspecting. */
Victor Stinner12083282019-05-17 23:05:29 +0200615 return 0;
Victor Stinnerc96be812019-05-14 17:34:56 +0200616 }
Guido van Rossumd8faa362007-04-27 19:54:29 +0000617
Victor Stinner12083282019-05-17 23:05:29 +0200618 if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
619 return 0;
620 }
621
622 PyObject *exception, *value, *tb;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000623 PyErr_Fetch(&exception, &value, &tb);
Victor Stinner12083282019-05-17 23:05:29 +0200624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 fflush(stdout);
Victor Stinner12083282019-05-17 23:05:29 +0200626
627 int exitcode = 0;
628 if (value == NULL || value == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 goto done;
Victor Stinner12083282019-05-17 23:05:29 +0200630 }
631
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 if (PyExceptionInstance_Check(value)) {
633 /* The error code should be in the `code' attribute. */
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200634 _Py_IDENTIFIER(code);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200635 PyObject *code = _PyObject_GetAttrId(value, &PyId_code);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 if (code) {
637 Py_DECREF(value);
638 value = code;
639 if (value == Py_None)
640 goto done;
641 }
642 /* If we failed to dig out the 'code' attribute,
643 just let the else clause below print the error. */
644 }
Victor Stinner12083282019-05-17 23:05:29 +0200645
646 if (PyLong_Check(value)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 exitcode = (int)PyLong_AsLong(value);
Victor Stinner12083282019-05-17 23:05:29 +0200648 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 else {
Victor Stinnerbd303c12013-11-07 23:07:29 +0100650 PyObject *sys_stderr = _PySys_GetObjectId(&PyId_stderr);
Nick Coghland979e432014-02-09 10:43:21 +1000651 /* We clear the exception here to avoid triggering the assertion
652 * in PyObject_Str that ensures it won't silently lose exception
653 * details.
654 */
655 PyErr_Clear();
Victor Stinner7126dbc2010-05-21 23:45:42 +0000656 if (sys_stderr != NULL && sys_stderr != Py_None) {
657 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
658 } else {
659 PyObject_Print(value, stderr, Py_PRINT_RAW);
660 fflush(stderr);
661 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 PySys_WriteStderr("\n");
663 exitcode = 1;
664 }
Victor Stinner12083282019-05-17 23:05:29 +0200665
Tim Peterscf615b52003-04-19 18:47:02 +0000666 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000667 /* Restore and clear the exception info, in order to properly decref
668 * the exception, value, and traceback. If we just exit instead,
669 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
670 * some finalizers from running.
671 */
672 PyErr_Restore(exception, value, tb);
673 PyErr_Clear();
Victor Stinner12083282019-05-17 23:05:29 +0200674 *exitcode_p = exitcode;
675 return 1;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000676}
677
Victor Stinner12083282019-05-17 23:05:29 +0200678
679static void
680handle_system_exit(void)
681{
682 int exitcode;
683 if (_Py_HandleSystemExit(&exitcode)) {
684 Py_Exit(exitcode);
685 }
686}
687
688
Victor Stinner438a12d2019-05-24 17:01:38 +0200689static void
690_PyErr_PrintEx(PyThreadState *tstate, int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000691{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +0000693
Victor Stinner12083282019-05-17 23:05:29 +0200694 handle_system_exit();
695
Victor Stinner438a12d2019-05-24 17:01:38 +0200696 _PyErr_Fetch(tstate, &exception, &v, &tb);
697 if (exception == NULL) {
698 goto done;
699 }
700
701 _PyErr_NormalizeException(tstate, &exception, &v, &tb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 if (tb == NULL) {
703 tb = Py_None;
704 Py_INCREF(tb);
705 }
706 PyException_SetTraceback(v, tb);
Victor Stinner438a12d2019-05-24 17:01:38 +0200707 if (exception == NULL) {
708 goto done;
709 }
710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000711 /* Now we know v != NULL too */
712 if (set_sys_last_vars) {
xdegaye66caacf2017-10-23 18:08:41 +0200713 if (_PySys_SetObjectId(&PyId_last_type, exception) < 0) {
Victor Stinner438a12d2019-05-24 17:01:38 +0200714 _PyErr_Clear(tstate);
xdegaye66caacf2017-10-23 18:08:41 +0200715 }
716 if (_PySys_SetObjectId(&PyId_last_value, v) < 0) {
Victor Stinner438a12d2019-05-24 17:01:38 +0200717 _PyErr_Clear(tstate);
xdegaye66caacf2017-10-23 18:08:41 +0200718 }
719 if (_PySys_SetObjectId(&PyId_last_traceback, tb) < 0) {
Victor Stinner438a12d2019-05-24 17:01:38 +0200720 _PyErr_Clear(tstate);
xdegaye66caacf2017-10-23 18:08:41 +0200721 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722 }
Victor Stinner09054372013-11-06 22:41:44 +0100723 hook = _PySys_GetObjectId(&PyId_excepthook);
Victor Stinner1c1e68c2020-03-27 15:11:45 +0100724 if (_PySys_Audit(tstate, "sys.excepthook", "OOOO", hook ? hook : Py_None,
725 exception, v, tb) < 0) {
Steve Dowerbea33f52019-11-28 08:46:11 -0800726 if (PyErr_ExceptionMatches(PyExc_RuntimeError)) {
727 PyErr_Clear();
728 goto done;
729 }
730 _PyErr_WriteUnraisableMsg("in audit hook", NULL);
731 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 if (hook) {
Victor Stinner71cb64a2016-08-20 00:57:43 +0200733 PyObject* stack[3];
734 PyObject *result;
735
736 stack[0] = exception;
737 stack[1] = v;
738 stack[2] = tb;
Victor Stinner559bb6a2016-08-22 22:48:54 +0200739 result = _PyObject_FastCall(hook, stack, 3);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 if (result == NULL) {
Victor Stinner12083282019-05-17 23:05:29 +0200741 handle_system_exit();
742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 PyObject *exception2, *v2, *tb2;
Victor Stinner438a12d2019-05-24 17:01:38 +0200744 _PyErr_Fetch(tstate, &exception2, &v2, &tb2);
745 _PyErr_NormalizeException(tstate, &exception2, &v2, &tb2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 /* It should not be possible for exception2 or v2
747 to be NULL. However PyErr_Display() can't
748 tolerate NULLs, so just be safe. */
749 if (exception2 == NULL) {
750 exception2 = Py_None;
751 Py_INCREF(exception2);
752 }
753 if (v2 == NULL) {
754 v2 = Py_None;
755 Py_INCREF(v2);
756 }
757 fflush(stdout);
758 PySys_WriteStderr("Error in sys.excepthook:\n");
759 PyErr_Display(exception2, v2, tb2);
760 PySys_WriteStderr("\nOriginal exception was:\n");
761 PyErr_Display(exception, v, tb);
762 Py_DECREF(exception2);
763 Py_DECREF(v2);
764 Py_XDECREF(tb2);
765 }
766 Py_XDECREF(result);
Victor Stinner438a12d2019-05-24 17:01:38 +0200767 }
768 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 PySys_WriteStderr("sys.excepthook is missing\n");
770 PyErr_Display(exception, v, tb);
771 }
Victor Stinner438a12d2019-05-24 17:01:38 +0200772
773done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 Py_XDECREF(exception);
775 Py_XDECREF(v);
776 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000777}
778
Victor Stinner438a12d2019-05-24 17:01:38 +0200779void
780_PyErr_Print(PyThreadState *tstate)
781{
782 _PyErr_PrintEx(tstate, 1);
783}
784
785void
786PyErr_PrintEx(int set_sys_last_vars)
787{
788 PyThreadState *tstate = _PyThreadState_GET();
789 _PyErr_PrintEx(tstate, set_sys_last_vars);
790}
791
792void
793PyErr_Print(void)
794{
795 PyErr_PrintEx(1);
796}
797
Benjamin Petersone6528212008-07-15 15:32:09 +0000798static void
799print_exception(PyObject *f, PyObject *value)
800{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000801 int err = 0;
Serhiy Storchaka98c44332020-10-10 22:23:42 +0300802 PyObject *type, *tb, *tmp;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200803 _Py_IDENTIFIER(print_file_and_line);
Benjamin Petersone6528212008-07-15 15:32:09 +0000804
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000805 if (!PyExceptionInstance_Check(value)) {
Victor Stinner52ce3b02013-12-09 02:10:08 +0100806 err = PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
807 err += PyFile_WriteString(Py_TYPE(value)->tp_name, f);
808 err += PyFile_WriteString(" found\n", f);
809 if (err)
810 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 return;
812 }
Benjamin Peterson26582602008-08-23 20:08:07 +0000813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 Py_INCREF(value);
815 fflush(stdout);
816 type = (PyObject *) Py_TYPE(value);
817 tb = PyException_GetTraceback(value);
818 if (tb && tb != Py_None)
819 err = PyTraceBack_Print(tb, f);
820 if (err == 0 &&
Serhiy Storchaka98c44332020-10-10 22:23:42 +0300821 (err = _PyObject_LookupAttrId(value, &PyId_print_file_and_line, &tmp)) > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000822 {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100823 PyObject *message, *filename, *text;
Ammar Askar90d29702020-06-02 08:17:24 +0000824 Py_ssize_t lineno, offset;
Serhiy Storchaka98c44332020-10-10 22:23:42 +0300825 err = 0;
826 Py_DECREF(tmp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000827 if (!parse_syntax_error(value, &message, &filename,
828 &lineno, &offset, &text))
829 PyErr_Clear();
830 else {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100831 PyObject *line;
832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 Py_DECREF(value);
834 value = message;
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100835
Ammar Askar90d29702020-06-02 08:17:24 +0000836 line = PyUnicode_FromFormat(" File \"%S\", line %zd\n",
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100837 filename, lineno);
838 Py_DECREF(filename);
839 if (line != NULL) {
840 PyFile_WriteObject(line, f, Py_PRINT_RAW);
841 Py_DECREF(line);
842 }
843
844 if (text != NULL) {
845 print_error_text(f, offset, text);
846 Py_DECREF(text);
847 }
848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 /* Can't be bothered to check all those
850 PyFile_WriteString() calls */
851 if (PyErr_Occurred())
852 err = -1;
853 }
854 }
855 if (err) {
856 /* Don't do anything else */
857 }
858 else {
859 PyObject* moduleName;
Serhiy Storchakaceeef102018-06-15 11:09:43 +0300860 const char *className;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200861 _Py_IDENTIFIER(__module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 assert(PyExceptionClass_Check(type));
863 className = PyExceptionClass_Name(type);
864 if (className != NULL) {
Serhiy Storchakaceeef102018-06-15 11:09:43 +0300865 const char *dot = strrchr(className, '.');
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 if (dot != NULL)
867 className = dot+1;
868 }
Benjamin Petersone6528212008-07-15 15:32:09 +0000869
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200870 moduleName = _PyObject_GetAttrId(type, &PyId___module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000871 if (moduleName == NULL || !PyUnicode_Check(moduleName))
872 {
Victor Stinner13b21bd2011-05-26 14:25:13 +0200873 Py_XDECREF(moduleName);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 err = PyFile_WriteString("<unknown>", f);
875 }
876 else {
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +0200877 if (!_PyUnicode_EqualToASCIIId(moduleName, &PyId_builtins))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 {
Victor Stinner937114f2013-11-07 00:12:30 +0100879 err = PyFile_WriteObject(moduleName, f, Py_PRINT_RAW);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 err += PyFile_WriteString(".", f);
881 }
882 Py_DECREF(moduleName);
883 }
884 if (err == 0) {
885 if (className == NULL)
886 err = PyFile_WriteString("<unknown>", f);
887 else
888 err = PyFile_WriteString(className, f);
889 }
890 }
891 if (err == 0 && (value != Py_None)) {
892 PyObject *s = PyObject_Str(value);
893 /* only print colon if the str() of the
894 object is not the empty string
895 */
Martin Panter3263f682016-02-28 03:16:11 +0000896 if (s == NULL) {
897 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 err = -1;
Martin Panter3263f682016-02-28 03:16:11 +0000899 PyFile_WriteString(": <exception str() failed>", f);
900 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000901 else if (!PyUnicode_Check(s) ||
Victor Stinnere251d6d2011-11-20 19:20:00 +0100902 PyUnicode_GetLength(s) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 err = PyFile_WriteString(": ", f);
904 if (err == 0)
905 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
906 Py_XDECREF(s);
907 }
908 /* try to write a newline in any case */
Martin Panter3263f682016-02-28 03:16:11 +0000909 if (err < 0) {
910 PyErr_Clear();
911 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 err += PyFile_WriteString("\n", f);
913 Py_XDECREF(tb);
914 Py_DECREF(value);
915 /* If an error happened here, don't show it.
916 XXX This is wrong, but too many callers rely on this behavior. */
917 if (err != 0)
918 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +0000919}
920
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200921static const char cause_message[] =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 "\nThe above exception was the direct cause "
923 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +0000924
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200925static const char context_message[] =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 "\nDuring handling of the above exception, "
927 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +0000928
929static void
930print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
931{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 int err = 0, res;
933 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +0000934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 if (seen != NULL) {
936 /* Exception chaining */
Zane Bitterde860732017-10-17 17:29:39 -0400937 PyObject *value_id = PyLong_FromVoidPtr(value);
938 if (value_id == NULL || PySet_Add(seen, value_id) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 PyErr_Clear();
940 else if (PyExceptionInstance_Check(value)) {
Zane Bitterde860732017-10-17 17:29:39 -0400941 PyObject *check_id = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 cause = PyException_GetCause(value);
943 context = PyException_GetContext(value);
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700944 if (cause) {
Zane Bitterde860732017-10-17 17:29:39 -0400945 check_id = PyLong_FromVoidPtr(cause);
946 if (check_id == NULL) {
947 res = -1;
948 } else {
949 res = PySet_Contains(seen, check_id);
950 Py_DECREF(check_id);
951 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 if (res == -1)
953 PyErr_Clear();
954 if (res == 0) {
955 print_exception_recursive(
956 f, cause, seen);
957 err |= PyFile_WriteString(
958 cause_message, f);
959 }
960 }
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700961 else if (context &&
962 !((PyBaseExceptionObject *)value)->suppress_context) {
Zane Bitterde860732017-10-17 17:29:39 -0400963 check_id = PyLong_FromVoidPtr(context);
964 if (check_id == NULL) {
965 res = -1;
966 } else {
967 res = PySet_Contains(seen, check_id);
968 Py_DECREF(check_id);
969 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 if (res == -1)
971 PyErr_Clear();
972 if (res == 0) {
973 print_exception_recursive(
974 f, context, seen);
975 err |= PyFile_WriteString(
976 context_message, f);
977 }
978 }
979 Py_XDECREF(context);
980 Py_XDECREF(cause);
981 }
Zane Bitterde860732017-10-17 17:29:39 -0400982 Py_XDECREF(value_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 }
984 print_exception(f, value);
985 if (err != 0)
986 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +0000987}
988
Thomas Wouters477c8d52006-05-27 19:21:47 +0000989void
Victor Stinnercd590a72019-05-28 00:39:52 +0200990_PyErr_Display(PyObject *file, PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000991{
Victor Stinnercd590a72019-05-28 00:39:52 +0200992 assert(file != NULL && file != Py_None);
993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 PyObject *seen;
Antoine Pitrou24201d42013-10-13 21:53:13 +0200995 if (PyExceptionInstance_Check(value)
996 && tb != NULL && PyTraceBack_Check(tb)) {
997 /* Put the traceback on the exception, otherwise it won't get
998 displayed. See issue #18776. */
999 PyObject *cur_tb = PyException_GetTraceback(value);
1000 if (cur_tb == NULL)
1001 PyException_SetTraceback(value, tb);
1002 else
1003 Py_DECREF(cur_tb);
1004 }
Victor Stinnercd590a72019-05-28 00:39:52 +02001005
1006 /* We choose to ignore seen being possibly NULL, and report
1007 at least the main exception (it could be a MemoryError).
1008 */
1009 seen = PySet_New(NULL);
1010 if (seen == NULL) {
1011 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 }
Victor Stinnercd590a72019-05-28 00:39:52 +02001013 print_exception_recursive(file, value, seen);
1014 Py_XDECREF(seen);
Victor Stinnera85a1d32019-05-28 16:01:17 +02001015
1016 /* Call file.flush() */
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001017 PyObject *res = _PyObject_CallMethodIdNoArgs(file, &PyId_flush);
Victor Stinnera85a1d32019-05-28 16:01:17 +02001018 if (!res) {
1019 /* Silently ignore file.flush() error */
1020 PyErr_Clear();
1021 }
1022 else {
1023 Py_DECREF(res);
1024 }
Victor Stinnercd590a72019-05-28 00:39:52 +02001025}
1026
1027void
1028PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
1029{
1030 PyObject *file = _PySys_GetObjectId(&PyId_stderr);
1031 if (file == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 _PyObject_Dump(value);
1033 fprintf(stderr, "lost sys.stderr\n");
Victor Stinnercd590a72019-05-28 00:39:52 +02001034 return;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 }
Victor Stinnercd590a72019-05-28 00:39:52 +02001036 if (file == Py_None) {
1037 return;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 }
Victor Stinnercd590a72019-05-28 00:39:52 +02001039
1040 _PyErr_Display(file, exception, value, tb);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001041}
1042
Guido van Rossum82598051997-03-05 00:20:32 +00001043PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001044PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001046{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 PyObject *ret = NULL;
1048 mod_ty mod;
Victor Stinner95701bd2013-11-06 18:41:07 +01001049 PyArena *arena;
Victor Stinner95701bd2013-11-06 18:41:07 +01001050 PyObject *filename;
1051
1052 filename = _PyUnicode_FromId(&PyId_string); /* borrowed */
1053 if (filename == NULL)
1054 return NULL;
1055
1056 arena = PyArena_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 if (arena == NULL)
1058 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001059
Lysandros Nikolaou564cd182020-06-22 02:47:46 +03001060 mod = PyParser_ASTFromStringObject(str, filename, start, flags, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062 if (mod != NULL)
Victor Stinner95701bd2013-11-06 18:41:07 +01001063 ret = run_mod(mod, filename, globals, locals, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 PyArena_Free(arena);
1065 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001066}
1067
Victor Stinnerb6d98c12020-12-08 14:38:08 +01001068
1069static PyObject *
1070pyrun_file(FILE *fp, PyObject *filename, int start, PyObject *globals,
1071 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001072{
Victor Stinnerb6d98c12020-12-08 14:38:08 +01001073 PyArena *arena = PyArena_New();
1074 if (arena == NULL) {
1075 return NULL;
1076 }
1077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 mod_ty mod;
Lysandros Nikolaou564cd182020-06-22 02:47:46 +03001079 mod = PyParser_ASTFromFileObject(fp, filename, NULL, start, NULL, NULL,
1080 flags, NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001081
Victor Stinnerb6d98c12020-12-08 14:38:08 +01001082 if (closeit) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 fclose(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 }
Victor Stinner95701bd2013-11-06 18:41:07 +01001085
Victor Stinnerb6d98c12020-12-08 14:38:08 +01001086 PyObject *ret;
1087 if (mod != NULL) {
1088 ret = run_mod(mod, filename, globals, locals, flags, arena);
1089 }
1090 else {
1091 ret = NULL;
1092 }
1093 PyArena_Free(arena);
1094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001096}
1097
Victor Stinnerb6d98c12020-12-08 14:38:08 +01001098
1099PyObject *
1100PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
1101 PyObject *locals, int closeit, PyCompilerFlags *flags)
1102{
1103 PyObject *filename_obj = PyUnicode_DecodeFSDefault(filename);
1104 if (filename_obj == NULL) {
1105 return NULL;
1106 }
1107
1108 PyObject *res = pyrun_file(fp, filename_obj, start, globals,
1109 locals, closeit, flags);
1110 Py_DECREF(filename_obj);
1111 return res;
1112
1113}
1114
1115
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001116static void
1117flush_io(void)
1118{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 PyObject *f, *r;
1120 PyObject *type, *value, *traceback;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 /* Save the current exception */
1123 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001124
Victor Stinnerbd303c12013-11-07 23:07:29 +01001125 f = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 if (f != NULL) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001127 r = _PyObject_CallMethodIdNoArgs(f, &PyId_flush);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001128 if (r)
1129 Py_DECREF(r);
1130 else
1131 PyErr_Clear();
1132 }
Victor Stinnerbd303c12013-11-07 23:07:29 +01001133 f = _PySys_GetObjectId(&PyId_stdout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001134 if (f != NULL) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001135 r = _PyObject_CallMethodIdNoArgs(f, &PyId_flush);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 if (r)
1137 Py_DECREF(r);
1138 else
1139 PyErr_Clear();
1140 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001143}
1144
Guido van Rossum82598051997-03-05 00:20:32 +00001145static PyObject *
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001146run_eval_code_obj(PyThreadState *tstate, PyCodeObject *co, PyObject *globals, PyObject *locals)
Gregory P. Smith38f11cc2019-02-16 12:57:40 -08001147{
1148 PyObject *v;
Gregory P. Smithd9bc5432019-02-20 17:35:54 -08001149 /*
1150 * We explicitly re-initialize _Py_UnhandledKeyboardInterrupt every eval
1151 * _just in case_ someone is calling into an embedded Python where they
1152 * don't care about an uncaught KeyboardInterrupt exception (why didn't they
1153 * leave config.install_signal_handlers set to 0?!?) but then later call
1154 * Py_Main() itself (which _checks_ this flag and dies with a signal after
1155 * its interpreter exits). We don't want a previous embedded interpreter's
1156 * uncaught exception to trigger an unexplained signal exit from a future
1157 * Py_Main() based one.
1158 */
1159 _Py_UnhandledKeyboardInterrupt = 0;
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001160
1161 /* Set globals['__builtins__'] if it doesn't exist */
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02001162 if (globals != NULL && _PyDict_GetItemStringWithError(globals, "__builtins__") == NULL) {
1163 if (PyErr_Occurred() ||
1164 PyDict_SetItemString(globals, "__builtins__",
1165 tstate->interp->builtins) < 0)
1166 {
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001167 return NULL;
1168 }
1169 }
1170
Gregory P. Smith38f11cc2019-02-16 12:57:40 -08001171 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001172 if (!v && _PyErr_Occurred(tstate) == PyExc_KeyboardInterrupt) {
Gregory P. Smith38f11cc2019-02-16 12:57:40 -08001173 _Py_UnhandledKeyboardInterrupt = 1;
1174 }
1175 return v;
1176}
1177
1178static PyObject *
Victor Stinner95701bd2013-11-06 18:41:07 +01001179run_mod(mod_ty mod, PyObject *filename, PyObject *globals, PyObject *locals,
1180 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001181{
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001182 PyThreadState *tstate = _PyThreadState_GET();
1183 PyCodeObject *co = PyAST_CompileObject(mod, filename, flags, -1, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001184 if (co == NULL)
1185 return NULL;
Steve Dowerb82e17e2019-05-23 08:45:22 -07001186
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001187 if (_PySys_Audit(tstate, "exec", "O", co) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07001188 Py_DECREF(co);
1189 return NULL;
1190 }
1191
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001192 PyObject *v = run_eval_code_obj(tstate, co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001193 Py_DECREF(co);
1194 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001195}
1196
Guido van Rossum82598051997-03-05 00:20:32 +00001197static PyObject *
Victor Stinnerb6d98c12020-12-08 14:38:08 +01001198run_pyc_file(FILE *fp, PyObject *globals, PyObject *locals,
1199 PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001200{
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001201 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 PyCodeObject *co;
1203 PyObject *v;
1204 long magic;
1205 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001207 magic = PyMarshal_ReadLongFromFile(fp);
1208 if (magic != PyImport_GetMagicNumber()) {
Victor Stinner5200f552015-03-18 13:56:25 +01001209 if (!PyErr_Occurred())
1210 PyErr_SetString(PyExc_RuntimeError,
1211 "Bad magic number in .pyc file");
Zackery Spytzea737752018-06-23 21:15:24 -06001212 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 }
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08001214 /* Skip the rest of the header. */
1215 (void) PyMarshal_ReadLongFromFile(fp);
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001216 (void) PyMarshal_ReadLongFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 (void) PyMarshal_ReadLongFromFile(fp);
Zackery Spytzea737752018-06-23 21:15:24 -06001218 if (PyErr_Occurred()) {
1219 goto error;
1220 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001221 v = PyMarshal_ReadLastObjectFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001222 if (v == NULL || !PyCode_Check(v)) {
1223 Py_XDECREF(v);
1224 PyErr_SetString(PyExc_RuntimeError,
1225 "Bad code object in .pyc file");
Zackery Spytzea737752018-06-23 21:15:24 -06001226 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 }
Zackery Spytzea737752018-06-23 21:15:24 -06001228 fclose(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 co = (PyCodeObject *)v;
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001230 v = run_eval_code_obj(tstate, co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 if (v && flags)
1232 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1233 Py_DECREF(co);
1234 return v;
Zackery Spytzea737752018-06-23 21:15:24 -06001235error:
1236 fclose(fp);
1237 return NULL;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001238}
1239
Guido van Rossum82598051997-03-05 00:20:32 +00001240PyObject *
Victor Stinner14e461d2013-08-26 22:28:21 +02001241Py_CompileStringObject(const char *str, PyObject *filename, int start,
1242 PyCompilerFlags *flags, int optimize)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001243{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 PyCodeObject *co;
1245 mod_ty mod;
1246 PyArena *arena = PyArena_New();
1247 if (arena == NULL)
1248 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001249
Lysandros Nikolaou564cd182020-06-22 02:47:46 +03001250 mod = PyParser_ASTFromStringObject(str, filename, start, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001251 if (mod == NULL) {
1252 PyArena_Free(arena);
1253 return NULL;
1254 }
1255 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
1256 PyObject *result = PyAST_mod2obj(mod);
1257 PyArena_Free(arena);
1258 return result;
1259 }
Victor Stinner14e461d2013-08-26 22:28:21 +02001260 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 PyArena_Free(arena);
1262 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001263}
1264
Victor Stinner14e461d2013-08-26 22:28:21 +02001265PyObject *
1266Py_CompileStringExFlags(const char *str, const char *filename_str, int start,
1267 PyCompilerFlags *flags, int optimize)
1268{
1269 PyObject *filename, *co;
1270 filename = PyUnicode_DecodeFSDefault(filename_str);
1271 if (filename == NULL)
1272 return NULL;
1273 co = Py_CompileStringObject(str, filename, start, flags, optimize);
1274 Py_DECREF(filename);
1275 return co;
1276}
1277
Dino Viehland41540692019-05-28 16:21:17 -07001278const char *
1279_Py_SourceAsString(PyObject *cmd, const char *funcname, const char *what, PyCompilerFlags *cf, PyObject **cmd_copy)
1280{
1281 const char *str;
1282 Py_ssize_t size;
1283 Py_buffer view;
1284
1285 *cmd_copy = NULL;
1286 if (PyUnicode_Check(cmd)) {
1287 cf->cf_flags |= PyCF_IGNORE_COOKIE;
1288 str = PyUnicode_AsUTF8AndSize(cmd, &size);
1289 if (str == NULL)
1290 return NULL;
1291 }
1292 else if (PyBytes_Check(cmd)) {
1293 str = PyBytes_AS_STRING(cmd);
1294 size = PyBytes_GET_SIZE(cmd);
1295 }
1296 else if (PyByteArray_Check(cmd)) {
1297 str = PyByteArray_AS_STRING(cmd);
1298 size = PyByteArray_GET_SIZE(cmd);
1299 }
1300 else if (PyObject_GetBuffer(cmd, &view, PyBUF_SIMPLE) == 0) {
1301 /* Copy to NUL-terminated buffer. */
1302 *cmd_copy = PyBytes_FromStringAndSize(
1303 (const char *)view.buf, view.len);
1304 PyBuffer_Release(&view);
1305 if (*cmd_copy == NULL) {
1306 return NULL;
1307 }
1308 str = PyBytes_AS_STRING(*cmd_copy);
1309 size = PyBytes_GET_SIZE(*cmd_copy);
1310 }
1311 else {
1312 PyErr_Format(PyExc_TypeError,
1313 "%s() arg 1 must be a %s object",
1314 funcname, what);
1315 return NULL;
1316 }
1317
1318 if (strlen(str) != (size_t)size) {
1319 PyErr_SetString(PyExc_ValueError,
1320 "source code string cannot contain null bytes");
1321 Py_CLEAR(*cmd_copy);
1322 return NULL;
1323 }
1324 return str;
1325}
1326
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001327struct symtable *
Victor Stinner14e461d2013-08-26 22:28:21 +02001328Py_SymtableStringObject(const char *str, PyObject *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001329{
Victor Stinner37d66d72019-06-13 02:16:41 +02001330 PyCompilerFlags flags = _PyCompilerFlags_INIT;
Dino Viehland41540692019-05-28 16:21:17 -07001331 return _Py_SymtableStringObjectFlags(str, filename, start, &flags);
1332}
1333
1334struct symtable *
1335_Py_SymtableStringObjectFlags(const char *str, PyObject *filename, int start, PyCompilerFlags *flags)
1336{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 struct symtable *st;
1338 mod_ty mod;
Victor Stinner14e461d2013-08-26 22:28:21 +02001339 PyArena *arena;
1340
1341 arena = PyArena_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 if (arena == NULL)
1343 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001344
Lysandros Nikolaou564cd182020-06-22 02:47:46 +03001345 mod = PyParser_ASTFromStringObject(str, filename, start, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 if (mod == NULL) {
1347 PyArena_Free(arena);
1348 return NULL;
1349 }
Victor Stinner14e461d2013-08-26 22:28:21 +02001350 st = PySymtable_BuildObject(mod, filename, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 PyArena_Free(arena);
1352 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001353}
1354
Victor Stinner14e461d2013-08-26 22:28:21 +02001355struct symtable *
1356Py_SymtableString(const char *str, const char *filename_str, int start)
1357{
1358 PyObject *filename;
1359 struct symtable *st;
1360
1361 filename = PyUnicode_DecodeFSDefault(filename_str);
1362 if (filename == NULL)
1363 return NULL;
1364 st = Py_SymtableStringObject(str, filename, start);
1365 Py_DECREF(filename);
1366 return st;
1367}
1368
Zachary Warec4821d62014-11-21 23:35:12 -06001369#if defined(USE_STACKCHECK)
1370#if defined(WIN32) && defined(_MSC_VER)
1371
1372/* Stack checking for Microsoft C */
1373
1374#include <malloc.h>
1375#include <excpt.h>
1376
1377/*
1378 * Return non-zero when we run out of memory on the stack; zero otherwise.
1379 */
1380int
1381PyOS_CheckStack(void)
1382{
1383 __try {
1384 /* alloca throws a stack overflow exception if there's
1385 not enough space left on the stack */
1386 alloca(PYOS_STACK_MARGIN * sizeof(void*));
1387 return 0;
1388 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
1389 EXCEPTION_EXECUTE_HANDLER :
1390 EXCEPTION_CONTINUE_SEARCH) {
1391 int errcode = _resetstkoflw();
1392 if (errcode == 0)
1393 {
1394 Py_FatalError("Could not reset the stack!");
1395 }
1396 }
1397 return 1;
1398}
1399
1400#endif /* WIN32 && _MSC_VER */
1401
1402/* Alternate implementations can be added here... */
1403
1404#endif /* USE_STACKCHECK */
1405
Pablo Galindo46bd5ed2020-12-02 05:16:31 +00001406/* Deprecated C API functions still provided for binary compatibility */
1407
1408#undef PyRun_AnyFile
1409PyAPI_FUNC(int)
1410PyRun_AnyFile(FILE *fp, const char *name)
1411{
1412 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
1413}
1414
1415#undef PyRun_AnyFileEx
1416PyAPI_FUNC(int)
1417PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
1418{
1419 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
1420}
1421
1422#undef PyRun_AnyFileFlags
1423PyAPI_FUNC(int)
1424PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
1425{
1426 return PyRun_AnyFileExFlags(fp, name, 0, flags);
1427}
1428
1429#undef PyRun_File
1430PyAPI_FUNC(PyObject *)
1431PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
1432{
1433 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
1434}
1435
1436#undef PyRun_FileEx
1437PyAPI_FUNC(PyObject *)
1438PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
1439{
1440 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
1441}
1442
1443#undef PyRun_FileFlags
1444PyAPI_FUNC(PyObject *)
1445PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
1446 PyCompilerFlags *flags)
1447{
1448 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
1449}
1450
1451#undef PyRun_SimpleFile
1452PyAPI_FUNC(int)
1453PyRun_SimpleFile(FILE *f, const char *p)
1454{
1455 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
1456}
1457
1458#undef PyRun_SimpleFileEx
1459PyAPI_FUNC(int)
1460PyRun_SimpleFileEx(FILE *f, const char *p, int c)
1461{
1462 return PyRun_SimpleFileExFlags(f, p, c, NULL);
1463}
1464
1465
1466#undef PyRun_String
1467PyAPI_FUNC(PyObject *)
1468PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
1469{
1470 return PyRun_StringFlags(str, s, g, l, NULL);
1471}
1472
1473#undef PyRun_SimpleString
1474PyAPI_FUNC(int)
1475PyRun_SimpleString(const char *s)
1476{
1477 return PyRun_SimpleStringFlags(s, NULL);
1478}
1479
1480#undef Py_CompileString
1481PyAPI_FUNC(PyObject *)
1482Py_CompileString(const char *str, const char *p, int s)
1483{
1484 return Py_CompileStringExFlags(str, p, s, NULL, -1);
1485}
1486
1487#undef Py_CompileStringFlags
1488PyAPI_FUNC(PyObject *)
1489Py_CompileStringFlags(const char *str, const char *p, int s,
1490 PyCompilerFlags *flags)
1491{
1492 return Py_CompileStringExFlags(str, p, s, flags, -1);
1493}
1494
1495#undef PyRun_InteractiveOne
1496PyAPI_FUNC(int)
1497PyRun_InteractiveOne(FILE *f, const char *p)
1498{
1499 return PyRun_InteractiveOneFlags(f, p, NULL);
1500}
1501
1502#undef PyRun_InteractiveLoop
1503PyAPI_FUNC(int)
1504PyRun_InteractiveLoop(FILE *f, const char *p)
1505{
1506 return PyRun_InteractiveLoopFlags(f, p, NULL);
1507}
1508
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001509#ifdef __cplusplus
1510}
1511#endif