blob: adb43e75f9ab72c05c8c5d372052f80692e5ee8d [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
Victor Stinner4f98f462020-04-15 04:01:58 +020026#include "marshal.h" // PyMarshal_ReadLongFromFile()
27
28#ifdef MS_WINDOWS
29# include "malloc.h" // alloca()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000030#endif
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000031
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000032#ifdef MS_WINDOWS
Victor Stinner4f98f462020-04-15 04:01:58 +020033# undef BYTE
34# include "windows.h"
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000035#endif
Martin v. Löwis5c88d812009-01-02 20:47:48 +000036
Guido van Rossuma44823b1995-03-14 15:01:17 +000037
Victor Stinnerbd303c12013-11-07 23:07:29 +010038_Py_IDENTIFIER(builtins);
Victor Stinner09054372013-11-06 22:41:44 +010039_Py_IDENTIFIER(excepthook);
Victor Stinner3f36a572013-11-12 21:39:02 +010040_Py_IDENTIFIER(flush);
Victor Stinnerbd303c12013-11-07 23:07:29 +010041_Py_IDENTIFIER(last_traceback);
Victor Stinner09054372013-11-06 22:41:44 +010042_Py_IDENTIFIER(last_type);
43_Py_IDENTIFIER(last_value);
Victor Stinnerbd303c12013-11-07 23:07:29 +010044_Py_IDENTIFIER(ps1);
45_Py_IDENTIFIER(ps2);
46_Py_IDENTIFIER(stdin);
47_Py_IDENTIFIER(stdout);
48_Py_IDENTIFIER(stderr);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +010049_Py_static_string(PyId_string, "<string>");
Victor Stinner09054372013-11-06 22:41:44 +010050
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000051#ifdef __cplusplus
52extern "C" {
Neal Norwitz4281cef2006-03-04 19:58:13 +000053#endif
54
Guido van Rossumb73cc041993-11-01 16:28:59 +000055/* Forward */
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +000056static void flush_io(void);
Victor Stinner95701bd2013-11-06 18:41:07 +010057static PyObject *run_mod(mod_ty, PyObject *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000058 PyCompilerFlags *, PyArena *);
Victor Stinnerb6d98c12020-12-08 14:38:08 +010059static PyObject *run_pyc_file(FILE *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000060 PyCompilerFlags *);
xdegayee0582a32017-11-12 16:50:48 +010061static int PyRun_InteractiveOneObjectEx(FILE *, PyObject *, PyCompilerFlags *);
Victor Stinnerb6d98c12020-12-08 14:38:08 +010062static PyObject* pyrun_file(FILE *fp, PyObject *filename, int start,
63 PyObject *globals, PyObject *locals, int closeit,
64 PyCompilerFlags *flags);
65
Guido van Rossumce3a72a2007-10-19 23:16:50 +000066
Victor Stinnera82f63f2020-12-09 22:37:27 +010067int
68_PyRun_AnyFileObject(FILE *fp, PyObject *filename, int closeit,
69 PyCompilerFlags *flags)
70{
71 int decref_filename = 0;
72 if (filename == NULL) {
73 filename = PyUnicode_FromString("???");
74 if (filename == NULL) {
75 PyErr_Print();
76 return -1;
77 }
78 decref_filename = 1;
79 }
80
81 int res;
82 if (_Py_FdIsInteractive(fp, filename)) {
83 res = _PyRun_InteractiveLoopObject(fp, filename, flags);
84 if (closeit) {
85 fclose(fp);
86 }
87 }
88 else {
89 res = _PyRun_SimpleFileObject(fp, filename, closeit, flags);
90 }
91
92 if (decref_filename) {
93 Py_DECREF(filename);
94 }
95 return res;
96}
97
98
Guido van Rossum1984f1e1992-08-04 12:41:02 +000099/* Parse input from a file and execute it */
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000100int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000101PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000102 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000103{
Victor Stinnera82f63f2020-12-09 22:37:27 +0100104 PyObject *filename_obj;
105 if (filename != NULL) {
106 filename_obj = PyUnicode_DecodeFSDefault(filename);
107 if (filename_obj == NULL) {
108 PyErr_Print();
109 return -1;
110 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000111 }
Victor Stinnera82f63f2020-12-09 22:37:27 +0100112 else {
113 filename_obj = NULL;
114 }
115 int res = _PyRun_AnyFileObject(fp, filename_obj, closeit, flags);
116 Py_XDECREF(filename_obj);
117 return res;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000118}
119
Victor Stinnera82f63f2020-12-09 22:37:27 +0100120
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000121int
Victor Stinnera82f63f2020-12-09 22:37:27 +0100122_PyRun_InteractiveLoopObject(FILE *fp, PyObject *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000123{
Victor Stinner37d66d72019-06-13 02:16:41 +0200124 PyCompilerFlags local_flags = _PyCompilerFlags_INIT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000125 if (flags == NULL) {
126 flags = &local_flags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000127 }
Victor Stinnera82f63f2020-12-09 22:37:27 +0100128
129 PyObject *v = _PySys_GetObjectId(&PyId_ps1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000130 if (v == NULL) {
Victor Stinner09054372013-11-06 22:41:44 +0100131 _PySys_SetObjectId(&PyId_ps1, v = PyUnicode_FromString(">>> "));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 Py_XDECREF(v);
133 }
Victor Stinner09054372013-11-06 22:41:44 +0100134 v = _PySys_GetObjectId(&PyId_ps2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 if (v == NULL) {
Victor Stinner09054372013-11-06 22:41:44 +0100136 _PySys_SetObjectId(&PyId_ps2, v = PyUnicode_FromString("... "));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000137 Py_XDECREF(v);
138 }
Victor Stinnera82f63f2020-12-09 22:37:27 +0100139
140#ifdef Py_REF_DEBUG
141 int show_ref_count = _Py_GetConfig()->show_ref_count;
142#endif
143 int err = 0;
144 int ret;
145 int nomem_count = 0;
xdegayee0582a32017-11-12 16:50:48 +0100146 do {
147 ret = PyRun_InteractiveOneObjectEx(fp, filename, flags);
148 if (ret == -1 && PyErr_Occurred()) {
149 /* Prevent an endless loop after multiple consecutive MemoryErrors
150 * while still allowing an interactive command to fail with a
151 * MemoryError. */
152 if (PyErr_ExceptionMatches(PyExc_MemoryError)) {
153 if (++nomem_count > 16) {
154 PyErr_Clear();
155 err = -1;
156 break;
157 }
158 } else {
159 nomem_count = 0;
160 }
161 PyErr_Print();
162 flush_io();
163 } else {
164 nomem_count = 0;
165 }
Eric Snowdae02762017-09-14 00:35:58 -0700166#ifdef Py_REF_DEBUG
Victor Stinner25420fe2017-11-20 18:12:22 -0800167 if (show_ref_count) {
Eric Snowdae02762017-09-14 00:35:58 -0700168 _PyDebug_PrintTotalRefs();
Victor Stinner25420fe2017-11-20 18:12:22 -0800169 }
Eric Snowdae02762017-09-14 00:35:58 -0700170#endif
xdegayee0582a32017-11-12 16:50:48 +0100171 } while (ret != E_EOF);
Victor Stinner95701bd2013-11-06 18:41:07 +0100172 return err;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000173}
174
Victor Stinnera82f63f2020-12-09 22:37:27 +0100175
176int
177PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
178{
179 PyObject *filename_obj = PyUnicode_DecodeFSDefault(filename);
180 if (filename_obj == NULL) {
181 PyErr_Print();
182 return -1;
183 }
184
185 int err = _PyRun_InteractiveLoopObject(fp, filename_obj, flags);
186 Py_DECREF(filename_obj);
187 return err;
188
189}
190
191
xdegayee0582a32017-11-12 16:50:48 +0100192/* A PyRun_InteractiveOneObject() auxiliary function that does not print the
193 * error on failure. */
194static int
195PyRun_InteractiveOneObjectEx(FILE *fp, PyObject *filename,
196 PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000197{
Victor Stinner95701bd2013-11-06 18:41:07 +0100198 PyObject *m, *d, *v, *w, *oenc = NULL, *mod_name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199 mod_ty mod;
200 PyArena *arena;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200201 const char *ps1 = "", *ps2 = "", *enc = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000202 int errcode = 0;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200203 _Py_IDENTIFIER(encoding);
Victor Stinner95701bd2013-11-06 18:41:07 +0100204 _Py_IDENTIFIER(__main__);
205
206 mod_name = _PyUnicode_FromId(&PyId___main__); /* borrowed */
207 if (mod_name == NULL) {
Victor Stinner95701bd2013-11-06 18:41:07 +0100208 return -1;
209 }
Tim Petersfe2127d2001-07-16 05:37:24 +0000210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000211 if (fp == stdin) {
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -0400212 /* Fetch encoding from sys.stdin if possible. */
Victor Stinnerbd303c12013-11-07 23:07:29 +0100213 v = _PySys_GetObjectId(&PyId_stdin);
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -0400214 if (v && v != Py_None) {
215 oenc = _PyObject_GetAttrId(v, &PyId_encoding);
216 if (oenc)
Serhiy Storchaka06515832016-11-20 09:13:07 +0200217 enc = PyUnicode_AsUTF8(oenc);
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -0400218 if (!enc)
219 PyErr_Clear();
220 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000221 }
Victor Stinner09054372013-11-06 22:41:44 +0100222 v = _PySys_GetObjectId(&PyId_ps1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000223 if (v != NULL) {
224 v = PyObject_Str(v);
225 if (v == NULL)
226 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +0000227 else if (PyUnicode_Check(v)) {
Serhiy Storchaka06515832016-11-20 09:13:07 +0200228 ps1 = PyUnicode_AsUTF8(v);
Victor Stinner386fe712010-05-19 00:34:15 +0000229 if (ps1 == NULL) {
230 PyErr_Clear();
231 ps1 = "";
232 }
233 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 }
Victor Stinner09054372013-11-06 22:41:44 +0100235 w = _PySys_GetObjectId(&PyId_ps2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000236 if (w != NULL) {
237 w = PyObject_Str(w);
238 if (w == NULL)
239 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +0000240 else if (PyUnicode_Check(w)) {
Serhiy Storchaka06515832016-11-20 09:13:07 +0200241 ps2 = PyUnicode_AsUTF8(w);
Victor Stinner386fe712010-05-19 00:34:15 +0000242 if (ps2 == NULL) {
243 PyErr_Clear();
244 ps2 = "";
245 }
246 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247 }
248 arena = PyArena_New();
249 if (arena == NULL) {
250 Py_XDECREF(v);
251 Py_XDECREF(w);
252 Py_XDECREF(oenc);
253 return -1;
254 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100255
Lysandros Nikolaou564cd182020-06-22 02:47:46 +0300256 mod = PyParser_ASTFromFileObject(fp, filename, enc, Py_single_input,
257 ps1, ps2, flags, &errcode, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000259 Py_XDECREF(v);
260 Py_XDECREF(w);
261 Py_XDECREF(oenc);
262 if (mod == NULL) {
263 PyArena_Free(arena);
264 if (errcode == E_EOF) {
265 PyErr_Clear();
266 return E_EOF;
267 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000268 return -1;
269 }
Victor Stinner95701bd2013-11-06 18:41:07 +0100270 m = PyImport_AddModuleObject(mod_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000271 if (m == NULL) {
272 PyArena_Free(arena);
273 return -1;
274 }
275 d = PyModule_GetDict(m);
276 v = run_mod(mod, filename, d, d, flags, arena);
277 PyArena_Free(arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000278 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000279 return -1;
280 }
281 Py_DECREF(v);
Antoine Pitrou9845c7e2014-05-11 13:42:17 +0200282 flush_io();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000284}
285
Victor Stinner95701bd2013-11-06 18:41:07 +0100286int
xdegayee0582a32017-11-12 16:50:48 +0100287PyRun_InteractiveOneObject(FILE *fp, PyObject *filename, PyCompilerFlags *flags)
288{
289 int res;
290
291 res = PyRun_InteractiveOneObjectEx(fp, filename, flags);
292 if (res == -1) {
293 PyErr_Print();
294 flush_io();
295 }
296 return res;
297}
298
299int
Victor Stinner95701bd2013-11-06 18:41:07 +0100300PyRun_InteractiveOneFlags(FILE *fp, const char *filename_str, PyCompilerFlags *flags)
301{
302 PyObject *filename;
303 int res;
304
305 filename = PyUnicode_DecodeFSDefault(filename_str);
306 if (filename == NULL) {
307 PyErr_Print();
308 return -1;
309 }
310 res = PyRun_InteractiveOneObject(fp, filename, flags);
311 Py_DECREF(filename);
312 return res;
313}
314
315
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000316/* Check whether a file maybe a pyc file: Look at the extension,
317 the file type, and, if we may close it, at the first few bytes. */
318
319static int
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100320maybe_pyc_file(FILE *fp, PyObject *filename, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000321{
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100322 PyObject *ext = PyUnicode_FromString(".pyc");
323 if (ext == NULL) {
324 return -1;
325 }
326 Py_ssize_t endswith = PyUnicode_Tailmatch(filename, ext, 0, PY_SSIZE_T_MAX, +1);
327 Py_DECREF(ext);
328 if (endswith) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000329 return 1;
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100330 }
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332 /* Only look into the file if we are allowed to close it, since
333 it then should also be seekable. */
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100334 if (!closeit) {
335 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336 }
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100337
338 /* Read only two bytes of the magic. If the file was opened in
339 text mode, the bytes 3 and 4 of the magic (\r\n) might not
340 be read as they are on disk. */
341 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
342 unsigned char buf[2];
343 /* Mess: In case of -x, the stream is NOT at its start now,
344 and ungetc() was used to push back the first newline,
345 which makes the current stream position formally undefined,
346 and a x-platform nightmare.
347 Unfortunately, we have no direct way to know whether -x
348 was specified. So we use a terrible hack: if the current
349 stream position is not 0, we assume -x was specified, and
350 give up. Bug 132850 on SourceForge spells out the
351 hopelessness of trying anything else (fseek and ftell
352 don't work predictably x-platform for text-mode files).
353 */
354 int ispyc = 0;
355 if (ftell(fp) == 0) {
356 if (fread(buf, 1, 2, fp) == 2 &&
357 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
358 ispyc = 1;
359 rewind(fp);
360 }
361 return ispyc;
Tim Petersd08e3822003-04-17 15:24:21 +0000362}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000363
Andrew Svetlov90c0eb22012-11-01 14:51:14 +0200364
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100365static int
366set_main_loader(PyObject *d, PyObject *filename, const char *loader_name)
367{
Victor Stinner81a7be32020-04-14 15:14:01 +0200368 PyInterpreterState *interp = _PyInterpreterState_GET();
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100369 PyObject *bootstrap = PyObject_GetAttrString(interp->importlib,
370 "_bootstrap_external");
371 if (bootstrap == NULL) {
Nick Coghlan3f94cbf2012-07-15 19:10:39 +1000372 return -1;
373 }
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100374
375 PyObject *loader_type = PyObject_GetAttrString(bootstrap, loader_name);
376 Py_DECREF(bootstrap);
377 if (loader_type == NULL) {
378 return -1;
379 }
380
381 PyObject *loader = PyObject_CallFunction(loader_type,
382 "sO", "__main__", filename);
Nick Coghlanb7a58942012-07-15 23:21:08 +1000383 Py_DECREF(loader_type);
384 if (loader == NULL) {
Nick Coghlan85e729e2012-07-15 18:09:52 +1000385 return -1;
386 }
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100387
Nick Coghlanb7a58942012-07-15 23:21:08 +1000388 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100389 Py_DECREF(loader);
390 return -1;
Nick Coghlanb7a58942012-07-15 23:21:08 +1000391 }
Nick Coghlan85e729e2012-07-15 18:09:52 +1000392 Py_DECREF(loader);
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100393 return 0;
Nick Coghlan85e729e2012-07-15 18:09:52 +1000394}
395
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100396
Victor Stinner550e4672020-12-09 00:32:54 +0100397int
398_PyRun_SimpleFileObject(FILE *fp, PyObject *filename, int closeit,
399 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000400{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 PyObject *m, *d, *v;
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +0100402 int set_file_name = 0, ret = -1;
Guido van Rossumfdef2711994-09-14 13:31:04 +0000403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404 m = PyImport_AddModule("__main__");
405 if (m == NULL)
406 return -1;
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +0100407 Py_INCREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 d = PyModule_GetDict(m);
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +0200409 if (_PyDict_GetItemStringWithError(d, "__file__") == NULL) {
410 if (PyErr_Occurred()) {
411 goto done;
412 }
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100413 if (PyDict_SetItemString(d, "__file__", filename) < 0) {
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +0100414 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415 }
Barry Warsaw916048d2011-09-20 14:45:44 -0400416 if (PyDict_SetItemString(d, "__cached__", Py_None) < 0) {
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +0100417 goto done;
Barry Warsaw916048d2011-09-20 14:45:44 -0400418 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 set_file_name = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 }
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100421
422 int pyc = maybe_pyc_file(fp, filename, closeit);
423 if (pyc < 0) {
424 goto done;
425 }
426
427 if (pyc) {
Christian Heimes04ac4c12012-09-11 15:47:28 +0200428 FILE *pyc_fp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 /* Try to run a pyc file. First, re-open in binary */
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100430 if (closeit) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 fclose(fp);
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100432 }
433
434 pyc_fp = _Py_fopen_obj(filename, "rb");
435 if (pyc_fp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000436 fprintf(stderr, "python: Can't reopen .pyc file\n");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000437 goto done;
438 }
Nick Coghlan85e729e2012-07-15 18:09:52 +1000439
440 if (set_main_loader(d, filename, "SourcelessFileLoader") < 0) {
441 fprintf(stderr, "python: failed to set __main__.__loader__\n");
442 ret = -1;
Christian Heimes04ac4c12012-09-11 15:47:28 +0200443 fclose(pyc_fp);
Nick Coghlan85e729e2012-07-15 18:09:52 +1000444 goto done;
445 }
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100446 v = run_pyc_file(pyc_fp, d, d, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447 } else {
Nick Coghlan85e729e2012-07-15 18:09:52 +1000448 /* When running from stdin, leave __main__.__loader__ alone */
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100449 if (PyUnicode_CompareWithASCIIString(filename, "<stdin>") != 0 &&
Nick Coghlan85e729e2012-07-15 18:09:52 +1000450 set_main_loader(d, filename, "SourceFileLoader") < 0) {
451 fprintf(stderr, "python: failed to set __main__.__loader__\n");
452 ret = -1;
453 goto done;
454 }
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100455 v = pyrun_file(fp, filename, Py_file_input, d, d,
456 closeit, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 }
458 flush_io();
459 if (v == NULL) {
Zackery Spytzd8cba5d2018-07-03 13:47:22 -0600460 Py_CLEAR(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 PyErr_Print();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 goto done;
463 }
464 Py_DECREF(v);
465 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +0000466 done:
INADA Naoki82daa602018-11-29 20:01:27 +0900467 if (set_file_name) {
468 if (PyDict_DelItemString(d, "__file__")) {
469 PyErr_Clear();
470 }
471 if (PyDict_DelItemString(d, "__cached__")) {
472 PyErr_Clear();
473 }
474 }
Zackery Spytzd8cba5d2018-07-03 13:47:22 -0600475 Py_XDECREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000477}
478
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100479
480int
481PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
482 PyCompilerFlags *flags)
483{
484 PyObject *filename_obj = PyUnicode_DecodeFSDefault(filename);
485 if (filename_obj == NULL) {
486 return -1;
487 }
Victor Stinner550e4672020-12-09 00:32:54 +0100488 int res = _PyRun_SimpleFileObject(fp, filename_obj, closeit, flags);
Victor Stinnerb6d98c12020-12-08 14:38:08 +0100489 Py_DECREF(filename_obj);
490 return res;
491}
492
493
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000494int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000495PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +0000496{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 PyObject *m, *d, *v;
498 m = PyImport_AddModule("__main__");
499 if (m == NULL)
500 return -1;
501 d = PyModule_GetDict(m);
502 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
503 if (v == NULL) {
504 PyErr_Print();
505 return -1;
506 }
507 Py_DECREF(v);
508 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000509}
510
Barry Warsaw035574d1997-08-29 22:07:17 +0000511static int
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100512parse_syntax_error(PyObject *err, PyObject **message, PyObject **filename,
Ammar Askar90d29702020-06-02 08:17:24 +0000513 Py_ssize_t *lineno, Py_ssize_t *offset, PyObject **text)
Barry Warsaw035574d1997-08-29 22:07:17 +0000514{
Ammar Askar90d29702020-06-02 08:17:24 +0000515 Py_ssize_t hold;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 PyObject *v;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200517 _Py_IDENTIFIER(msg);
518 _Py_IDENTIFIER(filename);
519 _Py_IDENTIFIER(lineno);
520 _Py_IDENTIFIER(offset);
521 _Py_IDENTIFIER(text);
Barry Warsaw035574d1997-08-29 22:07:17 +0000522
Benjamin Peterson80d50422012-04-03 00:30:38 -0400523 *message = NULL;
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100524 *filename = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 /* new style errors. `err' is an instance */
Benjamin Peterson0a9a6362012-04-03 00:35:36 -0400527 *message = _PyObject_GetAttrId(err, &PyId_msg);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400528 if (!*message)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000529 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +0000530
Benjamin Peterson0a9a6362012-04-03 00:35:36 -0400531 v = _PyObject_GetAttrId(err, &PyId_filename);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400532 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400534 if (v == Py_None) {
535 Py_DECREF(v);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100536 *filename = _PyUnicode_FromId(&PyId_string);
537 if (*filename == NULL)
538 goto finally;
539 Py_INCREF(*filename);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400540 }
541 else {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100542 *filename = v;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400543 }
Barry Warsaw035574d1997-08-29 22:07:17 +0000544
Benjamin Peterson0a9a6362012-04-03 00:35:36 -0400545 v = _PyObject_GetAttrId(err, &PyId_lineno);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400546 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000547 goto finally;
Ammar Askar90d29702020-06-02 08:17:24 +0000548 hold = PyLong_AsSsize_t(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000549 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 if (hold < 0 && PyErr_Occurred())
551 goto finally;
Serhiy Storchaka56f6e762015-09-06 21:25:30 +0300552 *lineno = hold;
Barry Warsaw035574d1997-08-29 22:07:17 +0000553
Benjamin Peterson0a9a6362012-04-03 00:35:36 -0400554 v = _PyObject_GetAttrId(err, &PyId_offset);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400555 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 goto finally;
557 if (v == Py_None) {
558 *offset = -1;
559 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 } else {
Ammar Askar90d29702020-06-02 08:17:24 +0000561 hold = PyLong_AsSsize_t(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 if (hold < 0 && PyErr_Occurred())
564 goto finally;
Serhiy Storchaka56f6e762015-09-06 21:25:30 +0300565 *offset = hold;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 }
Barry Warsaw035574d1997-08-29 22:07:17 +0000567
Benjamin Peterson0a9a6362012-04-03 00:35:36 -0400568 v = _PyObject_GetAttrId(err, &PyId_text);
Benjamin Peterson80d50422012-04-03 00:30:38 -0400569 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400571 if (v == Py_None) {
572 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 *text = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400574 }
575 else {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100576 *text = v;
Benjamin Peterson80d50422012-04-03 00:30:38 -0400577 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +0000579
580finally:
Benjamin Peterson80d50422012-04-03 00:30:38 -0400581 Py_XDECREF(*message);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100582 Py_XDECREF(*filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +0000584}
585
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000586static void
Ammar Askar90d29702020-06-02 08:17:24 +0000587print_error_text(PyObject *f, Py_ssize_t offset, PyObject *text_obj)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000588{
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700589 /* Convert text to a char pointer; return if error */
590 const char *text = PyUnicode_AsUTF8(text_obj);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100591 if (text == NULL)
592 return;
593
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700594 /* Convert offset from 1-based to 0-based */
595 offset--;
596
597 /* Strip leading whitespace from text, adjusting offset as we go */
598 while (*text == ' ' || *text == '\t' || *text == '\f') {
599 text++;
600 offset--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 }
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700602
603 /* Calculate text length excluding trailing newline */
604 Py_ssize_t len = strlen(text);
605 if (len > 0 && text[len-1] == '\n') {
606 len--;
607 }
608
609 /* Clip offset to at most len */
610 if (offset > len) {
611 offset = len;
612 }
613
614 /* Skip past newlines embedded in text */
615 for (;;) {
616 const char *nl = strchr(text, '\n');
617 if (nl == NULL) {
618 break;
619 }
620 Py_ssize_t inl = nl - text;
Ammar Askar90d29702020-06-02 08:17:24 +0000621 if (inl >= offset) {
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700622 break;
623 }
624 inl += 1;
625 text += inl;
626 len -= inl;
627 offset -= (int)inl;
628 }
629
630 /* Print text */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 PyFile_WriteString(" ", f);
632 PyFile_WriteString(text, f);
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700633
634 /* Make sure there's a newline at the end */
635 if (text[len] != '\n') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 PyFile_WriteString("\n", f);
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700637 }
638
639 /* Don't print caret if it points to the left of the text */
640 if (offset < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 return;
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700642
643 /* Write caret line */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 PyFile_WriteString(" ", f);
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700645 while (--offset >= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 PyFile_WriteString(" ", f);
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700647 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000649}
650
Tim Peterscf615b52003-04-19 18:47:02 +0000651
Victor Stinner12083282019-05-17 23:05:29 +0200652int
653_Py_HandleSystemExit(int *exitcode_p)
654{
Victor Stinnerda7933e2020-04-13 03:04:28 +0200655 int inspect = _Py_GetConfig()->inspect;
Victor Stinnerc96be812019-05-14 17:34:56 +0200656 if (inspect) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 /* Don't exit if -i flag was given. This flag is set to 0
658 * when entering interactive mode for inspecting. */
Victor Stinner12083282019-05-17 23:05:29 +0200659 return 0;
Victor Stinnerc96be812019-05-14 17:34:56 +0200660 }
Guido van Rossumd8faa362007-04-27 19:54:29 +0000661
Victor Stinner12083282019-05-17 23:05:29 +0200662 if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
663 return 0;
664 }
665
666 PyObject *exception, *value, *tb;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000667 PyErr_Fetch(&exception, &value, &tb);
Victor Stinner12083282019-05-17 23:05:29 +0200668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000669 fflush(stdout);
Victor Stinner12083282019-05-17 23:05:29 +0200670
671 int exitcode = 0;
672 if (value == NULL || value == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000673 goto done;
Victor Stinner12083282019-05-17 23:05:29 +0200674 }
675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 if (PyExceptionInstance_Check(value)) {
677 /* The error code should be in the `code' attribute. */
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200678 _Py_IDENTIFIER(code);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200679 PyObject *code = _PyObject_GetAttrId(value, &PyId_code);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000680 if (code) {
681 Py_DECREF(value);
682 value = code;
683 if (value == Py_None)
684 goto done;
685 }
686 /* If we failed to dig out the 'code' attribute,
687 just let the else clause below print the error. */
688 }
Victor Stinner12083282019-05-17 23:05:29 +0200689
690 if (PyLong_Check(value)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000691 exitcode = (int)PyLong_AsLong(value);
Victor Stinner12083282019-05-17 23:05:29 +0200692 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 else {
Victor Stinnerbd303c12013-11-07 23:07:29 +0100694 PyObject *sys_stderr = _PySys_GetObjectId(&PyId_stderr);
Nick Coghland979e432014-02-09 10:43:21 +1000695 /* We clear the exception here to avoid triggering the assertion
696 * in PyObject_Str that ensures it won't silently lose exception
697 * details.
698 */
699 PyErr_Clear();
Victor Stinner7126dbc2010-05-21 23:45:42 +0000700 if (sys_stderr != NULL && sys_stderr != Py_None) {
701 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
702 } else {
703 PyObject_Print(value, stderr, Py_PRINT_RAW);
704 fflush(stderr);
705 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000706 PySys_WriteStderr("\n");
707 exitcode = 1;
708 }
Victor Stinner12083282019-05-17 23:05:29 +0200709
Tim Peterscf615b52003-04-19 18:47:02 +0000710 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000711 /* Restore and clear the exception info, in order to properly decref
712 * the exception, value, and traceback. If we just exit instead,
713 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
714 * some finalizers from running.
715 */
716 PyErr_Restore(exception, value, tb);
717 PyErr_Clear();
Victor Stinner12083282019-05-17 23:05:29 +0200718 *exitcode_p = exitcode;
719 return 1;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000720}
721
Victor Stinner12083282019-05-17 23:05:29 +0200722
723static void
724handle_system_exit(void)
725{
726 int exitcode;
727 if (_Py_HandleSystemExit(&exitcode)) {
728 Py_Exit(exitcode);
729 }
730}
731
732
Victor Stinner438a12d2019-05-24 17:01:38 +0200733static void
734_PyErr_PrintEx(PyThreadState *tstate, int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000735{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +0000737
Victor Stinner12083282019-05-17 23:05:29 +0200738 handle_system_exit();
739
Victor Stinner438a12d2019-05-24 17:01:38 +0200740 _PyErr_Fetch(tstate, &exception, &v, &tb);
741 if (exception == NULL) {
742 goto done;
743 }
744
745 _PyErr_NormalizeException(tstate, &exception, &v, &tb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 if (tb == NULL) {
747 tb = Py_None;
748 Py_INCREF(tb);
749 }
750 PyException_SetTraceback(v, tb);
Victor Stinner438a12d2019-05-24 17:01:38 +0200751 if (exception == NULL) {
752 goto done;
753 }
754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000755 /* Now we know v != NULL too */
756 if (set_sys_last_vars) {
xdegaye66caacf2017-10-23 18:08:41 +0200757 if (_PySys_SetObjectId(&PyId_last_type, exception) < 0) {
Victor Stinner438a12d2019-05-24 17:01:38 +0200758 _PyErr_Clear(tstate);
xdegaye66caacf2017-10-23 18:08:41 +0200759 }
760 if (_PySys_SetObjectId(&PyId_last_value, v) < 0) {
Victor Stinner438a12d2019-05-24 17:01:38 +0200761 _PyErr_Clear(tstate);
xdegaye66caacf2017-10-23 18:08:41 +0200762 }
763 if (_PySys_SetObjectId(&PyId_last_traceback, tb) < 0) {
Victor Stinner438a12d2019-05-24 17:01:38 +0200764 _PyErr_Clear(tstate);
xdegaye66caacf2017-10-23 18:08:41 +0200765 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 }
Victor Stinner09054372013-11-06 22:41:44 +0100767 hook = _PySys_GetObjectId(&PyId_excepthook);
Victor Stinner1c1e68c2020-03-27 15:11:45 +0100768 if (_PySys_Audit(tstate, "sys.excepthook", "OOOO", hook ? hook : Py_None,
769 exception, v, tb) < 0) {
Steve Dowerbea33f52019-11-28 08:46:11 -0800770 if (PyErr_ExceptionMatches(PyExc_RuntimeError)) {
771 PyErr_Clear();
772 goto done;
773 }
774 _PyErr_WriteUnraisableMsg("in audit hook", NULL);
775 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000776 if (hook) {
Victor Stinner71cb64a2016-08-20 00:57:43 +0200777 PyObject* stack[3];
778 PyObject *result;
779
780 stack[0] = exception;
781 stack[1] = v;
782 stack[2] = tb;
Victor Stinner559bb6a2016-08-22 22:48:54 +0200783 result = _PyObject_FastCall(hook, stack, 3);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 if (result == NULL) {
Victor Stinner12083282019-05-17 23:05:29 +0200785 handle_system_exit();
786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 PyObject *exception2, *v2, *tb2;
Victor Stinner438a12d2019-05-24 17:01:38 +0200788 _PyErr_Fetch(tstate, &exception2, &v2, &tb2);
789 _PyErr_NormalizeException(tstate, &exception2, &v2, &tb2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 /* It should not be possible for exception2 or v2
791 to be NULL. However PyErr_Display() can't
792 tolerate NULLs, so just be safe. */
793 if (exception2 == NULL) {
794 exception2 = Py_None;
795 Py_INCREF(exception2);
796 }
797 if (v2 == NULL) {
798 v2 = Py_None;
799 Py_INCREF(v2);
800 }
801 fflush(stdout);
802 PySys_WriteStderr("Error in sys.excepthook:\n");
803 PyErr_Display(exception2, v2, tb2);
804 PySys_WriteStderr("\nOriginal exception was:\n");
805 PyErr_Display(exception, v, tb);
806 Py_DECREF(exception2);
807 Py_DECREF(v2);
808 Py_XDECREF(tb2);
809 }
810 Py_XDECREF(result);
Victor Stinner438a12d2019-05-24 17:01:38 +0200811 }
812 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 PySys_WriteStderr("sys.excepthook is missing\n");
814 PyErr_Display(exception, v, tb);
815 }
Victor Stinner438a12d2019-05-24 17:01:38 +0200816
817done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000818 Py_XDECREF(exception);
819 Py_XDECREF(v);
820 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000821}
822
Victor Stinner438a12d2019-05-24 17:01:38 +0200823void
824_PyErr_Print(PyThreadState *tstate)
825{
826 _PyErr_PrintEx(tstate, 1);
827}
828
829void
830PyErr_PrintEx(int set_sys_last_vars)
831{
832 PyThreadState *tstate = _PyThreadState_GET();
833 _PyErr_PrintEx(tstate, set_sys_last_vars);
834}
835
836void
837PyErr_Print(void)
838{
839 PyErr_PrintEx(1);
840}
841
Benjamin Petersone6528212008-07-15 15:32:09 +0000842static void
843print_exception(PyObject *f, PyObject *value)
844{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 int err = 0;
Serhiy Storchaka98c44332020-10-10 22:23:42 +0300846 PyObject *type, *tb, *tmp;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200847 _Py_IDENTIFIER(print_file_and_line);
Benjamin Petersone6528212008-07-15 15:32:09 +0000848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 if (!PyExceptionInstance_Check(value)) {
Victor Stinner52ce3b02013-12-09 02:10:08 +0100850 err = PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
851 err += PyFile_WriteString(Py_TYPE(value)->tp_name, f);
852 err += PyFile_WriteString(" found\n", f);
853 if (err)
854 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 return;
856 }
Benjamin Peterson26582602008-08-23 20:08:07 +0000857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 Py_INCREF(value);
859 fflush(stdout);
860 type = (PyObject *) Py_TYPE(value);
861 tb = PyException_GetTraceback(value);
862 if (tb && tb != Py_None)
863 err = PyTraceBack_Print(tb, f);
864 if (err == 0 &&
Serhiy Storchaka98c44332020-10-10 22:23:42 +0300865 (err = _PyObject_LookupAttrId(value, &PyId_print_file_and_line, &tmp)) > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100867 PyObject *message, *filename, *text;
Ammar Askar90d29702020-06-02 08:17:24 +0000868 Py_ssize_t lineno, offset;
Serhiy Storchaka98c44332020-10-10 22:23:42 +0300869 err = 0;
870 Py_DECREF(tmp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000871 if (!parse_syntax_error(value, &message, &filename,
872 &lineno, &offset, &text))
873 PyErr_Clear();
874 else {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100875 PyObject *line;
876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 Py_DECREF(value);
878 value = message;
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100879
Ammar Askar90d29702020-06-02 08:17:24 +0000880 line = PyUnicode_FromFormat(" File \"%S\", line %zd\n",
Victor Stinnerefa7a0e2013-11-07 12:37:56 +0100881 filename, lineno);
882 Py_DECREF(filename);
883 if (line != NULL) {
884 PyFile_WriteObject(line, f, Py_PRINT_RAW);
885 Py_DECREF(line);
886 }
887
888 if (text != NULL) {
889 print_error_text(f, offset, text);
890 Py_DECREF(text);
891 }
892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 /* Can't be bothered to check all those
894 PyFile_WriteString() calls */
895 if (PyErr_Occurred())
896 err = -1;
897 }
898 }
899 if (err) {
900 /* Don't do anything else */
901 }
902 else {
903 PyObject* moduleName;
Serhiy Storchakaceeef102018-06-15 11:09:43 +0300904 const char *className;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200905 _Py_IDENTIFIER(__module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 assert(PyExceptionClass_Check(type));
907 className = PyExceptionClass_Name(type);
908 if (className != NULL) {
Serhiy Storchakaceeef102018-06-15 11:09:43 +0300909 const char *dot = strrchr(className, '.');
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 if (dot != NULL)
911 className = dot+1;
912 }
Benjamin Petersone6528212008-07-15 15:32:09 +0000913
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200914 moduleName = _PyObject_GetAttrId(type, &PyId___module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 if (moduleName == NULL || !PyUnicode_Check(moduleName))
916 {
Victor Stinner13b21bd2011-05-26 14:25:13 +0200917 Py_XDECREF(moduleName);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 err = PyFile_WriteString("<unknown>", f);
919 }
920 else {
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +0200921 if (!_PyUnicode_EqualToASCIIId(moduleName, &PyId_builtins))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 {
Victor Stinner937114f2013-11-07 00:12:30 +0100923 err = PyFile_WriteObject(moduleName, f, Py_PRINT_RAW);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 err += PyFile_WriteString(".", f);
925 }
926 Py_DECREF(moduleName);
927 }
928 if (err == 0) {
929 if (className == NULL)
930 err = PyFile_WriteString("<unknown>", f);
931 else
932 err = PyFile_WriteString(className, f);
933 }
934 }
935 if (err == 0 && (value != Py_None)) {
936 PyObject *s = PyObject_Str(value);
937 /* only print colon if the str() of the
938 object is not the empty string
939 */
Martin Panter3263f682016-02-28 03:16:11 +0000940 if (s == NULL) {
941 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 err = -1;
Martin Panter3263f682016-02-28 03:16:11 +0000943 PyFile_WriteString(": <exception str() failed>", f);
944 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 else if (!PyUnicode_Check(s) ||
Victor Stinnere251d6d2011-11-20 19:20:00 +0100946 PyUnicode_GetLength(s) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 err = PyFile_WriteString(": ", f);
948 if (err == 0)
949 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
950 Py_XDECREF(s);
951 }
952 /* try to write a newline in any case */
Martin Panter3263f682016-02-28 03:16:11 +0000953 if (err < 0) {
954 PyErr_Clear();
955 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 err += PyFile_WriteString("\n", f);
957 Py_XDECREF(tb);
958 Py_DECREF(value);
959 /* If an error happened here, don't show it.
960 XXX This is wrong, but too many callers rely on this behavior. */
961 if (err != 0)
962 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +0000963}
964
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200965static const char cause_message[] =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 "\nThe above exception was the direct cause "
967 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +0000968
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200969static const char context_message[] =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 "\nDuring handling of the above exception, "
971 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +0000972
973static void
974print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
975{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 int err = 0, res;
977 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +0000978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 if (seen != NULL) {
980 /* Exception chaining */
Zane Bitterde860732017-10-17 17:29:39 -0400981 PyObject *value_id = PyLong_FromVoidPtr(value);
982 if (value_id == NULL || PySet_Add(seen, value_id) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 PyErr_Clear();
984 else if (PyExceptionInstance_Check(value)) {
Zane Bitterde860732017-10-17 17:29:39 -0400985 PyObject *check_id = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 cause = PyException_GetCause(value);
987 context = PyException_GetContext(value);
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700988 if (cause) {
Zane Bitterde860732017-10-17 17:29:39 -0400989 check_id = PyLong_FromVoidPtr(cause);
990 if (check_id == NULL) {
991 res = -1;
992 } else {
993 res = PySet_Contains(seen, check_id);
994 Py_DECREF(check_id);
995 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 if (res == -1)
997 PyErr_Clear();
998 if (res == 0) {
999 print_exception_recursive(
1000 f, cause, seen);
1001 err |= PyFile_WriteString(
1002 cause_message, f);
1003 }
1004 }
Benjamin Petersond5a1c442012-05-14 22:09:31 -07001005 else if (context &&
1006 !((PyBaseExceptionObject *)value)->suppress_context) {
Zane Bitterde860732017-10-17 17:29:39 -04001007 check_id = PyLong_FromVoidPtr(context);
1008 if (check_id == NULL) {
1009 res = -1;
1010 } else {
1011 res = PySet_Contains(seen, check_id);
1012 Py_DECREF(check_id);
1013 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 if (res == -1)
1015 PyErr_Clear();
1016 if (res == 0) {
1017 print_exception_recursive(
1018 f, context, seen);
1019 err |= PyFile_WriteString(
1020 context_message, f);
1021 }
1022 }
1023 Py_XDECREF(context);
1024 Py_XDECREF(cause);
1025 }
Zane Bitterde860732017-10-17 17:29:39 -04001026 Py_XDECREF(value_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 }
1028 print_exception(f, value);
1029 if (err != 0)
1030 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001031}
1032
Thomas Wouters477c8d52006-05-27 19:21:47 +00001033void
Victor Stinnercd590a72019-05-28 00:39:52 +02001034_PyErr_Display(PyObject *file, PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001035{
Victor Stinnercd590a72019-05-28 00:39:52 +02001036 assert(file != NULL && file != Py_None);
1037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 PyObject *seen;
Antoine Pitrou24201d42013-10-13 21:53:13 +02001039 if (PyExceptionInstance_Check(value)
1040 && tb != NULL && PyTraceBack_Check(tb)) {
1041 /* Put the traceback on the exception, otherwise it won't get
1042 displayed. See issue #18776. */
1043 PyObject *cur_tb = PyException_GetTraceback(value);
1044 if (cur_tb == NULL)
1045 PyException_SetTraceback(value, tb);
1046 else
1047 Py_DECREF(cur_tb);
1048 }
Victor Stinnercd590a72019-05-28 00:39:52 +02001049
1050 /* We choose to ignore seen being possibly NULL, and report
1051 at least the main exception (it could be a MemoryError).
1052 */
1053 seen = PySet_New(NULL);
1054 if (seen == NULL) {
1055 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 }
Victor Stinnercd590a72019-05-28 00:39:52 +02001057 print_exception_recursive(file, value, seen);
1058 Py_XDECREF(seen);
Victor Stinnera85a1d32019-05-28 16:01:17 +02001059
1060 /* Call file.flush() */
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001061 PyObject *res = _PyObject_CallMethodIdNoArgs(file, &PyId_flush);
Victor Stinnera85a1d32019-05-28 16:01:17 +02001062 if (!res) {
1063 /* Silently ignore file.flush() error */
1064 PyErr_Clear();
1065 }
1066 else {
1067 Py_DECREF(res);
1068 }
Victor Stinnercd590a72019-05-28 00:39:52 +02001069}
1070
1071void
1072PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
1073{
1074 PyObject *file = _PySys_GetObjectId(&PyId_stderr);
1075 if (file == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 _PyObject_Dump(value);
1077 fprintf(stderr, "lost sys.stderr\n");
Victor Stinnercd590a72019-05-28 00:39:52 +02001078 return;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 }
Victor Stinnercd590a72019-05-28 00:39:52 +02001080 if (file == Py_None) {
1081 return;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 }
Victor Stinnercd590a72019-05-28 00:39:52 +02001083
1084 _PyErr_Display(file, exception, value, tb);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001085}
1086
Guido van Rossum82598051997-03-05 00:20:32 +00001087PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001088PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001090{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 PyObject *ret = NULL;
1092 mod_ty mod;
Victor Stinner95701bd2013-11-06 18:41:07 +01001093 PyArena *arena;
Victor Stinner95701bd2013-11-06 18:41:07 +01001094 PyObject *filename;
1095
1096 filename = _PyUnicode_FromId(&PyId_string); /* borrowed */
1097 if (filename == NULL)
1098 return NULL;
1099
1100 arena = PyArena_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 if (arena == NULL)
1102 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001103
Lysandros Nikolaou564cd182020-06-22 02:47:46 +03001104 mod = PyParser_ASTFromStringObject(str, filename, start, flags, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 if (mod != NULL)
Victor Stinner95701bd2013-11-06 18:41:07 +01001107 ret = run_mod(mod, filename, globals, locals, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001108 PyArena_Free(arena);
1109 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001110}
1111
Victor Stinnerb6d98c12020-12-08 14:38:08 +01001112
1113static PyObject *
1114pyrun_file(FILE *fp, PyObject *filename, int start, PyObject *globals,
1115 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001116{
Victor Stinnerb6d98c12020-12-08 14:38:08 +01001117 PyArena *arena = PyArena_New();
1118 if (arena == NULL) {
1119 return NULL;
1120 }
1121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 mod_ty mod;
Lysandros Nikolaou564cd182020-06-22 02:47:46 +03001123 mod = PyParser_ASTFromFileObject(fp, filename, NULL, start, NULL, NULL,
1124 flags, NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001125
Victor Stinnerb6d98c12020-12-08 14:38:08 +01001126 if (closeit) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001127 fclose(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001128 }
Victor Stinner95701bd2013-11-06 18:41:07 +01001129
Victor Stinnerb6d98c12020-12-08 14:38:08 +01001130 PyObject *ret;
1131 if (mod != NULL) {
1132 ret = run_mod(mod, filename, globals, locals, flags, arena);
1133 }
1134 else {
1135 ret = NULL;
1136 }
1137 PyArena_Free(arena);
1138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001139 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001140}
1141
Victor Stinnerb6d98c12020-12-08 14:38:08 +01001142
1143PyObject *
1144PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
1145 PyObject *locals, int closeit, PyCompilerFlags *flags)
1146{
1147 PyObject *filename_obj = PyUnicode_DecodeFSDefault(filename);
1148 if (filename_obj == NULL) {
1149 return NULL;
1150 }
1151
1152 PyObject *res = pyrun_file(fp, filename_obj, start, globals,
1153 locals, closeit, flags);
1154 Py_DECREF(filename_obj);
1155 return res;
1156
1157}
1158
1159
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001160static void
1161flush_io(void)
1162{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 PyObject *f, *r;
1164 PyObject *type, *value, *traceback;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 /* Save the current exception */
1167 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001168
Victor Stinnerbd303c12013-11-07 23:07:29 +01001169 f = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001170 if (f != NULL) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001171 r = _PyObject_CallMethodIdNoArgs(f, &PyId_flush);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001172 if (r)
1173 Py_DECREF(r);
1174 else
1175 PyErr_Clear();
1176 }
Victor Stinnerbd303c12013-11-07 23:07:29 +01001177 f = _PySys_GetObjectId(&PyId_stdout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 if (f != NULL) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001179 r = _PyObject_CallMethodIdNoArgs(f, &PyId_flush);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001180 if (r)
1181 Py_DECREF(r);
1182 else
1183 PyErr_Clear();
1184 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001187}
1188
Guido van Rossum82598051997-03-05 00:20:32 +00001189static PyObject *
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001190run_eval_code_obj(PyThreadState *tstate, PyCodeObject *co, PyObject *globals, PyObject *locals)
Gregory P. Smith38f11cc2019-02-16 12:57:40 -08001191{
1192 PyObject *v;
Gregory P. Smithd9bc5432019-02-20 17:35:54 -08001193 /*
1194 * We explicitly re-initialize _Py_UnhandledKeyboardInterrupt every eval
1195 * _just in case_ someone is calling into an embedded Python where they
1196 * don't care about an uncaught KeyboardInterrupt exception (why didn't they
1197 * leave config.install_signal_handlers set to 0?!?) but then later call
1198 * Py_Main() itself (which _checks_ this flag and dies with a signal after
1199 * its interpreter exits). We don't want a previous embedded interpreter's
1200 * uncaught exception to trigger an unexplained signal exit from a future
1201 * Py_Main() based one.
1202 */
1203 _Py_UnhandledKeyboardInterrupt = 0;
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001204
1205 /* Set globals['__builtins__'] if it doesn't exist */
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02001206 if (globals != NULL && _PyDict_GetItemStringWithError(globals, "__builtins__") == NULL) {
1207 if (PyErr_Occurred() ||
1208 PyDict_SetItemString(globals, "__builtins__",
1209 tstate->interp->builtins) < 0)
1210 {
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001211 return NULL;
1212 }
1213 }
1214
Gregory P. Smith38f11cc2019-02-16 12:57:40 -08001215 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001216 if (!v && _PyErr_Occurred(tstate) == PyExc_KeyboardInterrupt) {
Gregory P. Smith38f11cc2019-02-16 12:57:40 -08001217 _Py_UnhandledKeyboardInterrupt = 1;
1218 }
1219 return v;
1220}
1221
1222static PyObject *
Victor Stinner95701bd2013-11-06 18:41:07 +01001223run_mod(mod_ty mod, PyObject *filename, PyObject *globals, PyObject *locals,
1224 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001225{
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001226 PyThreadState *tstate = _PyThreadState_GET();
1227 PyCodeObject *co = PyAST_CompileObject(mod, filename, flags, -1, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 if (co == NULL)
1229 return NULL;
Steve Dowerb82e17e2019-05-23 08:45:22 -07001230
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001231 if (_PySys_Audit(tstate, "exec", "O", co) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07001232 Py_DECREF(co);
1233 return NULL;
1234 }
1235
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001236 PyObject *v = run_eval_code_obj(tstate, co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 Py_DECREF(co);
1238 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001239}
1240
Guido van Rossum82598051997-03-05 00:20:32 +00001241static PyObject *
Victor Stinnerb6d98c12020-12-08 14:38:08 +01001242run_pyc_file(FILE *fp, PyObject *globals, PyObject *locals,
1243 PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001244{
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001245 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001246 PyCodeObject *co;
1247 PyObject *v;
1248 long magic;
1249 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001251 magic = PyMarshal_ReadLongFromFile(fp);
1252 if (magic != PyImport_GetMagicNumber()) {
Victor Stinner5200f552015-03-18 13:56:25 +01001253 if (!PyErr_Occurred())
1254 PyErr_SetString(PyExc_RuntimeError,
1255 "Bad magic number in .pyc file");
Zackery Spytzea737752018-06-23 21:15:24 -06001256 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001257 }
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08001258 /* Skip the rest of the header. */
1259 (void) PyMarshal_ReadLongFromFile(fp);
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001260 (void) PyMarshal_ReadLongFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 (void) PyMarshal_ReadLongFromFile(fp);
Zackery Spytzea737752018-06-23 21:15:24 -06001262 if (PyErr_Occurred()) {
1263 goto error;
1264 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 v = PyMarshal_ReadLastObjectFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001266 if (v == NULL || !PyCode_Check(v)) {
1267 Py_XDECREF(v);
1268 PyErr_SetString(PyExc_RuntimeError,
1269 "Bad code object in .pyc file");
Zackery Spytzea737752018-06-23 21:15:24 -06001270 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001271 }
Zackery Spytzea737752018-06-23 21:15:24 -06001272 fclose(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 co = (PyCodeObject *)v;
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001274 v = run_eval_code_obj(tstate, co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 if (v && flags)
1276 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1277 Py_DECREF(co);
1278 return v;
Zackery Spytzea737752018-06-23 21:15:24 -06001279error:
1280 fclose(fp);
1281 return NULL;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001282}
1283
Guido van Rossum82598051997-03-05 00:20:32 +00001284PyObject *
Victor Stinner14e461d2013-08-26 22:28:21 +02001285Py_CompileStringObject(const char *str, PyObject *filename, int start,
1286 PyCompilerFlags *flags, int optimize)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001287{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001288 PyCodeObject *co;
1289 mod_ty mod;
1290 PyArena *arena = PyArena_New();
1291 if (arena == NULL)
1292 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001293
Lysandros Nikolaou564cd182020-06-22 02:47:46 +03001294 mod = PyParser_ASTFromStringObject(str, filename, start, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001295 if (mod == NULL) {
1296 PyArena_Free(arena);
1297 return NULL;
1298 }
1299 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
1300 PyObject *result = PyAST_mod2obj(mod);
1301 PyArena_Free(arena);
1302 return result;
1303 }
Victor Stinner14e461d2013-08-26 22:28:21 +02001304 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 PyArena_Free(arena);
1306 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001307}
1308
Victor Stinner14e461d2013-08-26 22:28:21 +02001309PyObject *
1310Py_CompileStringExFlags(const char *str, const char *filename_str, int start,
1311 PyCompilerFlags *flags, int optimize)
1312{
1313 PyObject *filename, *co;
1314 filename = PyUnicode_DecodeFSDefault(filename_str);
1315 if (filename == NULL)
1316 return NULL;
1317 co = Py_CompileStringObject(str, filename, start, flags, optimize);
1318 Py_DECREF(filename);
1319 return co;
1320}
1321
Dino Viehland41540692019-05-28 16:21:17 -07001322const char *
1323_Py_SourceAsString(PyObject *cmd, const char *funcname, const char *what, PyCompilerFlags *cf, PyObject **cmd_copy)
1324{
1325 const char *str;
1326 Py_ssize_t size;
1327 Py_buffer view;
1328
1329 *cmd_copy = NULL;
1330 if (PyUnicode_Check(cmd)) {
1331 cf->cf_flags |= PyCF_IGNORE_COOKIE;
1332 str = PyUnicode_AsUTF8AndSize(cmd, &size);
1333 if (str == NULL)
1334 return NULL;
1335 }
1336 else if (PyBytes_Check(cmd)) {
1337 str = PyBytes_AS_STRING(cmd);
1338 size = PyBytes_GET_SIZE(cmd);
1339 }
1340 else if (PyByteArray_Check(cmd)) {
1341 str = PyByteArray_AS_STRING(cmd);
1342 size = PyByteArray_GET_SIZE(cmd);
1343 }
1344 else if (PyObject_GetBuffer(cmd, &view, PyBUF_SIMPLE) == 0) {
1345 /* Copy to NUL-terminated buffer. */
1346 *cmd_copy = PyBytes_FromStringAndSize(
1347 (const char *)view.buf, view.len);
1348 PyBuffer_Release(&view);
1349 if (*cmd_copy == NULL) {
1350 return NULL;
1351 }
1352 str = PyBytes_AS_STRING(*cmd_copy);
1353 size = PyBytes_GET_SIZE(*cmd_copy);
1354 }
1355 else {
1356 PyErr_Format(PyExc_TypeError,
1357 "%s() arg 1 must be a %s object",
1358 funcname, what);
1359 return NULL;
1360 }
1361
1362 if (strlen(str) != (size_t)size) {
1363 PyErr_SetString(PyExc_ValueError,
1364 "source code string cannot contain null bytes");
1365 Py_CLEAR(*cmd_copy);
1366 return NULL;
1367 }
1368 return str;
1369}
1370
Zachary Warec4821d62014-11-21 23:35:12 -06001371#if defined(USE_STACKCHECK)
1372#if defined(WIN32) && defined(_MSC_VER)
1373
1374/* Stack checking for Microsoft C */
1375
1376#include <malloc.h>
1377#include <excpt.h>
1378
1379/*
1380 * Return non-zero when we run out of memory on the stack; zero otherwise.
1381 */
1382int
1383PyOS_CheckStack(void)
1384{
1385 __try {
1386 /* alloca throws a stack overflow exception if there's
1387 not enough space left on the stack */
1388 alloca(PYOS_STACK_MARGIN * sizeof(void*));
1389 return 0;
1390 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
1391 EXCEPTION_EXECUTE_HANDLER :
1392 EXCEPTION_CONTINUE_SEARCH) {
1393 int errcode = _resetstkoflw();
1394 if (errcode == 0)
1395 {
1396 Py_FatalError("Could not reset the stack!");
1397 }
1398 }
1399 return 1;
1400}
1401
1402#endif /* WIN32 && _MSC_VER */
1403
1404/* Alternate implementations can be added here... */
1405
1406#endif /* USE_STACKCHECK */
1407
Pablo Galindo46bd5ed2020-12-02 05:16:31 +00001408/* Deprecated C API functions still provided for binary compatibility */
1409
1410#undef PyRun_AnyFile
1411PyAPI_FUNC(int)
1412PyRun_AnyFile(FILE *fp, const char *name)
1413{
1414 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
1415}
1416
1417#undef PyRun_AnyFileEx
1418PyAPI_FUNC(int)
1419PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
1420{
1421 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
1422}
1423
1424#undef PyRun_AnyFileFlags
1425PyAPI_FUNC(int)
1426PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
1427{
1428 return PyRun_AnyFileExFlags(fp, name, 0, flags);
1429}
1430
1431#undef PyRun_File
1432PyAPI_FUNC(PyObject *)
1433PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
1434{
1435 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
1436}
1437
1438#undef PyRun_FileEx
1439PyAPI_FUNC(PyObject *)
1440PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
1441{
1442 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
1443}
1444
1445#undef PyRun_FileFlags
1446PyAPI_FUNC(PyObject *)
1447PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
1448 PyCompilerFlags *flags)
1449{
1450 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
1451}
1452
1453#undef PyRun_SimpleFile
1454PyAPI_FUNC(int)
1455PyRun_SimpleFile(FILE *f, const char *p)
1456{
1457 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
1458}
1459
1460#undef PyRun_SimpleFileEx
1461PyAPI_FUNC(int)
1462PyRun_SimpleFileEx(FILE *f, const char *p, int c)
1463{
1464 return PyRun_SimpleFileExFlags(f, p, c, NULL);
1465}
1466
1467
1468#undef PyRun_String
1469PyAPI_FUNC(PyObject *)
1470PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
1471{
1472 return PyRun_StringFlags(str, s, g, l, NULL);
1473}
1474
1475#undef PyRun_SimpleString
1476PyAPI_FUNC(int)
1477PyRun_SimpleString(const char *s)
1478{
1479 return PyRun_SimpleStringFlags(s, NULL);
1480}
1481
1482#undef Py_CompileString
1483PyAPI_FUNC(PyObject *)
1484Py_CompileString(const char *str, const char *p, int s)
1485{
1486 return Py_CompileStringExFlags(str, p, s, NULL, -1);
1487}
1488
1489#undef Py_CompileStringFlags
1490PyAPI_FUNC(PyObject *)
1491Py_CompileStringFlags(const char *str, const char *p, int s,
1492 PyCompilerFlags *flags)
1493{
1494 return Py_CompileStringExFlags(str, p, s, flags, -1);
1495}
1496
1497#undef PyRun_InteractiveOne
1498PyAPI_FUNC(int)
1499PyRun_InteractiveOne(FILE *f, const char *p)
1500{
1501 return PyRun_InteractiveOneFlags(f, p, NULL);
1502}
1503
1504#undef PyRun_InteractiveLoop
1505PyAPI_FUNC(int)
1506PyRun_InteractiveLoop(FILE *f, const char *p)
1507{
1508 return PyRun_InteractiveLoopFlags(f, p, NULL);
1509}
1510
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001511#ifdef __cplusplus
1512}
1513#endif