blob: 79ff42ba95a493c0d49e8a3a764e1b49f85ffb14 [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()
Victor Stinner57364ce2021-03-24 01:29:09 +010019#include "pycore_parser.h" // _PyParser_ASTFromString()
Victor Stinner4f98f462020-04-15 04:01:58 +020020#include "pycore_pyerrors.h" // _PyErr_Fetch
21#include "pycore_pylifecycle.h" // _Py_UnhandledKeyboardInterrupt
Victor Stinnere5014be2020-04-14 17:52:15 +020022#include "pycore_pystate.h" // _PyInterpreterState_GET()
Victor Stinner4f98f462020-04-15 04:01:58 +020023#include "pycore_sysmodule.h" // _PySys_Audit()
Guido van Rossum1984f1e1992-08-04 12:41:02 +000024
Victor Stinner4f98f462020-04-15 04:01:58 +020025#include "token.h" // INDENT
Victor Stinner4f98f462020-04-15 04:01:58 +020026#include "errcode.h" // E_EOF
27#include "code.h" // PyCodeObject
Victor Stinner4f98f462020-04-15 04:01:58 +020028#include "marshal.h" // PyMarshal_ReadLongFromFile()
29
30#ifdef MS_WINDOWS
31# include "malloc.h" // alloca()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000032#endif
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000033
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000034#ifdef MS_WINDOWS
Victor Stinner4f98f462020-04-15 04:01:58 +020035# undef BYTE
36# include "windows.h"
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000037#endif
Martin v. Löwis5c88d812009-01-02 20:47:48 +000038
Guido van Rossuma44823b1995-03-14 15:01:17 +000039
Victor Stinnerbd303c12013-11-07 23:07:29 +010040_Py_IDENTIFIER(builtins);
Victor Stinner09054372013-11-06 22:41:44 +010041_Py_IDENTIFIER(excepthook);
Victor Stinner3f36a572013-11-12 21:39:02 +010042_Py_IDENTIFIER(flush);
Victor Stinnerbd303c12013-11-07 23:07:29 +010043_Py_IDENTIFIER(last_traceback);
Victor Stinner09054372013-11-06 22:41:44 +010044_Py_IDENTIFIER(last_type);
45_Py_IDENTIFIER(last_value);
Victor Stinnerbd303c12013-11-07 23:07:29 +010046_Py_IDENTIFIER(ps1);
47_Py_IDENTIFIER(ps2);
48_Py_IDENTIFIER(stdin);
49_Py_IDENTIFIER(stdout);
50_Py_IDENTIFIER(stderr);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +010051_Py_static_string(PyId_string, "<string>");
Victor Stinner09054372013-11-06 22:41:44 +010052
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000053#ifdef __cplusplus
54extern "C" {
Neal Norwitz4281cef2006-03-04 19:58:13 +000055#endif
56
Guido van Rossumb73cc041993-11-01 16:28:59 +000057/* Forward */
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +000058static void flush_io(void);
Victor Stinner95701bd2013-11-06 18:41:07 +010059static PyObject *run_mod(mod_ty, PyObject *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000060 PyCompilerFlags *, PyArena *);
Victor Stinnerb6d98c12020-12-08 14:38:08 +010061static PyObject *run_pyc_file(FILE *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000062 PyCompilerFlags *);
xdegayee0582a32017-11-12 16:50:48 +010063static int PyRun_InteractiveOneObjectEx(FILE *, PyObject *, PyCompilerFlags *);
Victor Stinnerb6d98c12020-12-08 14:38:08 +010064static PyObject* pyrun_file(FILE *fp, PyObject *filename, int start,
65 PyObject *globals, PyObject *locals, int closeit,
66 PyCompilerFlags *flags);
67
Guido van Rossumce3a72a2007-10-19 23:16:50 +000068
Victor Stinnera82f63f2020-12-09 22:37:27 +010069int
70_PyRun_AnyFileObject(FILE *fp, PyObject *filename, int closeit,
71 PyCompilerFlags *flags)
72{
73 int decref_filename = 0;
74 if (filename == NULL) {
75 filename = PyUnicode_FromString("???");
76 if (filename == NULL) {
77 PyErr_Print();
78 return -1;
79 }
80 decref_filename = 1;
81 }
82
83 int res;
84 if (_Py_FdIsInteractive(fp, filename)) {
85 res = _PyRun_InteractiveLoopObject(fp, filename, flags);
86 if (closeit) {
87 fclose(fp);
88 }
89 }
90 else {
91 res = _PyRun_SimpleFileObject(fp, filename, closeit, flags);
92 }
93
94 if (decref_filename) {
95 Py_DECREF(filename);
96 }
97 return res;
98}
99
100
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000101/* Parse input from a file and execute it */
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000102int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000103PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000104 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000105{
Victor Stinnera82f63f2020-12-09 22:37:27 +0100106 PyObject *filename_obj;
107 if (filename != NULL) {
108 filename_obj = PyUnicode_DecodeFSDefault(filename);
109 if (filename_obj == NULL) {
110 PyErr_Print();
111 return -1;
112 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000113 }
Victor Stinnera82f63f2020-12-09 22:37:27 +0100114 else {
115 filename_obj = NULL;
116 }
117 int res = _PyRun_AnyFileObject(fp, filename_obj, closeit, flags);
118 Py_XDECREF(filename_obj);
119 return res;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000120}
121
Victor Stinnera82f63f2020-12-09 22:37:27 +0100122
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000123int
Victor Stinnera82f63f2020-12-09 22:37:27 +0100124_PyRun_InteractiveLoopObject(FILE *fp, PyObject *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000125{
Victor Stinner37d66d72019-06-13 02:16:41 +0200126 PyCompilerFlags local_flags = _PyCompilerFlags_INIT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000127 if (flags == NULL) {
128 flags = &local_flags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000129 }
Victor Stinnera82f63f2020-12-09 22:37:27 +0100130
131 PyObject *v = _PySys_GetObjectId(&PyId_ps1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 if (v == NULL) {
Victor Stinner09054372013-11-06 22:41:44 +0100133 _PySys_SetObjectId(&PyId_ps1, v = PyUnicode_FromString(">>> "));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000134 Py_XDECREF(v);
135 }
Victor Stinner09054372013-11-06 22:41:44 +0100136 v = _PySys_GetObjectId(&PyId_ps2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000137 if (v == NULL) {
Victor Stinner09054372013-11-06 22:41:44 +0100138 _PySys_SetObjectId(&PyId_ps2, v = PyUnicode_FromString("... "));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000139 Py_XDECREF(v);
140 }
Victor Stinnera82f63f2020-12-09 22:37:27 +0100141
142#ifdef Py_REF_DEBUG
143 int show_ref_count = _Py_GetConfig()->show_ref_count;
144#endif
145 int err = 0;
146 int ret;
147 int nomem_count = 0;
xdegayee0582a32017-11-12 16:50:48 +0100148 do {
149 ret = PyRun_InteractiveOneObjectEx(fp, filename, flags);
150 if (ret == -1 && PyErr_Occurred()) {
151 /* Prevent an endless loop after multiple consecutive MemoryErrors
152 * while still allowing an interactive command to fail with a
153 * MemoryError. */
154 if (PyErr_ExceptionMatches(PyExc_MemoryError)) {
155 if (++nomem_count > 16) {
156 PyErr_Clear();
157 err = -1;
158 break;
159 }
160 } else {
161 nomem_count = 0;
162 }
163 PyErr_Print();
164 flush_io();
165 } else {
166 nomem_count = 0;
167 }
Eric Snowdae02762017-09-14 00:35:58 -0700168#ifdef Py_REF_DEBUG
Victor Stinner25420fe2017-11-20 18:12:22 -0800169 if (show_ref_count) {
Eric Snowdae02762017-09-14 00:35:58 -0700170 _PyDebug_PrintTotalRefs();
Victor Stinner25420fe2017-11-20 18:12:22 -0800171 }
Eric Snowdae02762017-09-14 00:35:58 -0700172#endif
xdegayee0582a32017-11-12 16:50:48 +0100173 } while (ret != E_EOF);
Victor Stinner95701bd2013-11-06 18:41:07 +0100174 return err;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000175}
176
Victor Stinnera82f63f2020-12-09 22:37:27 +0100177
178int
179PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
180{
181 PyObject *filename_obj = PyUnicode_DecodeFSDefault(filename);
182 if (filename_obj == NULL) {
183 PyErr_Print();
184 return -1;
185 }
186
187 int err = _PyRun_InteractiveLoopObject(fp, filename_obj, flags);
188 Py_DECREF(filename_obj);
189 return err;
190
191}
192
193
xdegayee0582a32017-11-12 16:50:48 +0100194/* A PyRun_InteractiveOneObject() auxiliary function that does not print the
195 * error on failure. */
196static int
197PyRun_InteractiveOneObjectEx(FILE *fp, PyObject *filename,
198 PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000199{
Victor Stinner95701bd2013-11-06 18:41:07 +0100200 PyObject *m, *d, *v, *w, *oenc = NULL, *mod_name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000201 mod_ty mod;
202 PyArena *arena;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200203 const char *ps1 = "", *ps2 = "", *enc = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000204 int errcode = 0;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200205 _Py_IDENTIFIER(encoding);
Victor Stinner95701bd2013-11-06 18:41:07 +0100206 _Py_IDENTIFIER(__main__);
207
208 mod_name = _PyUnicode_FromId(&PyId___main__); /* borrowed */
209 if (mod_name == NULL) {
Victor Stinner95701bd2013-11-06 18:41:07 +0100210 return -1;
211 }
Tim Petersfe2127d2001-07-16 05:37:24 +0000212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 if (fp == stdin) {
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -0400214 /* Fetch encoding from sys.stdin if possible. */
Victor Stinnerbd303c12013-11-07 23:07:29 +0100215 v = _PySys_GetObjectId(&PyId_stdin);
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -0400216 if (v && v != Py_None) {
217 oenc = _PyObject_GetAttrId(v, &PyId_encoding);
218 if (oenc)
Serhiy Storchaka06515832016-11-20 09:13:07 +0200219 enc = PyUnicode_AsUTF8(oenc);
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -0400220 if (!enc)
221 PyErr_Clear();
222 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000223 }
Victor Stinner09054372013-11-06 22:41:44 +0100224 v = _PySys_GetObjectId(&PyId_ps1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000225 if (v != NULL) {
226 v = PyObject_Str(v);
227 if (v == NULL)
228 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +0000229 else if (PyUnicode_Check(v)) {
Serhiy Storchaka06515832016-11-20 09:13:07 +0200230 ps1 = PyUnicode_AsUTF8(v);
Victor Stinner386fe712010-05-19 00:34:15 +0000231 if (ps1 == NULL) {
232 PyErr_Clear();
233 ps1 = "";
234 }
235 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000236 }
Victor Stinner09054372013-11-06 22:41:44 +0100237 w = _PySys_GetObjectId(&PyId_ps2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 if (w != NULL) {
239 w = PyObject_Str(w);
240 if (w == NULL)
241 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +0000242 else if (PyUnicode_Check(w)) {
Serhiy Storchaka06515832016-11-20 09:13:07 +0200243 ps2 = PyUnicode_AsUTF8(w);
Victor Stinner386fe712010-05-19 00:34:15 +0000244 if (ps2 == NULL) {
245 PyErr_Clear();
246 ps2 = "";
247 }
248 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 }
250 arena = PyArena_New();
251 if (arena == NULL) {
252 Py_XDECREF(v);
253 Py_XDECREF(w);
254 Py_XDECREF(oenc);
255 return -1;
256 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100257
Victor Stinner57364ce2021-03-24 01:29:09 +0100258 mod = _PyParser_ASTFromFile(fp, filename, enc, Py_single_input,
259 ps1, ps2, flags, &errcode, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 Py_XDECREF(v);
262 Py_XDECREF(w);
263 Py_XDECREF(oenc);
264 if (mod == NULL) {
265 PyArena_Free(arena);
266 if (errcode == E_EOF) {
267 PyErr_Clear();
268 return E_EOF;
269 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000270 return -1;
271 }
Victor Stinner95701bd2013-11-06 18:41:07 +0100272 m = PyImport_AddModuleObject(mod_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000273 if (m == NULL) {
274 PyArena_Free(arena);
275 return -1;
276 }
277 d = PyModule_GetDict(m);
278 v = run_mod(mod, filename, d, d, flags, arena);
279 PyArena_Free(arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 return -1;
282 }
283 Py_DECREF(v);
Antoine Pitrou9845c7e2014-05-11 13:42:17 +0200284 flush_io();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000285 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000286}
287
Victor Stinner95701bd2013-11-06 18:41:07 +0100288int
xdegayee0582a32017-11-12 16:50:48 +0100289PyRun_InteractiveOneObject(FILE *fp, PyObject *filename, PyCompilerFlags *flags)
290{
291 int res;
292
293 res = PyRun_InteractiveOneObjectEx(fp, filename, flags);
294 if (res == -1) {
295 PyErr_Print();
296 flush_io();
297 }
298 return res;
299}
300
301int
Victor Stinner95701bd2013-11-06 18:41:07 +0100302PyRun_InteractiveOneFlags(FILE *fp, const char *filename_str, PyCompilerFlags *flags)
303{
304 PyObject *filename;
305 int res;
306
307 filename = PyUnicode_DecodeFSDefault(filename_str);
308 if (filename == NULL) {
309 PyErr_Print();
310 return -1;
311 }
312 res = PyRun_InteractiveOneObject(fp, filename, flags);
313 Py_DECREF(filename);
314 return res;
315}
316
317
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000318/* Check whether a file maybe a pyc file: Look at the extension,
319 the file type, and, if we may close it, at the first few bytes. */
320
321static int
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100322maybe_pyc_file(FILE *fp, PyObject *filename, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000323{
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100324 PyObject *ext = PyUnicode_FromString(".pyc");
325 if (ext == NULL) {
326 return -1;
327 }
328 Py_ssize_t endswith = PyUnicode_Tailmatch(filename, ext, 0, PY_SSIZE_T_MAX, +1);
329 Py_DECREF(ext);
330 if (endswith) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 return 1;
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100332 }
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 /* Only look into the file if we are allowed to close it, since
335 it then should also be seekable. */
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100336 if (!closeit) {
337 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 }
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100339
340 /* Read only two bytes of the magic. If the file was opened in
341 text mode, the bytes 3 and 4 of the magic (\r\n) might not
342 be read as they are on disk. */
343 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
344 unsigned char buf[2];
345 /* Mess: In case of -x, the stream is NOT at its start now,
346 and ungetc() was used to push back the first newline,
347 which makes the current stream position formally undefined,
348 and a x-platform nightmare.
349 Unfortunately, we have no direct way to know whether -x
350 was specified. So we use a terrible hack: if the current
351 stream position is not 0, we assume -x was specified, and
352 give up. Bug 132850 on SourceForge spells out the
353 hopelessness of trying anything else (fseek and ftell
354 don't work predictably x-platform for text-mode files).
355 */
356 int ispyc = 0;
357 if (ftell(fp) == 0) {
358 if (fread(buf, 1, 2, fp) == 2 &&
359 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
360 ispyc = 1;
361 rewind(fp);
362 }
363 return ispyc;
Tim Petersd08e3822003-04-17 15:24:21 +0000364}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000365
Andrew Svetlov90c0eb22012-11-01 14:51:14 +0200366
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100367static int
368set_main_loader(PyObject *d, PyObject *filename, const char *loader_name)
369{
Victor Stinner81a7be32020-04-14 15:14:01 +0200370 PyInterpreterState *interp = _PyInterpreterState_GET();
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100371 PyObject *bootstrap = PyObject_GetAttrString(interp->importlib,
372 "_bootstrap_external");
373 if (bootstrap == NULL) {
Nick Coghlan3f94cbf2012-07-15 19:10:39 +1000374 return -1;
375 }
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100376
377 PyObject *loader_type = PyObject_GetAttrString(bootstrap, loader_name);
378 Py_DECREF(bootstrap);
379 if (loader_type == NULL) {
380 return -1;
381 }
382
383 PyObject *loader = PyObject_CallFunction(loader_type,
384 "sO", "__main__", filename);
Nick Coghlanb7a58942012-07-15 23:21:08 +1000385 Py_DECREF(loader_type);
386 if (loader == NULL) {
Nick Coghlan85e729e2012-07-15 18:09:52 +1000387 return -1;
388 }
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100389
Nick Coghlanb7a58942012-07-15 23:21:08 +1000390 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100391 Py_DECREF(loader);
392 return -1;
Nick Coghlanb7a58942012-07-15 23:21:08 +1000393 }
Nick Coghlan85e729e2012-07-15 18:09:52 +1000394 Py_DECREF(loader);
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100395 return 0;
Nick Coghlan85e729e2012-07-15 18:09:52 +1000396}
397
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100398
Victor Stinner550e4672020-12-09 00:32:54 +0100399int
400_PyRun_SimpleFileObject(FILE *fp, PyObject *filename, int closeit,
401 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000402{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 PyObject *m, *d, *v;
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +0100404 int set_file_name = 0, ret = -1;
Guido van Rossumfdef2711994-09-14 13:31:04 +0000405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000406 m = PyImport_AddModule("__main__");
407 if (m == NULL)
408 return -1;
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +0100409 Py_INCREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000410 d = PyModule_GetDict(m);
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +0200411 if (_PyDict_GetItemStringWithError(d, "__file__") == NULL) {
412 if (PyErr_Occurred()) {
413 goto done;
414 }
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100415 if (PyDict_SetItemString(d, "__file__", filename) < 0) {
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +0100416 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 }
Barry Warsaw916048d2011-09-20 14:45:44 -0400418 if (PyDict_SetItemString(d, "__cached__", Py_None) < 0) {
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +0100419 goto done;
Barry Warsaw916048d2011-09-20 14:45:44 -0400420 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 set_file_name = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 }
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100423
424 int pyc = maybe_pyc_file(fp, filename, closeit);
425 if (pyc < 0) {
426 goto done;
427 }
428
429 if (pyc) {
Christian Heimes04ac4c12012-09-11 15:47:28 +0200430 FILE *pyc_fp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 /* Try to run a pyc file. First, re-open in binary */
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100432 if (closeit) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000433 fclose(fp);
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100434 }
435
436 pyc_fp = _Py_fopen_obj(filename, "rb");
437 if (pyc_fp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000438 fprintf(stderr, "python: Can't reopen .pyc file\n");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 goto done;
440 }
Nick Coghlan85e729e2012-07-15 18:09:52 +1000441
442 if (set_main_loader(d, filename, "SourcelessFileLoader") < 0) {
443 fprintf(stderr, "python: failed to set __main__.__loader__\n");
444 ret = -1;
Christian Heimes04ac4c12012-09-11 15:47:28 +0200445 fclose(pyc_fp);
Nick Coghlan85e729e2012-07-15 18:09:52 +1000446 goto done;
447 }
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100448 v = run_pyc_file(pyc_fp, d, d, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000449 } else {
Nick Coghlan85e729e2012-07-15 18:09:52 +1000450 /* When running from stdin, leave __main__.__loader__ alone */
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100451 if (PyUnicode_CompareWithASCIIString(filename, "<stdin>") != 0 &&
Nick Coghlan85e729e2012-07-15 18:09:52 +1000452 set_main_loader(d, filename, "SourceFileLoader") < 0) {
453 fprintf(stderr, "python: failed to set __main__.__loader__\n");
454 ret = -1;
455 goto done;
456 }
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100457 v = pyrun_file(fp, filename, Py_file_input, d, d,
458 closeit, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 }
460 flush_io();
461 if (v == NULL) {
Zackery Spytzd8cba5d2018-07-03 13:47:22 -0600462 Py_CLEAR(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 PyErr_Print();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000464 goto done;
465 }
466 Py_DECREF(v);
467 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +0000468 done:
INADA Naoki82daa602018-11-29 20:01:27 +0900469 if (set_file_name) {
470 if (PyDict_DelItemString(d, "__file__")) {
471 PyErr_Clear();
472 }
473 if (PyDict_DelItemString(d, "__cached__")) {
474 PyErr_Clear();
475 }
476 }
Zackery Spytzd8cba5d2018-07-03 13:47:22 -0600477 Py_XDECREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000479}
480
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100481
482int
483PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
484 PyCompilerFlags *flags)
485{
486 PyObject *filename_obj = PyUnicode_DecodeFSDefault(filename);
487 if (filename_obj == NULL) {
488 return -1;
489 }
Victor Stinner550e4672020-12-09 00:32:54 +0100490 int res = _PyRun_SimpleFileObject(fp, filename_obj, closeit, flags);
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100491 Py_DECREF(filename_obj);
492 return res;
493}
494
495
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000496int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000497PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +0000498{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 PyObject *m, *d, *v;
500 m = PyImport_AddModule("__main__");
501 if (m == NULL)
502 return -1;
503 d = PyModule_GetDict(m);
504 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
505 if (v == NULL) {
506 PyErr_Print();
507 return -1;
508 }
509 Py_DECREF(v);
510 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000511}
512
Barry Warsaw035574d1997-08-29 22:07:17 +0000513static int
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100514parse_syntax_error(PyObject *err, PyObject **message, PyObject **filename,
Ammar Askar90d29702020-06-02 08:17:24 +0000515 Py_ssize_t *lineno, Py_ssize_t *offset, PyObject **text)
Barry Warsaw035574d1997-08-29 22:07:17 +0000516{
Ammar Askar90d29702020-06-02 08:17:24 +0000517 Py_ssize_t hold;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 PyObject *v;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200519 _Py_IDENTIFIER(msg);
520 _Py_IDENTIFIER(filename);
521 _Py_IDENTIFIER(lineno);
522 _Py_IDENTIFIER(offset);
523 _Py_IDENTIFIER(text);
Barry Warsaw035574d1997-08-29 22:07:17 +0000524
Benjamin Peterson80d50422012-04-03 00:30:38 -0400525 *message = NULL;
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100526 *filename = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 /* new style errors. `err' is an instance */
Benjamin Peterson0a9a6362012-04-03 00:35:36 -0400529 *message = _PyObject_GetAttrId(err, &PyId_msg);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400530 if (!*message)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +0000532
Benjamin Peterson0a9a6362012-04-03 00:35:36 -0400533 v = _PyObject_GetAttrId(err, &PyId_filename);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400534 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400536 if (v == Py_None) {
537 Py_DECREF(v);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100538 *filename = _PyUnicode_FromId(&PyId_string);
539 if (*filename == NULL)
540 goto finally;
541 Py_INCREF(*filename);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400542 }
543 else {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100544 *filename = v;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400545 }
Barry Warsaw035574d1997-08-29 22:07:17 +0000546
Benjamin Peterson0a9a6362012-04-03 00:35:36 -0400547 v = _PyObject_GetAttrId(err, &PyId_lineno);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400548 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000549 goto finally;
Ammar Askar90d29702020-06-02 08:17:24 +0000550 hold = PyLong_AsSsize_t(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 if (hold < 0 && PyErr_Occurred())
553 goto finally;
Serhiy Storchaka56f6e762015-09-06 21:25:30 +0300554 *lineno = hold;
Barry Warsaw035574d1997-08-29 22:07:17 +0000555
Benjamin Peterson0a9a6362012-04-03 00:35:36 -0400556 v = _PyObject_GetAttrId(err, &PyId_offset);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400557 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000558 goto finally;
559 if (v == Py_None) {
560 *offset = -1;
561 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 } else {
Ammar Askar90d29702020-06-02 08:17:24 +0000563 hold = PyLong_AsSsize_t(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 if (hold < 0 && PyErr_Occurred())
566 goto finally;
Serhiy Storchaka56f6e762015-09-06 21:25:30 +0300567 *offset = hold;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 }
Barry Warsaw035574d1997-08-29 22:07:17 +0000569
Benjamin Peterson0a9a6362012-04-03 00:35:36 -0400570 v = _PyObject_GetAttrId(err, &PyId_text);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400571 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000572 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400573 if (v == Py_None) {
574 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 *text = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400576 }
577 else {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100578 *text = v;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400579 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +0000581
582finally:
Benjamin Peterson80d50422012-04-03 00:30:38 -0400583 Py_XDECREF(*message);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100584 Py_XDECREF(*filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +0000586}
587
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000588static void
Ammar Askar90d29702020-06-02 08:17:24 +0000589print_error_text(PyObject *f, Py_ssize_t offset, PyObject *text_obj)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000590{
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700591 /* Convert text to a char pointer; return if error */
592 const char *text = PyUnicode_AsUTF8(text_obj);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100593 if (text == NULL)
594 return;
595
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700596 /* Convert offset from 1-based to 0-based */
597 offset--;
598
599 /* Strip leading whitespace from text, adjusting offset as we go */
600 while (*text == ' ' || *text == '\t' || *text == '\f') {
601 text++;
602 offset--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 }
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700604
605 /* Calculate text length excluding trailing newline */
606 Py_ssize_t len = strlen(text);
607 if (len > 0 && text[len-1] == '\n') {
608 len--;
609 }
610
611 /* Clip offset to at most len */
612 if (offset > len) {
613 offset = len;
614 }
615
616 /* Skip past newlines embedded in text */
617 for (;;) {
618 const char *nl = strchr(text, '\n');
619 if (nl == NULL) {
620 break;
621 }
622 Py_ssize_t inl = nl - text;
Ammar Askar90d29702020-06-02 08:17:24 +0000623 if (inl >= offset) {
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700624 break;
625 }
626 inl += 1;
627 text += inl;
628 len -= inl;
629 offset -= (int)inl;
630 }
631
632 /* Print text */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000633 PyFile_WriteString(" ", f);
634 PyFile_WriteString(text, f);
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700635
636 /* Make sure there's a newline at the end */
637 if (text[len] != '\n') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 PyFile_WriteString("\n", f);
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700639 }
640
641 /* Don't print caret if it points to the left of the text */
642 if (offset < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 return;
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700644
645 /* Write caret line */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 PyFile_WriteString(" ", f);
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700647 while (--offset >= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 PyFile_WriteString(" ", f);
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700649 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000651}
652
Tim Peterscf615b52003-04-19 18:47:02 +0000653
Victor Stinner12083282019-05-17 23:05:29 +0200654int
655_Py_HandleSystemExit(int *exitcode_p)
656{
Victor Stinnerda7933e2020-04-13 03:04:28 +0200657 int inspect = _Py_GetConfig()->inspect;
Victor Stinnerc96be812019-05-14 17:34:56 +0200658 if (inspect) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000659 /* Don't exit if -i flag was given. This flag is set to 0
660 * when entering interactive mode for inspecting. */
Victor Stinner12083282019-05-17 23:05:29 +0200661 return 0;
Victor Stinnerc96be812019-05-14 17:34:56 +0200662 }
Guido van Rossumd8faa362007-04-27 19:54:29 +0000663
Victor Stinner12083282019-05-17 23:05:29 +0200664 if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
665 return 0;
666 }
667
668 PyObject *exception, *value, *tb;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000669 PyErr_Fetch(&exception, &value, &tb);
Victor Stinner12083282019-05-17 23:05:29 +0200670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 fflush(stdout);
Victor Stinner12083282019-05-17 23:05:29 +0200672
673 int exitcode = 0;
674 if (value == NULL || value == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 goto done;
Victor Stinner12083282019-05-17 23:05:29 +0200676 }
677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 if (PyExceptionInstance_Check(value)) {
679 /* The error code should be in the `code' attribute. */
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200680 _Py_IDENTIFIER(code);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200681 PyObject *code = _PyObject_GetAttrId(value, &PyId_code);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000682 if (code) {
683 Py_DECREF(value);
684 value = code;
685 if (value == Py_None)
686 goto done;
687 }
688 /* If we failed to dig out the 'code' attribute,
689 just let the else clause below print the error. */
690 }
Victor Stinner12083282019-05-17 23:05:29 +0200691
692 if (PyLong_Check(value)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 exitcode = (int)PyLong_AsLong(value);
Victor Stinner12083282019-05-17 23:05:29 +0200694 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000695 else {
Victor Stinnerbd303c12013-11-07 23:07:29 +0100696 PyObject *sys_stderr = _PySys_GetObjectId(&PyId_stderr);
Nick Coghland979e432014-02-09 10:43:21 +1000697 /* We clear the exception here to avoid triggering the assertion
698 * in PyObject_Str that ensures it won't silently lose exception
699 * details.
700 */
701 PyErr_Clear();
Victor Stinner7126dbc2010-05-21 23:45:42 +0000702 if (sys_stderr != NULL && sys_stderr != Py_None) {
703 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
704 } else {
705 PyObject_Print(value, stderr, Py_PRINT_RAW);
706 fflush(stderr);
707 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 PySys_WriteStderr("\n");
709 exitcode = 1;
710 }
Victor Stinner12083282019-05-17 23:05:29 +0200711
Tim Peterscf615b52003-04-19 18:47:02 +0000712 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 /* Restore and clear the exception info, in order to properly decref
714 * the exception, value, and traceback. If we just exit instead,
715 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
716 * some finalizers from running.
717 */
718 PyErr_Restore(exception, value, tb);
719 PyErr_Clear();
Victor Stinner12083282019-05-17 23:05:29 +0200720 *exitcode_p = exitcode;
721 return 1;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000722}
723
Victor Stinner12083282019-05-17 23:05:29 +0200724
725static void
726handle_system_exit(void)
727{
728 int exitcode;
729 if (_Py_HandleSystemExit(&exitcode)) {
730 Py_Exit(exitcode);
731 }
732}
733
734
Victor Stinner438a12d2019-05-24 17:01:38 +0200735static void
736_PyErr_PrintEx(PyThreadState *tstate, int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000737{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000738 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +0000739
Victor Stinner12083282019-05-17 23:05:29 +0200740 handle_system_exit();
741
Victor Stinner438a12d2019-05-24 17:01:38 +0200742 _PyErr_Fetch(tstate, &exception, &v, &tb);
743 if (exception == NULL) {
744 goto done;
745 }
746
747 _PyErr_NormalizeException(tstate, &exception, &v, &tb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 if (tb == NULL) {
749 tb = Py_None;
750 Py_INCREF(tb);
751 }
752 PyException_SetTraceback(v, tb);
Victor Stinner438a12d2019-05-24 17:01:38 +0200753 if (exception == NULL) {
754 goto done;
755 }
756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000757 /* Now we know v != NULL too */
758 if (set_sys_last_vars) {
xdegaye66caacf2017-10-23 18:08:41 +0200759 if (_PySys_SetObjectId(&PyId_last_type, exception) < 0) {
Victor Stinner438a12d2019-05-24 17:01:38 +0200760 _PyErr_Clear(tstate);
xdegaye66caacf2017-10-23 18:08:41 +0200761 }
762 if (_PySys_SetObjectId(&PyId_last_value, v) < 0) {
Victor Stinner438a12d2019-05-24 17:01:38 +0200763 _PyErr_Clear(tstate);
xdegaye66caacf2017-10-23 18:08:41 +0200764 }
765 if (_PySys_SetObjectId(&PyId_last_traceback, tb) < 0) {
Victor Stinner438a12d2019-05-24 17:01:38 +0200766 _PyErr_Clear(tstate);
xdegaye66caacf2017-10-23 18:08:41 +0200767 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 }
Victor Stinner09054372013-11-06 22:41:44 +0100769 hook = _PySys_GetObjectId(&PyId_excepthook);
Victor Stinner1c1e68c2020-03-27 15:11:45 +0100770 if (_PySys_Audit(tstate, "sys.excepthook", "OOOO", hook ? hook : Py_None,
771 exception, v, tb) < 0) {
Steve Dowerbea33f52019-11-28 08:46:11 -0800772 if (PyErr_ExceptionMatches(PyExc_RuntimeError)) {
773 PyErr_Clear();
774 goto done;
775 }
776 _PyErr_WriteUnraisableMsg("in audit hook", NULL);
777 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 if (hook) {
Victor Stinner71cb64a2016-08-20 00:57:43 +0200779 PyObject* stack[3];
780 PyObject *result;
781
782 stack[0] = exception;
783 stack[1] = v;
784 stack[2] = tb;
Victor Stinner559bb6a2016-08-22 22:48:54 +0200785 result = _PyObject_FastCall(hook, stack, 3);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 if (result == NULL) {
Victor Stinner12083282019-05-17 23:05:29 +0200787 handle_system_exit();
788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 PyObject *exception2, *v2, *tb2;
Victor Stinner438a12d2019-05-24 17:01:38 +0200790 _PyErr_Fetch(tstate, &exception2, &v2, &tb2);
791 _PyErr_NormalizeException(tstate, &exception2, &v2, &tb2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 /* It should not be possible for exception2 or v2
793 to be NULL. However PyErr_Display() can't
794 tolerate NULLs, so just be safe. */
795 if (exception2 == NULL) {
796 exception2 = Py_None;
797 Py_INCREF(exception2);
798 }
799 if (v2 == NULL) {
800 v2 = Py_None;
801 Py_INCREF(v2);
802 }
803 fflush(stdout);
804 PySys_WriteStderr("Error in sys.excepthook:\n");
805 PyErr_Display(exception2, v2, tb2);
806 PySys_WriteStderr("\nOriginal exception was:\n");
807 PyErr_Display(exception, v, tb);
808 Py_DECREF(exception2);
809 Py_DECREF(v2);
810 Py_XDECREF(tb2);
811 }
812 Py_XDECREF(result);
Victor Stinner438a12d2019-05-24 17:01:38 +0200813 }
814 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 PySys_WriteStderr("sys.excepthook is missing\n");
816 PyErr_Display(exception, v, tb);
817 }
Victor Stinner438a12d2019-05-24 17:01:38 +0200818
819done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 Py_XDECREF(exception);
821 Py_XDECREF(v);
822 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000823}
824
Victor Stinner438a12d2019-05-24 17:01:38 +0200825void
826_PyErr_Print(PyThreadState *tstate)
827{
828 _PyErr_PrintEx(tstate, 1);
829}
830
831void
832PyErr_PrintEx(int set_sys_last_vars)
833{
834 PyThreadState *tstate = _PyThreadState_GET();
835 _PyErr_PrintEx(tstate, set_sys_last_vars);
836}
837
838void
839PyErr_Print(void)
840{
841 PyErr_PrintEx(1);
842}
843
Benjamin Petersone6528212008-07-15 15:32:09 +0000844static void
845print_exception(PyObject *f, PyObject *value)
846{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 int err = 0;
Serhiy Storchaka98c44332020-10-10 22:23:42 +0300848 PyObject *type, *tb, *tmp;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200849 _Py_IDENTIFIER(print_file_and_line);
Benjamin Petersone6528212008-07-15 15:32:09 +0000850
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 if (!PyExceptionInstance_Check(value)) {
Victor Stinner52ce3b02013-12-09 02:10:08 +0100852 err = PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
853 err += PyFile_WriteString(Py_TYPE(value)->tp_name, f);
854 err += PyFile_WriteString(" found\n", f);
855 if (err)
856 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000857 return;
858 }
Benjamin Peterson26582602008-08-23 20:08:07 +0000859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 Py_INCREF(value);
861 fflush(stdout);
862 type = (PyObject *) Py_TYPE(value);
863 tb = PyException_GetTraceback(value);
864 if (tb && tb != Py_None)
865 err = PyTraceBack_Print(tb, f);
866 if (err == 0 &&
Serhiy Storchaka98c44332020-10-10 22:23:42 +0300867 (err = _PyObject_LookupAttrId(value, &PyId_print_file_and_line, &tmp)) > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100869 PyObject *message, *filename, *text;
Ammar Askar90d29702020-06-02 08:17:24 +0000870 Py_ssize_t lineno, offset;
Serhiy Storchaka98c44332020-10-10 22:23:42 +0300871 err = 0;
872 Py_DECREF(tmp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000873 if (!parse_syntax_error(value, &message, &filename,
874 &lineno, &offset, &text))
875 PyErr_Clear();
876 else {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100877 PyObject *line;
878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 Py_DECREF(value);
880 value = message;
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100881
Ammar Askar90d29702020-06-02 08:17:24 +0000882 line = PyUnicode_FromFormat(" File \"%S\", line %zd\n",
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100883 filename, lineno);
884 Py_DECREF(filename);
885 if (line != NULL) {
886 PyFile_WriteObject(line, f, Py_PRINT_RAW);
887 Py_DECREF(line);
888 }
889
890 if (text != NULL) {
891 print_error_text(f, offset, text);
892 Py_DECREF(text);
893 }
894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000895 /* Can't be bothered to check all those
896 PyFile_WriteString() calls */
897 if (PyErr_Occurred())
898 err = -1;
899 }
900 }
901 if (err) {
902 /* Don't do anything else */
903 }
904 else {
905 PyObject* moduleName;
Serhiy Storchakaceeef102018-06-15 11:09:43 +0300906 const char *className;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200907 _Py_IDENTIFIER(__module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 assert(PyExceptionClass_Check(type));
909 className = PyExceptionClass_Name(type);
910 if (className != NULL) {
Serhiy Storchakaceeef102018-06-15 11:09:43 +0300911 const char *dot = strrchr(className, '.');
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 if (dot != NULL)
913 className = dot+1;
914 }
Benjamin Petersone6528212008-07-15 15:32:09 +0000915
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200916 moduleName = _PyObject_GetAttrId(type, &PyId___module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 if (moduleName == NULL || !PyUnicode_Check(moduleName))
918 {
Victor Stinner13b21bd2011-05-26 14:25:13 +0200919 Py_XDECREF(moduleName);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 err = PyFile_WriteString("<unknown>", f);
921 }
922 else {
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +0200923 if (!_PyUnicode_EqualToASCIIId(moduleName, &PyId_builtins))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 {
Victor Stinner937114f2013-11-07 00:12:30 +0100925 err = PyFile_WriteObject(moduleName, f, Py_PRINT_RAW);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 err += PyFile_WriteString(".", f);
927 }
928 Py_DECREF(moduleName);
929 }
930 if (err == 0) {
931 if (className == NULL)
932 err = PyFile_WriteString("<unknown>", f);
933 else
934 err = PyFile_WriteString(className, f);
935 }
936 }
937 if (err == 0 && (value != Py_None)) {
938 PyObject *s = PyObject_Str(value);
939 /* only print colon if the str() of the
940 object is not the empty string
941 */
Martin Panter3263f682016-02-28 03:16:11 +0000942 if (s == NULL) {
943 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 err = -1;
Martin Panter3263f682016-02-28 03:16:11 +0000945 PyFile_WriteString(": <exception str() failed>", f);
946 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 else if (!PyUnicode_Check(s) ||
Victor Stinnere251d6d2011-11-20 19:20:00 +0100948 PyUnicode_GetLength(s) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 err = PyFile_WriteString(": ", f);
950 if (err == 0)
951 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
952 Py_XDECREF(s);
953 }
954 /* try to write a newline in any case */
Martin Panter3263f682016-02-28 03:16:11 +0000955 if (err < 0) {
956 PyErr_Clear();
957 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 err += PyFile_WriteString("\n", f);
959 Py_XDECREF(tb);
960 Py_DECREF(value);
961 /* If an error happened here, don't show it.
962 XXX This is wrong, but too many callers rely on this behavior. */
963 if (err != 0)
964 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +0000965}
966
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200967static const char cause_message[] =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 "\nThe above exception was the direct cause "
969 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +0000970
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200971static const char context_message[] =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 "\nDuring handling of the above exception, "
973 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +0000974
975static void
976print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
977{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 int err = 0, res;
979 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +0000980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 if (seen != NULL) {
982 /* Exception chaining */
Zane Bitterde860732017-10-17 17:29:39 -0400983 PyObject *value_id = PyLong_FromVoidPtr(value);
984 if (value_id == NULL || PySet_Add(seen, value_id) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 PyErr_Clear();
986 else if (PyExceptionInstance_Check(value)) {
Zane Bitterde860732017-10-17 17:29:39 -0400987 PyObject *check_id = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 cause = PyException_GetCause(value);
989 context = PyException_GetContext(value);
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700990 if (cause) {
Zane Bitterde860732017-10-17 17:29:39 -0400991 check_id = PyLong_FromVoidPtr(cause);
992 if (check_id == NULL) {
993 res = -1;
994 } else {
995 res = PySet_Contains(seen, check_id);
996 Py_DECREF(check_id);
997 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 if (res == -1)
999 PyErr_Clear();
1000 if (res == 0) {
1001 print_exception_recursive(
1002 f, cause, seen);
1003 err |= PyFile_WriteString(
1004 cause_message, f);
1005 }
1006 }
Benjamin Petersond5a1c442012-05-14 22:09:31 -07001007 else if (context &&
1008 !((PyBaseExceptionObject *)value)->suppress_context) {
Zane Bitterde860732017-10-17 17:29:39 -04001009 check_id = PyLong_FromVoidPtr(context);
1010 if (check_id == NULL) {
1011 res = -1;
1012 } else {
1013 res = PySet_Contains(seen, check_id);
1014 Py_DECREF(check_id);
1015 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 if (res == -1)
1017 PyErr_Clear();
1018 if (res == 0) {
1019 print_exception_recursive(
1020 f, context, seen);
1021 err |= PyFile_WriteString(
1022 context_message, f);
1023 }
1024 }
1025 Py_XDECREF(context);
1026 Py_XDECREF(cause);
1027 }
Zane Bitterde860732017-10-17 17:29:39 -04001028 Py_XDECREF(value_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 }
1030 print_exception(f, value);
1031 if (err != 0)
1032 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001033}
1034
Thomas Wouters477c8d52006-05-27 19:21:47 +00001035void
Victor Stinnercd590a72019-05-28 00:39:52 +02001036_PyErr_Display(PyObject *file, PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001037{
Victor Stinnercd590a72019-05-28 00:39:52 +02001038 assert(file != NULL && file != Py_None);
1039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 PyObject *seen;
Antoine Pitrou24201d42013-10-13 21:53:13 +02001041 if (PyExceptionInstance_Check(value)
1042 && tb != NULL && PyTraceBack_Check(tb)) {
1043 /* Put the traceback on the exception, otherwise it won't get
1044 displayed. See issue #18776. */
1045 PyObject *cur_tb = PyException_GetTraceback(value);
1046 if (cur_tb == NULL)
1047 PyException_SetTraceback(value, tb);
1048 else
1049 Py_DECREF(cur_tb);
1050 }
Victor Stinnercd590a72019-05-28 00:39:52 +02001051
1052 /* We choose to ignore seen being possibly NULL, and report
1053 at least the main exception (it could be a MemoryError).
1054 */
1055 seen = PySet_New(NULL);
1056 if (seen == NULL) {
1057 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 }
Victor Stinnercd590a72019-05-28 00:39:52 +02001059 print_exception_recursive(file, value, seen);
1060 Py_XDECREF(seen);
Victor Stinnera85a1d32019-05-28 16:01:17 +02001061
1062 /* Call file.flush() */
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001063 PyObject *res = _PyObject_CallMethodIdNoArgs(file, &PyId_flush);
Victor Stinnera85a1d32019-05-28 16:01:17 +02001064 if (!res) {
1065 /* Silently ignore file.flush() error */
1066 PyErr_Clear();
1067 }
1068 else {
1069 Py_DECREF(res);
1070 }
Victor Stinnercd590a72019-05-28 00:39:52 +02001071}
1072
1073void
1074PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
1075{
1076 PyObject *file = _PySys_GetObjectId(&PyId_stderr);
1077 if (file == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 _PyObject_Dump(value);
1079 fprintf(stderr, "lost sys.stderr\n");
Victor Stinnercd590a72019-05-28 00:39:52 +02001080 return;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 }
Victor Stinnercd590a72019-05-28 00:39:52 +02001082 if (file == Py_None) {
1083 return;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 }
Victor Stinnercd590a72019-05-28 00:39:52 +02001085
1086 _PyErr_Display(file, exception, value, tb);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001087}
1088
Guido van Rossum82598051997-03-05 00:20:32 +00001089PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001090PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001092{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093 PyObject *ret = NULL;
1094 mod_ty mod;
Victor Stinner95701bd2013-11-06 18:41:07 +01001095 PyArena *arena;
Victor Stinner95701bd2013-11-06 18:41:07 +01001096 PyObject *filename;
1097
1098 filename = _PyUnicode_FromId(&PyId_string); /* borrowed */
1099 if (filename == NULL)
1100 return NULL;
1101
1102 arena = PyArena_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001103 if (arena == NULL)
1104 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001105
Victor Stinner57364ce2021-03-24 01:29:09 +01001106 mod = _PyParser_ASTFromString(str, filename, start, flags, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001108 if (mod != NULL)
Victor Stinner95701bd2013-11-06 18:41:07 +01001109 ret = run_mod(mod, filename, globals, locals, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001110 PyArena_Free(arena);
1111 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001112}
1113
Victor Stinnerb6d98c12020-12-08 14:38:08 +01001114
1115static PyObject *
1116pyrun_file(FILE *fp, PyObject *filename, int start, PyObject *globals,
1117 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001118{
Victor Stinnerb6d98c12020-12-08 14:38:08 +01001119 PyArena *arena = PyArena_New();
1120 if (arena == NULL) {
1121 return NULL;
1122 }
1123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 mod_ty mod;
Victor Stinner57364ce2021-03-24 01:29:09 +01001125 mod = _PyParser_ASTFromFile(fp, filename, NULL, start, NULL, NULL,
1126 flags, NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001127
Victor Stinnerb6d98c12020-12-08 14:38:08 +01001128 if (closeit) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001129 fclose(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 }
Victor Stinner95701bd2013-11-06 18:41:07 +01001131
Victor Stinnerb6d98c12020-12-08 14:38:08 +01001132 PyObject *ret;
1133 if (mod != NULL) {
1134 ret = run_mod(mod, filename, globals, locals, flags, arena);
1135 }
1136 else {
1137 ret = NULL;
1138 }
1139 PyArena_Free(arena);
1140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001141 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001142}
1143
Victor Stinnerb6d98c12020-12-08 14:38:08 +01001144
1145PyObject *
1146PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
1147 PyObject *locals, int closeit, PyCompilerFlags *flags)
1148{
1149 PyObject *filename_obj = PyUnicode_DecodeFSDefault(filename);
1150 if (filename_obj == NULL) {
1151 return NULL;
1152 }
1153
1154 PyObject *res = pyrun_file(fp, filename_obj, start, globals,
1155 locals, closeit, flags);
1156 Py_DECREF(filename_obj);
1157 return res;
1158
1159}
1160
1161
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001162static void
1163flush_io(void)
1164{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001165 PyObject *f, *r;
1166 PyObject *type, *value, *traceback;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 /* Save the current exception */
1169 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001170
Victor Stinnerbd303c12013-11-07 23:07:29 +01001171 f = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001172 if (f != NULL) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001173 r = _PyObject_CallMethodIdNoArgs(f, &PyId_flush);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 if (r)
1175 Py_DECREF(r);
1176 else
1177 PyErr_Clear();
1178 }
Victor Stinnerbd303c12013-11-07 23:07:29 +01001179 f = _PySys_GetObjectId(&PyId_stdout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001180 if (f != NULL) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001181 r = _PyObject_CallMethodIdNoArgs(f, &PyId_flush);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 if (r)
1183 Py_DECREF(r);
1184 else
1185 PyErr_Clear();
1186 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001189}
1190
Guido van Rossum82598051997-03-05 00:20:32 +00001191static PyObject *
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001192run_eval_code_obj(PyThreadState *tstate, PyCodeObject *co, PyObject *globals, PyObject *locals)
Gregory P. Smith38f11cc2019-02-16 12:57:40 -08001193{
1194 PyObject *v;
Gregory P. Smithd9bc5432019-02-20 17:35:54 -08001195 /*
1196 * We explicitly re-initialize _Py_UnhandledKeyboardInterrupt every eval
1197 * _just in case_ someone is calling into an embedded Python where they
1198 * don't care about an uncaught KeyboardInterrupt exception (why didn't they
1199 * leave config.install_signal_handlers set to 0?!?) but then later call
1200 * Py_Main() itself (which _checks_ this flag and dies with a signal after
1201 * its interpreter exits). We don't want a previous embedded interpreter's
1202 * uncaught exception to trigger an unexplained signal exit from a future
1203 * Py_Main() based one.
1204 */
1205 _Py_UnhandledKeyboardInterrupt = 0;
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001206
1207 /* Set globals['__builtins__'] if it doesn't exist */
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02001208 if (globals != NULL && _PyDict_GetItemStringWithError(globals, "__builtins__") == NULL) {
1209 if (PyErr_Occurred() ||
1210 PyDict_SetItemString(globals, "__builtins__",
1211 tstate->interp->builtins) < 0)
1212 {
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001213 return NULL;
1214 }
1215 }
1216
Gregory P. Smith38f11cc2019-02-16 12:57:40 -08001217 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001218 if (!v && _PyErr_Occurred(tstate) == PyExc_KeyboardInterrupt) {
Gregory P. Smith38f11cc2019-02-16 12:57:40 -08001219 _Py_UnhandledKeyboardInterrupt = 1;
1220 }
1221 return v;
1222}
1223
1224static PyObject *
Victor Stinner95701bd2013-11-06 18:41:07 +01001225run_mod(mod_ty mod, PyObject *filename, PyObject *globals, PyObject *locals,
1226 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001227{
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001228 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinnera81fca62021-03-24 00:51:50 +01001229 PyCodeObject *co = _PyAST_Compile(mod, filename, flags, -1, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001230 if (co == NULL)
1231 return NULL;
Steve Dowerb82e17e2019-05-23 08:45:22 -07001232
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001233 if (_PySys_Audit(tstate, "exec", "O", co) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07001234 Py_DECREF(co);
1235 return NULL;
1236 }
1237
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001238 PyObject *v = run_eval_code_obj(tstate, co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 Py_DECREF(co);
1240 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001241}
1242
Guido van Rossum82598051997-03-05 00:20:32 +00001243static PyObject *
Victor Stinnerb6d98c12020-12-08 14:38:08 +01001244run_pyc_file(FILE *fp, PyObject *globals, PyObject *locals,
1245 PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001246{
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001247 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 PyCodeObject *co;
1249 PyObject *v;
1250 long magic;
1251 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 magic = PyMarshal_ReadLongFromFile(fp);
1254 if (magic != PyImport_GetMagicNumber()) {
Victor Stinner5200f552015-03-18 13:56:25 +01001255 if (!PyErr_Occurred())
1256 PyErr_SetString(PyExc_RuntimeError,
1257 "Bad magic number in .pyc file");
Zackery Spytzea737752018-06-23 21:15:24 -06001258 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 }
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08001260 /* Skip the rest of the header. */
1261 (void) PyMarshal_ReadLongFromFile(fp);
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001262 (void) PyMarshal_ReadLongFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 (void) PyMarshal_ReadLongFromFile(fp);
Zackery Spytzea737752018-06-23 21:15:24 -06001264 if (PyErr_Occurred()) {
1265 goto error;
1266 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001267 v = PyMarshal_ReadLastObjectFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 if (v == NULL || !PyCode_Check(v)) {
1269 Py_XDECREF(v);
1270 PyErr_SetString(PyExc_RuntimeError,
1271 "Bad code object in .pyc file");
Zackery Spytzea737752018-06-23 21:15:24 -06001272 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 }
Zackery Spytzea737752018-06-23 21:15:24 -06001274 fclose(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 co = (PyCodeObject *)v;
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001276 v = run_eval_code_obj(tstate, co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001277 if (v && flags)
1278 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1279 Py_DECREF(co);
1280 return v;
Zackery Spytzea737752018-06-23 21:15:24 -06001281error:
1282 fclose(fp);
1283 return NULL;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001284}
1285
Guido van Rossum82598051997-03-05 00:20:32 +00001286PyObject *
Victor Stinner14e461d2013-08-26 22:28:21 +02001287Py_CompileStringObject(const char *str, PyObject *filename, int start,
1288 PyCompilerFlags *flags, int optimize)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001289{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 PyCodeObject *co;
1291 mod_ty mod;
1292 PyArena *arena = PyArena_New();
1293 if (arena == NULL)
1294 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001295
Victor Stinner57364ce2021-03-24 01:29:09 +01001296 mod = _PyParser_ASTFromString(str, filename, start, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001297 if (mod == NULL) {
1298 PyArena_Free(arena);
1299 return NULL;
1300 }
1301 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
1302 PyObject *result = PyAST_mod2obj(mod);
1303 PyArena_Free(arena);
1304 return result;
1305 }
Victor Stinnera81fca62021-03-24 00:51:50 +01001306 co = _PyAST_Compile(mod, filename, flags, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 PyArena_Free(arena);
1308 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001309}
1310
Victor Stinner14e461d2013-08-26 22:28:21 +02001311PyObject *
1312Py_CompileStringExFlags(const char *str, const char *filename_str, int start,
1313 PyCompilerFlags *flags, int optimize)
1314{
1315 PyObject *filename, *co;
1316 filename = PyUnicode_DecodeFSDefault(filename_str);
1317 if (filename == NULL)
1318 return NULL;
1319 co = Py_CompileStringObject(str, filename, start, flags, optimize);
1320 Py_DECREF(filename);
1321 return co;
1322}
1323
Dino Viehland41540692019-05-28 16:21:17 -07001324const char *
1325_Py_SourceAsString(PyObject *cmd, const char *funcname, const char *what, PyCompilerFlags *cf, PyObject **cmd_copy)
1326{
1327 const char *str;
1328 Py_ssize_t size;
1329 Py_buffer view;
1330
1331 *cmd_copy = NULL;
1332 if (PyUnicode_Check(cmd)) {
1333 cf->cf_flags |= PyCF_IGNORE_COOKIE;
1334 str = PyUnicode_AsUTF8AndSize(cmd, &size);
1335 if (str == NULL)
1336 return NULL;
1337 }
1338 else if (PyBytes_Check(cmd)) {
1339 str = PyBytes_AS_STRING(cmd);
1340 size = PyBytes_GET_SIZE(cmd);
1341 }
1342 else if (PyByteArray_Check(cmd)) {
1343 str = PyByteArray_AS_STRING(cmd);
1344 size = PyByteArray_GET_SIZE(cmd);
1345 }
1346 else if (PyObject_GetBuffer(cmd, &view, PyBUF_SIMPLE) == 0) {
1347 /* Copy to NUL-terminated buffer. */
1348 *cmd_copy = PyBytes_FromStringAndSize(
1349 (const char *)view.buf, view.len);
1350 PyBuffer_Release(&view);
1351 if (*cmd_copy == NULL) {
1352 return NULL;
1353 }
1354 str = PyBytes_AS_STRING(*cmd_copy);
1355 size = PyBytes_GET_SIZE(*cmd_copy);
1356 }
1357 else {
1358 PyErr_Format(PyExc_TypeError,
1359 "%s() arg 1 must be a %s object",
1360 funcname, what);
1361 return NULL;
1362 }
1363
1364 if (strlen(str) != (size_t)size) {
1365 PyErr_SetString(PyExc_ValueError,
1366 "source code string cannot contain null bytes");
1367 Py_CLEAR(*cmd_copy);
1368 return NULL;
1369 }
1370 return str;
1371}
1372
Zachary Warec4821d62014-11-21 23:35:12 -06001373#if defined(USE_STACKCHECK)
1374#if defined(WIN32) && defined(_MSC_VER)
1375
1376/* Stack checking for Microsoft C */
1377
1378#include <malloc.h>
1379#include <excpt.h>
1380
1381/*
1382 * Return non-zero when we run out of memory on the stack; zero otherwise.
1383 */
1384int
1385PyOS_CheckStack(void)
1386{
1387 __try {
1388 /* alloca throws a stack overflow exception if there's
1389 not enough space left on the stack */
1390 alloca(PYOS_STACK_MARGIN * sizeof(void*));
1391 return 0;
1392 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
1393 EXCEPTION_EXECUTE_HANDLER :
1394 EXCEPTION_CONTINUE_SEARCH) {
1395 int errcode = _resetstkoflw();
1396 if (errcode == 0)
1397 {
1398 Py_FatalError("Could not reset the stack!");
1399 }
1400 }
1401 return 1;
1402}
1403
1404#endif /* WIN32 && _MSC_VER */
1405
1406/* Alternate implementations can be added here... */
1407
1408#endif /* USE_STACKCHECK */
1409
Pablo Galindo46bd5ed2020-12-02 05:16:31 +00001410/* Deprecated C API functions still provided for binary compatibility */
1411
1412#undef PyRun_AnyFile
1413PyAPI_FUNC(int)
1414PyRun_AnyFile(FILE *fp, const char *name)
1415{
1416 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
1417}
1418
1419#undef PyRun_AnyFileEx
1420PyAPI_FUNC(int)
1421PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
1422{
1423 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
1424}
1425
1426#undef PyRun_AnyFileFlags
1427PyAPI_FUNC(int)
1428PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
1429{
1430 return PyRun_AnyFileExFlags(fp, name, 0, flags);
1431}
1432
1433#undef PyRun_File
1434PyAPI_FUNC(PyObject *)
1435PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
1436{
1437 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
1438}
1439
1440#undef PyRun_FileEx
1441PyAPI_FUNC(PyObject *)
1442PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
1443{
1444 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
1445}
1446
1447#undef PyRun_FileFlags
1448PyAPI_FUNC(PyObject *)
1449PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
1450 PyCompilerFlags *flags)
1451{
1452 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
1453}
1454
1455#undef PyRun_SimpleFile
1456PyAPI_FUNC(int)
1457PyRun_SimpleFile(FILE *f, const char *p)
1458{
1459 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
1460}
1461
1462#undef PyRun_SimpleFileEx
1463PyAPI_FUNC(int)
1464PyRun_SimpleFileEx(FILE *f, const char *p, int c)
1465{
1466 return PyRun_SimpleFileExFlags(f, p, c, NULL);
1467}
1468
1469
1470#undef PyRun_String
1471PyAPI_FUNC(PyObject *)
1472PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
1473{
1474 return PyRun_StringFlags(str, s, g, l, NULL);
1475}
1476
1477#undef PyRun_SimpleString
1478PyAPI_FUNC(int)
1479PyRun_SimpleString(const char *s)
1480{
1481 return PyRun_SimpleStringFlags(s, NULL);
1482}
1483
1484#undef Py_CompileString
1485PyAPI_FUNC(PyObject *)
1486Py_CompileString(const char *str, const char *p, int s)
1487{
1488 return Py_CompileStringExFlags(str, p, s, NULL, -1);
1489}
1490
1491#undef Py_CompileStringFlags
1492PyAPI_FUNC(PyObject *)
1493Py_CompileStringFlags(const char *str, const char *p, int s,
1494 PyCompilerFlags *flags)
1495{
1496 return Py_CompileStringExFlags(str, p, s, flags, -1);
1497}
1498
1499#undef PyRun_InteractiveOne
1500PyAPI_FUNC(int)
1501PyRun_InteractiveOne(FILE *f, const char *p)
1502{
1503 return PyRun_InteractiveOneFlags(f, p, NULL);
1504}
1505
1506#undef PyRun_InteractiveLoop
1507PyAPI_FUNC(int)
1508PyRun_InteractiveLoop(FILE *f, const char *p)
1509{
1510 return PyRun_InteractiveLoopFlags(f, p, NULL);
1511}
1512
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001513#ifdef __cplusplus
1514}
1515#endif